@kumiai/rpc 0.9.0 → 0.10.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/lib/peer.js CHANGED
@@ -1,17 +1,18 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
2
  import { BroadcastClient, createBroadcastResponder, createBroadcastTransport, defaultJitter, encodeEventFrame } from '@kumiai/broadcast';
3
- import { fromUTF } from '@sozai/codec';
4
3
  import { createRuntime } from '@sozai/runtime';
4
+ import { decodeAppAAD, encodeAppAAD } from './app-aad.js';
5
5
  import { createAppLane } from './app-lane.js';
6
6
  import { classifyCommit, digestAppliedCommit, UNKNOWN_FRAME_VERSION } from './classify.js';
7
7
  import { CommitDeadlineError, isHeadMismatch, JournalEpochError, RecoveryRequiredError } from './commit.js';
8
8
  import { decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion } from './commit-frame.js';
9
- import { isMissingLedgerEntries } from './crypto.js';
10
- import { asLogPosition } from './cursor.js';
9
+ import { isFrameAhead, isMissingLedgerEntries } from './crypto.js';
10
+ import { asLogPosition, assertForwardPage } from './cursor.js';
11
11
  import { createDirectedClient, createInboxAcceptor, createInboxPath, createUnroutedTagResponder } from './directed.js';
12
12
  import { PeerDisposedError } from './errors.js';
13
13
  import { adaptBusHandlers } from './handlers.js';
14
14
  import { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_VERSION } from './handshake.js';
15
+ import { notifyHost } from './host-notice.js';
15
16
  import { createHubMux } from './hub-mux.js';
16
17
  import { createLedgerEntryResolver, encodeLedgerEntries } from './ledger-entries.js';
17
18
  import { createOpenOncePath } from './open-once.js';
@@ -58,8 +59,16 @@ const DEFAULT_RECOVERY_JITTER_MS = 250;
58
59
  * requester the port still authorizes), never a leak. The cap sits well above the in-flight
59
60
  * request count, so eviction only reaches ids whose deadline long passed.
60
61
  */ const SUPPRESSED_REQUESTS_MAX = 1024;
62
+ const CONFIDENCE_RANK = {
63
+ claimed: 0,
64
+ observed: 1,
65
+ authenticated: 2
66
+ };
61
67
  export function createGroupPeer(params) {
62
68
  const { hub, crypto, mls, journal, adoptJournalled, anchorStore, appCursorStore, protocols, handlers, suppress } = params;
69
+ if (crypto.pending != null && mls == null) {
70
+ throw new Error('GroupCrypto.pending requires mls and the durable commit lane');
71
+ }
63
72
  // Normalized ONCE, here, at the one ingress every downstream `localDID` use reads from —
64
73
  // equivalent DID forms must compare and derive topics identically (`@kokuin/token`
65
74
  // canonicalizes, it does not validate).
@@ -108,13 +117,6 @@ export function createGroupPeer(params) {
108
117
  appEventHandlers.set(name, adaptBusHandlers(protocol, handlers[name], suppress).events);
109
118
  }
110
119
  /**
111
- * The live epoch this peer frames commits at, seeded from the handle, not zero. Not the app
112
- * lane's epoch (anchor-bound) but the commit lane's: `frameCommit` refuses to seal bodies once
113
- * the live handle has moved past this. Zero is not neutral — the first lane operation (replay
114
- * then pull) runs BEFORE this is re-read, so a peer restarted holding a journalled commit would
115
- * have its own replay wrongly refused at startup.
116
- */ let epoch = crypto.epoch();
117
- /**
118
120
  * The app-lane anchor: the per-epoch secret and epoch the app-lane topic derivation is bound
119
121
  * to. Seeded at genesis and rotated when an applied Commit changes the roster OR rejoins a
120
122
  * member — captured from the port's own post-commit epoch secret, never the recovery secret.
@@ -137,7 +139,8 @@ export function createGroupPeer(params) {
137
139
  * {@link GroupPeerMLSParams.anchorStore} and construction restores it from there.
138
140
  *
139
141
  * Only the epoch is observable outside this scope (see {@link GroupPeer.anchorEpoch}).
140
- */ let anchor = {
142
+ */ // Placeholder until `ready` restores or captures the anchor; nothing derives a topic before.
143
+ let anchor = {
141
144
  secret: new Uint8Array(),
142
145
  epoch: crypto.epoch()
143
146
  };
@@ -154,14 +157,27 @@ export function createGroupPeer(params) {
154
157
  retentionSeconds: appLogRetentionSeconds,
155
158
  anchor: ()=>anchor,
156
159
  groupID: ()=>commitTopicID,
157
- justifiedEpochCeiling: ()=>justifiedEpochCeiling(),
158
160
  ...appCursorStore != null ? {
159
161
  appCursorStore
160
162
  } : {},
161
163
  ...onAppWindowPruned != null ? {
162
164
  onAppWindowPruned
163
- } : {}
165
+ } : {},
166
+ onAppDeliveryStalled: (event)=>{
167
+ hostOutbox.push(()=>notifyHost(params.onAppDeliveryStalled, event));
168
+ },
169
+ scheduleDelivery: (start)=>{
170
+ hostOutbox.push(start);
171
+ }
164
172
  });
