@johnhenry/browsermesh-discovery 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.
package/src/swarm.mjs ADDED
@@ -0,0 +1,1440 @@
1
+ /**
2
+ * clawser-mesh-swarm.js -- Swarm Coordination for BrowserMesh.
3
+ *
4
+ * Leader election, task distribution, and swarm lifecycle management.
5
+ * Peers form a swarm where one node acts as leader, distributing tasks
6
+ * across followers using pluggable strategies.
7
+ *
8
+ * Run tests:
9
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-swarm.test.mjs
10
+ */
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Wire Constants — imported from canonical registry
14
+ // ---------------------------------------------------------------------------
15
+
16
+ import { MESH_TYPE } from '@johnhenry/browsermesh-primitives'
17
+
18
+ export const SWARM_JOIN = MESH_TYPE.SWARM_JOIN
19
+ export const SWARM_LEAVE = MESH_TYPE.SWARM_LEAVE
20
+ export const SWARM_HEARTBEAT = MESH_TYPE.SWARM_HEARTBEAT
21
+ export const SWARM_TASK_ASSIGN = MESH_TYPE.SWARM_TASK_ASSIGN
22
+
23
+ // SWIM protocol wire types
24
+ export const SWIM_PING = 0xF0;
25
+ export const SWIM_ACK = 0xF1;
26
+ export const SWIM_PING_REQ = 0xF2;
27
+ export const SWIM_PING_ACK = 0xF3;
28
+
29
+ /** @type {readonly string[]} */
30
+ export const SWIM_MEMBER_STATES = Object.freeze(['alive', 'suspect', 'dead', 'left']);
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Enums
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /** @type {readonly string[]} */
37
+ export const SwarmRole = Object.freeze(['leader', 'follower', 'candidate']);
38
+
39
+ /** @type {readonly string[]} */
40
+ export const TaskStrategy = Object.freeze([
41
+ 'leader-follower',
42
+ 'round-robin',
43
+ 'load-balanced',
44
+ 'redundant',
45
+ 'pipeline',
46
+ ]);
47
+
48
+ /** @type {readonly string[]} */
49
+ const TASK_STATUSES = Object.freeze([
50
+ 'pending',
51
+ 'assigned',
52
+ 'running',
53
+ 'completed',
54
+ 'failed',
55
+ ]);
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // SwarmMember
59
+ // ---------------------------------------------------------------------------
60
+
61
+ /**
62
+ * Represents a single member of the swarm.
63
+ */
64
+ export class SwarmMember {
65
+ /**
66
+ * @param {object} opts
67
+ * @param {string} opts.podId - Unique identifier for this member
68
+ * @param {string} [opts.role] - One of SwarmRole
69
+ * @param {number} [opts.load] - Current load factor 0-1
70
+ * @param {string[]} [opts.capabilities] - Advertised capabilities
71
+ * @param {number} [opts.joinedAt] - Unix timestamp (ms) when joined
72
+ * @param {number} [opts.lastHeartbeat] - Unix timestamp (ms) of last heartbeat
73
+ */
74
+ constructor({
75
+ podId,
76
+ role = 'candidate',
77
+ load = 0,
78
+ capabilities = [],
79
+ joinedAt = Date.now(),
80
+ lastHeartbeat = Date.now(),
81
+ }) {
82
+ if (!podId || typeof podId !== 'string') {
83
+ throw new Error('podId is required and must be a non-empty string');
84
+ }
85
+ this.podId = podId;
86
+ this.role = role;
87
+ this.load = load;
88
+ this.capabilities = [...capabilities];
89
+ this.joinedAt = joinedAt;
90
+ this.lastHeartbeat = lastHeartbeat;
91
+ }
92
+
93
+ /**
94
+ * Whether this member's heartbeat is stale (no heartbeat within timeoutMs).
95
+ *
96
+ * @param {number} [timeoutMs=30000] - Staleness threshold in ms
97
+ * @returns {boolean}
98
+ */
99
+ isStale(timeoutMs = 30000) {
100
+ return (Date.now() - this.lastHeartbeat) > timeoutMs;
101
+ }
102
+
103
+ /**
104
+ * Serialize to a plain JSON-safe object.
105
+ * @returns {object}
106
+ */
107
+ toJSON() {
108
+ return {
109
+ podId: this.podId,
110
+ role: this.role,
111
+ load: this.load,
112
+ capabilities: [...this.capabilities],
113
+ joinedAt: this.joinedAt,
114
+ lastHeartbeat: this.lastHeartbeat,
115
+ };
116
+ }
117
+
118
+ /**
119
+ * Re-hydrate from a plain object.
120
+ * @param {object} data
121
+ * @returns {SwarmMember}
122
+ */
123
+ static fromJSON(data) {
124
+ return new SwarmMember(data);
125
+ }
126
+ }
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // SwarmTask
130
+ // ---------------------------------------------------------------------------
131
+
132
+ let _taskCounter = 0;
133
+
134
+ /**
135
+ * Represents a task to be distributed across swarm members.
136
+ */
137
+ export class SwarmTask {
138
+ /**
139
+ * @param {object} opts
140
+ * @param {string} [opts.taskId] - Unique task identifier
141
+ * @param {string} opts.description - Human-readable description
142
+ * @param {string} [opts.strategy] - One of TaskStrategy
143
+ * @param {string[]} [opts.assignedTo] - podIds assigned to this task
144
+ * @param {string} [opts.status] - One of TASK_STATUSES
145
+ * @param {*} [opts.input] - Task input data
146
+ * @param {*} [opts.output] - Task output data
147
+ * @param {number} [opts.createdAt] - Unix timestamp (ms)
148
+ * @param {number|null} [opts.startedAt] - Unix timestamp (ms) when started
149
+ * @param {number|null} [opts.completedAt] - Unix timestamp (ms) when completed/failed
150
+ */
151
+ constructor({
152
+ taskId = null,
153
+ description,
154
+ strategy = 'leader-follower',
155
+ assignedTo = [],
156
+ status = 'pending',
157
+ input = null,
158
+ output = null,
159
+ createdAt = Date.now(),
160
+ startedAt = null,
161
+ completedAt = null,
162
+ }) {
163
+ if (!description || typeof description !== 'string') {
164
+ throw new Error('description is required and must be a non-empty string');
165
+ }
166
+ this.taskId = taskId || `task_${++_taskCounter}`;
167
+ this.description = description;
168
+ this.strategy = strategy;
169
+ this.assignedTo = [...assignedTo];
170
+ this.status = status;
171
+ this.input = input;
172
+ this.output = output;
173
+ this.createdAt = createdAt;
174
+ this.startedAt = startedAt;
175
+ this.completedAt = completedAt;
176
+ }
177
+
178
+ /**
179
+ * Serialize to a plain JSON-safe object.
180
+ * @returns {object}
181
+ */
182
+ toJSON() {
183
+ return {
184
+ taskId: this.taskId,
185
+ description: this.description,
186
+ strategy: this.strategy,
187
+ assignedTo: [...this.assignedTo],
188
+ status: this.status,
189
+ input: this.input,
190
+ output: this.output,
191
+ createdAt: this.createdAt,
192
+ startedAt: this.startedAt,
193
+ completedAt: this.completedAt,
194
+ };
195
+ }
196
+
197
+ /**
198
+ * Re-hydrate from a plain object.
199
+ * @param {object} data
200
+ * @returns {SwarmTask}
201
+ */
202
+ static fromJSON(data) {
203
+ return new SwarmTask(data);
204
+ }
205
+ }
206
+
207
+ // ---------------------------------------------------------------------------
208
+ // LeaderElection
209
+ // ---------------------------------------------------------------------------
210
+
211
+ /**
212
+ * Deterministic leader election using lowest-lexicographic-podId.
213
+ * Tracks heartbeats to detect stale leaders and trigger re-election.
214
+ */
215
+ export class LeaderElection {
216
+ /** @type {string} */
217
+ #localPodId;
218
+
219
+ /** @type {Set<string>} */
220
+ #candidates = new Set();
221
+
222
+ /** @type {string|null} */
223
+ #leader = null;
224
+
225
+ /** @type {Map<string, number>} podId -> last heartbeat timestamp */
226
+ #heartbeats = new Map();
227
+
228
+ /** @type {number} */
229
+ #heartbeatMs;
230
+
231
+ /** @type {number} */
232
+ #electionTimeoutMs;
233
+
234
+ /**
235
+ * @param {string} localPodId
236
+ * @param {object} [opts]
237
+ * @param {number} [opts.heartbeatMs=5000]
238
+ * @param {number} [opts.electionTimeoutMs=15000]
239
+ */
240
+ constructor(localPodId, opts = {}) {
241
+ if (!localPodId || typeof localPodId !== 'string') {
242
+ throw new Error('localPodId is required and must be a non-empty string');
243
+ }
244
+ this.#localPodId = localPodId;
245
+ this.#heartbeatMs = opts.heartbeatMs ?? 5000;
246
+ this.#electionTimeoutMs = opts.electionTimeoutMs ?? 15000;
247
+ this.#candidates.add(localPodId);
248
+ this.#heartbeats.set(localPodId, Date.now());
249
+ }
250
+
251
+ /** @returns {string|null} Current leader podId or null */
252
+ get leader() {
253
+ return this.#leader;
254
+ }
255
+
256
+ /**
257
+ * Current role of the local pod.
258
+ * @returns {string} One of SwarmRole values
259
+ */
260
+ get role() {
261
+ if (this.#leader === this.#localPodId) return 'leader';
262
+ if (this.#leader !== null) return 'follower';
263
+ return 'candidate';
264
+ }
265
+
266
+ /** @returns {string} The local podId */
267
+ get localPodId() {
268
+ return this.#localPodId;
269
+ }
270
+
271
+ /**
272
+ * Add a candidate to the election pool.
273
+ * @param {string} podId
274
+ */
275
+ addCandidate(podId) {
276
+ this.#candidates.add(podId);
277
+ if (!this.#heartbeats.has(podId)) {
278
+ this.#heartbeats.set(podId, Date.now());
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Remove a candidate from the election pool.
284
+ * If the removed candidate was the leader, leader is cleared.
285
+ *
286
+ * @param {string} podId
287
+ * @returns {boolean} true if the candidate existed
288
+ */
289
+ removeCandidate(podId) {
290
+ const existed = this.#candidates.delete(podId);
291
+ this.#heartbeats.delete(podId);
292
+ if (this.#leader === podId) {
293
+ this.#leader = null;
294
+ }
295
+ return existed;
296
+ }
297
+
298
+ /**
299
+ * Run an election. The candidate with the lowest lexicographic podId wins.
300
+ *
301
+ * @returns {string} The elected leader's podId
302
+ */
303
+ elect() {
304
+ const sorted = [...this.#candidates].sort();
305
+ if (sorted.length === 0) {
306
+ throw new Error('No candidates available for election');
307
+ }
308
+ this.#leader = sorted[0];
309
+ return this.#leader;
310
+ }
311
+
312
+ /**
313
+ * Record a heartbeat from a peer.
314
+ *
315
+ * @param {string} fromPodId
316
+ * @param {number} [timestamp] - Defaults to Date.now()
317
+ */
318
+ receiveHeartbeat(fromPodId, timestamp) {
319
+ this.#heartbeats.set(fromPodId, timestamp ?? Date.now());
320
+ }
321
+
322
+ /**
323
+ * Check if the current leader is still alive (has sent a heartbeat
324
+ * within electionTimeoutMs).
325
+ *
326
+ * @param {number} [now] - Current timestamp for testing
327
+ * @returns {boolean} true if leader is alive, false if stale or no leader
328
+ */
329
+ checkLeaderAlive(now) {
330
+ if (!this.#leader) return false;
331
+ const ts = now ?? Date.now();
332
+ const lastHb = this.#heartbeats.get(this.#leader);
333
+ if (lastHb === undefined) return false;
334
+ return (ts - lastHb) <= this.#electionTimeoutMs;
335
+ }
336
+
337
+ /**
338
+ * Yield leadership to the next candidate in lexicographic order.
339
+ * Returns the new leader or null if no other candidates exist.
340
+ *
341
+ * @returns {string|null}
342
+ */
343
+ yieldLeadership() {
344
+ const sorted = [...this.#candidates].sort();
345
+ if (sorted.length <= 1) {
346
+ this.#leader = null;
347
+ return null;
348
+ }
349
+ const currentIdx = sorted.indexOf(this.#leader);
350
+ const nextIdx = (currentIdx + 1) % sorted.length;
351
+ this.#leader = sorted[nextIdx];
352
+ return this.#leader;
353
+ }
354
+
355
+ /**
356
+ * Get all current candidates sorted lexicographically.
357
+ * @returns {string[]}
358
+ */
359
+ get candidates() {
360
+ return [...this.#candidates].sort();
361
+ }
362
+
363
+ /**
364
+ * Serialize to a plain JSON-safe object.
365
+ * @returns {object}
366
+ */
367
+ toJSON() {
368
+ return {
369
+ localPodId: this.#localPodId,
370
+ leader: this.#leader,
371
+ candidates: [...this.#candidates],
372
+ heartbeats: Object.fromEntries(this.#heartbeats),
373
+ heartbeatMs: this.#heartbeatMs,
374
+ electionTimeoutMs: this.#electionTimeoutMs,
375
+ };
376
+ }
377
+
378
+ /**
379
+ * Re-hydrate from a plain object.
380
+ * @param {object} data
381
+ * @returns {LeaderElection}
382
+ */
383
+ static fromJSON(data) {
384
+ const el = new LeaderElection(data.localPodId, {
385
+ heartbeatMs: data.heartbeatMs,
386
+ electionTimeoutMs: data.electionTimeoutMs,
387
+ });
388
+ // Remove default local candidate, restore serialized set
389
+ el.#candidates.clear();
390
+ for (const c of data.candidates) {
391
+ el.#candidates.add(c);
392
+ }
393
+ el.#leader = data.leader;
394
+ el.#heartbeats.clear();
395
+ for (const [k, v] of Object.entries(data.heartbeats)) {
396
+ el.#heartbeats.set(k, v);
397
+ }
398
+ return el;
399
+ }
400
+ }
401
+
402
+ // ---------------------------------------------------------------------------
403
+ // TaskDistributor
404
+ // ---------------------------------------------------------------------------
405
+
406
+ /**
407
+ * Distributes tasks to swarm members based on pluggable strategies.
408
+ */
409
+ export class TaskDistributor {
410
+ /** @type {Map<string, SwarmMember>} podId -> SwarmMember */
411
+ #members = new Map();
412
+
413
+ /** @type {number} Round-robin index tracker */
414
+ #rrIndex = 0;
415
+
416
+ /**
417
+ * @param {SwarmMember[]} [members]
418
+ */
419
+ constructor(members = []) {
420
+ for (const m of members) {
421
+ this.#members.set(m.podId, m);
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Add a member to the distributor pool.
427
+ * @param {SwarmMember} member
428
+ */
429
+ addMember(member) {
430
+ this.#members.set(member.podId, member);
431
+ }
432
+
433
+ /**
434
+ * Remove a member from the pool.
435
+ * @param {string} podId
436
+ * @returns {boolean}
437
+ */
438
+ removeMember(podId) {
439
+ return this.#members.delete(podId);
440
+ }
441
+
442
+ /**
443
+ * Get a member by podId.
444
+ * @param {string} podId
445
+ * @returns {SwarmMember|null}
446
+ */
447
+ getMember(podId) {
448
+ return this.#members.get(podId) || null;
449
+ }
450
+
451
+ /**
452
+ * All members as an array.
453
+ * @returns {SwarmMember[]}
454
+ */
455
+ get members() {
456
+ return [...this.#members.values()];
457
+ }
458
+
459
+ /** @returns {number} */
460
+ get size() {
461
+ return this.#members.size;
462
+ }
463
+
464
+ /**
465
+ * Distribute a task to members using the given strategy.
466
+ * Returns an array of assigned podIds.
467
+ *
468
+ * Strategies:
469
+ * - leader-follower: assigns to the first member (by insertion order)
470
+ * - round-robin: rotates through members cyclically
471
+ * - load-balanced: picks the member with the lowest load
472
+ * - redundant: assigns to ALL members
473
+ * - pipeline: assigns to all members in order (same as redundant, semantically different)
474
+ *
475
+ * @param {SwarmTask} task
476
+ * @param {string} [strategy] - Override task's strategy
477
+ * @returns {string[]} Assigned podIds
478
+ */
479
+ distribute(task, strategy) {
480
+ const strat = strategy || task.strategy || 'leader-follower';
481
+ const all = [...this.#members.values()];
482
+
483
+ if (all.length === 0) return [];
484
+
485
+ switch (strat) {
486
+ case 'leader-follower': {
487
+ const assigned = [all[0].podId];
488
+ task.assignedTo = assigned;
489
+ task.status = 'assigned';
490
+ return assigned;
491
+ }
492
+
493
+ case 'round-robin': {
494
+ const idx = this.#rrIndex % all.length;
495
+ this.#rrIndex++;
496
+ const assigned = [all[idx].podId];
497
+ task.assignedTo = assigned;
498
+ task.status = 'assigned';
499
+ return assigned;
500
+ }
501
+
502
+ case 'load-balanced': {
503
+ const sorted = [...all].sort((a, b) => a.load - b.load);
504
+ const assigned = [sorted[0].podId];
505
+ task.assignedTo = assigned;
506
+ task.status = 'assigned';
507
+ return assigned;
508
+ }
509
+
510
+ case 'redundant': {
511
+ const assigned = all.map(m => m.podId);
512
+ task.assignedTo = assigned;
513
+ task.status = 'assigned';
514
+ return assigned;
515
+ }
516
+
517
+ case 'pipeline': {
518
+ const assigned = all.map(m => m.podId);
519
+ task.assignedTo = assigned;
520
+ task.status = 'assigned';
521
+ return assigned;
522
+ }
523
+
524
+ default:
525
+ throw new Error(`Unknown task strategy: ${strat}`);
526
+ }
527
+ }
528
+ }
529
+
530
+ // ---------------------------------------------------------------------------
531
+ // SwarmCoordinator
532
+ // ---------------------------------------------------------------------------
533
+
534
+ /**
535
+ * High-level facade for swarm management: joining/leaving, leader election,
536
+ * task submission and lifecycle.
537
+ *
538
+ * Internally tracks a `Map<swarmId, {election, distributor, tasks}>` so a
539
+ * single pod can participate in more than one concurrent swarm. `'local'`
540
+ * is the default/legacy swarm — every method that doesn't take an explicit
541
+ * `swarmId` operates on it, so single-swarm callers (all production
542
+ * call-sites and every pre-multi-swarm test) see IDENTICAL behavior to
543
+ * before this refactor. No wire format changed: there's no wireTransport()
544
+ * on this class today (the SWARM_* constants are unused re-exports — see
545
+ * the file header), so there's nothing to add a swarmId field to yet;
546
+ * that's a separate, not-yet-written wire integration.
547
+ */
548
+ export class SwarmCoordinator {
549
+ /** @type {string} */
550
+ #localPodId;
551
+
552
+ /** @type {Map<string, {election: LeaderElection, distributor: TaskDistributor, tasks: Map<string, SwarmTask>}>} */
553
+ #swarms = new Map();
554
+
555
+ /** @type {object} Election opts (heartbeatMs, electionTimeoutMs) applied to every swarm created after construction */
556
+ #electionOpts;
557
+
558
+ /** @type {SwimMembership|null} */
559
+ #swim = null;
560
+
561
+ /**
562
+ * @param {string} localPodId
563
+ * @param {object} [opts]
564
+ * @param {number} [opts.heartbeatMs]
565
+ * @param {number} [opts.electionTimeoutMs]
566
+ * @param {SwimMembership} [opts.swim] - Optional SWIM membership protocol instance
567
+ */
568
+ constructor(localPodId, opts = {}) {
569
+ this.#localPodId = localPodId;
570
+ this.#electionOpts = opts;
571
+ this.#createSwarm('local');
572
+
573
+ // Wire up SWIM membership protocol if provided. SWIM tracks failure
574
+ // detection for the local pod's default swarm only — join/leave here
575
+ // default to 'local', matching pre-multi-swarm behavior.
576
+ this.#swim = opts.swim ?? null;
577
+ if (this.#swim) {
578
+ this.#swim.onJoin = (podId) => this.join(podId);
579
+ this.#swim.onDead = (podId) => this.leave(podId);
580
+ }
581
+ }
582
+
583
+ /**
584
+ * Create a new swarm state bundle, adding the local pod as its first
585
+ * member (mirrors the constructor's original single-swarm setup).
586
+ * @param {string} swarmId
587
+ * @returns {{election: LeaderElection, distributor: TaskDistributor, tasks: Map<string, SwarmTask>}}
588
+ */
589
+ #createSwarm(swarmId) {
590
+ const election = new LeaderElection(this.#localPodId, this.#electionOpts);
591
+ const distributor = new TaskDistributor();
592
+ distributor.addMember(new SwarmMember({ podId: this.#localPodId }));
593
+ const swarm = { election, distributor, tasks: new Map() };
594
+ this.#swarms.set(swarmId, swarm);
595
+ return swarm;
596
+ }
597
+
598
+ /**
599
+ * Get a swarm's state bundle, auto-creating it (with the local pod as
600
+ * its first member) if it doesn't exist yet — mirrors how the original
601
+ * single-swarm constructor always had exactly one ready-to-use swarm.
602
+ * @param {string} [swarmId='local']
603
+ */
604
+ #getSwarm(swarmId = 'local') {
605
+ return this.#swarms.get(swarmId) || this.#createSwarm(swarmId);
606
+ }
607
+
608
+ /**
609
+ * Explicitly create a swarm without joining any extra members yet.
610
+ * Idempotent — returns the existing swarm's state if already present.
611
+ * @param {string} swarmId
612
+ * @returns {boolean} true if a new swarm was created, false if it already existed
613
+ */
614
+ createSwarm(swarmId) {
615
+ if (this.#swarms.has(swarmId)) return false;
616
+ this.#createSwarm(swarmId);
617
+ return true;
618
+ }
619
+
620
+ /**
621
+ * Disband a swarm and discard its state (members, election, tasks).
622
+ * The `'local'` swarm can't be disbanded — it's the coordinator's
623
+ * always-available default, matching every single-swarm call-site.
624
+ *
625
+ * @param {string} swarmId
626
+ * @returns {boolean} true if the swarm existed and was removed
627
+ */
628
+ disbandSwarm(swarmId) {
629
+ if (swarmId === 'local') {
630
+ throw new Error("cannot disband the 'local' swarm");
631
+ }
632
+ return this.#swarms.delete(swarmId);
633
+ }
634
+
635
+ /** @param {string} swarmId @returns {boolean} */
636
+ hasSwarm(swarmId) {
637
+ return this.#swarms.has(swarmId);
638
+ }
639
+
640
+ /**
641
+ * List all tracked swarms with a summary of their state.
642
+ * @returns {Array<{swarmId: string, size: number, isLeader: boolean, leader: string|null, taskCount: number}>}
643
+ */
644
+ listSwarms() {
645
+ return [...this.#swarms.entries()].map(([swarmId, swarm]) => ({
646
+ swarmId,
647
+ size: swarm.distributor.size,
648
+ isLeader: swarm.election.role === 'leader',
649
+ leader: swarm.election.leader,
650
+ taskCount: swarm.tasks.size,
651
+ }));
652
+ }
653
+
654
+ /** @returns {LeaderElection} The 'local' swarm's election (unchanged accessor) */
655
+ get election() {
656
+ return this.#getSwarm('local').election;
657
+ }
658
+
659
+ /** @returns {TaskDistributor} The 'local' swarm's distributor (unchanged accessor) */
660
+ get distributor() {
661
+ return this.#getSwarm('local').distributor;
662
+ }
663
+
664
+ /** @returns {SwimMembership|null} */
665
+ get swim() {
666
+ return this.#swim;
667
+ }
668
+
669
+ /**
670
+ * List member podIds of a swarm (defaults to 'local').
671
+ * @param {string} [swarmId='local']
672
+ * @returns {string[]}
673
+ */
674
+ listMembers(swarmId = 'local') {
675
+ return (this.#swarms.get(swarmId)?.distributor.members ?? []).map(m => m.podId);
676
+ }
677
+
678
+ /**
679
+ * Add a new member to a swarm (defaults to 'local' — unchanged
680
+ * behavior for every pre-multi-swarm call-site).
681
+ *
682
+ * @param {string} podId
683
+ * @param {string[]} [capabilities]
684
+ * @param {string} [swarmId='local']
685
+ * @returns {SwarmMember}
686
+ */
687
+ join(podId, capabilities = [], swarmId = 'local') {
688
+ const swarm = this.#getSwarm(swarmId);
689
+ const member = new SwarmMember({ podId, capabilities });
690
+ swarm.distributor.addMember(member);
691
+ swarm.election.addCandidate(podId);
692
+ if (swarmId === 'local' && this.#swim) {
693
+ this.#swim.addMember(podId);
694
+ }
695
+ return member;
696
+ }
697
+
698
+ /**
699
+ * Remove a member from a swarm (defaults to 'local').
700
+ *
701
+ * @param {string} podId
702
+ * @param {string} [swarmId='local']
703
+ * @returns {boolean}
704
+ */
705
+ leave(podId, swarmId = 'local') {
706
+ const swarm = this.#swarms.get(swarmId);
707
+ if (!swarm) return false;
708
+ swarm.election.removeCandidate(podId);
709
+ if (swarmId === 'local' && this.#swim) {
710
+ this.#swim.removeMember(podId);
711
+ }
712
+ return swarm.distributor.removeMember(podId);
713
+ }
714
+
715
+ /**
716
+ * Submit a new task to a swarm (defaults to 'local').
717
+ * The task is created, distributed, and stored.
718
+ *
719
+ * @param {string} description
720
+ * @param {string} [strategy]
721
+ * @param {*} [input]
722
+ * @param {string} [swarmId='local']
723
+ * @returns {SwarmTask}
724
+ */
725
+ submitTask(description, strategy, input, swarmId = 'local') {
726
+ const swarm = this.#getSwarm(swarmId);
727
+ const task = new SwarmTask({
728
+ description,
729
+ strategy: strategy || 'leader-follower',
730
+ input: input ?? null,
731
+ });
732
+ swarm.distributor.distribute(task);
733
+ swarm.tasks.set(task.taskId, task);
734
+ return task;
735
+ }
736
+
737
+ /**
738
+ * Find a task by ID across all swarms. Task IDs are unique per
739
+ * coordinator (module-level counter), so no swarmId is needed.
740
+ * @param {string} taskId
741
+ * @returns {SwarmTask|null}
742
+ */
743
+ getTask(taskId) {
744
+ for (const swarm of this.#swarms.values()) {
745
+ const task = swarm.tasks.get(taskId);
746
+ if (task) return task;
747
+ }
748
+ return null;
749
+ }
750
+
751
+ /**
752
+ * Mark a task as completed.
753
+ *
754
+ * @param {string} taskId
755
+ * @param {*} [output]
756
+ * @returns {boolean} true if the task was found and completed
757
+ */
758
+ completeTask(taskId, output) {
759
+ const task = this.getTask(taskId);
760
+ if (!task) return false;
761
+ task.status = 'completed';
762
+ task.output = output ?? null;
763
+ task.completedAt = Date.now();
764
+ return true;
765
+ }
766
+
767
+ /**
768
+ * Mark a task as failed.
769
+ *
770
+ * @param {string} taskId
771
+ * @param {*} [error]
772
+ * @returns {boolean} true if the task was found and marked failed
773
+ */
774
+ failTask(taskId, error) {
775
+ const task = this.getTask(taskId);
776
+ if (!task) return false;
777
+ task.status = 'failed';
778
+ task.output = error ?? null;
779
+ task.completedAt = Date.now();
780
+ return true;
781
+ }
782
+
783
+ /**
784
+ * Cancel a pending or assigned task.
785
+ *
786
+ * @param {string} taskId
787
+ * @returns {boolean} true if the task was found and cancelled
788
+ */
789
+ cancelTask(taskId) {
790
+ const task = this.getTask(taskId);
791
+ if (!task) return false;
792
+ if (task.status === 'completed' || task.status === 'failed') return false;
793
+ task.status = 'cancelled';
794
+ task.completedAt = Date.now();
795
+ return true;
796
+ }
797
+
798
+ /**
799
+ * List tasks, optionally filtering by status and/or swarm. Defaults to
800
+ * the 'local' swarm — unchanged behavior for pre-multi-swarm callers,
801
+ * since they only ever submit tasks to 'local'. Pass `swarmId: null`
802
+ * (or any falsy-but-explicit value doesn't work — use the string
803
+ * `'*'`) to list across every swarm.
804
+ *
805
+ * @param {object} [opts]
806
+ * @param {string} [opts.status] - Filter by task status
807
+ * @param {string} [opts.swarmId='local'] - Which swarm to list from, or '*' for all swarms
808
+ * @returns {SwarmTask[]}
809
+ */
810
+ listTasks(opts = {}) {
811
+ const swarmId = opts.swarmId ?? 'local';
812
+ let tasks;
813
+ if (swarmId === '*') {
814
+ tasks = [...this.#swarms.values()].flatMap(s => [...s.tasks.values()]);
815
+ } else {
816
+ tasks = [...(this.#swarms.get(swarmId)?.tasks.values() ?? [])];
817
+ }
818
+ if (opts.status) {
819
+ tasks = tasks.filter(t => t.status === opts.status);
820
+ }
821
+ return tasks;
822
+ }
823
+
824
+ /** @returns {number} Number of members in the 'local' swarm (unchanged accessor) */
825
+ get swarmSize() {
826
+ return this.#getSwarm('local').distributor.size;
827
+ }
828
+
829
+ /** @returns {boolean} true if the local pod is the elected leader of the 'local' swarm (unchanged accessor) */
830
+ get isLeader() {
831
+ return this.#getSwarm('local').election.role === 'leader';
832
+ }
833
+ }
834
+
835
+ // ---------------------------------------------------------------------------
836
+ // SwimMembership — SWIM protocol (Scalable Weakly-consistent Infection-style
837
+ // Membership) for failure detection and membership dissemination.
838
+ // ---------------------------------------------------------------------------
839
+
840
+ /**
841
+ * Implements the SWIM protocol for decentralised failure detection.
842
+ *
843
+ * Each tick the local node pings a random peer. If the peer does not
844
+ * respond within `pingTimeoutMs`, indirect pings are sent through `k`
845
+ * random intermediaries. If the target still does not respond it is
846
+ * marked *suspect*, and after `suspectTimeoutMs` it is declared *dead*.
847
+ *
848
+ * Membership updates (join, suspect, dead, leave) are piggybacked on
849
+ * every ping/ack message so they disseminate in O(log n) rounds.
850
+ */
851
+ export class SwimMembership {
852
+ /** @type {string} */
853
+ #localId;
854
+
855
+ /** @type {function} */
856
+ #sendFn;
857
+
858
+ /** @type {Map<string, {state: string, incarnation: number, suspectAt: number|null}>} */
859
+ #members = new Map();
860
+
861
+ /** @type {number} */
862
+ #localIncarnation = 0;
863
+
864
+ /** @type {string[]} */
865
+ #pingQueue = [];
866
+
867
+ /** @type {Map<number, {targetId: string, timer: *}>} seq -> pending info */
868
+ #pendingPings = new Map();
869
+
870
+ /** @type {Array<{podId: string, state: string, incarnation: number}>} */
871
+ #updateBuffer = [];
872
+
873
+ /** @type {*} */
874
+ #timer = null;
875
+
876
+ /** @type {number} */
877
+ #seqCounter = 0;
878
+
879
+ /** @type {number} */
880
+ #pingIntervalMs;
881
+
882
+ /** @type {number} */
883
+ #pingTimeoutMs;
884
+
885
+ /** @type {number} */
886
+ #suspectTimeoutMs;
887
+
888
+ /** @type {number} */
889
+ #indirectPingCount;
890
+
891
+ /** @type {function|null} */
892
+ onJoin;
893
+
894
+ /** @type {function|null} */
895
+ onSuspect;
896
+
897
+ /** @type {function|null} */
898
+ onDead;
899
+
900
+ /** @type {function|null} */
901
+ onLeave;
902
+
903
+ /** @type {function} */
904
+ #nowFn;
905
+
906
+ /**
907
+ * @param {object} opts
908
+ * @param {string} opts.localId - This node's pod ID
909
+ * @param {function} opts.sendFn - (targetId, msg) => void
910
+ * @param {number} [opts.pingIntervalMs=1000]
911
+ * @param {number} [opts.pingTimeoutMs=500]
912
+ * @param {number} [opts.suspectTimeoutMs=5000]
913
+ * @param {number} [opts.indirectPingCount=3]
914
+ * @param {function|null} [opts.onJoin]
915
+ * @param {function|null} [opts.onSuspect]
916
+ * @param {function|null} [opts.onDead]
917
+ * @param {function|null} [opts.onLeave]
918
+ * @param {function} [opts.nowFn=Date.now]
919
+ */
920
+ constructor({
921
+ localId,
922
+ sendFn,
923
+ pingIntervalMs = 1000,
924
+ pingTimeoutMs = 500,
925
+ suspectTimeoutMs = 5000,
926
+ indirectPingCount = 3,
927
+ onJoin = null,
928
+ onSuspect = null,
929
+ onDead = null,
930
+ onLeave = null,
931
+ nowFn = Date.now,
932
+ }) {
933
+ if (!localId || typeof localId !== 'string') {
934
+ throw new Error('localId is required and must be a non-empty string');
935
+ }
936
+ if (typeof sendFn !== 'function') {
937
+ throw new Error('sendFn is required and must be a function');
938
+ }
939
+ this.#localId = localId;
940
+ this.#sendFn = sendFn;
941
+ this.#pingIntervalMs = pingIntervalMs;
942
+ this.#pingTimeoutMs = pingTimeoutMs;
943
+ this.#suspectTimeoutMs = suspectTimeoutMs;
944
+ this.#indirectPingCount = indirectPingCount;
945
+ this.onJoin = onJoin;
946
+ this.onSuspect = onSuspect;
947
+ this.onDead = onDead;
948
+ this.onLeave = onLeave;
949
+ this.#nowFn = nowFn;
950
+
951
+ // Add self as the first alive member
952
+ this.#members.set(localId, { state: 'alive', incarnation: 0, suspectAt: null });
953
+ }
954
+
955
+ /** @returns {string} */
956
+ get localId() {
957
+ return this.#localId;
958
+ }
959
+
960
+ /** @returns {number} Total member count */
961
+ get size() {
962
+ return this.#members.size;
963
+ }
964
+
965
+ /** @returns {number} Count of alive members */
966
+ get aliveCount() {
967
+ let count = 0;
968
+ for (const entry of this.#members.values()) {
969
+ if (entry.state === 'alive') count++;
970
+ }
971
+ return count;
972
+ }
973
+
974
+ /**
975
+ * Begin periodic ping rounds.
976
+ */
977
+ start() {
978
+ if (this.#timer) return;
979
+ this.#timer = setInterval(() => this.#pingRound(), this.#pingIntervalMs);
980
+ }
981
+
982
+ /**
983
+ * Stop the protocol — clear interval, pending ping timers, and suspect timers.
984
+ */
985
+ stop() {
986
+ if (this.#timer) {
987
+ clearInterval(this.#timer);
988
+ this.#timer = null;
989
+ }
990
+ for (const pending of this.#pendingPings.values()) {
991
+ if (pending.timer) clearTimeout(pending.timer);
992
+ }
993
+ this.#pendingPings.clear();
994
+ }
995
+
996
+ /**
997
+ * Add a member as alive with incarnation 0.
998
+ *
999
+ * @param {string} podId
1000
+ */
1001
+ addMember(podId) {
1002
+ if (podId === this.#localId) return;
1003
+ if (this.#members.has(podId)) return;
1004
+ this.#members.set(podId, { state: 'alive', incarnation: 0, suspectAt: null });
1005
+ this.#enqueueUpdate({ podId, state: 'alive', incarnation: 0 });
1006
+ if (this.onJoin) this.onJoin(podId);
1007
+ }
1008
+
1009
+ /**
1010
+ * Mark a member as left, enqueue a leave update, and invoke the onLeave callback.
1011
+ *
1012
+ * @param {string} podId
1013
+ */
1014
+ removeMember(podId) {
1015
+ const entry = this.#members.get(podId);
1016
+ if (!entry) return;
1017
+ entry.state = 'left';
1018
+ entry.suspectAt = null;
1019
+ this.#enqueueUpdate({ podId, state: 'left', incarnation: entry.incarnation });
1020
+ if (this.onLeave) this.onLeave(podId);
1021
+ }
1022
+
1023
+ /**
1024
+ * Return the state of a member, or null if unknown.
1025
+ *
1026
+ * @param {string} podId
1027
+ * @returns {string|null}
1028
+ */
1029
+ getState(podId) {
1030
+ const entry = this.#members.get(podId);
1031
+ return entry ? entry.state : null;
1032
+ }
1033
+
1034
+ /**
1035
+ * Return a copy of the full membership map.
1036
+ *
1037
+ * @returns {Map<string, {state: string, incarnation: number, suspectAt: number|null}>}
1038
+ */
1039
+ getMembers() {
1040
+ return new Map(this.#members);
1041
+ }
1042
+
1043
+ /**
1044
+ * Return an array of pod IDs whose state is 'alive'.
1045
+ *
1046
+ * @returns {string[]}
1047
+ */
1048
+ aliveMembers() {
1049
+ const result = [];
1050
+ for (const [podId, entry] of this.#members) {
1051
+ if (entry.state === 'alive') result.push(podId);
1052
+ }
1053
+ return result;
1054
+ }
1055
+
1056
+ /**
1057
+ * Dispatch an incoming SWIM message to the appropriate handler.
1058
+ *
1059
+ * @param {string} fromId - Sender pod ID
1060
+ * @param {object} msg - Wire message
1061
+ */
1062
+ handleMessage(fromId, msg) {
1063
+ switch (msg.type) {
1064
+ case SWIM_PING:
1065
+ this.#handlePing(fromId, msg);
1066
+ break;
1067
+ case SWIM_ACK:
1068
+ this.#handleAck(fromId, msg);
1069
+ break;
1070
+ case SWIM_PING_REQ:
1071
+ this.#handlePingReq(fromId, msg);
1072
+ break;
1073
+ case SWIM_PING_ACK:
1074
+ this.#handlePingAck(fromId, msg);
1075
+ break;
1076
+ }
1077
+ }
1078
+
1079
+ /**
1080
+ * Serialize for inspection.
1081
+ *
1082
+ * @returns {object}
1083
+ */
1084
+ toJSON() {
1085
+ const members = {};
1086
+ for (const [podId, entry] of this.#members) {
1087
+ members[podId] = { ...entry };
1088
+ }
1089
+ return {
1090
+ localId: this.#localId,
1091
+ localIncarnation: this.#localIncarnation,
1092
+ members,
1093
+ updateBufferSize: this.#updateBuffer.length,
1094
+ };
1095
+ }
1096
+
1097
+ // -------------------------------------------------------------------------
1098
+ // Private — ping round
1099
+ // -------------------------------------------------------------------------
1100
+
1101
+ /**
1102
+ * Pick the next target from a shuffled queue and send a SWIM_PING
1103
+ * with piggybacked updates. Start an ack timer.
1104
+ */
1105
+ #pingRound() {
1106
+ if (this.#pingQueue.length === 0) {
1107
+ this.#refillPingQueue();
1108
+ }
1109
+ if (this.#pingQueue.length === 0) return; // no peers
1110
+
1111
+ const targetId = this.#pingQueue.shift();
1112
+ const entry = this.#members.get(targetId);
1113
+ if (!entry || entry.state === 'dead' || entry.state === 'left') return;
1114
+
1115
+ const seq = ++this.#seqCounter;
1116
+ const updates = this.#drainUpdates();
1117
+
1118
+ this.#sendFn(targetId, {
1119
+ type: SWIM_PING,
1120
+ from: this.#localId,
1121
+ seq,
1122
+ updates,
1123
+ });
1124
+
1125
+ const timer = setTimeout(() => this.#onPingTimeout(targetId, seq), this.#pingTimeoutMs);
1126
+ this.#pendingPings.set(seq, { targetId, timer });
1127
+ }
1128
+
1129
+ // -------------------------------------------------------------------------
1130
+ // Private — message handlers
1131
+ // -------------------------------------------------------------------------
1132
+
1133
+ /**
1134
+ * Handle an incoming SWIM_PING: process piggybacked updates and reply
1135
+ * with a SWIM_ACK carrying our own updates.
1136
+ *
1137
+ * @param {string} fromId
1138
+ * @param {object} msg
1139
+ */
1140
+ #handlePing(fromId, msg) {
1141
+ if (msg.updates) {
1142
+ for (const u of msg.updates) this.#processUpdate(u);
1143
+ }
1144
+ const updates = this.#drainUpdates();
1145
+ this.#sendFn(fromId, {
1146
+ type: SWIM_ACK,
1147
+ from: this.#localId,
1148
+ seq: msg.seq,
1149
+ updates,
1150
+ });
1151
+ }
1152
+
1153
+ /**
1154
+ * Handle an incoming SWIM_ACK: clear the pending ping timer and process
1155
+ * piggybacked updates.
1156
+ *
1157
+ * @param {string} fromId
1158
+ * @param {object} msg
1159
+ */
1160
+ #handleAck(fromId, msg) {
1161
+ const pending = this.#pendingPings.get(msg.seq);
1162
+ if (pending) {
1163
+ clearTimeout(pending.timer);
1164
+ this.#pendingPings.delete(msg.seq);
1165
+ }
1166
+ if (msg.updates) {
1167
+ for (const u of msg.updates) this.#processUpdate(u);
1168
+ }
1169
+ }
1170
+
1171
+ /**
1172
+ * Handle a SWIM_PING_REQ: ping the target on behalf of the requester.
1173
+ *
1174
+ * @param {string} fromId
1175
+ * @param {object} msg
1176
+ */
1177
+ #handlePingReq(fromId, msg) {
1178
+ const seq = ++this.#seqCounter;
1179
+ const updates = this.#drainUpdates();
1180
+
1181
+ this.#sendFn(msg.target, {
1182
+ type: SWIM_PING,
1183
+ from: this.#localId,
1184
+ seq,
1185
+ updates,
1186
+ });
1187
+
1188
+ // When the ack comes back, forward it as SWIM_PING_ACK
1189
+ const timer = setTimeout(() => {
1190
+ this.#pendingPings.delete(seq);
1191
+ // Target didn't respond — notify requester with empty ack
1192
+ this.#sendFn(fromId, {
1193
+ type: SWIM_PING_ACK,
1194
+ from: this.#localId,
1195
+ target: msg.target,
1196
+ originalFrom: fromId,
1197
+ seq: msg.seq,
1198
+ updates: [],
1199
+ });
1200
+ }, this.#pingTimeoutMs);
1201
+
1202
+ this.#pendingPings.set(seq, {
1203
+ targetId: msg.target,
1204
+ timer,
1205
+ // Stash requester info so #handleAck can forward
1206
+ indirectFor: { originalFrom: fromId, originalSeq: msg.seq },
1207
+ });
1208
+ }
1209
+
1210
+ /**
1211
+ * Handle a SWIM_PING_ACK: the indirect ping succeeded — clear the
1212
+ * indirect timeout for the target.
1213
+ *
1214
+ * @param {string} fromId
1215
+ * @param {object} msg
1216
+ */
1217
+ #handlePingAck(fromId, msg) {
1218
+ // Clear pending indirect timeout for this target
1219
+ const pending = this.#pendingPings.get(msg.seq);
1220
+ if (pending) {
1221
+ clearTimeout(pending.timer);
1222
+ this.#pendingPings.delete(msg.seq);
1223
+ }
1224
+ if (msg.updates) {
1225
+ for (const u of msg.updates) this.#processUpdate(u);
1226
+ }
1227
+ }
1228
+
1229
+ // -------------------------------------------------------------------------
1230
+ // Private — timeouts
1231
+ // -------------------------------------------------------------------------
1232
+
1233
+ /**
1234
+ * Called when a direct ping times out. Send SWIM_PING_REQ to k random
1235
+ * alive members and start an indirect timeout.
1236
+ *
1237
+ * @param {string} targetId
1238
+ * @param {number} seq
1239
+ */
1240
+ #onPingTimeout(targetId, seq) {
1241
+ this.#pendingPings.delete(seq);
1242
+
1243
+ // Pick k random alive peers (excluding self and target) to relay
1244
+ const candidates = this.aliveMembers().filter(id => id !== targetId && id !== this.#localId);
1245
+ const relays = this.#pickRandom(candidates, this.#indirectPingCount);
1246
+
1247
+ if (relays.length === 0) {
1248
+ // No intermediaries — go straight to suspect
1249
+ this.#onIndirectTimeout(targetId);
1250
+ return;
1251
+ }
1252
+
1253
+ const indirectSeq = ++this.#seqCounter;
1254
+ for (const relayId of relays) {
1255
+ this.#sendFn(relayId, {
1256
+ type: SWIM_PING_REQ,
1257
+ from: this.#localId,
1258
+ target: targetId,
1259
+ seq: indirectSeq,
1260
+ });
1261
+ }
1262
+
1263
+ // Start indirect timeout — if no SWIM_PING_ACK arrives, mark suspect
1264
+ const timer = setTimeout(() => {
1265
+ this.#pendingPings.delete(indirectSeq);
1266
+ this.#onIndirectTimeout(targetId);
1267
+ }, this.#pingTimeoutMs);
1268
+
1269
+ this.#pendingPings.set(indirectSeq, { targetId, timer });
1270
+ }
1271
+
1272
+ /**
1273
+ * Called when indirect pings also fail. Mark the target as suspect
1274
+ * and start a suspect timer.
1275
+ *
1276
+ * @param {string} targetId
1277
+ */
1278
+ #onIndirectTimeout(targetId) {
1279
+ const entry = this.#members.get(targetId);
1280
+ if (!entry || entry.state !== 'alive') return;
1281
+
1282
+ entry.state = 'suspect';
1283
+ entry.suspectAt = this.#nowFn();
1284
+ this.#enqueueUpdate({ podId: targetId, state: 'suspect', incarnation: entry.incarnation });
1285
+ if (this.onSuspect) this.onSuspect(targetId);
1286
+
1287
+ // Start suspect timer
1288
+ const timer = setTimeout(() => this.#onSuspectTimeout(targetId), this.#suspectTimeoutMs);
1289
+ // Store with a unique seq so it can be cleared on stop()
1290
+ const seq = ++this.#seqCounter;
1291
+ this.#pendingPings.set(seq, { targetId, timer });
1292
+ }
1293
+
1294
+ /**
1295
+ * Called when the suspect timer expires. If the member is still
1296
+ * suspect, declare it dead.
1297
+ *
1298
+ * @param {string} podId
1299
+ */
1300
+ #onSuspectTimeout(podId) {
1301
+ const entry = this.#members.get(podId);
1302
+ if (!entry || entry.state !== 'suspect') return;
1303
+
1304
+ entry.state = 'dead';
1305
+ entry.suspectAt = null;
1306
+ this.#enqueueUpdate({ podId, state: 'dead', incarnation: entry.incarnation });
1307
+ if (this.onDead) this.onDead(podId);
1308
+ }
1309
+
1310
+ // -------------------------------------------------------------------------
1311
+ // Private — update dissemination
1312
+ // -------------------------------------------------------------------------
1313
+
1314
+ /**
1315
+ * Apply a SWIM membership update using the standard rules:
1316
+ * - Higher incarnation always wins
1317
+ * - Same incarnation: dead > suspect > alive
1318
+ * - Self-suspicion: bump local incarnation, broadcast alive
1319
+ *
1320
+ * @param {{podId: string, state: string, incarnation: number}} update
1321
+ */
1322
+ #processUpdate(update) {
1323
+ const { podId, state, incarnation } = update;
1324
+
1325
+ // Self-suspicion refutation
1326
+ if (podId === this.#localId) {
1327
+ if (state === 'suspect' || state === 'dead') {
1328
+ this.#localIncarnation = Math.max(this.#localIncarnation, incarnation) + 1;
1329
+ this.#enqueueUpdate({ podId: this.#localId, state: 'alive', incarnation: this.#localIncarnation });
1330
+ }
1331
+ return;
1332
+ }
1333
+
1334
+ const entry = this.#members.get(podId);
1335
+ if (!entry) {
1336
+ // Unknown member — add if alive or suspect
1337
+ if (state === 'alive' || state === 'suspect') {
1338
+ this.#members.set(podId, { state, incarnation, suspectAt: state === 'suspect' ? this.#nowFn() : null });
1339
+ if (state === 'alive' && this.onJoin) this.onJoin(podId);
1340
+ if (state === 'suspect' && this.onSuspect) this.onSuspect(podId);
1341
+ }
1342
+ return;
1343
+ }
1344
+
1345
+ // Higher incarnation always wins
1346
+ if (incarnation > entry.incarnation) {
1347
+ const oldState = entry.state;
1348
+ entry.incarnation = incarnation;
1349
+ entry.state = state;
1350
+ entry.suspectAt = state === 'suspect' ? this.#nowFn() : null;
1351
+ this.#fireStateCallbacks(podId, oldState, state);
1352
+ return;
1353
+ }
1354
+
1355
+ // Same incarnation — apply state priority: dead > suspect > alive
1356
+ if (incarnation === entry.incarnation) {
1357
+ const priority = { alive: 0, suspect: 1, dead: 2, left: 3 };
1358
+ if ((priority[state] ?? -1) > (priority[entry.state] ?? -1)) {
1359
+ const oldState = entry.state;
1360
+ entry.state = state;
1361
+ entry.suspectAt = state === 'suspect' ? this.#nowFn() : null;
1362
+ this.#fireStateCallbacks(podId, oldState, state);
1363
+ }
1364
+ }
1365
+ // Lower incarnation — ignore
1366
+ }
1367
+
1368
+ /**
1369
+ * Fire the appropriate callback when a member's state changes.
1370
+ *
1371
+ * @param {string} podId
1372
+ * @param {string} oldState
1373
+ * @param {string} newState
1374
+ */
1375
+ #fireStateCallbacks(podId, oldState, newState) {
1376
+ if (oldState === newState) return;
1377
+ if (newState === 'alive' && this.onJoin) this.onJoin(podId);
1378
+ if (newState === 'suspect' && this.onSuspect) this.onSuspect(podId);
1379
+ if (newState === 'dead' && this.onDead) this.onDead(podId);
1380
+ if (newState === 'left' && this.onLeave) this.onLeave(podId);
1381
+ }
1382
+
1383
+ /**
1384
+ * Enqueue a membership update for piggybacking on future messages.
1385
+ * The buffer is capped at 10 entries; duplicates for the same podId
1386
+ * are replaced, keeping the newest update.
1387
+ *
1388
+ * @param {{podId: string, state: string, incarnation: number}} update
1389
+ */
1390
+ #enqueueUpdate(update) {
1391
+ // Deduplicate by podId — keep newest
1392
+ const idx = this.#updateBuffer.findIndex(u => u.podId === update.podId);
1393
+ if (idx !== -1) {
1394
+ this.#updateBuffer[idx] = update;
1395
+ } else {
1396
+ this.#updateBuffer.push(update);
1397
+ }
1398
+ // Cap at 10
1399
+ if (this.#updateBuffer.length > 10) {
1400
+ this.#updateBuffer.shift();
1401
+ }
1402
+ }
1403
+
1404
+ /**
1405
+ * Return and clear the current update buffer.
1406
+ *
1407
+ * @returns {Array<{podId: string, state: string, incarnation: number}>}
1408
+ */
1409
+ #drainUpdates() {
1410
+ const updates = [...this.#updateBuffer];
1411
+ this.#updateBuffer = [];
1412
+ return updates;
1413
+ }
1414
+
1415
+ /**
1416
+ * Shuffle alive members (excluding self) into the ping queue.
1417
+ */
1418
+ #refillPingQueue() {
1419
+ const alive = this.aliveMembers().filter(id => id !== this.#localId);
1420
+ this.#pingQueue = this.#pickRandom(alive, alive.length);
1421
+ }
1422
+
1423
+ /**
1424
+ * Fisher-Yates shuffle of `arr`, returning the first `count` elements.
1425
+ *
1426
+ * @param {string[]} arr
1427
+ * @param {number} count
1428
+ * @returns {string[]}
1429
+ */
1430
+ #pickRandom(arr, count) {
1431
+ const copy = [...arr];
1432
+ for (let i = copy.length - 1; i > 0; i--) {
1433
+ const j = Math.floor(Math.random() * (i + 1));
1434
+ [copy[i], copy[j]] = [copy[j], copy[i]];
1435
+ }
1436
+ return copy.slice(0, count);
1437
+ }
1438
+ }
1439
+
1440
+ export { TASK_STATUSES };