@kumiai/rpc 0.9.1 → 0.10.1

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,10 +139,12 @@ 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
  };
147
+ let appNoticeInSerial = false;
144
148
  /**
145
149
  * The peer's app lane: the retained-frame buffer, its durable read position, and the drain. It
146
150
  * reads the anchor back through the accessor below rather than being handed one, since the
@@ -154,14 +158,40 @@ export function createGroupPeer(params) {
154
158
  retentionSeconds: appLogRetentionSeconds,
155
159
  anchor: ()=>anchor,
156
160
  groupID: ()=>commitTopicID,
157
- justifiedEpochCeiling: ()=>justifiedEpochCeiling(),
158
161
  ...appCursorStore != null ? {
159
162
  appCursorStore
160
163
  } : {},
161
164
  ...onAppWindowPruned != null ? {
162
165
  onAppWindowPruned
163
- } : {}
166
+ } : {},
167
+ ...params.onAppDeliveryStalled != null ? {
168
+ onAppDeliveryStalled: (event)=>{
169
+ hostOutbox.push(()=>{
170
+ if (!disposed) notifyHost(params.onAppDeliveryStalled, event);
171
+ });
172
+ }
173
+ } : {},
174
+ ...params.onAppDeliveryResumed != null ? {
175
+ onAppDeliveryResumed: (event)=>{
176
+ const notify = ()=>{
177
+ if (!disposed) notifyHost(params.onAppDeliveryResumed, event);
178
+ };
179
+ if (appNoticeInSerial) hostOutbox.push(notify);
180
+ else queueMicrotask(notify);
181
+ }
182
+ } : {},
183
+ scheduleDelivery: (start)=>{
184
+ hostOutbox.push(start);
185
+ }
164
186
  });
187
+ let sealBarrier;
188
+ let releaseSealBarrier;
189
+ let sealError;
190
+ const finishSealBarrier = ()=>{
191
+ sealBarrier = undefined;
192
+ releaseSealBarrier?.();
193
+ releaseSealBarrier = undefined;
194
+ };
165
195
  /**
166
196
  * Capture the anchor from the port's post-commit handle and persist it. The one place the
167
197
  * anchor is written from the live epoch, and the one place it is saved.
@@ -171,10 +201,14 @@ export function createGroupPeer(params) {
171
201
  * the next roster change rotates it again. Closing it needs the anchor inside the same durable
172
202
  * write as the handle, which this layer cannot reach.
173
203
  */ const captureAnchor = async ()=>{
204
+ // Secret and epoch from one export: a pair from two reads can straddle a handle move.
205
+ const { secret, epoch } = await crypto.exportSecret(APP_TOPIC_LABEL);
174
206
  anchor = {
175
- secret: await crypto.exportSecret(APP_TOPIC_LABEL),
176
- epoch: crypto.epoch()
207
+ secret,
208
+ epoch
177
209
  };
210
+ sealError = undefined;
211
+ finishSealBarrier();
178
212
  await anchorStore?.save(anchor);
179
213
  // The anchor moving IS the segment boundary, so every capture ends the segment the buffer
180
214
  // belongs to. AFTER the assignment above: the lane rebuilds its cursors off the live anchor.
@@ -191,18 +225,69 @@ export function createGroupPeer(params) {
191
225
  */ const openedFrames = new WeakMap();
192
226
  /**
193
227
  * 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").
228
+ * the refusal's locked answer ({@link "crypto".FrameEpochError}), never the epoch hint.
195
229
  * On the open-once failure path ({@link "open-once".OpenOncePathParams.retainOnFailure}) answering
196
230
  * `true` withholds the ack so the frame survives a reconnect. Mailbox-class frames have no staging
197
231
  * of their own (unlike `app-lane.ts`'s `note`/`ahead`), which is what made acking a transient
198
232
  * refusal here a permanent loss.
199
- */ const retainOnFailure = (message)=>{
200
- const at = crypto.frameEpoch(message.payload);
201
- return at != null && at > crypto.epoch();
233
+ */ const retainOnFailure = (_message, error)=>isFrameAhead(error);
234
+ // Live log pushes carry no authoritative bytes or position. One queued journal-first pull
235
+ // covers a burst; a failed pull retries without waiting for another hub delivery.
236
+ let appPullNeeded = false;
237
+ let appPullActive = false;
238
+ let appPullTimer;
239
+ let appPullBackoff = 1000;
240
+ let appPullRetryNow = false;
241
+ const armAppPull = (delay)=>{
242
+ if (disposed || appPullActive || appPullTimer != null) return;
243
+ appPullTimer = setTimeout(()=>{
244
+ appPullTimer = undefined;
245
+ if (disposed) return;
246
+ appPullActive = true;
247
+ appPullNeeded = false;
248
+ let retryDelay = 0;
249
+ void (async ()=>{
250
+ try {
251
+ await ready;
252
+ if (disposed) return;
253
+ await runSerial(async ()=>{
254
+ await replayJournal();
255
+ await ensureLedger(Date.now() + recoveryTimeoutMs);
256
+ await reconcileCommits();
257
+ });
258
+ appPullBackoff = 1000;
259
+ } catch {
260
+ appPullNeeded = true;
261
+ retryDelay = appPullBackoff;
262
+ appPullBackoff = Math.min(appPullBackoff * 2, 60_000);
263
+ } finally{
264
+ appPullActive = false;
265
+ if (appPullNeeded && !disposed) {
266
+ armAppPull(appPullRetryNow ? 0 : retryDelay);
267
+ appPullRetryNow = false;
268
+ }
269
+ }
270
+ })();
271
+ }, delay);
272
+ };
273
+ const requestAppPull = ()=>{
274
+ appPullNeeded = true;
275
+ armAppPull(0);
276
+ };
277
+ const retryAppPull = ()=>{
278
+ if (disposed) return;
279
+ appPullBackoff = 1000;
280
+ appPullNeeded = true;
281
+ if (appPullTimer != null) {
282
+ clearTimeout(appPullTimer);
283
+ appPullTimer = undefined;
284
+ }
285
+ appPullRetryNow = appPullActive;
286
+ armAppPull(0);
202
287
  };
203
288
  /**
204
289
  * 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
290
+ * log position noted once its open settles. Every consumer's own `unwrap` is then a pure lookup of the
206
291
  * opened result ({@link openedFrames}), and nothing downstream touches the handle.
207
292
  *
208
293
  * See {@link createOpenOncePath} for why a lane may only open a frame once.
@@ -210,9 +295,17 @@ export function createGroupPeer(params) {
210
295
  return createOpenOncePath({
211
296
  mux,
212
297
  topicID,
213
- unwrap: (b)=>crypto.unwrap(b, {
214
- expectedAAD: fromUTF(topicID)
215
- }),
298
+ unwrap: (b)=>{
299
+ const hinted = crypto.frameAAD(b);
300
+ const decoded = hinted == null ? null : decodeAppAAD(hinted);
301
+ const intent = decoded?.topicID === topicID ? decoded.intent : 'ephemeral';
302
+ return crypto.unwrap(b, {
303
+ expectedAAD: encodeAppAAD({
304
+ topicID,
305
+ intent
306
+ })
307
+ });
308
+ },
216
309
  retainOnFailure,
217
310
  project: (_message, opened)=>{
218
311
  const { payload, senderDID } = opened;
@@ -227,12 +320,19 @@ export function createGroupPeer(params) {
227
320
  // acceptor, `gather`'s quorum) must see one canonical sender regardless of which DID form
228
321
  // MLS recovered this frame under.
229
322
  openedFrames.set(payload, {
230
- payload,
323
+ ...opened,
231
324
  senderDID: normalizeDID(senderDID)
232
325
  });
233
326
  return payload;
234
327
  },
235
- note: (message)=>appLane.note(name, topicID, message)
328
+ note: (message, failure)=>appLane.note(name, topicID, message, failure),
329
+ wakeup: (message)=>{
330
+ if (crypto.pending == null) return false;
331
+ const aad = crypto.frameAAD(message.payload);
332
+ if (aad == null || decodeAppAAD(aad)?.intent !== 'log') return false;
333
+ requestAppPull();
334
+ return true;
335
+ }
236
336
  });
237
337
  };
238
338
  /**
@@ -271,7 +371,6 @@ export function createGroupPeer(params) {
271
371
  });
272
372
  };
273
373
  const buildEpoch = async ()=>{
274
- epoch = crypto.epoch();
275
374
  const next = new Map();
276
375
  // ONE inbox lane for the whole peer, not one per protocol: the topic does not name a
277
376
  // protocol, so every acceptor and directed client opening its own frames is the defect this
@@ -283,7 +382,10 @@ export function createGroupPeer(params) {
283
382
  mux,
284
383
  topicID: selfInbox,
285
384
  unwrap: (b)=>crypto.unwrap(b, {
286
- expectedAAD: fromUTF(selfInbox)
385
+ expectedAAD: encodeAppAAD({
386
+ topicID: selfInbox,
387
+ intent: 'ephemeral'
388
+ })
287
389
  }),
288
390
  retainOnFailure
289
391
  })
@@ -374,29 +476,23 @@ export function createGroupPeer(params) {
374
476
  throw new AggregateError(reasons, 'Group epoch teardown failed');
375
477
  }
376
478
  };
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)=>{
479
+ /** Wait while an advance can move the handle before its new anchor is captured. */ const sealForSegment = async (name, bytes, intent = 'ephemeral')=>{
393
480
  while(true){
481
+ if (sealError != null) throw sealError;
482
+ if (sealBarrier != null) {
483
+ await sealBarrier;
484
+ continue;
485
+ }
394
486
  const at = anchor;
395
487
  const topicID = protocolTopic(at.secret, at.epoch, name);
396
488
  const payload = await crypto.wrap(bytes, {
397
- aad: fromUTF(topicID)
489
+ aad: encodeAppAAD({
490
+ topicID,
491
+ intent
492
+ })
398
493
  });
399
- if (anchor === at) return {
494
+ if (sealError != null) throw sealError;
495
+ if (anchor === at && sealBarrier == null) return {
400
496
  topicID,
401
497
  payload
402
498
  };
@@ -414,7 +510,10 @@ export function createGroupPeer(params) {
414
510
  const at = anchor;
415
511
  const topicID = inboxTopic(at.secret, at.epoch, recipientDID);
416
512
  const payload = await crypto.wrap(tagged, {
417
- aad: fromUTF(topicID)
513
+ aad: encodeAppAAD({
514
+ topicID,
515
+ intent: 'ephemeral'
516
+ })
418
517
  });
419
518
  if (anchor === at) return {
420
519
  topicID,
@@ -432,8 +531,10 @@ export function createGroupPeer(params) {
432
531
  // lane (retained, pullable); ephemeral events and RPC stay on the live mailbox lane. The
433
532
  // log payload is byte-identical to what the broadcast transport would produce, so online
434
533
  // 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));
534
+ const protocol = protocols[name];
535
+ if (protocol === undefined) throw new Error(`Unknown protocol: ${name}`);
536
+ if (retentionOf(protocol, prc) === 'log') {
537
+ const { topicID, payload } = await sealForSegment(name, encodeEventFrame(prc, data), 'log');
437
538
  await mux.publish({
438
539
  topicID,
439
540
  payload,
@@ -449,7 +550,9 @@ export function createGroupPeer(params) {
449
550
  }),
450
551
  gather: (prc, config)=>runtime.client.gather(prc, config?.param, {
451
552
  quorum: config?.quorum,
452
- timeoutMs: config?.timeoutMs
553
+ timeoutMs: config?.timeoutMs,
554
+ onReply: config?.onReply,
555
+ signal: config?.signal
453
556
  }),
454
557
  to: async (memberDID)=>{
455
558
  // Normalized ONCE, at the ingress: the cache key, the topic derivation and the
@@ -542,9 +645,12 @@ export function createGroupPeer(params) {
542
645
  * The heal trigger, RECORDED and never awaited where found: `recover()` takes the commit mutex,
543
646
  * so a pull that awaited it would wait on a tail including the pull. The trigger only writes
544
647
  * 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.
648
+ * operation. An active recovery absorbs concurrent requests.
546
649
  */ let healRequested = false;
547
- let healing = false;
650
+ let activeRecovery = null;
651
+ let recoveryGeneration = 0;
652
+ let bootstrapHealRequested = false;
653
+ let episode = null;
548
654
  /**
549
655
  * Positive evidence this peer is off the group's line, and the sole guard on `commit()`. Set
550
656
  * when a pull sees proof the peer cannot reconcile: a frame framed AHEAD of its epoch, its OWN
@@ -581,11 +687,41 @@ export function createGroupPeer(params) {
581
687
  * `null` means no rejoin in progress. Survives a failed bootstrap, so a retry filters the same
582
688
  * entries rather than snapshotting an empty ledger.
583
689
  */ let inFlightEntries = null;
690
+ let awaitingBootstrap = null;
691
+ let rejoinAnchorNeedsCapture = false;
692
+ let rejoinRuntimeNeedsBuild = false;
584
693
  /**
585
694
  * Entries a heal decided must be re-enacted, waiting for a lane operation with a return value —
586
695
  * same problem as `lostCommit`. A heal triggered by a pull has nowhere to put them; the host
587
696
  * re-enacts with an ordinary `commit()`.
588
697
  */ let pendingReenact = [];
698
+ let hostOutbox = [];
699
+ const emitStrand = (observation)=>{
700
+ hostOutbox.push(()=>notifyHost(params.onStrand, observation));
701
+ };
702
+ const emitRecovery = (event)=>{
703
+ hostOutbox.push(()=>notifyHost(params.onRecovery, event));
704
+ };
705
+ const observeStrand = (observation)=>{
706
+ bootstrapHealRequested = false;
707
+ if (commitTopicID == null) return;
708
+ if (episode != null && CONFIDENCE_RANK[observation.confidence] <= CONFIDENCE_RANK[episode.strongest]) return;
709
+ episode = {
710
+ strongest: observation.confidence
711
+ };
712
+ emitStrand({
713
+ ...observation,
714
+ groupID: commitTopicID
715
+ });
716
+ };
717
+ const closeEpisode = ()=>{
718
+ episode = null;
719
+ };
720
+ const flushHostOutbox = ()=>{
721
+ const batch = hostOutbox;
722
+ hostOutbox = [];
723
+ for (const notice of batch)notice();
724
+ };
589
725
  /**
590
726
  * The group's commit mutex: every commit-lane operation serialized through one tail. The
591
727
  * compare-and-set resolves races between devices, not two callers here — two `build()` calls
@@ -595,12 +731,23 @@ export function createGroupPeer(params) {
595
731
  * why a loss is RETURNED to the host, never handed to it under the lock.
596
732
  */ let commitTail = Promise.resolve();
597
733
  const runSerial = (fn)=>{
598
- const op = commitTail.then(()=>{
734
+ const op = commitTail.then(async ()=>{
599
735
  journalReplayed = false;
600
- return fn();
736
+ appNoticeInSerial = true;
737
+ try {
738
+ return await fn();
739
+ } finally{
740
+ appNoticeInSerial = false;
741
+ }
601
742
  });
602
743
  commitTail = op.then(()=>{}, ()=>{});
603
- return op;
744
+ return op.then((value)=>{
745
+ flushHostOutbox();
746
+ return value;
747
+ }, (error)=>{
748
+ flushHostOutbox();
749
+ throw error;
750
+ });
604
751
  };
605
752
  /**
606
753
  * Whether the journal has been replayed in the lane operation now running. Cleared when an
@@ -615,12 +762,14 @@ export function createGroupPeer(params) {
615
762
  const recoveryWaiters = new Map();
616
763
  const recoveryTimers = new Map();
617
764
  const pendingReplies = new Map();
765
+ const inFlightBootstraps = new Set();
618
766
  const suppressedRequests = new Set();
619
767
  /**
620
768
  * Ledger-gather waiters, keyed by requestID. Called for EVERY reply, not just the first: a
621
769
  * responder whose ledger fails the head check withheld an entry, so the requester falls through
622
770
  * to the next reply rather than giving up.
623
771
  */ const ledgerWaiters = new Map();
772
+ const ledgerGatherFinishes = new Set();
624
773
  const pendingLedgerReplies = new Set();
625
774
  // Responder: after a jitter delay, answer a recovery request with GroupInfo sealed to the
626
775
  // ephemeral key inside the signed request — unless another responder's reply has already
@@ -679,7 +828,10 @@ export function createGroupPeer(params) {
679
828
  clearTimeout(timer);
680
829
  recoveryTimers.delete(reply.requestID);
681
830
  }
682
- waiter(reply.groupInfo);
831
+ waiter({
832
+ kind: 'reply',
833
+ sealed: reply.groupInfo
834
+ });
683
835
  }
684
836
  };
685
837
  /**
@@ -727,62 +879,6 @@ export function createGroupPeer(params) {
727
879
  ledgerWaiters.get(reply.requestID)?.(reply.sealed);
728
880
  };
729
881
  /**
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
882
  * THE ONE PATH THE HANDLE RATCHETS ON, and the invariant it holds: a handle does not ratchet
787
883
  * past an epoch until that epoch's frames are read and its anchor is taken. Both are one-way
788
884
  * doors — after the advance those frames are ciphertext forever, and that epoch's secret can
@@ -801,7 +897,7 @@ export function createGroupPeer(params) {
801
897
  *
802
898
  * The anchor is captured from the port's POST-advance handle — the epoch every member lands on
803
899
  * by making this same advance — which is what makes it agreed rather than local.
804
- */ const advanceHandle = async (port, advance, rotatesAnyway = ()=>false)=>{
900
+ */ const advanceHandle = async (port, advance, rotatesAnyway = ()=>false, appliedEpochs)=>{
805
901
  // Read this epoch's app frames BEFORE the advance that leaves it — the last moment they can
806
902
  // be read, since the advance ratchets the handle on and takes this epoch's key material with
807
903
  // it. Per frame-epoch, not per rotation: a segment spanning five epochs is dispensed five
@@ -809,26 +905,40 @@ export function createGroupPeer(params) {
809
905
  await appLane.deliver();
810
906
  // Normalized at this ingress so an MLS-recovered form flip between the two reads (never a
811
907
  // 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();
908
+ const rosterBefore = (await port.rosterEntries()).map((e)=>normalizeDID(e.did));
909
+ const epochBefore = await port.readEpoch();
910
+ sealBarrier = new Promise((resolve)=>{
911
+ releaseSealBarrier = resolve;
912
+ });
913
+ try {
914
+ const advanced = await advance();
915
+ const epochs = appliedEpochs?.(advanced);
916
+ const actualBefore = epochs?.epochBefore ?? epochBefore;
917
+ const epochAfter = epochs?.epochAfter ?? await port.readEpoch();
918
+ // GATED ON THE HANDLE ACTUALLY RATCHETING: a roster diff alone is not evidence that it did. A
919
+ // commit that REMOVES this member does not advance its handle (there is no epoch to move to,
920
+ // since the commit's path excludes the dropped leaf), yet real MLS still applies proposals to
921
+ // the tree — so the roster comes back WITHOUT this member at an epoch that did not move.
922
+ // (Measured against ts-mls: `processMessage` returns without throwing, epoch stays,
923
+ // `listMembers()` has lost the leaf.) Undiscriminated, that reads as a rotation.
924
+ //
925
+ // An ungated capture would clear the segment buffer while the handle still holds its epoch,
926
+ // dropping frames that can still be opened.
927
+ const ratcheted = epochAfter !== actualBefore;
928
+ if (ratcheted && (detectRosterChange(rosterBefore, (await port.rosterEntries()).map((e)=>normalizeDID(e.did))) || rotatesAnyway(advanced))) {
929
+ await captureAnchor();
930
+ }
931
+ return advanced;
932
+ } catch (error) {
933
+ if (await port.readEpoch() !== epochBefore && sealBarrier != null) {
934
+ sealError = new Error('app anchor unavailable after failed epoch advance', {
935
+ cause: error
936
+ });
937
+ }
938
+ throw error;
939
+ } finally{
940
+ finishSealBarrier();
830
941
  }
831
- return advanced;
832
942
  };
833
943
  /**
834
944
  * Read the commit log forward from the cursor, classify every frame, advance the cursor over
@@ -855,6 +965,7 @@ export function createGroupPeer(params) {
855
965
  commitLogHead = head == null ? null : asLogPosition(head);
856
966
  };
857
967
  while(true){
968
+ const pageAfter = reconciledHead;
858
969
  const result = await mux.fetchTopic({
859
970
  topicID,
860
971
  // From the cursor. With no cursor (fresh member, trimmed backlog, just rejoined) read
@@ -864,6 +975,10 @@ export function createGroupPeer(params) {
864
975
  } : {},
865
976
  limit: COMMIT_FETCH_LIMIT
866
977
  });
978
+ // A short page may carry a one-shot fork reveal below the cursor. Only a full page loops.
979
+ if (result.messages.length === COMMIT_FETCH_LIMIT) {
980
+ assertForwardPage(pageAfter, result.messages);
981
+ }
867
982
  if (result.messages.length === 0) {
868
983
  // Drained. The tip an EMPTY page reports is not redundant: a topic keeps its head when
869
984
  // its frames age out, so anchoring on the cursor here would compare-and-set against
@@ -889,13 +1004,14 @@ export function createGroupPeer(params) {
889
1004
  if (frame.version !== HANDSHAKE_VERSION) {
890
1005
  // No digest: the frame's version put its commit bytes out of reach entirely. Settled at
891
1006
  // `ahead` before the digest is read.
1007
+ const localEpoch = await port.readEpoch();
892
1008
  const unreadable = classifyCommit({
893
1009
  header: UNKNOWN_FRAME_VERSION,
894
1010
  sequenceID: position,
895
1011
  commitDigest: null,
896
1012
  state: {
897
1013
  localDID,
898
- epoch: crypto.epoch(),
1014
+ epoch: localEpoch,
899
1015
  appliedByEpoch
900
1016
  }
901
1017
  });
@@ -905,6 +1021,14 @@ export function createGroupPeer(params) {
905
1021
  if (unreadable.row === 'ahead') {
906
1022
  healRequested = true;
907
1023
  stranded = true;
1024
+ observeStrand({
1025
+ position,
1026
+ commitDigest: null,
1027
+ localEpoch,
1028
+ claimedEpoch: null,
1029
+ kind: 'unknown-version',
1030
+ confidence: 'claimed'
1031
+ });
908
1032
  }
909
1033
  continue;
910
1034
  }
@@ -923,13 +1047,14 @@ export function createGroupPeer(params) {
923
1047
  // version fails BEFORE the commit bytes are extracted, so there is no next frame to
924
1048
  // heal from — dropping it would step over the group's whole future. To the classifier.
925
1049
  if (isUnsupportedCommitFrameVersion(error)) {
1050
+ const localEpoch = await port.readEpoch();
926
1051
  const unreadable = classifyCommit({
927
1052
  header: UNKNOWN_FRAME_VERSION,
928
1053
  sequenceID: position,
929
1054
  commitDigest: null,
930
1055
  state: {
931
1056
  localDID,
932
- epoch: crypto.epoch(),
1057
+ epoch: localEpoch,
933
1058
  appliedByEpoch
934
1059
  }
935
1060
  });
@@ -938,6 +1063,14 @@ export function createGroupPeer(params) {
938
1063
  if (unreadable.row === 'ahead') {
939
1064
  healRequested = true;
940
1065
  stranded = true;
1066
+ observeStrand({
1067
+ position,
1068
+ commitDigest: null,
1069
+ localEpoch,
1070
+ claimedEpoch: null,
1071
+ kind: 'unknown-version',
1072
+ confidence: 'claimed'
1073
+ });
941
1074
  }
942
1075
  continue;
943
1076
  }
@@ -954,111 +1087,144 @@ export function createGroupPeer(params) {
954
1087
  // `message.senderDID` — the hub's word about who handed it over, and the hub is not
955
1088
  // trusted: it could stamp every recipient's own DID onto one poison frame and make the
956
1089
  // 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
1090
+ let localEpoch = await port.readEpoch();
1091
+ while(true){
1092
+ const readHeader = await port.readCommitHeader(commitFrame.commit);
1093
+ // Normalized before `classifyCommit` compares it against `state.localDID` (also
1094
+ // normalized, at construction) — an own-unmerged commit authenticated under a different
1095
+ // form of this member's own DID must still be recognized as its own.
1096
+ const header = readHeader?.committerDID != null ? {
1097
+ ...readHeader,
1098
+ committerDID: normalizeDID(readHeader.committerDID)
1099
+ } : readHeader;
1100
+ const disposition = classifyCommit({
1101
+ header,
1102
+ sequenceID: position,
1103
+ commitDigest,
1104
+ state: {
1105
+ localDID,
1106
+ epoch: localEpoch,
1107
+ appliedByEpoch
1108
+ }
1109
+ });
1110
+ if (disposition.row === 'own-unmerged') {
1111
+ // Sender data names this peer at its current epoch, but neither commit content nor hub
1112
+ // acceptance is verified. The peer cannot process its own commit without pending state,
1113
+ // so the drain stops here and it heals.
1114
+ healRequested = true;
1115
+ stranded = true;
1116
+ observeStrand({
1117
+ position,
1118
+ commitDigest,
1119
+ localEpoch,
1120
+ claimedEpoch: header?.epoch ?? null,
1121
+ kind: 'own-unmerged',
1122
+ confidence: 'authenticated'
1123
+ });
1124
+ return advancedEpoch;
973
1125
  }
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') {
1126
+ if (disposition.row === 'ahead') {
1127
+ // The group advanced at an epoch this peer did not. Step over the frame — the heal
1128
+ // repairs this, not a re-read — and ask for one.
1129
+ reconciledHead = position;
1003
1130
  healRequested = true;
1004
1131
  stranded = true;
1132
+ observeStrand({
1133
+ position,
1134
+ commitDigest,
1135
+ localEpoch,
1136
+ claimedEpoch: header?.epoch ?? null,
1137
+ kind: 'ahead',
1138
+ confidence: 'claimed'
1139
+ });
1140
+ break;
1005
1141
  }
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)
1142
+ if (disposition.row === 'history') {
1143
+ // A frame from an epoch below this peer's, with no record for it or a record naming
1144
+ // this same commit. Not a fork, not poison, not the port's business — its blob is never
1145
+ // touched.
1146
+ reconciledHead = position;
1147
+ break;
1148
+ }
1149
+ if (disposition.row === 'fork') {
1150
+ // Two commits at one epoch. The lower-sequenceID branch wins; the loser rejoins onto it
1151
+ // (a heal). The winner just steps over the frame.
1152
+ reconciledHead = position;
1153
+ if (disposition.branch === 'losing') {
1154
+ healRequested = true;
1155
+ stranded = true;
1156
+ observeStrand({
1157
+ position,
1158
+ commitDigest,
1159
+ localEpoch,
1160
+ claimedEpoch: header?.epoch ?? null,
1161
+ kind: 'fork-losing',
1162
+ confidence: 'observed'
1163
+ });
1164
+ }
1165
+ break;
1166
+ }
1167
+ if (disposition.row === 'poison') {
1168
+ reconciledHead = position; // not a commit at all: stepped over, and never retried
1169
+ break;
1170
+ }
1171
+ // Framed at this peer's epoch, by somebody else: a frame it can apply. Everything below is
1172
+ // the port's answer to it.
1173
+ const framedEpoch = localEpoch;
1174
+ let applied;
1175
+ try {
1176
+ // Through the seam, like every other site that ratchets the handle: it reads this
1177
+ // epoch's app frames ahead of the apply and takes the anchor if the roster moved.
1178
+ applied = await advanceHandle(port, ()=>{
1179
+ return port.processCommit(commitFrame.commit, {
1180
+ senderDID: message.senderDID,
1181
+ // The resolver, not the bodies: the blob opens only if the port asks for entries
1182
+ // this commit names, and only for a commit it applies — framed at this peer's
1183
+ // epoch, the epoch the blob is sealed under, making body delivery atomic with the
1184
+ // commit. Called from INSIDE the apply, so the open must not touch the handle's
1185
+ // ratchet: `openEntries` reads only the epoch's exporter secret and is pure.
1186
+ resolveLedgerEntries: createLedgerEntryResolver(commitFrame.sealedEntries, crypto.openEntries)
1187
+ });
1188
+ }, // A REJOIN rotates the anchor too, from a member the roster diff cannot see: an
1189
+ // external commit by a member the roster still holds leaves every DID where it was.
1190
+ // Only an APPLIED commit says anything about the group.
1191
+ (result)=>result.advanced && header?.external === true, (result)=>result);
1192
+ } catch (error) {
1193
+ if (!isMissingLedgerEntries(error)) {
1194
+ // The port broke its contract. The cursor stays and the frame is re-read — the pull is
1195
+ // a retry, and this is not an outcome it can name.
1196
+ throw error;
1197
+ }
1198
+ // The commit names ledger entries whose bodies will not resolve. POISON: drop, advance,
1199
+ // do NOT heal. The bodies ride the commit sealed under its framed epoch, so a blob this
1200
+ // peer cannot open is one no member at this epoch can — nobody applies it, and the next
1201
+ // honest commit is framed at the same epoch and compare-and-sets behind it.
1202
+ //
1203
+ // Healing here would hand any member a group-wide recovery storm for one publish.
1204
+ // Retrying only delays that. The one case where this peer really is the broken one
1205
+ // announces itself later: the next commit is then framed AHEAD of this peer's, which
1206
+ // heals it.
1207
+ reconciledHead = position;
1208
+ break;
1209
+ }
1210
+ if (!applied.advanced && applied.epochBefore !== framedEpoch) {
1211
+ advancedEpoch = true;
1212
+ localEpoch = applied.epochBefore;
1213
+ continue;
1214
+ }
1215
+ if (applied.advanced) {
1216
+ advancedEpoch = true;
1217
+ // The fork check's record; the only place it is written from the log.
1218
+ appliedByEpoch.set(framedEpoch, {
1219
+ sequenceID: position,
1220
+ digest: commitDigest
1028
1221
  });
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
1222
  }
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.
1223
+ // `{ advanced: false }` here is the port REFUSING a well-formed commit at this peer's own
1224
+ // epoch from another member: poison on the same terms as an unresolvable one.
1048
1225
  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
- });
1226
+ break;
1058
1227
  }
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
1228
  }
1063
1229
  // A short page ends the log: every frame this reply named is processed, so its tip is
1064
1230
  // reconciled. A full page is not — loop and take the head from the reply that finally drains.
@@ -1080,9 +1246,28 @@ export function createGroupPeer(params) {
1080
1246
  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
1247
  }
1082
1248
  if (mls == null || commitTopicID == null) return false;
1083
- const advanced = await walkCommits(mls, commitTopicID);
1084
- await appLane.deliver();
1085
- return advanced;
1249
+ const epochBefore = await mls.readEpoch();
1250
+ const anchorBefore = anchor;
1251
+ try {
1252
+ const advanced = await walkCommits(mls, commitTopicID);
1253
+ await appLane.deliver();
1254
+ return advanced;
1255
+ } catch (error) {
1256
+ // A failed final drain can follow applied commits. Refresh the runtime before a retry.
1257
+ if (inboxLane != null && (await mls.readEpoch() !== epochBefore || anchor !== anchorBefore)) {
1258
+ try {
1259
+ await rebuildEpoch();
1260
+ } catch {
1261
+ // The walk's original failure remains the retryable cause.
1262
+ }
1263
+ }
1264
+ if (crypto.pending != null && !appPullActive) {
1265
+ appPullNeeded = true;
1266
+ armAppPull(appPullBackoff);
1267
+ appPullBackoff = Math.min(appPullBackoff * 2, 60_000);
1268
+ }
1269
+ throw error;
1270
+ }
1086
1271
  };
1087
1272
  /** Pull the commit log, and rebuild the app lane if the pull moved the epoch. */ const reconcileCommits = async ()=>{
1088
1273
  const advanced = await pullCommits();
@@ -1104,7 +1289,9 @@ export function createGroupPeer(params) {
1104
1289
  // A wakeup is a lane operation: step 0, the ledger invariant, then the pull. No return
1105
1290
  // value, so anything found is stashed for the next call that has one.
1106
1291
  const replayed = await replayJournal();
1107
- await ensureLedger(Date.now() + recoveryTimeoutMs);
1292
+ if (mls != null && await ensureLedger(Date.now() + recoveryTimeoutMs)) {
1293
+ await finalizeBootstrap(mls);
1294
+ }
1108
1295
  const pulled = await pullCommits();
1109
1296
  if (replayed || pulled) await rebuildEpoch();
1110
1297
  }).catch(()=>{
@@ -1164,7 +1351,7 @@ export function createGroupPeer(params) {
1164
1351
  // A peer restored with an incomplete ledger was killed between rejoining and bootstrapping.
1165
1352
  // The invariant finds it here and at every later lane operation, with no memory of how it
1166
1353
  // got there.
1167
- await ensureLedger(Date.now() + recoveryTimeoutMs);
1354
+ if (await ensureLedger(Date.now() + recoveryTimeoutMs)) await finalizeBootstrap(mls);
1168
1355
  await pullCommits();
1169
1356
  }).catch(()=>{
1170
1357
  // a failed seed leaves the cursor put; the next wakeup replays and pulls again
@@ -1175,13 +1362,16 @@ export function createGroupPeer(params) {
1175
1362
  * from the epoch the commit is FRAMED at — the epoch every member that can apply it is at, and
1176
1363
  * the one this group stays at until the commit is adopted. A host that adopted first has rotated
1177
1364
  * 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) {
1365
+ * open. `framedAt` is null for an external commit, framed at the group's epoch, not this handle's.
1366
+ */ const frameCommit = async (commit, bodies, framedAt)=>{
1367
+ const { sealed: sealedEntries, epoch } = await crypto.sealEntries(encodeLedgerEntries(bodies));
1368
+ if (framedAt != null && epoch !== framedAt) {
1181
1369
  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
1370
  }
1183
- const sealedEntries = await crypto.sealEntries(encodeLedgerEntries(bodies));
1184
- return encodeHandshakeFrame(HANDSHAKE_KIND.commit, encodeCommitFrame(commit, sealedEntries));
1371
+ return {
1372
+ payload: encodeHandshakeFrame(HANDSHAKE_KIND.commit, encodeCommitFrame(commit, sealedEntries)),
1373
+ epoch
1374
+ };
1185
1375
  };
1186
1376
  /**
1187
1377
  * Step 0 of every lane operation, strictly ahead of the pull. Settle any journalled commit:
@@ -1220,10 +1410,11 @@ export function createGroupPeer(params) {
1220
1410
  // Republishing means RE-SEALING the bodies, sealable only under the host's current epoch —
1221
1411
  // which equals the framed epoch only while `onAccepted` is the sole place the host adopts.
1222
1412
  // 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.`);
1413
+ const handleEpoch = await mls.readEpoch();
1414
+ if (handleEpoch !== entry.epoch) {
1415
+ 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
1416
  }
1226
- const payload = await frameCommit(entry.commit, entry.bodies);
1417
+ const { payload } = await frameCommit(entry.commit, entry.bodies, entry.epoch);
1227
1418
  let sequenceID;
1228
1419
  try {
1229
1420
  sequenceID = (await mux.publish({
@@ -1290,6 +1481,49 @@ export function createGroupPeer(params) {
1290
1481
  } : {}
1291
1482
  };
1292
1483
  };
1484
+ const repairRejoin = async ()=>{
1485
+ if (awaitingBootstrap == null) return;
1486
+ // Restore the subscription before gathering the ledger: responders may already have
1487
+ // rotated to the new app anchor. A failed repair remains pending for the next lane call.
1488
+ if (rejoinAnchorNeedsCapture) {
1489
+ await captureAnchor();
1490
+ rejoinAnchorNeedsCapture = false;
1491
+ }
1492
+ if (rejoinRuntimeNeedsBuild) {
1493
+ await rebuildEpoch();
1494
+ rejoinRuntimeNeedsBuild = false;
1495
+ }
1496
+ };
1497
+ const finalizeBootstrap = async (port)=>{
1498
+ assertLive();
1499
+ if (awaitingBootstrap == null) return;
1500
+ const { attemptID, trigger, entries } = awaitingBootstrap;
1501
+ await repairRejoin();
1502
+ assertLive();
1503
+ const held = new Set(await port.getLedger());
1504
+ assertLive();
1505
+ const owed = entries.filter((token)=>!held.has(token));
1506
+ if (owed.length > 0) pendingReenact = [
1507
+ ...pendingReenact,
1508
+ ...owed
1509
+ ];
1510
+ awaitingBootstrap = null;
1511
+ inFlightEntries = null;
1512
+ if (bootstrapHealRequested) {
1513
+ healRequested = false;
1514
+ bootstrapHealRequested = false;
1515
+ }
1516
+ recoveryGeneration += 1;
1517
+ closeEpisode();
1518
+ if (commitTopicID != null) {
1519
+ emitRecovery({
1520
+ phase: 'bootstrapped',
1521
+ groupID: commitTopicID,
1522
+ attemptID,
1523
+ trigger
1524
+ });
1525
+ }
1526
+ };
1293
1527
  /**
1294
1528
  * The ledger completeness invariant, checked before every lane operation and repaired on the
1295
1529
  * spot. Purely local (the head folded from the handle's entries against the authenticated head
@@ -1305,6 +1539,7 @@ export function createGroupPeer(params) {
1305
1539
  * retryable, degraded state, not an error the host can act on.
1306
1540
  */ const ensureLedger = async (deadline)=>{
1307
1541
  if (mls == null || rendezvousTopicID == null) return true;
1542
+ await repairRejoin();
1308
1543
  const port = mls;
1309
1544
  const topicID = rendezvousTopicID;
1310
1545
  if (await port.isLedgerComplete()) return true;
@@ -1319,16 +1554,27 @@ export function createGroupPeer(params) {
1319
1554
  // for one publish; without the second, so does the hub.
1320
1555
  const requestID = newPublishID();
1321
1556
  const request = await port.createRecoveryRequest(requestID);
1557
+ if (disposed) return false;
1322
1558
  return await new Promise((resolve)=>{
1323
1559
  let settled = false;
1560
+ const bootstraps = new Set();
1324
1561
  const finish = (complete)=>{
1325
1562
  if (settled) return;
1326
1563
  settled = true;
1327
1564
  ledgerWaiters.delete(requestID);
1565
+ ledgerGatherFinishes.delete(finishOnDispose);
1328
1566
  clearTimeout(timer);
1329
- resolve(complete);
1567
+ // Keep the lane until every bootstrap already touching this handle has finished.
1568
+ if (bootstraps.size === 0) resolve(complete && !disposed);
1569
+ else void Promise.allSettled([
1570
+ ...bootstraps
1571
+ ]).then((results)=>{
1572
+ resolve(!disposed && (complete || results.some((result)=>result.status === 'fulfilled')));
1573
+ });
1330
1574
  };
1575
+ const finishOnDispose = ()=>finish(false);
1331
1576
  const timer = setTimeout(()=>finish(false), Math.max(0, deadline - Date.now()));
1577
+ ledgerGatherFinishes.add(finishOnDispose);
1332
1578
  ledgerWaiters.set(requestID, (sealed)=>{
1333
1579
  void (async ()=>{
1334
1580
  if (settled || disposed) return;
@@ -1338,10 +1584,17 @@ export function createGroupPeer(params) {
1338
1584
  // here, since the next responder's reply is sealed to the same key.
1339
1585
  const tokens = await port.openSealedLedger(sealed, requestID);
1340
1586
  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);
1587
+ // Timeout or disposal can settle the gather while opening the reply.
1588
+ if (settled || disposed) return;
1589
+ const bootstrap = port.bootstrapLedger(tokens);
1590
+ bootstraps.add(bootstrap);
1591
+ inFlightBootstraps.add(bootstrap);
1592
+ try {
1593
+ await bootstrap;
1594
+ } finally{
1595
+ bootstraps.delete(bootstrap);
1596
+ inFlightBootstraps.delete(bootstrap);
1597
+ }
1345
1598
  finish(true);
1346
1599
  } catch {
1347
1600
  // Recomputed head does not match the authenticated one: this responder withheld,
@@ -1382,6 +1635,7 @@ export function createGroupPeer(params) {
1382
1635
  if (!await ensureLedger(Date.now() + recoveryTimeoutMs)) {
1383
1636
  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
1637
  }
1638
+ await finalizeBootstrap(mls);
1385
1639
  const deadline = Date.now() + commitDeadlineMs;
1386
1640
  for(let attempt = 0; attempt < COMMIT_ATTEMPT_CEILING; attempt++){
1387
1641
  // 1. Pull the log to the end: every frame processed, and the tip to race at learned from
@@ -1405,8 +1659,7 @@ export function createGroupPeer(params) {
1405
1659
  // which need not be one the head can ever name.
1406
1660
  const publishID = newPublishID();
1407
1661
  const expectedHead = commitLogHead;
1408
- const framedEpoch = crypto.epoch();
1409
- const payload = await frameCommit(pending.commit, pending.bodies);
1662
+ const { payload, epoch: framedEpoch } = await frameCommit(pending.commit, pending.bodies, crypto.frameEpoch(pending.commit));
1410
1663
  await slot.put({
1411
1664
  publishID,
1412
1665
  expectedHead,
@@ -1485,25 +1738,42 @@ export function createGroupPeer(params) {
1485
1738
  assertLive();
1486
1739
  return runSerial(async ()=>{
1487
1740
  if (await replayJournal()) await rebuildEpoch();
1488
- await ensureLedger(Date.now() + recoveryTimeoutMs);
1741
+ if (mls != null && await ensureLedger(Date.now() + recoveryTimeoutMs)) {
1742
+ await finalizeBootstrap(mls);
1743
+ }
1744
+ assertLive();
1489
1745
  return takeLost();
1490
1746
  });
1491
1747
  };
1492
1748
  /**
1493
1749
  * 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.
1750
+ * The outcome distinguishes a silent responder, disposal and a failed request publish.
1495
1751
  */ const requestGroupInfo = async (request, requestID, topicID, deadline)=>{
1496
- const wait = Math.max(0, Math.min(recoveryTimeoutMs, deadline - Date.now()));
1752
+ const remaining = deadline - Date.now();
1753
+ const wait = Math.max(0, Math.min(recoveryTimeoutMs, remaining));
1754
+ const atDeadline = remaining <= recoveryTimeoutMs;
1497
1755
  return await new Promise((resolve)=>{
1498
1756
  recoveryWaiters.set(requestID, resolve);
1499
1757
  recoveryTimers.set(requestID, setTimeout(()=>{
1500
1758
  recoveryTimers.delete(requestID);
1501
- if (recoveryWaiters.delete(requestID)) resolve(null);
1759
+ if (recoveryWaiters.delete(requestID)) resolve({
1760
+ kind: 'timeout',
1761
+ atDeadline
1762
+ });
1502
1763
  }, wait));
1503
1764
  void Promise.resolve(mux.publish({
1504
1765
  topicID,
1505
1766
  payload: encodeHandshakeFrame(HANDSHAKE_KIND.recoveryRequest, encodeRecoveryRequest(requestID, request))
1506
- })).catch(()=>{});
1767
+ })).catch((error)=>{
1768
+ if (!recoveryWaiters.delete(requestID)) return;
1769
+ const timer = recoveryTimers.get(requestID);
1770
+ if (timer != null) clearTimeout(timer);
1771
+ recoveryTimers.delete(requestID);
1772
+ resolve({
1773
+ kind: 'publish-failed',
1774
+ error
1775
+ });
1776
+ });
1507
1777
  });
1508
1778
  };
1509
1779
  /**
@@ -1528,22 +1798,40 @@ export function createGroupPeer(params) {
1528
1798
  * own. NEVER calls `commit()` and `commit()` never calls it — both take the same non-reentrant
1529
1799
  * mutex, so either nesting deadlocks. The re-enactment a heal owes is a SUBSEQUENT `commit()` the
1530
1800
  * host makes once this releases the lane.
1531
- */ const recover = async ()=>{
1532
- await ready;
1801
+ */ const attemptBody = async (trigger, generation, port, commits, rendezvous)=>{
1533
1802
  assertLive();
1534
- if (mls == null || commitTopicID == null || rendezvousTopicID == null) {
1803
+ if (recoveryGeneration !== generation && !stranded && !healRequested) {
1535
1804
  return {
1536
- advanced: false,
1537
- reenact: []
1805
+ advanced: true
1538
1806
  };
1539
1807
  }
1540
- const port = mls;
1541
- const commits = commitTopicID;
1542
- const rendezvous = rendezvousTopicID;
1543
- return runSerial(async ()=>{
1808
+ const attemptID = newPublishID();
1809
+ const base = {
1810
+ groupID: commits,
1811
+ attemptID,
1812
+ trigger
1813
+ };
1814
+ queueMicrotask(()=>notifyHost(params.onRecovery, {
1815
+ ...base,
1816
+ phase: 'started'
1817
+ }));
1818
+ const failed = (reason)=>{
1819
+ emitRecovery({
1820
+ ...base,
1821
+ phase: 'failed',
1822
+ reason
1823
+ });
1824
+ return {
1825
+ advanced: false
1826
+ };
1827
+ };
1828
+ try {
1544
1829
  // 0. Replay the journal ahead of everything, as every lane operation does: a peer holding a
1545
1830
  // commit whose fate it never learned settles that first, and may find nothing left to heal.
1546
1831
  if (await replayJournal()) await rebuildEpoch();
1832
+ assertLive();
1833
+ if (await ensureLedger(Date.now() + recoveryTimeoutMs)) await finalizeBootstrap(port);
1834
+ assertLive();
1547
1835
  const deadline = Date.now() + recoveryDeadlineMs;
1548
1836
  while(Date.now() < deadline){
1549
1837
  // 1. Pull to the end. It may resolve the strand outright, and a heal it no longer needs
@@ -1552,34 +1840,49 @@ export function createGroupPeer(params) {
1552
1840
  // applies the winner's commit HERE.
1553
1841
  healRequested = false;
1554
1842
  await reconcileCommits();
1843
+ assertLive();
1555
1844
  // 2. The head to race at, from the store's own reply.
1556
1845
  const expectedHead = await readCommitHead(commits);
1846
+ assertLive();
1557
1847
  // 3. Mint a request and rendezvous for a sealed GroupInfo. Fresh request per attempt: the
1558
1848
  // ephemeral key is minted with it, and a reply to an already-used request is unopenable.
1559
1849
  const requestID = newPublishID();
1560
1850
  const request = await port.createRecoveryRequest(requestID);
1561
- const sealed = await requestGroupInfo(request, requestID, rendezvous, deadline);
1562
- if (sealed == null) {
1563
- break;
1851
+ assertLive();
1852
+ const outcome = await requestGroupInfo(request, requestID, rendezvous, deadline);
1853
+ if (outcome.kind === 'disposed' || disposed) throw new PeerDisposedError('Peer is disposed');
1854
+ if (outcome.kind === 'publish-failed') throw outcome.error;
1855
+ if (outcome.kind === 'timeout') {
1856
+ // Nobody answered. Heal REQUIRES another online member that can seal a GroupInfo;
1857
+ // without one it cannot work. The peer stays degraded and asks again later.
1858
+ return failed(outcome.atDeadline ? 'deadline' : 'no-responder');
1564
1859
  }
1565
1860
  // 4. Open it and BUILD the external commit, adopting nothing. Bytes this peer cannot open
1566
1861
  // are a hub-injected or misaddressed reply: ask again.
1567
1862
  let pending;
1568
1863
  try {
1569
- pending = await port.applyRecovery(sealed, requestID);
1864
+ pending = await port.applyRecovery(outcome.sealed, requestID);
1570
1865
  } catch {
1571
1866
  pending = null;
1572
1867
  }
1868
+ assertLive();
1573
1869
  if (pending == null) continue;
1574
1870
  // 5. The entries this peer holds, snapshotted BEFORE the rejoined handle replaces them —
1575
1871
  // the last moment they can be read. Kept across a failed attempt, so a retry filters
1576
1872
  // the same entries rather than snapshotting the empty ledger a failed bootstrap left.
1577
- if (inFlightEntries == null) inFlightEntries = await port.getLedger();
1873
+ inFlightEntries = [
1874
+ ...new Set([
1875
+ ...inFlightEntries ?? awaitingBootstrap?.entries ?? [],
1876
+ ...await port.getLedger()
1877
+ ])
1878
+ ];
1879
+ assertLive();
1578
1880
  const inFlight = inFlightEntries;
1579
1881
  // 6. Publish the external commit, compare-and-set at the head: it changes the ratchet
1580
1882
  // tree, so it races like any commit.
1581
1883
  const publishID = newPublishID();
1582
- const payload = await frameCommit(pending.commit, []);
1884
+ const { payload } = await frameCommit(pending.commit, [], null);
1885
+ assertLive();
1583
1886
  let sequenceID;
1584
1887
  try {
1585
1888
  sequenceID = (await mux.publish({
@@ -1590,65 +1893,161 @@ export function createGroupPeer(params) {
1590
1893
  publishID
1591
1894
  })).sequenceID;
1592
1895
  } catch (error) {
1896
+ if (disposed) throw new PeerDisposedError('Peer is disposed', {
1897
+ cause: error
1898
+ });
1593
1899
  if (!isHeadMismatch(error)) throw error;
1594
1900
  continue;
1595
1901
  }
1902
+ assertLive();
1596
1903
  // 7. Accepted: the group has this peer's new leaf. Adopt the rejoined handle — the only
1597
1904
  // place it may be adopted. Deliberately UNJOURNALLED: a crash here leaves an orphaned
1598
1905
  // external commit that repairs itself — framed at the group's epoch, not this peer's,
1599
1906
  // so the own-commit trigger stays quiet, the heal condition still holds, and `resync`
1600
1907
  // later collects the leaf the orphan added.
1601
1908
  const rejoinedAtEpoch = (await port.readCommitHeader(pending.commit))?.epoch;
1909
+ assertLive();
1910
+ const epochBeforeRejoin = await port.readEpoch();
1602
1911
  // Through the seam, like every other site that ratchets the handle — and it rotates
1603
1912
  // ANYWAY: this is the rejoin, which no roster diff can see (see {@link anchor}). The
1604
1913
  // anchor is the POST-commit epoch: the handle advances inside the seam and only then is
1605
1914
  // the anchor captured, exactly where an applying member lands.
1606
- await advanceHandle(port, ()=>pending.onAccepted(), ()=>true);
1915
+ await advanceHandle(port, async ()=>{
1916
+ try {
1917
+ await pending.onAccepted();
1918
+ } finally{
1919
+ // The adapter may adopt the handle and then fail to persist it. Observe the
1920
+ // ratchet itself: a pre-adoption failure leaves this snapshot with the retry.
1921
+ if (await port.readEpoch() !== epochBeforeRejoin) {
1922
+ awaitingBootstrap = {
1923
+ attemptID,
1924
+ trigger,
1925
+ entries: inFlight
1926
+ };
1927
+ // Adoption enacted these bytes even if persistence rejected afterward.
1928
+ if (rejoinedAtEpoch != null) {
1929
+ appliedByEpoch.set(rejoinedAtEpoch, {
1930
+ sequenceID,
1931
+ digest: digestAppliedCommit(pending.commit)
1932
+ });
1933
+ }
1934
+ stranded = false;
1935
+ rejoinAnchorNeedsCapture = true;
1936
+ rejoinRuntimeNeedsBuild = true;
1937
+ }
1938
+ }
1939
+ }, ()=>true);
1940
+ rejoinAnchorNeedsCapture = false;
1941
+ assertLive();
1607
1942
  const accepted = asLogPosition(sequenceID);
1608
1943
  reconciledHead = accepted;
1609
1944
  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
1945
  healRequested = false;
1619
1946
  // The one place the commit gate is released: the rejoin landed, so this peer's leaf is
1620
1947
  // back in the tree and the stale-epoch fork it guards is closed. A bootstrap that still
1621
1948
  // fails below is `commit()`'s own ledger-completeness check to handle.
1622
- stranded = false;
1623
1949
  await rebuildEpoch();
1950
+ rejoinRuntimeNeedsBuild = false;
1951
+ assertLive();
1624
1952
  // 8. Bootstrap: REQUIRED, not a formality. Until it runs, the ledger is empty against a
1625
1953
  // live head — every admin promoted since genesis is invisible and the next commit is
1626
1954
  // rejected. Failure here is a persistent degraded state, NOT a heal.
1627
1955
  if (!await ensureLedger(deadline)) {
1628
- healRequested = true;
1629
- return {
1630
- advanced: false,
1631
- reenact: []
1956
+ assertLive();
1957
+ awaitingBootstrap = {
1958
+ attemptID,
1959
+ trigger,
1960
+ entries: inFlight
1632
1961
  };
1962
+ healRequested = true;
1963
+ bootstrapHealRequested = true;
1964
+ return failed('bootstrap-failed');
1633
1965
  }
1966
+ assertLive();
1634
1967
  // 9. Re-enact by MEMBERSHIP, never by the failure that brought this peer here: keep only
1635
1968
  // entries the group's ledger does NOT hold. An entry it DOES hold was enacted for
1636
1969
  // everyone, and appending it again puts it at the END of the log where the fold is
1637
1970
  // last-write-wins — it would win, silently reverting whatever a later admin wrote over
1638
1971
  // the same subject.
1639
1972
  const held = new Set(await port.getLedger());
1973
+ assertLive();
1640
1974
  const reenact = inFlight.filter((token)=>!held.has(token));
1641
1975
  inFlightEntries = null;
1976
+ awaitingBootstrap = null;
1977
+ bootstrapHealRequested = false;
1978
+ if (reenact.length > 0) pendingReenact = [
1979
+ ...pendingReenact,
1980
+ ...reenact
1981
+ ];
1982
+ recoveryGeneration += 1;
1983
+ closeEpisode();
1984
+ emitRecovery({
1985
+ ...base,
1986
+ phase: 'succeeded'
1987
+ });
1642
1988
  return {
1643
- advanced: true,
1644
- reenact
1989
+ advanced: true
1645
1990
  };
1646
1991
  }
1647
- return {
1648
- advanced: false,
1649
- reenact: []
1650
- };
1992
+ return failed('deadline');
1993
+ } catch (error) {
1994
+ if (disposed || error instanceof PeerDisposedError) {
1995
+ emitRecovery({
1996
+ ...base,
1997
+ phase: 'failed',
1998
+ reason: 'disposed'
1999
+ });
2000
+ throw error instanceof PeerDisposedError ? error : new PeerDisposedError('Peer is disposed');
2001
+ }
2002
+ emitRecovery({
2003
+ ...base,
2004
+ phase: 'failed',
2005
+ reason: 'error',
2006
+ error
2007
+ });
2008
+ throw error;
2009
+ }
2010
+ };
2011
+ const runRecovery = (trigger)=>{
2012
+ if (activeRecovery != null) return activeRecovery;
2013
+ const generation = recoveryGeneration;
2014
+ const attempt = (async ()=>{
2015
+ await ready;
2016
+ assertLive();
2017
+ if (mls == null || commitTopicID == null || rendezvousTopicID == null) {
2018
+ return {
2019
+ advanced: false
2020
+ };
2021
+ }
2022
+ const port = mls;
2023
+ const commits = commitTopicID;
2024
+ const rendezvous = rendezvousTopicID;
2025
+ return runSerial(async ()=>{
2026
+ try {
2027
+ return await attemptBody(trigger, generation, port, commits, rendezvous);
2028
+ } finally{
2029
+ // The body and its mutex hold are finished before runSerial flushes terminal
2030
+ // notices. A synchronous observer retry must not join this settled attempt.
2031
+ if (activeRecovery === attempt) activeRecovery = null;
2032
+ }
2033
+ });
2034
+ })();
2035
+ activeRecovery = attempt;
2036
+ void attempt.then(()=>{
2037
+ if (activeRecovery === attempt) activeRecovery = null;
2038
+ }, ()=>{
2039
+ if (activeRecovery === attempt) activeRecovery = null;
1651
2040
  });
2041
+ return attempt;
2042
+ };
2043
+ const recover = async ()=>{
2044
+ const { advanced } = await runRecovery('consumer');
2045
+ const reenact = pendingReenact;
2046
+ pendingReenact = [];
2047
+ return {
2048
+ advanced,
2049
+ reenact
2050
+ };
1652
2051
  };
1653
2052
  /**
1654
2053
  * Run a heal the lane asked for, never from inside the lane. `recover()` takes the commit mutex,
@@ -1656,22 +2055,43 @@ export function createGroupPeer(params) {
1656
2055
  * flight absorbs any trigger raised while it runs: the frame that raised it is still in the log,
1657
2056
  * and the next pull raises it again if the heal did not settle it.
1658
2057
  */ const healIfRequested = async ()=>{
1659
- if (!healRequested || healing) return;
1660
- healing = true;
2058
+ if (!healRequested || activeRecovery != null) return;
1661
2059
  healRequested = false;
1662
2060
  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
- ];
2061
+ await runRecovery('automatic');
1670
2062
  } catch {
1671
2063
  // No responder, or a reply that would not open. The peer stays degraded, and the frame that
1672
2064
  // asked for the heal is still in the log: the next pull asks again.
1673
- } finally{
1674
- healing = false;
2065
+ }
2066
+ };
2067
+ let pendingRestoreTimer;
2068
+ let abortPendingRestore;
2069
+ const pendingRestoreAborted = new Promise((resolve)=>{
2070
+ abortPendingRestore = resolve;
2071
+ });
2072
+ const restorePending = async ()=>{
2073
+ if (crypto.pending == null) return;
2074
+ let backoff = 1000;
2075
+ while(!disposed){
2076
+ try {
2077
+ const records = await Promise.race([
2078
+ crypto.pending.list(),
2079
+ pendingRestoreAborted.then(()=>null)
2080
+ ]);
2081
+ if (records == null || disposed) return;
2082
+ await appLane.restore(records);
2083
+ return;
2084
+ } catch {
2085
+ if (disposed) return;
2086
+ await Promise.race([
2087
+ new Promise((resolve)=>{
2088
+ pendingRestoreTimer = setTimeout(resolve, backoff);
2089
+ }),
2090
+ pendingRestoreAborted
2091
+ ]);
2092
+ pendingRestoreTimer = undefined;
2093
+ backoff = Math.min(backoff * 2, 60_000);
2094
+ }
1675
2095
  }
1676
2096
  };
1677
2097
  const ready = (async ()=>{
@@ -1691,8 +2111,24 @@ export function createGroupPeer(params) {
1691
2111
  } else {
1692
2112
  await captureAnchor();
1693
2113
  }
2114
+ await restorePending();
2115
+ if (disposed) return;
1694
2116
  await initControlLanes();
1695
2117
  await buildEpoch();
2118
+ // The seed pull precedes the app listeners. Read once more after registration to close
2119
+ // the publication gap; a failed read is retried on the same independent schedule.
2120
+ if (crypto.pending != null) {
2121
+ try {
2122
+ await runSerial(async ()=>{
2123
+ await replayJournal();
2124
+ await ensureLedger(Date.now() + recoveryTimeoutMs);
2125
+ await reconcileCommits();
2126
+ });
2127
+ } catch {
2128
+ appPullNeeded = true;
2129
+ armAppPull(appPullBackoff);
2130
+ }
2131
+ }
1696
2132
  })();
1697
2133
  // A failed init rejects every public call, but must not raise an unhandled rejection before the
1698
2134
  // first is made.
@@ -1706,6 +2142,28 @@ export function createGroupPeer(params) {
1706
2142
  assertLive();
1707
2143
  return fn();
1708
2144
  };
2145
+ const readyOrAbort = async (signal)=>{
2146
+ if (signal == null) {
2147
+ await ready;
2148
+ return 'ready';
2149
+ }
2150
+ if (signal.aborted) return 'aborted';
2151
+ let onAbort;
2152
+ const aborted = new Promise((resolve)=>{
2153
+ onAbort = ()=>resolve('aborted');
2154
+ signal.addEventListener('abort', onAbort, {
2155
+ once: true
2156
+ });
2157
+ });
2158
+ try {
2159
+ return await Promise.race([
2160
+ ready.then(()=>'ready'),
2161
+ aborted
2162
+ ]);
2163
+ } finally{
2164
+ if (onAbort != null) signal.removeEventListener('abort', onAbort);
2165
+ }
2166
+ };
1709
2167
  // Hoisted and explicitly typed (rather than inlined in the return object below) so the
1710
2168
  // checker can match its type against `GroupPeer<Protocols>['protocol']` by identity: inlined,
1711
2169
  // the whole return-object structural check against `GroupPeer<Protocols>` recurses through
@@ -1716,12 +2174,32 @@ export function createGroupPeer(params) {
1716
2174
  return {
1717
2175
  dispatch: (prc, config)=>withReady(()=>surfaceFor(key).dispatch(prc, config)),
1718
2176
  request: (prc, config)=>withReady(()=>surfaceFor(key).request(prc, config)),
1719
- gather: (prc, config)=>withReady(()=>surfaceFor(key).gather(prc, config)),
2177
+ gather: async (prc, config)=>{
2178
+ const outcome = await readyOrAbort(config?.signal);
2179
+ assertLive();
2180
+ if (outcome === 'aborted') return [];
2181
+ return surfaceFor(key).gather(prc, config);
2182
+ },
1720
2183
  to: (memberDID)=>withReady(()=>surfaceFor(key).to(memberDID))
1721
2184
  };
1722
2185
  };
1723
2186
  return {
1724
2187
  protocol: protocolMethod,
2188
+ retryAppDelivery: async (topicID)=>{
2189
+ if (disposed) return;
2190
+ appLane.retryDelivery(topicID);
2191
+ retryAppPull();
2192
+ },
2193
+ dropAppFrame: async (topicID, position)=>{
2194
+ await ready;
2195
+ assertLive();
2196
+ await runSerial(async ()=>{
2197
+ await appLane.dropFrame(topicID, position);
2198
+ await replayJournal();
2199
+ await ensureLedger(Date.now() + recoveryTimeoutMs);
2200
+ await reconcileCommits();
2201
+ });
2202
+ },
1725
2203
  commit,
1726
2204
  replay,
1727
2205
  recover,
@@ -1750,6 +2228,11 @@ export function createGroupPeer(params) {
1750
2228
  dispose: ()=>{
1751
2229
  if (disposePromise != null) return disposePromise;
1752
2230
  disposed = true;
2231
+ abortPendingRestore?.();
2232
+ if (pendingRestoreTimer != null) clearTimeout(pendingRestoreTimer);
2233
+ appLane.dispose();
2234
+ if (appPullTimer != null) clearTimeout(appPullTimer);
2235
+ appPullTimer = undefined;
1753
2236
  // Synchronous and FIRST, before anything is awaited: a lane op that already passed its own
1754
2237
  // `assertLive` can be running inside `runSerial`, past the point this `dispose()` can reach
1755
2238
  // it — awaiting the commit mutex here is unsafe (`build()`/`onAccepted()` are host-supplied
@@ -1757,18 +2240,26 @@ export function createGroupPeer(params) {
1757
2240
  // closes the mux's three routes to the wire immediately, so whatever the op does next, it
1758
2241
  // cannot land a write. `mux.dispose()` — the full teardown — stays LAST, unchanged.
1759
2242
  mux.suspendPublishing();
2243
+ // Release a lane waiting for ledger replies now; its deadline may be far away.
2244
+ for (const finish of [
2245
+ ...ledgerGatherFinishes
2246
+ ])finish();
1760
2247
  disposePromise = (async ()=>{
1761
2248
  // Tear down even a peer whose init failed — it still holds a hub drain.
1762
2249
  await settled;
2250
+ await Promise.allSettled([
2251
+ ...inFlightBootstraps
2252
+ ]);
1763
2253
  commitUnsubscribe?.();
1764
2254
  rendezvousUnsubscribe?.();
1765
2255
  // Resolve any in-flight recovery rendezvous FIRST, before clearing its timers: a
1766
2256
  // `recover()` blocked in `requestGroupInfo` is settled by exactly two things — a reply or
1767
2257
  // its timeout — and dispose is about to clear that timeout. Skipping this drain would hang
1768
2258
  // the heal, `commitTail`, and every lane operation queued behind it. Resolve, then clear,
1769
- // so a fired timer cannot race a half-drained map. (The ledger gather needs no such drain:
1770
- // its timeout is a local held in none of these maps.)
1771
- for (const waiter of recoveryWaiters.values())waiter(null);
2259
+ // so a fired timer cannot race a half-drained map.
2260
+ for (const waiter of recoveryWaiters.values())waiter({
2261
+ kind: 'disposed'
2262
+ });
1772
2263
  recoveryWaiters.clear();
1773
2264
  for (const timer of recoveryTimers.values())clearTimeout(timer);
1774
2265
  for (const timer of pendingReplies.values())clearTimeout(timer);