173
+ let sealBarrier;
174
+ let releaseSealBarrier;
175
+ let sealError;
176
+ const finishSealBarrier = ()=>{
177
+ sealBarrier = undefined;
178
+ releaseSealBarrier?.();
179
+ releaseSealBarrier = undefined;
180
+ };
165
181
  /**
166
182
  * Capture the anchor from the port's post-commit handle and persist it. The one place the
167
183
  * anchor is written from the live epoch, and the one place it is saved.
@@ -171,10 +187,14 @@ export function createGroupPeer(params) {
171
187
  * the next roster change rotates it again. Closing it needs the anchor inside the same durable
172
188
  * write as the handle, which this layer cannot reach.
173
189
  */ const captureAnchor = async ()=>{
190
+ // Secret and epoch from one export: a pair from two reads can straddle a handle move.
191
+ const { secret, epoch } = await crypto.exportSecret(APP_TOPIC_LABEL);
174
192
  anchor = {
175
- secret: await crypto.exportSecret(APP_TOPIC_LABEL),
176
- epoch: crypto.epoch()
193
+ secret,
194
+ epoch
177
195
  };
196
+ sealError = undefined;
197
+ finishSealBarrier();
178
198
  await anchorStore?.save(anchor);
179
199
  // The anchor moving IS the segment boundary, so every capture ends the segment the buffer
180
200
  // belongs to. AFTER the assignment above: the lane rebuilds its cursors off the live anchor.
@@ -191,18 +211,54 @@ export function createGroupPeer(params) {
191
211
  */ const openedFrames = new WeakMap();
192
212
  /**
193
213
  * Whether a frame `unwrap` just refused might still open once this handle catches up — read from
194
- * its cleartext epoch, never the throw (which can't tell "not reached yet" from "never again").
214
+ * the refusal's locked answer ({@link "crypto".FrameEpochError}), never the epoch hint.
195
215
  * On the open-once failure path ({@link "open-once".OpenOncePathParams.retainOnFailure}) answering
196
216
  * `true` withholds the ack so the frame survives a reconnect. Mailbox-class frames have no staging
197
217
  * of their own (unlike `app-lane.ts`'s `note`/`ahead`), which is what made acking a transient
198
218
  * refusal here a permanent loss.
199
- */ const retainOnFailure = (message)=>{
200
- const at = crypto.frameEpoch(message.payload);
201
- return at != null && at > crypto.epoch();
219
+ */ const retainOnFailure = (_message, error)=>isFrameAhead(error);
220
+ // Live log pushes carry no authoritative bytes or position. One queued journal-first pull
221
+ // covers a burst; a failed pull retries without waiting for another hub delivery.
222
+ let appPullNeeded = false;
223
+ let appPullActive = false;
224
+ let appPullTimer;
225
+ let appPullBackoff = 1000;
226
+ const armAppPull = (delay)=>{
227
+ if (disposed || appPullActive || appPullTimer != null) return;
228
+ appPullTimer = setTimeout(()=>{
229
+ appPullTimer = undefined;
230
+ if (disposed) return;
231
+ appPullActive = true;
232
+ appPullNeeded = false;
233
+ let retryDelay = 0;
234
+ void (async ()=>{
235
+ try {
236
+ await ready;
237
+ if (disposed) return;
238
+ await runSerial(async ()=>{
239
+ await replayJournal();
240
+ await ensureLedger(Date.now() + recoveryTimeoutMs);
241
+ await reconcileCommits();
242
+ });
243
+ appPullBackoff = 1000;
244
+ } catch {
245
+ appPullNeeded = true;
246
+ retryDelay = appPullBackoff;
247
+ appPullBackoff = Math.min(appPullBackoff * 2, 60_000);
248
+ } finally{
249
+ appPullActive = false;
250
+ if (appPullNeeded && !disposed) armAppPull(retryDelay);
251
+ }
252
+ })();
253
+ }, delay);
254
+ };
255
+ const requestAppPull = ()=>{
256
+ appPullNeeded = true;
257
+ armAppPull(0);
202
258
  };
203
259
  /**
204
260
  * The app lane's inbound path: one open per topic, fanned out as plaintext, with each frame's
205
- * log position noted before the open. Every consumer's own `unwrap` is then a pure lookup of the
261
+ * log position noted once its open settles. Every consumer's own `unwrap` is then a pure lookup of the
206
262
  * opened result ({@link openedFrames}), and nothing downstream touches the handle.
207
263
  *
208
264
  * See {@link createOpenOncePath} for why a lane may only open a frame once.
@@ -210,9 +266,17 @@ export function createGroupPeer(params) {
210
266
  return createOpenOncePath({
211
267
  mux,
212
268
  topicID,
213
- unwrap: (b)=>crypto.unwrap(b, {
214
- expectedAAD: fromUTF(topicID)
215
- }),
269
+ unwrap: (b)=>{
270
+ const hinted = crypto.frameAAD(b);
271
+ const decoded = hinted == null ? null : decodeAppAAD(hinted);
272
+ const intent = decoded?.topicID === topicID ? decoded.intent : 'ephemeral';
273
+ return crypto.unwrap(b, {
274
+ expectedAAD: encodeAppAAD({
275
+ topicID,
276
+ intent
277
+ })
278
+ });
279
+ },
216
280
  retainOnFailure,
217
281
  project: (_message, opened)=>{
218
282
  const { payload, senderDID } = opened;
@@ -227,12 +291,19 @@ export function createGroupPeer(params) {
227
291
  // acceptor, `gather`'s quorum) must see one canonical sender regardless of which DID form
228
292
  // MLS recovered this frame under.
229
293
  openedFrames.set(payload, {
230
- payload,
294
+ ...opened,
231
295
  senderDID: normalizeDID(senderDID)
232
296
  });
233
297
  return payload;
234
298
  },
235
- note: (message)=>appLane.note(name, topicID, message)
299
+ note: (message, failure)=>appLane.note(name, topicID, message, failure),
300
+ wakeup: (message)=>{
301
+ if (crypto.pending == null) return false;
302
+ const aad = crypto.frameAAD(message.payload);
303
+ if (aad == null || decodeAppAAD(aad)?.intent !== 'log') return false;
304
+ requestAppPull();
305
+ return true;
306
+ }
236
307
  });
237
308
  };
238
309
  /**
@@ -271,7 +342,6 @@ export function createGroupPeer(params) {
271
342
  });
272
343
  };
273
344
  const buildEpoch = async ()=>{
274
- epoch = crypto.epoch();
275
345
  const next = new Map();
276
346
  // ONE inbox lane for the whole peer, not one per protocol: the topic does not name a
277
347
  // protocol, so every acceptor and directed client opening its own frames is the defect this
@@ -283,7 +353,10 @@ export function createGroupPeer(params) {
283
353
  mux,
284
354
  topicID: selfInbox,
285
355
  unwrap: (b)=>crypto.unwrap(b, {
286
- expectedAAD: fromUTF(selfInbox)
356
+ expectedAAD: encodeAppAAD({
357
+ topicID: selfInbox,
358
+ intent: 'ephemeral'
359
+ })
287
360
  }),
288
361
  retainOnFailure
289
362
  })
@@ -374,29 +447,23 @@ export function createGroupPeer(params) {
374
447
  throw new AggregateError(reasons, 'Group epoch teardown failed');
375
448
  }
376
449
  };
377
- /**
378
- * Seal an app frame and name the segment it belongs on, as ONE answer: a frame must land on the
379
- * segment that CONTAINS its seal epoch, and only the live anchor knows which segment that is.
380
- *
381
- * Read from the live anchor and never from a `runtime`, because the two come apart exactly when
382
- * it matters: a rotation moves the anchor and the handle together inside the commit walk, but
383
- * runtimes rebuild only once the whole walk returns. A dispatch takes no mutex, so in that
384
- * window it can seal under the NEW epoch — publishing to the topic the runtime still holds would
385
- * land the frame on the segment the group just left, readable by nobody, ever.
386
- *
387
- * The anchor is re-read AFTER the seal and the pair thrown away if it moved — identity, not
388
- * epoch equality, since every capture mints a fresh anchor — which is what makes the two halves
389
- * one segment's: an anchor that did not move across the seal is one whose segment covers the
390
- * seal epoch. A moved anchor re-seals under the one now live instead of publishing against the
391
- * one it missed.
392
- */ const sealForSegment = async (name, bytes)=>{
450
+ /** Wait while an advance can move the handle before its new anchor is captured. */ const sealForSegment = async (name, bytes, intent = 'ephemeral')=>{
393
451
  while(true){
452
+ if (sealError != null) throw sealError;
453
+ if (sealBarrier != null) {
454
+ await sealBarrier;
455
+ continue;
456
+ }
394
457
  const at = anchor;
395
458
  const topicID = protocolTopic(at.secret, at.epoch, name);
396
459
  const payload = await crypto.wrap(bytes, {
397
- aad: fromUTF(topicID)
460
+ aad: encodeAppAAD({
461
+ topicID,
462
+ intent
463
+ })
398
464
  });
399
- if (anchor === at) return {
465
+ if (sealError != null) throw sealError;
466
+ if (anchor === at && sealBarrier == null) return {
400
467
  topicID,
401
468
  payload
402
469
  };
@@ -414,7 +481,10 @@ export function createGroupPeer(params) {
414
481
  const at = anchor;
415
482
  const topicID = inboxTopic(at.secret, at.epoch, recipientDID);
416
483
  const payload = await crypto.wrap(tagged, {
417
- aad: fromUTF(topicID)
484
+ aad: encodeAppAAD({
485
+ topicID,
486
+ intent: 'ephemeral'
487
+ })
418
488
  });
419
489
  if (anchor === at) return {
420
490
  topicID,
@@ -432,8 +502,10 @@ export function createGroupPeer(params) {
432
502
  // lane (retained, pullable); ephemeral events and RPC stay on the live mailbox lane. The
433
503
  // log payload is byte-identical to what the broadcast transport would produce, so online
434
504
  // subscribers still receive it through the same drain.
435
- if (retentionOf(protocols[name], prc) === 'log') {
436
- const { topicID, payload } = await sealForSegment(name, encodeEventFrame(prc, data));
505
+ const protocol = protocols[name];
506
+ if (protocol === undefined) throw new Error(`Unknown protocol: ${name}`);
507
+ if (retentionOf(protocol, prc) === 'log') {
508
+ const { topicID, payload } = await sealForSegment(name, encodeEventFrame(prc, data), 'log');
437
509
  await mux.publish({
438
510
  topicID,
439
511
  payload,
@@ -449,7 +521,9 @@ export function createGroupPeer(params) {
449
521
  }),
450
522
  gather: (prc, config)=>runtime.client.gather(prc, config?.param, {
451
523
  quorum: config?.quorum,
452
- timeoutMs: config?.timeoutMs
524
+ timeoutMs: config?.timeoutMs,
525
+ onReply: config?.onReply,
526
+ signal: config?.signal
453
527
  }),
454
528
  to: async (memberDID)=>{
455
529
  // Normalized ONCE, at the ingress: the cache key, the topic derivation and the
@@ -542,9 +616,12 @@ export function createGroupPeer(params) {
542
616
  * The heal trigger, RECORDED and never awaited where found: `recover()` takes the commit mutex,
543
617
  * so a pull that awaited it would wait on a tail including the pull. The trigger only writes
544
618
  * this flag; the pull unwinds, releases the lane, and the heal runs afterward as its own
545
- * operation. `healing` stops a second wakeup starting a concurrent one.
619
+ * operation. An active recovery absorbs concurrent requests.
546
620
  */ let healRequested = false;
547
- let healing = false;
621
+ let activeRecovery = null;
622
+ let recoveryGeneration = 0;
623
+ let bootstrapHealRequested = false;
624
+ let episode = null;
548
625
  /**
549
626
  * Positive evidence this peer is off the group's line, and the sole guard on `commit()`. Set
550
627
  * when a pull sees proof the peer cannot reconcile: a frame framed AHEAD of its epoch, its OWN
@@ -581,11 +658,41 @@ export function createGroupPeer(params) {
581
658
  * `null` means no rejoin in progress. Survives a failed bootstrap, so a retry filters the same
582
659
  * entries rather than snapshotting an empty ledger.
583
660
  */ let inFlightEntries = null;
661
+ let awaitingBootstrap = null;
662
+ let rejoinAnchorNeedsCapture = false;
663
+ let rejoinRuntimeNeedsBuild = false;
584
664
  /**
585
665
  * Entries a heal decided must be re-enacted, waiting for a lane operation with a return value —
586
666
  * same problem as `lostCommit`. A heal triggered by a pull has nowhere to put them; the host
587
667
  * re-enacts with an ordinary `commit()`.
588
668
  */ let pendingReenact = [];
669
+ let hostOutbox = [];
670
+ const emitStrand = (observation)=>{
671
+ hostOutbox.push(()=>notifyHost(params.onStrand, observation));
672
+ };
673
+ const emitRecovery = (event)=>{
674
+ hostOutbox.push(()=>notifyHost(params.onRecovery, event));
675
+ };
676
+ const observeStrand = (observation)=>{
677
+ bootstrapHealRequested = false;
678
+ if (commitTopicID == null) return;
679
+ if (episode != null && CONFIDENCE_RANK[observation.confidence] <= CONFIDENCE_RANK[episode.strongest]) return;
680
+ episode = {
681
+ strongest: observation.confidence
682
+ };
683
+ emitStrand({
684
+ ...observation,
685
+ groupID: commitTopicID
686
+ });
687
+ };
688
+ const closeEpisode = ()=>{
689
+ episode = null;
690
+ };
691
+ const flushHostOutbox = ()=>{
692
+ const batch = hostOutbox;
693
+ hostOutbox = [];
694
+ for (const notice of batch)notice();
695
+ };
589
696
  /**
590
697
  * The group's commit mutex: every commit-lane operation serialized through one tail. The
591
698
  * compare-and-set resolves races between devices, not two callers here — two `build()` calls
@@ -600,7 +707,13 @@ export function createGroupPeer(params) {
600
707
  return fn();
601
708
  });
602
709
  commitTail = op.then(()=>{}, ()=>{});
603
- return op;
710
+ return op.then((value)=>{
711
+ flushHostOutbox();
712
+ return value;
713
+ }, (error)=>{
714
+ flushHostOutbox();
715
+ throw error;
716
+ });
604
717
  };
605
718
  /**
606
719
  * Whether the journal has been replayed in the lane operation now running. Cleared when an
@@ -615,12 +728,14 @@ export function createGroupPeer(params) {
615
728
  const recoveryWaiters = new Map();
616
729
  const recoveryTimers = new Map();
617
730
  const pendingReplies = new Map();
731
+ const inFlightBootstraps = new Set();
618
732
  const suppressedRequests = new Set();
619
733
  /**
620
734
  * Ledger-gather waiters, keyed by requestID. Called for EVERY reply, not just the first: a
621
735
  * responder whose ledger fails the head check withheld an entry, so the requester falls through
622
736
  * to the next reply rather than giving up.
623
737
  */ const ledgerWaiters = new Map();
738
+ const ledgerGatherFinishes = new Set();
624
739
  const pendingLedgerReplies = new Set();
625
740
  // Responder: after a jitter delay, answer a recovery request with GroupInfo sealed to the
626
741
  // ephemeral key inside the signed request — unless another responder's reply has already
@@ -679,7 +794,10 @@ export function createGroupPeer(params) {
679
794
  clearTimeout(timer);
680
795
  recoveryTimers.delete(reply.requestID);
681
796
  }
682
- waiter(reply.groupInfo);
797
+ waiter({
798
+ kind: 'reply',
799
+ sealed: reply.groupInfo
800
+ });
683
801
  }
684
802
  };
685
803
  /**
@@ -727,62 +845,6 @@ export function createGroupPeer(params) {
727
845
  ledgerWaiters.get(reply.requestID)?.(reply.sealed);
728
846
  };
729
847
  /**
730
- * The highest epoch the group's OWN COMMIT LOG can justify a frame having been sealed at.
731
- *
732
- * A member seals at epoch E only after applying the commit that produced E, so a log whose
733
- * furthest commit is framed at H bounds every member at H + 1. READ FRESH, never from this
734
- * peer's own view of the log: a returning member's own view would bound the group at the epoch
735
- * IT reached — killing exactly the frames it came back for.
736
- *
737
- * THIS IS THE HUB'S WORD, and it can only ever be wrong in ONE direction. A commit's framed
738
- * epoch is cleartext — unauthenticated until applied — so a hub free to inject frames can RAISE
739
- * this ceiling at will but never LOWER it: the honest commits are in the log too, and the
740
- * ceiling is the max over all of them, so no injected frame can hide one. Raising it costs the
741
- * attacker nothing; lowering it — which would destroy an honest member's frames — is
742
- * unreachable.
743
- *
744
- * That asymmetry is why an untrusted field is acceptable HERE and would not be for opening a
745
- * frame: this decides how long to WAIT, never what to believe — `unwrap` alone still decides
746
- * what is finally read.
747
- *
748
- * Epochs are read pre-apply from the commit's own cleartext, and every frame is asked rather
749
- * than only the last: the log's furthest frame may be poison or a fork loser.
750
- */ const justifiedEpochCeiling = async ()=>{
751
- let ceiling = crypto.epoch();
752
- if (commitTopicID == null) return ceiling;
753
- let after = null;
754
- while(true){
755
- const result = await mux.fetchTopic({
756
- topicID: commitTopicID,
757
- ...after != null ? {
758
- after
759
- } : {},
760
- limit: COMMIT_FETCH_LIMIT
761
- });
762
- for (const message of result.messages){
763
- after = asLogPosition(message.sequenceID);
764
- let commit;
765
- try {
766
- const frame = decodeHandshakeFrame(message.payload);
767
- // An unknown wire version is unreadable here and stays unreadable: this ceiling is
768
- // built from epochs read out of commit bytes, and a frame this build cannot parse
769
- // yields none. Not the heal signal — raising that twice would not raise it harder.
770
- if (frame.version !== HANDSHAKE_VERSION) continue;
771
- if (frame.kind !== HANDSHAKE_KIND.commit) continue;
772
- commit = decodeCommitFrame(frame.payload).commit;
773
- } catch {
774
- continue; // not a commit frame: it says nothing about where the group got to
775
- }
776
- // The commit's CLEARTEXT epoch, not `readCommitHeader`: that resolves the committer
777
- // against this handle's own epoch secret and answers `null` for every commit framed ahead
778
- // of this peer — exactly the commits a returning member has yet to walk.
779
- const framedAt = crypto.frameEpoch(commit);
780
- if (framedAt != null && framedAt + 1 > ceiling) ceiling = framedAt + 1;
781
- }
782
- if (result.messages.length < COMMIT_FETCH_LIMIT) return ceiling;
783
- }
784
- };
785
- /**
786
848
  * THE ONE PATH THE HANDLE RATCHETS ON, and the invariant it holds: a handle does not ratchet
787
849
  * past an epoch until that epoch's frames are read and its anchor is taken. Both are one-way
788
850
  * doors — after the advance those frames are ciphertext forever, and that epoch's secret can
@@ -801,7 +863,7 @@ export function createGroupPeer(params) {
801
863
  *
802
864
  * The anchor is captured from the port's POST-advance handle — the epoch every member lands on
803
865
  * by making this same advance — which is what makes it agreed rather than local.
804
- */ const advanceHandle = async (port, advance, rotatesAnyway = ()=>false)=>{
866
+ */ const advanceHandle = async (port, advance, rotatesAnyway = ()=>false, appliedEpochs)=>{
805
867
  // Read this epoch's app frames BEFORE the advance that leaves it — the last moment they can
806
868
  // be read, since the advance ratchets the handle on and takes this epoch's key material with
807
869
  // it. Per frame-epoch, not per rotation: a segment spanning five epochs is dispensed five
@@ -809,26 +871,40 @@ export function createGroupPeer(params) {
809
871
  await appLane.deliver();
810
872
  // Normalized at this ingress so an MLS-recovered form flip between the two reads (never a
811
873
  // real membership change) does not read as one — see {@link detectRosterChange}.
812
- const rosterBefore = (await port.rosterDIDs()).map(normalizeDID);
813
- const epochBefore = crypto.epoch();
814
- const advanced = await advance();
815
- // GATED ON THE HANDLE ACTUALLY RATCHETING: a roster diff alone is not evidence that it did. A
816
- // commit that REMOVES this member does not advance its handle (there is no epoch to move to,
817
- // since the commit's path excludes the dropped leaf), yet real MLS still applies proposals to
818
- // the tree — so the roster comes back WITHOUT this member at an epoch that did not move.
819
- // (Measured against ts-mls: `processMessage` returns without throwing, epoch stays,
820
- // `listMembers()` has lost the leaf.) Undiscriminated, that reads as a rotation.
821
- //
822
- // An ungated capture would re-derive the anchor at the epoch it already names and clear the
823
- // segment buffer for nothing: {@link captureAnchor} drops undelivered frames on the premise a
824
- // rotation makes them unopenable, which is false here — the handle is still at the epoch those
825
- // frames were sealed at, and a frame the live lane staged mid-walk would be thrown away
826
- // openable.
827
- const ratcheted = crypto.epoch() !== epochBefore;
828
- if (ratcheted && (detectRosterChange(rosterBefore, (await port.rosterDIDs()).map(normalizeDID)) || rotatesAnyway(advanced))) {
829
- await captureAnchor();
874
+ const rosterBefore = (await port.rosterEntries()).map((e)=>normalizeDID(e.did));
875
+ const epochBefore = await port.readEpoch();
876
+ sealBarrier = new Promise((resolve)=>{
877
+ releaseSealBarrier = resolve;
878
+ });
879
+ try {
880
+ const advanced = await advance();
881
+ const epochs = appliedEpochs?.(advanced);
882
+ const actualBefore = epochs?.epochBefore ?? epochBefore;
883
+ const epochAfter = epochs?.epochAfter ?? await port.readEpoch();
884
+ // GATED ON THE HANDLE ACTUALLY RATCHETING: a roster diff alone is not evidence that it did. A
885
+ // commit that REMOVES this member does not advance its handle (there is no epoch to move to,
886
+ // since the commit's path excludes the dropped leaf), yet real MLS still applies proposals to
887
+ // the tree — so the roster comes back WITHOUT this member at an epoch that did not move.
888
+ // (Measured against ts-mls: `processMessage` returns without throwing, epoch stays,
889
+ // `listMembers()` has lost the leaf.) Undiscriminated, that reads as a rotation.
890
+ //
891
+ // An ungated capture would clear the segment buffer while the handle still holds its epoch,
892
+ // dropping frames that can still be opened.
893
+ const ratcheted = epochAfter !== actualBefore;
894
+ if (ratcheted && (detectRosterChange(rosterBefore, (await port.rosterEntries()).map((e)=>normalizeDID(e.did))) || rotatesAnyway(advanced))) {
895
+ await captureAnchor();
896
+ }
897
+ return advanced;
898
+ } catch (error) {
899
+ if (await port.readEpoch() !== epochBefore && sealBarrier != null) {
900
+ sealError = new Error('app anchor unavailable after failed epoch advance', {
901
+ cause: error
902
+ });
903
+ }
904
+ throw error;
905
+ } finally{
906
+ finishSealBarrier();
830
907
  }
831
- return advanced;
832
908
  };
833
909
  /**
834
910
  * Read the commit log forward from the cursor, classify every frame, advance the cursor over
@@ -855,6 +931,7 @@ export function createGroupPeer(params) {
855
931
  commitLogHead = head == null ? null : asLogPosition(head);
856
932
  };
857
933
  while(true){
934
+ const pageAfter = reconciledHead;
858
935
  const result = await mux.fetchTopic({
859
936
  topicID,
860
937
  // From the cursor. With no cursor (fresh member, trimmed backlog, just rejoined) read
@@ -864,6 +941,10 @@ export function createGroupPeer(params) {
864
941
  } : {},
865
942
  limit: COMMIT_FETCH_LIMIT
866
943
  });
944
+ // A short page may carry a one-shot fork reveal below the cursor. Only a full page loops.
945
+ if (result.messages.length === COMMIT_FETCH_LIMIT) {
946
+ assertForwardPage(pageAfter, result.messages);
947
+ }
867
948
  if (result.messages.length === 0) {
868
949
  // Drained. The tip an EMPTY page reports is not redundant: a topic keeps its head when
869
950
  // its frames age out, so anchoring on the cursor here would compare-and-set against
@@ -889,13 +970,14 @@ export function createGroupPeer(params) {
889
970
  if (frame.version !== HANDSHAKE_VERSION) {
890
971
  // No digest: the frame's version put its commit bytes out of reach entirely. Settled at
891
972
  // `ahead` before the digest is read.
973
+ const localEpoch = await port.readEpoch();
892
974
  const unreadable = classifyCommit({
893
975
  header: UNKNOWN_FRAME_VERSION,
894
976
  sequenceID: position,
895
977
  commitDigest: null,
896
978
  state: {
897
979
  localDID,
898
- epoch: crypto.epoch(),
980
+ epoch: localEpoch,
899
981
  appliedByEpoch
900
982
  }
901
983
  });
@@ -905,6 +987,14 @@ export function createGroupPeer(params) {
905
987
  if (unreadable.row === 'ahead') {
906
988
  healRequested = true;
907
989
  stranded = true;
990
+ observeStrand({
991
+ position,
992
+ commitDigest: null,
993
+ localEpoch,
994
+ claimedEpoch: null,
995
+ kind: 'unknown-version',
996
+ confidence: 'claimed'
997
+ });
908
998
  }
909
999
  continue;
910
1000
  }
@@ -923,13 +1013,14 @@ export function createGroupPeer(params) {
923
1013
  // version fails BEFORE the commit bytes are extracted, so there is no next frame to
924
1014
  // heal from — dropping it would step over the group's whole future. To the classifier.
925
1015
  if (isUnsupportedCommitFrameVersion(error)) {
1016
+ const localEpoch = await port.readEpoch();
926
1017
  const unreadable = classifyCommit({
927
1018
  header: UNKNOWN_FRAME_VERSION,
928
1019
  sequenceID: position,
929
1020
  commitDigest: null,
930
1021
  state: {
931
1022
  localDID,
932
- epoch: crypto.epoch(),
1023
+ epoch: localEpoch,
933
1024
  appliedByEpoch
934
1025
  }
935
1026
  });
@@ -938,6 +1029,14 @@ export function createGroupPeer(params) {
938
1029
  if (unreadable.row === 'ahead') {
939
1030
  healRequested = true;
940
1031
  stranded = true;
1032
+ observeStrand({
1033
+ position,
1034
+ commitDigest: null,
1035
+ localEpoch,
1036
+ claimedEpoch: null,
1037
+ kind: 'unknown-version',
1038
+ confidence: 'claimed'
1039
+ });
941
1040
  }
942
1041
  continue;
943
1042
  }
@@ -954,111 +1053,144 @@ export function createGroupPeer(params) {
954
1053
  // `message.senderDID` — the hub's word about who handed it over, and the hub is not
955
1054
  // trusted: it could stamp every recipient's own DID onto one poison frame and make the
956
1055
  // whole group heal at once.
957
- const readHeader = await port.readCommitHeader(commitFrame.commit);
958
- // Normalized before `classifyCommit` compares it against `state.localDID` (also
959
- // normalized, at construction) — an own-unmerged commit authenticated under a different
960
- // form of this member's own DID must still be recognized as its own.
961
- const header = readHeader?.committerDID != null ? {
962
- ...readHeader,
963
- committerDID: normalizeDID(readHeader.committerDID)
964
- } : readHeader;
965
- const disposition = classifyCommit({
966
- header,
967
- sequenceID: position,
968
- commitDigest,
969
- state: {
970
- localDID,
971
- epoch: crypto.epoch(),
972
- appliedByEpoch
1056
+ let localEpoch = await port.readEpoch();
1057
+ while(true){
1058
+ const readHeader = await port.readCommitHeader(commitFrame.commit);
1059
+ // Normalized before `classifyCommit` compares it against `state.localDID` (also
1060
+ // normalized, at construction) — an own-unmerged commit authenticated under a different
1061
+ // form of this member's own DID must still be recognized as its own.
1062
+ const header = readHeader?.committerDID != null ? {
1063
+ ...readHeader,
1064
+ committerDID: normalizeDID(readHeader.committerDID)
1065
+ } : readHeader;
1066
+ const disposition = classifyCommit({
1067
+ header,
1068
+ sequenceID: position,
1069
+ commitDigest,
1070
+ state: {
1071
+ localDID,
1072
+ epoch: localEpoch,
1073
+ appliedByEpoch
1074
+ }
1075
+ });
1076
+ if (disposition.row === 'own-unmerged') {
1077
+ // Sender data names this peer at its current epoch, but neither commit content nor hub
1078
+ // acceptance is verified. The peer cannot process its own commit without pending state,
1079
+ // so the drain stops here and it heals.
1080
+ healRequested = true;
1081
+ stranded = true;
1082
+ observeStrand({
1083
+ position,
1084
+ commitDigest,
1085
+ localEpoch,
1086
+ claimedEpoch: header?.epoch ?? null,
1087
+ kind: 'own-unmerged',
1088
+ confidence: 'authenticated'
1089
+ });
1090
+ return advancedEpoch;
973
1091
  }
974
- });
975
- if (disposition.row === 'own-unmerged') {
976
- // This peer's own commit, at the epoch it is still at: the hub took it, the group moved
977
- // on, and the pending state died with its process. Cannot be applied (MLS merges a
978
- // pending commit, never processes one), so the drain stops here and the peer heals.
979
- healRequested = true;
980
- stranded = true;
981
- return advancedEpoch;
982
- }
983
- if (disposition.row === 'ahead') {
984
- // The group advanced at an epoch this peer did not. Step over the frame — the heal
985
- // repairs this, not a re-read — and ask for one.
986
- reconciledHead = position;
987
- healRequested = true;
988
- stranded = true;
989
- continue;
990
- }
991
- if (disposition.row === 'history') {
992
- // A frame from an epoch below this peer's, with no record for it or a record naming
993
- // this same commit. Not a fork, not poison, not the port's business — its blob is never
994
- // touched.
995
- reconciledHead = position;
996
- continue;
997
- }
998
- if (disposition.row === 'fork') {
999
- // Two commits at one epoch. The lower-sequenceID branch wins; the loser rejoins onto it
1000
- // (a heal). The winner just steps over the frame.
1001
- reconciledHead = position;
1002
- if (disposition.branch === 'losing') {
1092
+ if (disposition.row === 'ahead') {
1093
+ // The group advanced at an epoch this peer did not. Step over the frame — the heal
1094
+ // repairs this, not a re-read — and ask for one.
1095
+ reconciledHead = position;
1003
1096
  healRequested = true;
1004
1097
  stranded = true;
1098
+ observeStrand({
1099
+ position,
1100
+ commitDigest,
1101
+ localEpoch,
1102
+ claimedEpoch: header?.epoch ?? null,
1103
+ kind: 'ahead',
1104
+ confidence: 'claimed'
1105
+ });
1106
+ break;
1005
1107
  }
1006
- continue;
1007
- }
1008
- if (disposition.row === 'poison') {
1009
- reconciledHead = position; // not a commit at all: stepped over, and never retried
1010
- continue;
1011
- }
1012
- // Framed at this peer's epoch, by somebody else: a frame it can apply. Everything below is
1013
- // the port's answer to it.
1014
- const framedEpoch = crypto.epoch();
1015
- let applied;
1016
- try {
1017
- // Through the seam, like every other site that ratchets the handle: it reads this
1018
- // epoch's app frames ahead of the apply and takes the anchor if the roster moved.
1019
- applied = await advanceHandle(port, ()=>{
1020
- return port.processCommit(commitFrame.commit, {
1021
- senderDID: message.senderDID,
1022
- // The resolver, not the bodies: the blob opens only if the port asks for entries
1023
- // this commit names, and only for a commit it applies — framed at this peer's
1024
- // epoch, the epoch the blob is sealed under, making body delivery atomic with the
1025
- // commit. Called from INSIDE the apply, so the open must not touch the handle's
1026
- // ratchet: `openEntries` reads only the epoch's exporter secret and is pure.
1027
- resolveLedgerEntries: createLedgerEntryResolver(commitFrame.sealedEntries, crypto.openEntries)
1108
+ if (disposition.row === 'history') {
1109
+ // A frame from an epoch below this peer's, with no record for it or a record naming
1110
+ // this same commit. Not a fork, not poison, not the port's business — its blob is never
1111
+ // touched.
1112
+ reconciledHead = position;
1113
+ break;
1114
+ }
1115
+ if (disposition.row === 'fork') {
1116
+ // Two commits at one epoch. The lower-sequenceID branch wins; the loser rejoins onto it
1117
+ // (a heal). The winner just steps over the frame.
1118
+ reconciledHead = position;
1119
+ if (disposition.branch === 'losing') {
1120
+ healRequested = true;
1121
+ stranded = true;
1122
+ observeStrand({
1123
+ position,
1124
+ commitDigest,
1125
+ localEpoch,
1126
+ claimedEpoch: header?.epoch ?? null,
1127
+ kind: 'fork-losing',
1128
+ confidence: 'observed'
1129
+ });
1130
+ }
1131
+ break;
1132
+ }
1133
+ if (disposition.row === 'poison') {
1134
+ reconciledHead = position; // not a commit at all: stepped over, and never retried
1135
+ break;
1136
+ }
1137
+ // Framed at this peer's epoch, by somebody else: a frame it can apply. Everything below is
1138
+ // the port's answer to it.
1139
+ const framedEpoch = localEpoch;
1140
+ let applied;
1141
+ try {
1142
+ // Through the seam, like every other site that ratchets the handle: it reads this
1143
+ // epoch's app frames ahead of the apply and takes the anchor if the roster moved.
1144
+ applied = await advanceHandle(port, ()=>{
1145
+ return port.processCommit(commitFrame.commit, {
1146
+ senderDID: message.senderDID,
1147
+ // The resolver, not the bodies: the blob opens only if the port asks for entries
1148
+ // this commit names, and only for a commit it applies — framed at this peer's
1149
+ // epoch, the epoch the blob is sealed under, making body delivery atomic with the
1150
+ // commit. Called from INSIDE the apply, so the open must not touch the handle's
1151
+ // ratchet: `openEntries` reads only the epoch's exporter secret and is pure.
1152
+ resolveLedgerEntries: createLedgerEntryResolver(commitFrame.sealedEntries, crypto.openEntries)
1153
+ });
1154
+ }, // A REJOIN rotates the anchor too, from a member the roster diff cannot see: an
1155
+ // external commit by a member the roster still holds leaves every DID where it was.
1156
+ // Only an APPLIED commit says anything about the group.
1157
+ (result)=>result.advanced && header?.external === true, (result)=>result);
1158
+ } catch (error) {
1159
+ if (!isMissingLedgerEntries(error)) {
1160
+ // The port broke its contract. The cursor stays and the frame is re-read — the pull is
1161
+ // a retry, and this is not an outcome it can name.
1162
+ throw error;
1163
+ }
1164
+ // The commit names ledger entries whose bodies will not resolve. POISON: drop, advance,
1165
+ // do NOT heal. The bodies ride the commit sealed under its framed epoch, so a blob this
1166
+ // peer cannot open is one no member at this epoch can — nobody applies it, and the next
1167
+ // honest commit is framed at the same epoch and compare-and-sets behind it.
1168
+ //
1169
+ // Healing here would hand any member a group-wide recovery storm for one publish.
1170
+ // Retrying only delays that. The one case where this peer really is the broken one
1171
+ // announces itself later: the next commit is then framed AHEAD of this peer's, which
1172
+ // heals it.
1173
+ reconciledHead = position;
1174
+ break;
1175
+ }
1176
+ if (!applied.advanced && applied.epochBefore !== framedEpoch) {
1177
+ advancedEpoch = true;
1178
+ localEpoch = applied.epochBefore;
1179
+ continue;
1180
+ }
1181
+ if (applied.advanced) {
1182
+ advancedEpoch = true;
1183
+ // The fork check's record; the only place it is written from the log.
1184
+ appliedByEpoch.set(framedEpoch, {
1185
+ sequenceID: position,
1186
+ digest: commitDigest
1028
1187
  });
1029
- }, // A REJOIN rotates the anchor too, from a member the roster diff cannot see: an
1030
- // external commit by a member the roster still holds leaves every DID where it was.
1031
- // Only an APPLIED commit says anything about the group.
1032
- (result)=>result.advanced && header?.external === true);
1033
- } catch (error) {
1034
- if (!isMissingLedgerEntries(error)) {
1035
- // The port broke its contract. The cursor stays and the frame is re-read — the pull is
1036
- // a retry, and this is not an outcome it can name.
1037
- throw error;
1038
1188
  }
1039
- // The commit names ledger entries whose bodies will not resolve. POISON: drop, advance,
1040
- // do NOT heal. The bodies ride the commit sealed under its framed epoch, so a blob this
1041
- // peer cannot open is one no member at this epoch can — nobody applies it, and the next
1042
- // honest commit is framed at the same epoch and compare-and-sets behind it.
1043
- //
1044
- // Healing here would hand any member a group-wide recovery storm for one publish.
1045
- // Retrying only delays that. The one case where this peer really is the broken one
1046
- // announces itself later: the next commit is then framed AHEAD of this peer's, which
1047
- // heals it.
1189
+ // `{ advanced: false }` here is the port REFUSING a well-formed commit at this peer's own
1190
+ // epoch from another member: poison on the same terms as an unresolvable one.
1048
1191
  reconciledHead = position;
1049
- continue;
1050
- }
1051
- if (applied.advanced) {
1052
- advancedEpoch = true;
1053
- // The fork check's record; the only place it is written from the log.
1054
- appliedByEpoch.set(framedEpoch, {
1055
- sequenceID: position,
1056
- digest: commitDigest
1057
- });
1192
+ break;
1058
1193
  }
1059
- // `{ advanced: false }` here is the port REFUSING a well-formed commit at this peer's own
1060
- // epoch from another member: poison on the same terms as an unresolvable one.
1061
- reconciledHead = position;
1062
1194
  }
1063
1195
  // A short page ends the log: every frame this reply named is processed, so its tip is
1064
1196
  // reconciled. A full page is not — loop and take the head from the reply that finally drains.
@@ -1080,9 +1212,28 @@ export function createGroupPeer(params) {
1080
1212
  throw new Error('pullCommits: the journal must be replayed first in every lane operation, or a peer that crashed on its own commit heals from it instead of adopting it');
1081
1213
  }
1082
1214
  if (mls == null || commitTopicID == null) return false;
1083
- const advanced = await walkCommits(mls, commitTopicID);
1084
- await appLane.deliver();
1085
- return advanced;
1215
+ const epochBefore = await mls.readEpoch();
1216
+ const anchorBefore = anchor;
1217
+ try {
1218
+ const advanced = await walkCommits(mls, commitTopicID);
1219
+ await appLane.deliver();
1220
+ return advanced;
1221
+ } catch (error) {
1222
+ // A failed final drain can follow applied commits. Refresh the runtime before a retry.
1223
+ if (inboxLane != null && (await mls.readEpoch() !== epochBefore || anchor !== anchorBefore)) {
1224
+ try {
1225
+ await rebuildEpoch();
1226
+ } catch {
1227
+ // The walk's original failure remains the retryable cause.
1228
+ }
1229
+ }
1230
+ if (crypto.pending != null && !appPullActive) {
1231
+ appPullNeeded = true;
1232
+ armAppPull(appPullBackoff);
1233
+ appPullBackoff = Math.min(appPullBackoff * 2, 60_000);
1234
+ }
1235
+ throw error;
1236
+ }
1086
1237
  };
1087
1238
  /** Pull the commit log, and rebuild the app lane if the pull moved the epoch. */ const reconcileCommits = async ()=>{
1088
1239
  const advanced = await pullCommits();
@@ -1104,7 +1255,9 @@ export function createGroupPeer(params) {
1104
1255
  // A wakeup is a lane operation: step 0, the ledger invariant, then the pull. No return
1105
1256
  // value, so anything found is stashed for the next call that has one.
1106
1257
  const replayed = await replayJournal();
1107
- await ensureLedger(Date.now() + recoveryTimeoutMs);
1258
+ if (mls != null && await ensureLedger(Date.now() + recoveryTimeoutMs)) {
1259
+ await finalizeBootstrap(mls);
1260
+ }
1108
1261
  const pulled = await pullCommits();
1109
1262
  if (replayed || pulled) await rebuildEpoch();
1110
1263
  }).catch(()=>{
@@ -1164,7 +1317,7 @@ export function createGroupPeer(params) {
1164
1317
  // A peer restored with an incomplete ledger was killed between rejoining and bootstrapping.
1165
1318
  // The invariant finds it here and at every later lane operation, with no memory of how it
1166
1319
  // got there.
1167
- await ensureLedger(Date.now() + recoveryTimeoutMs);
1320
+ if (await ensureLedger(Date.now() + recoveryTimeoutMs)) await finalizeBootstrap(mls);
1168
1321
  await pullCommits();
1169
1322
  }).catch(()=>{
1170
1323
  // a failed seed leaves the cursor put; the next wakeup replays and pulls again
@@ -1175,13 +1328,16 @@ export function createGroupPeer(params) {
1175
1328
  * from the epoch the commit is FRAMED at — the epoch every member that can apply it is at, and
1176
1329
  * the one this group stays at until the commit is adopted. A host that adopted first has rotated
1177
1330
  * past it and can seal for nobody, so it is told rather than publishing a blob no member can
1178
- * open.
1179
- */ const frameCommit = async (commit, bodies)=>{
1180
- if (crypto.epoch() !== epoch) {
1331
+ * open. `framedAt` is null for an external commit, framed at the group's epoch, not this handle's.
1332
+ */ const frameCommit = async (commit, bodies, framedAt)=>{
1333
+ const { sealed: sealedEntries, epoch } = await crypto.sealEntries(encodeLedgerEntries(bodies));
1334
+ if (framedAt != null && epoch !== framedAt) {
1181
1335
  throw new Error('commit: the local group has already advanced past the epoch this commit was framed at. A commit is adopted in onAccepted, never before.');
1182
1336
  }
1183
- const sealedEntries = await crypto.sealEntries(encodeLedgerEntries(bodies));
1184
- return encodeHandshakeFrame(HANDSHAKE_KIND.commit, encodeCommitFrame(commit, sealedEntries));
1337
+ return {
1338
+ payload: encodeHandshakeFrame(HANDSHAKE_KIND.commit, encodeCommitFrame(commit, sealedEntries)),
1339
+ epoch
1340
+ };
1185
1341
  };
1186
1342
  /**
1187
1343
  * Step 0 of every lane operation, strictly ahead of the pull. Settle any journalled commit:
@@ -1220,10 +1376,11 @@ export function createGroupPeer(params) {
1220
1376
  // Republishing means RE-SEALING the bodies, sealable only under the host's current epoch —
1221
1377
  // which equals the framed epoch only while `onAccepted` is the sole place the host adopts.
1222
1378
  // Sealing anyway publishes a blob no member can open and wedges the lane for the whole group.
1223
- if (crypto.epoch() !== entry.epoch) {
1224
- throw new JournalEpochError(`commit replay: the journalled commit was framed at epoch ${entry.epoch}, and this group is now at ${crypto.epoch()}. A commit is adopted in onAccepted, and nowhere else.`);
1379
+ const handleEpoch = await mls.readEpoch();
1380
+ if (handleEpoch !== entry.epoch) {
1381
+ throw new JournalEpochError(`commit replay: the journalled commit was framed at epoch ${entry.epoch}, and this group is now at ${handleEpoch}. A commit is adopted in onAccepted, and nowhere else.`);
1225
1382
  }
1226
- const payload = await frameCommit(entry.commit, entry.bodies);
1383
+ const { payload } = await frameCommit(entry.commit, entry.bodies, entry.epoch);
1227
1384
  let sequenceID;
1228
1385
  try {
1229
1386
  sequenceID = (await mux.publish({
@@ -1290,6 +1447,49 @@ export function createGroupPeer(params) {
1290
1447
  } : {}
1291
1448
  };
1292
1449
  };
1450
+ const repairRejoin = async ()=>{
1451
+ if (awaitingBootstrap == null) return;
1452
+ // Restore the subscription before gathering the ledger: responders may already have
1453
+ // rotated to the new app anchor. A failed repair remains pending for the next lane call.
1454
+ if (rejoinAnchorNeedsCapture) {
1455
+ await captureAnchor();
1456
+ rejoinAnchorNeedsCapture = false;
1457
+ }
1458
+ if (rejoinRuntimeNeedsBuild) {
1459
+ await rebuildEpoch();
1460
+ rejoinRuntimeNeedsBuild = false;
1461
+ }
1462
+ };
1463
+ const finalizeBootstrap = async (port)=>{
1464
+ assertLive();
1465
+ if (awaitingBootstrap == null) return;
1466
+ const { attemptID, trigger, entries } = awaitingBootstrap;
1467
+ await repairRejoin();
1468
+ assertLive();
1469
+ const held = new Set(await port.getLedger());
1470
+ assertLive();
1471
+ const owed = entries.filter((token)=>!held.has(token));
1472
+ if (owed.length > 0) pendingReenact = [
1473
+ ...pendingReenact,
1474
+ ...owed
1475
+ ];
1476
+ awaitingBootstrap = null;
1477
+ inFlightEntries = null;
1478
+ if (bootstrapHealRequested) {
1479
+ healRequested = false;
1480
+ bootstrapHealRequested = false;
1481
+ }
1482
+ recoveryGeneration += 1;
1483
+ closeEpisode();
1484
+ if (commitTopicID != null) {
1485
+ emitRecovery({
1486
+ phase: 'bootstrapped',
1487
+ groupID: commitTopicID,
1488
+ attemptID,
1489
+ trigger
1490
+ });
1491
+ }
1492
+ };
1293
1493
  /**
1294
1494
  * The ledger completeness invariant, checked before every lane operation and repaired on the
1295
1495
  * spot. Purely local (the head folded from the handle's entries against the authenticated head
@@ -1305,6 +1505,7 @@ export function createGroupPeer(params) {
1305
1505
  * retryable, degraded state, not an error the host can act on.
1306
1506
  */ const ensureLedger = async (deadline)=>{
1307
1507
  if (mls == null || rendezvousTopicID == null) return true;
1508
+ await repairRejoin();
1308
1509
  const port = mls;
1309
1510
  const topicID = rendezvousTopicID;
1310
1511
  if (await port.isLedgerComplete()) return true;
@@ -1319,16 +1520,27 @@ export function createGroupPeer(params) {
1319
1520
  // for one publish; without the second, so does the hub.
1320
1521
  const requestID = newPublishID();
1321
1522
  const request = await port.createRecoveryRequest(requestID);
1523
+ if (disposed) return false;
1322
1524
  return await new Promise((resolve)=>{
1323
1525
  let settled = false;
1526
+ const bootstraps = new Set();
1324
1527
  const finish = (complete)=>{
1325
1528
  if (settled) return;
1326
1529
  settled = true;
1327
1530
  ledgerWaiters.delete(requestID);
1531
+ ledgerGatherFinishes.delete(finishOnDispose);
1328
1532
  clearTimeout(timer);
1329
- resolve(complete);
1533
+ // Keep the lane until every bootstrap already touching this handle has finished.
1534
+ if (bootstraps.size === 0) resolve(complete && !disposed);
1535
+ else void Promise.allSettled([
1536
+ ...bootstraps
1537
+ ]).then((results)=>{
1538
+ resolve(!disposed && (complete || results.some((result)=>result.status === 'fulfilled')));
1539
+ });
1330
1540
  };
1541
+ const finishOnDispose = ()=>finish(false);
1331
1542
  const timer = setTimeout(()=>finish(false), Math.max(0, deadline - Date.now()));
1543
+ ledgerGatherFinishes.add(finishOnDispose);
1332
1544
  ledgerWaiters.set(requestID, (sealed)=>{
1333
1545
  void (async ()=>{
1334
1546
  if (settled || disposed) return;
@@ -1338,10 +1550,17 @@ export function createGroupPeer(params) {
1338
1550
  // here, since the next responder's reply is sealed to the same key.
1339
1551
  const tokens = await port.openSealedLedger(sealed, requestID);
1340
1552
  if (tokens == null) return;
1341
- // Re-check: `disposed` can flip during the openSealedLedger await, and bootstrapLedger
1342
- // REPLACES the host-owned ledger — it must not run against a torn-down handle.
1343
- if (disposed) return;
1344
- await port.bootstrapLedger(tokens);
1553
+ // Timeout or disposal can settle the gather while opening the reply.
1554
+ if (settled || disposed) return;
1555
+ const bootstrap = port.bootstrapLedger(tokens);
1556
+ bootstraps.add(bootstrap);
1557
+ inFlightBootstraps.add(bootstrap);
1558
+ try {
1559
+ await bootstrap;
1560
+ } finally{
1561
+ bootstraps.delete(bootstrap);
1562
+ inFlightBootstraps.delete(bootstrap);
1563
+ }
1345
1564
  finish(true);
1346
1565
  } catch {
1347
1566
  // Recomputed head does not match the authenticated one: this responder withheld,
@@ -1382,6 +1601,7 @@ export function createGroupPeer(params) {
1382
1601
  if (!await ensureLedger(Date.now() + recoveryTimeoutMs)) {
1383
1602
  throw new RecoveryRequiredError('commit: the ledger is incomplete, so this handle rejoined the group and its bootstrap has not completed — its roster has reset, and a commit built now would be judged against a group whose admins it cannot see. It must finish bootstrapping its ledger before it can commit again.');
1384
1603
  }
1604
+ await finalizeBootstrap(mls);
1385
1605
  const deadline = Date.now() + commitDeadlineMs;
1386
1606
  for(let attempt = 0; attempt < COMMIT_ATTEMPT_CEILING; attempt++){
1387
1607
  // 1. Pull the log to the end: every frame processed, and the tip to race at learned from
@@ -1405,8 +1625,7 @@ export function createGroupPeer(params) {
1405
1625
  // which need not be one the head can ever name.
1406
1626
  const publishID = newPublishID();
1407
1627
  const expectedHead = commitLogHead;
1408
- const framedEpoch = crypto.epoch();
1409
- const payload = await frameCommit(pending.commit, pending.bodies);
1628
+ const { payload, epoch: framedEpoch } = await frameCommit(pending.commit, pending.bodies, crypto.frameEpoch(pending.commit));
1410
1629
  await slot.put({
1411
1630
  publishID,
1412
1631
  expectedHead,
@@ -1485,25 +1704,42 @@ export function createGroupPeer(params) {
1485
1704
  assertLive();
1486
1705
  return runSerial(async ()=>{
1487
1706
  if (await replayJournal()) await rebuildEpoch();
1488
- await ensureLedger(Date.now() + recoveryTimeoutMs);
1707
+ if (mls != null && await ensureLedger(Date.now() + recoveryTimeoutMs)) {
1708
+ await finalizeBootstrap(mls);
1709
+ }
1710
+ assertLive();
1489
1711
  return takeLost();
1490
1712
  });
1491
1713
  };
1492
1714
  /**
1493
1715
  * Ask the group for its state and wait for one member to answer, bounded by the deadline.
1494
- * `null` when nobody does — heal is a rendezvous and cannot work without a responder.
1716
+ * The outcome distinguishes a silent responder, disposal and a failed request publish.
1495
1717
  */ const requestGroupInfo = async (request, requestID, topicID, deadline)=>{
1496
- const wait = Math.max(0, Math.min(recoveryTimeoutMs, deadline - Date.now()));
1718
+ const remaining = deadline - Date.now();
1719
+ const wait = Math.max(0, Math.min(recoveryTimeoutMs, remaining));
1720
+ const atDeadline = remaining <= recoveryTimeoutMs;
1497
1721
  return await new Promise((resolve)=>{
1498
1722
  recoveryWaiters.set(requestID, resolve);
1499
1723
  recoveryTimers.set(requestID, setTimeout(()=>{
1500
1724
  recoveryTimers.delete(requestID);
1501
- if (recoveryWaiters.delete(requestID)) resolve(null);
1725
+ if (recoveryWaiters.delete(requestID)) resolve({
1726
+ kind: 'timeout',
1727
+ atDeadline
1728
+ });
1502
1729
  }, wait));
1503
1730
  void Promise.resolve(mux.publish({
1504
1731
  topicID,
1505
1732
  payload: encodeHandshakeFrame(HANDSHAKE_KIND.recoveryRequest, encodeRecoveryRequest(requestID, request))
1506
- })).catch(()=>{});
1733
+ })).catch((error)=>{
1734
+ if (!recoveryWaiters.delete(requestID)) return;
1735
+ const timer = recoveryTimers.get(requestID);
1736
+ if (timer != null) clearTimeout(timer);
1737
+ recoveryTimers.delete(requestID);
1738
+ resolve({
1739
+ kind: 'publish-failed',
1740
+ error
1741
+ });
1742
+ });
1507
1743
  });
1508
1744
  };
1509
1745
  /**
@@ -1528,22 +1764,40 @@ export function createGroupPeer(params) {
1528
1764
  * own. NEVER calls `commit()` and `commit()` never calls it — both take the same non-reentrant
1529
1765
  * mutex, so either nesting deadlocks. The re-enactment a heal owes is a SUBSEQUENT `commit()` the
1530
1766
  * host makes once this releases the lane.
1531
- */ const recover = async ()=>{
1532
- await ready;
1767
+ */ const attemptBody = async (trigger, generation, port, commits, rendezvous)=>{
1533
1768
  assertLive();
1534
- if (mls == null || commitTopicID == null || rendezvousTopicID == null) {
1769
+ if (recoveryGeneration !== generation && !stranded && !healRequested) {
1535
1770
  return {
1536
- advanced: false,
1537
- reenact: []
1771
+ advanced: true
1538
1772
  };
1539
1773
  }
1540
- const port = mls;
1541
- const commits = commitTopicID;
1542
- const rendezvous = rendezvousTopicID;
1543
- return runSerial(async ()=>{
1774
+ const attemptID = newPublishID();
1775
+ const base = {
1776
+ groupID: commits,
1777
+ attemptID,
1778
+ trigger
1779
+ };
1780
+ queueMicrotask(()=>notifyHost(params.onRecovery, {
1781
+ ...base,
1782
+ phase: 'started'
1783
+ }));
1784
+ const failed = (reason)=>{
1785
+ emitRecovery({
1786
+ ...base,
1787
+ phase: 'failed',
1788
+ reason
1789
+ });
1790
+ return {
1791
+ advanced: false
1792
+ };
1793
+ };
1794
+ try {
1544
1795
  // 0. Replay the journal ahead of everything, as every lane operation does: a peer holding a
1545
1796
  // commit whose fate it never learned settles that first, and may find nothing left to heal.
1546
1797
  if (await replayJournal()) await rebuildEpoch();
1798
+ assertLive();
1799
+ if (await ensureLedger(Date.now() + recoveryTimeoutMs)) await finalizeBootstrap(port);
1800
+ assertLive();
1547
1801
  const deadline = Date.now() + recoveryDeadlineMs;
1548
1802
  while(Date.now() < deadline){
1549
1803
  // 1. Pull to the end. It may resolve the strand outright, and a heal it no longer needs
@@ -1552,34 +1806,49 @@ export function createGroupPeer(params) {
1552
1806
  // applies the winner's commit HERE.
1553
1807
  healRequested = false;
1554
1808
  await reconcileCommits();
1809
+ assertLive();
1555
1810
  // 2. The head to race at, from the store's own reply.
1556
1811
  const expectedHead = await readCommitHead(commits);
1812
+ assertLive();
1557
1813
  // 3. Mint a request and rendezvous for a sealed GroupInfo. Fresh request per attempt: the
1558
1814
  // ephemeral key is minted with it, and a reply to an already-used request is unopenable.
1559
1815
  const requestID = newPublishID();
1560
1816
  const request = await port.createRecoveryRequest(requestID);
1561
- const sealed = await requestGroupInfo(request, requestID, rendezvous, deadline);
1562
- if (sealed == null) {
1563
- break;
1817
+ assertLive();
1818
+ const outcome = await requestGroupInfo(request, requestID, rendezvous, deadline);
1819
+ if (outcome.kind === 'disposed' || disposed) throw new PeerDisposedError('Peer is disposed');
1820
+ if (outcome.kind === 'publish-failed') throw outcome.error;
1821
+ if (outcome.kind === 'timeout') {
1822
+ // Nobody answered. Heal REQUIRES another online member that can seal a GroupInfo;
1823
+ // without one it cannot work. The peer stays degraded and asks again later.
1824
+ return failed(outcome.atDeadline ? 'deadline' : 'no-responder');
1564
1825
  }
1565
1826
  // 4. Open it and BUILD the external commit, adopting nothing. Bytes this peer cannot open
1566
1827
  // are a hub-injected or misaddressed reply: ask again.
1567
1828
  let pending;
1568
1829
  try {
1569
- pending = await port.applyRecovery(sealed, requestID);
1830
+ pending = await port.applyRecovery(outcome.sealed, requestID);
1570
1831
  } catch {
1571
1832
  pending = null;
1572
1833
  }
1834
+ assertLive();
1573
1835
  if (pending == null) continue;
1574
1836
  // 5. The entries this peer holds, snapshotted BEFORE the rejoined handle replaces them —
1575
1837
  // the last moment they can be read. Kept across a failed attempt, so a retry filters
1576
1838
  // the same entries rather than snapshotting the empty ledger a failed bootstrap left.
1577
- if (inFlightEntries == null) inFlightEntries = await port.getLedger();
1839
+ inFlightEntries = [
1840
+ ...new Set([
1841
+ ...inFlightEntries ?? awaitingBootstrap?.entries ?? [],
1842
+ ...await port.getLedger()
1843
+ ])
1844
+ ];
1845
+ assertLive();
1578
1846
  const inFlight = inFlightEntries;
1579
1847
  // 6. Publish the external commit, compare-and-set at the head: it changes the ratchet
1580
1848
  // tree, so it races like any commit.
1581
1849
  const publishID = newPublishID();
1582
- const payload = await frameCommit(pending.commit, []);
1850
+ const { payload } = await frameCommit(pending.commit, [], null);
1851
+ assertLive();
1583
1852
  let sequenceID;
1584
1853
  try {
1585
1854
  sequenceID = (await mux.publish({
@@ -1590,65 +1859,161 @@ export function createGroupPeer(params) {
1590
1859
  publishID
1591
1860
  })).sequenceID;
1592
1861
  } catch (error) {
1862
+ if (disposed) throw new PeerDisposedError('Peer is disposed', {
1863
+ cause: error
1864
+ });
1593
1865
  if (!isHeadMismatch(error)) throw error;
1594
1866
  continue;
1595
1867
  }
1868
+ assertLive();
1596
1869
  // 7. Accepted: the group has this peer's new leaf. Adopt the rejoined handle — the only
1597
1870
  // place it may be adopted. Deliberately UNJOURNALLED: a crash here leaves an orphaned
1598
1871
  // external commit that repairs itself — framed at the group's epoch, not this peer's,
1599
1872
  // so the own-commit trigger stays quiet, the heal condition still holds, and `resync`
1600
1873
  // later collects the leaf the orphan added.
1601
1874
  const rejoinedAtEpoch = (await port.readCommitHeader(pending.commit))?.epoch;
1875
+ assertLive();
1876
+ const epochBeforeRejoin = await port.readEpoch();
1602
1877
  // Through the seam, like every other site that ratchets the handle — and it rotates
1603
1878
  // ANYWAY: this is the rejoin, which no roster diff can see (see {@link anchor}). The
1604
1879
  // anchor is the POST-commit epoch: the handle advances inside the seam and only then is
1605
1880
  // the anchor captured, exactly where an applying member lands.
1606
- await advanceHandle(port, ()=>pending.onAccepted(), ()=>true);
1881
+ await advanceHandle(port, async ()=>{
1882
+ try {
1883
+ await pending.onAccepted();
1884
+ } finally{
1885
+ // The adapter may adopt the handle and then fail to persist it. Observe the
1886
+ // ratchet itself: a pre-adoption failure leaves this snapshot with the retry.
1887
+ if (await port.readEpoch() !== epochBeforeRejoin) {
1888
+ awaitingBootstrap = {
1889
+ attemptID,
1890
+ trigger,
1891
+ entries: inFlight
1892
+ };
1893
+ // Adoption enacted these bytes even if persistence rejected afterward.
1894
+ if (rejoinedAtEpoch != null) {
1895
+ appliedByEpoch.set(rejoinedAtEpoch, {
1896
+ sequenceID,
1897
+ digest: digestAppliedCommit(pending.commit)
1898
+ });
1899
+ }
1900
+ stranded = false;
1901
+ rejoinAnchorNeedsCapture = true;
1902
+ rejoinRuntimeNeedsBuild = true;
1903
+ }
1904
+ }
1905
+ }, ()=>true);
1906
+ rejoinAnchorNeedsCapture = false;
1907
+ assertLive();
1607
1908
  const accepted = asLogPosition(sequenceID);
1608
1909
  reconciledHead = accepted;
1609
1910
  commitLogHead = accepted;
1610
- // Enacted at that epoch, like an applied commit: without the record a second commit at
1611
- // that epoch reads as history rather than the fork it is.
1612
- if (rejoinedAtEpoch != null) {
1613
- appliedByEpoch.set(rejoinedAtEpoch, {
1614
- sequenceID,
1615
- digest: digestAppliedCommit(pending.commit)
1616
- });
1617
- }
1618
1911
  healRequested = false;
1619
1912
  // The one place the commit gate is released: the rejoin landed, so this peer's leaf is
1620
1913
  // back in the tree and the stale-epoch fork it guards is closed. A bootstrap that still
1621
1914
  // fails below is `commit()`'s own ledger-completeness check to handle.
1622
- stranded = false;
1623
1915
  await rebuildEpoch();
1916
+ rejoinRuntimeNeedsBuild = false;
1917
+ assertLive();
1624
1918
  // 8. Bootstrap: REQUIRED, not a formality. Until it runs, the ledger is empty against a
1625
1919
  // live head — every admin promoted since genesis is invisible and the next commit is
1626
1920
  // rejected. Failure here is a persistent degraded state, NOT a heal.
1627
1921
  if (!await ensureLedger(deadline)) {
1628
- healRequested = true;
1629
- return {
1630
- advanced: false,
1631
- reenact: []
1922
+ assertLive();
1923
+ awaitingBootstrap = {
1924
+ attemptID,
1925
+ trigger,
1926
+ entries: inFlight
1632
1927
  };
1928
+ healRequested = true;
1929
+ bootstrapHealRequested = true;
1930
+ return failed('bootstrap-failed');
1633
1931
  }
1932
+ assertLive();
1634
1933
  // 9. Re-enact by MEMBERSHIP, never by the failure that brought this peer here: keep only
1635
1934
  // entries the group's ledger does NOT hold. An entry it DOES hold was enacted for
1636
1935
  // everyone, and appending it again puts it at the END of the log where the fold is
1637
1936
  // last-write-wins — it would win, silently reverting whatever a later admin wrote over
1638
1937
  // the same subject.
1639
1938
  const held = new Set(await port.getLedger());
1939
+ assertLive();
1640
1940
  const reenact = inFlight.filter((token)=>!held.has(token));
1641
1941
  inFlightEntries = null;
1942
+ awaitingBootstrap = null;
1943
+ bootstrapHealRequested = false;
1944
+ if (reenact.length > 0) pendingReenact = [
1945
+ ...pendingReenact,
1946
+ ...reenact
1947
+ ];
1948
+ recoveryGeneration += 1;
1949
+ closeEpisode();
1950
+ emitRecovery({
1951
+ ...base,
1952
+ phase: 'succeeded'
1953
+ });
1642
1954
  return {
1643
- advanced: true,
1644
- reenact
1955
+ advanced: true
1645
1956
  };
1646
1957
  }
1647
- return {
1648
- advanced: false,
1649
- reenact: []
1650
- };
1958
+ return failed('deadline');
1959
+ } catch (error) {
1960
+ if (disposed || error instanceof PeerDisposedError) {
1961
+ emitRecovery({
1962
+ ...base,
1963
+ phase: 'failed',
1964
+ reason: 'disposed'
1965
+ });
1966
+ throw error instanceof PeerDisposedError ? error : new PeerDisposedError('Peer is disposed');
1967
+ }
1968
+ emitRecovery({
1969
+ ...base,
1970
+ phase: 'failed',
1971
+ reason: 'error',
1972
+ error
1973
+ });
1974
+ throw error;
1975
+ }
1976
+ };
1977
+ const runRecovery = (trigger)=>{
1978
+ if (activeRecovery != null) return activeRecovery;
1979
+ const generation = recoveryGeneration;
1980
+ const attempt = (async ()=>{
1981
+ await ready;
1982
+ assertLive();
1983
+ if (mls == null || commitTopicID == null || rendezvousTopicID == null) {
1984
+ return {
1985
+ advanced: false
1986
+ };
1987
+ }
1988
+ const port = mls;
1989
+ const commits = commitTopicID;
1990
+ const rendezvous = rendezvousTopicID;
1991
+ return runSerial(async ()=>{
1992
+ try {
1993
+ return await attemptBody(trigger, generation, port, commits, rendezvous);
1994
+ } finally{
1995
+ // The body and its mutex hold are finished before runSerial flushes terminal
1996
+ // notices. A synchronous observer retry must not join this settled attempt.
1997
+ if (activeRecovery === attempt) activeRecovery = null;
1998
+ }
1999
+ });
2000
+ })();
2001
+ activeRecovery = attempt;
2002
+ void attempt.then(()=>{
2003
+ if (activeRecovery === attempt) activeRecovery = null;
2004
+ }, ()=>{
2005
+ if (activeRecovery === attempt) activeRecovery = null;
1651
2006
  });
2007
+ return attempt;
2008
+ };
2009
+ const recover = async ()=>{
2010
+ const { advanced } = await runRecovery('consumer');
2011
+ const reenact = pendingReenact;
2012
+ pendingReenact = [];
2013
+ return {
2014
+ advanced,
2015
+ reenact
2016
+ };
1652
2017
  };
1653
2018
  /**
1654
2019
  * Run a heal the lane asked for, never from inside the lane. `recover()` takes the commit mutex,
@@ -1656,22 +2021,43 @@ export function createGroupPeer(params) {
1656
2021
  * flight absorbs any trigger raised while it runs: the frame that raised it is still in the log,
1657
2022
  * and the next pull raises it again if the heal did not settle it.
1658
2023
  */ const healIfRequested = async ()=>{
1659
- if (!healRequested || healing) return;
1660
- healing = true;
2024
+ if (!healRequested || activeRecovery != null) return;
1661
2025
  healRequested = false;
1662
2026
  try {
1663
- // Still two commits; the second is the host's. No return value to put the entries in, so
1664
- // they wait for a lane operation that has one — same as a lost commit.
1665
- const { reenact } = await recover();
1666
- if (reenact.length > 0) pendingReenact = [
1667
- ...pendingReenact,
1668
- ...reenact
1669
- ];
2027
+ await runRecovery('automatic');
1670
2028
  } catch {
1671
2029
  // No responder, or a reply that would not open. The peer stays degraded, and the frame that
1672
2030
  // asked for the heal is still in the log: the next pull asks again.
1673
- } finally{
1674
- healing = false;
2031
+ }
2032
+ };
2033
+ let pendingRestoreTimer;
2034
+ let abortPendingRestore;
2035
+ const pendingRestoreAborted = new Promise((resolve)=>{
2036
+ abortPendingRestore = resolve;
2037
+ });
2038
+ const restorePending = async ()=>{
2039
+ if (crypto.pending == null) return;
2040
+ let backoff = 1000;
2041
+ while(!disposed){
2042
+ try {
2043
+ const records = await Promise.race([
2044
+ crypto.pending.list(),
2045
+ pendingRestoreAborted.then(()=>null)
2046
+ ]);
2047
+ if (records == null || disposed) return;
2048
+ await appLane.restore(records);
2049
+ return;
2050
+ } catch {
2051
+ if (disposed) return;
2052
+ await Promise.race([
2053
+ new Promise((resolve)=>{
2054
+ pendingRestoreTimer = setTimeout(resolve, backoff);
2055
+ }),
2056
+ pendingRestoreAborted
2057
+ ]);
2058
+ pendingRestoreTimer = undefined;
2059
+ backoff = Math.min(backoff * 2, 60_000);
2060
+ }
1675
2061
  }
1676
2062
  };
1677
2063
  const ready = (async ()=>{
@@ -1691,8 +2077,24 @@ export function createGroupPeer(params) {
1691
2077
  } else {
1692
2078
  await captureAnchor();
1693
2079
  }
2080
+ await restorePending();
2081
+ if (disposed) return;
1694
2082
  await initControlLanes();
1695
2083
  await buildEpoch();
2084
+ // The seed pull precedes the app listeners. Read once more after registration to close
2085
+ // the publication gap; a failed read is retried on the same independent schedule.
2086
+ if (crypto.pending != null) {
2087
+ try {
2088
+ await runSerial(async ()=>{
2089
+ await replayJournal();
2090
+ await ensureLedger(Date.now() + recoveryTimeoutMs);
2091
+ await reconcileCommits();
2092
+ });
2093
+ } catch {
2094
+ appPullNeeded = true;
2095
+ armAppPull(appPullBackoff);
2096
+ }
2097
+ }
1696
2098
  })();
1697
2099
  // A failed init rejects every public call, but must not raise an unhandled rejection before the
1698
2100
  // first is made.
@@ -1706,6 +2108,28 @@ export function createGroupPeer(params) {
1706
2108
  assertLive();
1707
2109
  return fn();
1708
2110
  };
2111
+ const readyOrAbort = async (signal)=>{
2112
+ if (signal == null) {
2113
+ await ready;
2114
+ return 'ready';
2115
+ }
2116
+ if (signal.aborted) return 'aborted';
2117
+ let onAbort;
2118
+ const aborted = new Promise((resolve)=>{
2119
+ onAbort = ()=>resolve('aborted');
2120
+ signal.addEventListener('abort', onAbort, {
2121
+ once: true
2122
+ });
2123
+ });
2124
+ try {
2125
+ return await Promise.race([
2126
+ ready.then(()=>'ready'),
2127
+ aborted
2128
+ ]);
2129
+ } finally{
2130
+ if (onAbort != null) signal.removeEventListener('abort', onAbort);
2131
+ }
2132
+ };
1709
2133
  // Hoisted and explicitly typed (rather than inlined in the return object below) so the
1710
2134
  // checker can match its type against `GroupPeer<Protocols>['protocol']` by identity: inlined,
1711
2135
  // the whole return-object structural check against `GroupPeer<Protocols>` recurses through
@@ -1716,12 +2140,27 @@ export function createGroupPeer(params) {
1716
2140
  return {
1717
2141
  dispatch: (prc, config)=>withReady(()=>surfaceFor(key).dispatch(prc, config)),
1718
2142
  request: (prc, config)=>withReady(()=>surfaceFor(key).request(prc, config)),
1719
- gather: (prc, config)=>withReady(()=>surfaceFor(key).gather(prc, config)),
2143
+ gather: async (prc, config)=>{
2144
+ const outcome = await readyOrAbort(config?.signal);
2145
+ assertLive();
2146
+ if (outcome === 'aborted') return [];
2147
+ return surfaceFor(key).gather(prc, config);
2148
+ },
1720
2149
  to: (memberDID)=>withReady(()=>surfaceFor(key).to(memberDID))
1721
2150
  };
1722
2151
  };
1723
2152
  return {
1724
2153
  protocol: protocolMethod,
2154
+ dropAppFrame: async (topicID, position)=>{
2155
+ await ready;
2156
+ assertLive();
2157
+ await runSerial(async ()=>{
2158
+ await appLane.dropFrame(topicID, position);
2159
+ await replayJournal();
2160
+ await ensureLedger(Date.now() + recoveryTimeoutMs);
2161
+ await reconcileCommits();
2162
+ });
2163
+ },
1725
2164
  commit,
1726
2165
  replay,
1727
2166
  recover,
@@ -1740,9 +2179,21 @@ export function createGroupPeer(params) {
1740
2179
  await runSerial(()=>rebuildEpoch());
1741
2180
  },
1742
2181
  anchorEpoch: ()=>anchor.epoch,
2182
+ reauthorize: ()=>{
2183
+ // No `assertLive`/`ready` wait: rearming a refused subscription is a synchronous, idempotent
2184
+ // hint the mux applies against its own state, safe on a peer that is still initializing and a
2185
+ // no-op on a disposed one (the mux guards `disposed`). It touches only topics the hub already
2186
+ // refused, so it cannot subscribe anything a normal retain would not have.
2187
+ mux.rearmRefusedTopics();
2188
+ },
1743
2189
  dispose: ()=>{
1744
2190
  if (disposePromise != null) return disposePromise;
1745
2191
  disposed = true;
2192
+ abortPendingRestore?.();
2193
+ if (pendingRestoreTimer != null) clearTimeout(pendingRestoreTimer);
2194
+ appLane.dispose();
2195
+ if (appPullTimer != null) clearTimeout(appPullTimer);
2196
+ appPullTimer = undefined;
1746
2197
  // Synchronous and FIRST, before anything is awaited: a lane op that already passed its own
1747
2198
  // `assertLive` can be running inside `runSerial`, past the point this `dispose()` can reach
1748
2199
  // it — awaiting the commit mutex here is unsafe (`build()`/`onAccepted()` are host-supplied
@@ -1750,18 +2201,26 @@ export function createGroupPeer(params) {
1750
2201
  // closes the mux's three routes to the wire immediately, so whatever the op does next, it
1751
2202
  // cannot land a write. `mux.dispose()` — the full teardown — stays LAST, unchanged.
1752
2203
  mux.suspendPublishing();
2204
+ // Release a lane waiting for ledger replies now; its deadline may be far away.
2205
+ for (const finish of [
2206
+ ...ledgerGatherFinishes
2207
+ ])finish();
1753
2208
  disposePromise = (async ()=>{
1754
2209
  // Tear down even a peer whose init failed — it still holds a hub drain.
1755
2210
  await settled;
2211
+ await Promise.allSettled([
2212
+ ...inFlightBootstraps
2213
+ ]);
1756
2214
  commitUnsubscribe?.();
1757
2215
  rendezvousUnsubscribe?.();
1758
2216
  // Resolve any in-flight recovery rendezvous FIRST, before clearing its timers: a
1759
2217
  // `recover()` blocked in `requestGroupInfo` is settled by exactly two things — a reply or
1760
2218
  // its timeout — and dispose is about to clear that timeout. Skipping this drain would hang
1761
2219
  // the heal, `commitTail`, and every lane operation queued behind it. Resolve, then clear,
1762
- // so a fired timer cannot race a half-drained map. (The ledger gather needs no such drain:
1763
- // its timeout is a local held in none of these maps.)
1764
- for (const waiter of recoveryWaiters.values())waiter(null);
2220
+ // so a fired timer cannot race a half-drained map.
2221
+ for (const waiter of recoveryWaiters.values())waiter({
2222
+ kind: 'disposed'
2223
+ });
1765
2224
  recoveryWaiters.clear();
1766
2225
  for (const timer of recoveryTimers.values())clearTimeout(timer);
1767
2226
  for (const timer of pendingReplies.values())clearTimeout(timer);