@kumiai/rpc 0.3.1 → 0.4.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,28 +1,44 @@
1
- import { BroadcastClient, createBroadcastTransport, defaultJitter, defaultRandomID } from '@kumiai/broadcast';
1
+ import { BroadcastClient, createBroadcastTransport, defaultJitter, encodeEventFrame } from '@kumiai/broadcast';
2
+ import { createRuntime } from '@sozai/runtime';
3
+ import { createAppLane } from './app-lane.js';
2
4
  import { createGroupBusServer } from './bus-server.js';
3
- import { classifyCommit } from './classify.js';
5
+ import { classifyCommit, UNKNOWN_FRAME_VERSION } from './classify.js';
4
6
  import { CommitDeadlineError, isHeadMismatch, JournalEpochError, RecoveryRequiredError } from './commit.js';
5
- import { decodeCommitFrame, encodeCommitFrame } from './commit-frame.js';
7
+ import { decodeCommitFrame, encodeCommitFrame, isUnsupportedCommitFrameVersion } from './commit-frame.js';
6
8
  import { isMissingLedgerEntries } from './crypto.js';
7
9
  import { asLogPosition } from './cursor.js';
8
- import { createDirectedClient, createInboxAcceptor } from './directed.js';
10
+ import { createDirectedClient, createInboxAcceptor, createInboxPath } from './directed.js';
9
11
  import { adaptBusHandlers } from './handlers.js';
10
- import { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND } from './handshake.js';
12
+ import { decodeHandshakeFrame, encodeHandshakeFrame, HANDSHAKE_KIND, HANDSHAKE_VERSION } from './handshake.js';
11
13
  import { createHubMux } from './hub-mux.js';
12
14
  import { createLedgerEntryResolver, encodeLedgerEntries } from './ledger-entries.js';
15
+ import { createOpenOncePath } from './open-once.js';
16
+ import { retentionOf } from './protocol.js';
13
17
  import { decodeLedgerReply, decodeLedgerRequest, decodeRecoveryReply, decodeRecoveryRequest, encodeLedgerReply, encodeLedgerRequest, encodeRecoveryReply, encodeRecoveryRequest } from './recovery.js';
14
- import { commitTopic, inboxTopic, protocolTopic, rendezvousTopic } from './topic.js';
18
+ import { detectRosterChange } from './roster.js';
19
+ import { APP_TOPIC_LABEL, commitTopic, inboxTopic, protocolTopic, rendezvousTopic } from './topic.js';
15
20
  const DEFAULT_RECOVERY_TIMEOUT_MS = 5000;
16
21
  const DEFAULT_RECOVERY_JITTER_MS = 250;
17
22
  /**
18
23
  * How long `recover()` keeps rejoining before giving up and leaving the peer degraded. A
19
- * deadline, like `commit()`'s, not an attempt count: losing the compare-and-set is the LIKELY
20
- * case, since a heal runs under commit pressure and two peers healing at once race each other.
24
+ * deadline, not an attempt count: losing the compare-and-set is expected — a heal runs under
25
+ * commit pressure and two peers healing at once race each other.
21
26
  */ const DEFAULT_RECOVERY_DEADLINE_MS = 30_000;
22
27
  /**
23
- * How long the hub is asked to keep the commit log. Bounds how long a member may be offline and
24
- * still converge by pulling alone, without another member awake to heal it.
25
- */ const DEFAULT_COMMIT_LOG_RETENTION_SECONDS = 30 * 24 * 60 * 60;
28
+ * How long the hub is asked to keep the commit log: **28 days**. Bounds how long a member may be
29
+ * offline and still converge by pulling alone, without another member awake to heal it.
30
+ *
31
+ * Deliberately below the reference hub ceiling (`createMemoryStore`'s `DEFAULT_MAX_RETENTION`, 30
32
+ * days): a hub refuses a retention above its ceiling rather than clamping it, so a default sitting
33
+ * exactly on the ceiling would leave no room for an upward override — refused outright, and the
34
+ * peer not a subscriber of its own commit topic. Asserted in `peer-control-lanes.test.ts`, since a
35
+ * tighter operator cap still refuses this default (reported via `hub-mux`).
36
+ */ export const DEFAULT_COMMIT_LOG_RETENTION_SECONDS = 28 * 24 * 60 * 60;
37
+ /**
38
+ * How long the hub is asked to keep an app topic's log. Aligned to the commit window so a
39
+ * returning member never rebuilds its membership without also recovering its messages. A separate
40
+ * dial, not the commit one reused — the alignment is a choice a host may override.
41
+ */ export const DEFAULT_APP_LOG_RETENTION_SECONDS = DEFAULT_COMMIT_LOG_RETENTION_SECONDS;
26
42
  /** How many commit frames a single pull asks for. Pull loops until the log is drained. */ const COMMIT_FETCH_LIMIT = 100;
27
43
  /**
28
44
  * How long `commit` keeps rebasing before giving up. A deadline, not an attempt count: several
@@ -34,70 +50,237 @@ const DEFAULT_RECOVERY_JITTER_MS = 250;
34
50
  */ const COMMIT_ATTEMPT_CEILING = 1000;
35
51
  /**
36
52
  * Cap on the storm-collapse suppression set. The requestID comes off the wire, so without a bound
37
- * a hostile relay could replay replies under endless distinct ids and grow the set forever.
53
+ * a hostile relay could replay replies under endless distinct ids and grow it forever.
38
54
  *
39
- * Eviction is safe at any size: a dropped entry only COSTS a redundant reply, never leaks. A
40
- * suppression only stops THIS peer scheduling its own reply to a re-delivered request; a reply
41
- * scheduled after eviction just re-seals current GroupInfo to a requester the port still
42
- * authorizes against the live roster — a wasted publish a removed requester gets nothing from.
43
- * The cap sits well above the in-flight request count, so eviction only reaches ids whose
44
- * requester deadline long passed and which no honest peer asks about again (every attempt mints a
45
- * fresh id).
55
+ * Eviction is safe at any size: a dropped entry only costs a redundant reply (a re-seal to a
56
+ * requester the port still authorizes), never a leak. The cap sits well above the in-flight
57
+ * request count, so eviction only reaches ids whose deadline long passed.
46
58
  */ const SUPPRESSED_REQUESTS_MAX = 1024;
47
59
  export function createGroupPeer(params) {
48
- const { hub, crypto, mls, journal, adoptJournalled, localDID, protocols, handlers, suppress } = params;
49
- const getRandomID = params.getRandomID;
50
- const newPublishID = getRandomID ?? defaultRandomID;
60
+ const { hub, crypto, mls, journal, adoptJournalled, anchorStore, appCursorStore, localDID, protocols, handlers, suppress } = params;
61
+ const onAppWindowPruned = params.onAppWindowPruned;
62
+ // Destructured rather than held as `runtime`: that name is taken in this scope by
63
+ // {@link ProtocolRuntime}, which is a different thing entirely.
64
+ const { getRandomID } = params.runtime ?? createRuntime();
65
+ const newPublishID = getRandomID;
51
66
  const recoveryTimeoutMs = params.recovery?.timeoutMs ?? DEFAULT_RECOVERY_TIMEOUT_MS;
52
67
  const recoveryDeadlineMs = params.recovery?.deadlineMs ?? DEFAULT_RECOVERY_DEADLINE_MS;
53
68
  const getReplyDelayMs = params.recovery?.getDelayMs ?? (()=>defaultJitter(DEFAULT_RECOVERY_JITTER_MS));
54
69
  const commitLogRetentionSeconds = params.commitLogRetentionSeconds ?? DEFAULT_COMMIT_LOG_RETENTION_SECONDS;
70
+ const appLogRetentionSeconds = params.appLogRetentionSeconds ?? DEFAULT_APP_LOG_RETENTION_SECONDS;
55
71
  const commitDeadlineMs = params.commitDeadlineMs ?? DEFAULT_COMMIT_DEADLINE_MS;
56
72
  const mux = createHubMux({
57
73
  hub,
58
- localDID
74
+ localDID,
75
+ ...params.onSubscribeFailed != null ? {
76
+ onSubscribeFailed: params.onSubscribeFailed
77
+ } : {},
78
+ ...params.onReceiveEnded != null ? {
79
+ onReceiveEnded: params.onReceiveEnded
80
+ } : {}
59
81
  });
60
82
  let runtimes = new Map();
61
- let secret = new Uint8Array();
62
83
  /**
63
- * The epoch the app lane is built at, seeded from the handle, not zero. Zero is not neutral:
64
- * `frameCommit` refuses to seal bodies when the live handle has moved past this, and the first
65
- * lane operation (the seed: replay then pull) runs BEFORE the app lane is built — so a peer that
66
- * restarted holding a journalled commit would have its own replay refused at startup by a guard
67
- * about a host adopting early, and recover only if the host called a lane operation later.
84
+ * The epoch's self-inbox topic and the one path that opens its frames. Held per peer rather
85
+ * than per protocol because the topic is not per protocol, and rebuilt with the epoch — the
86
+ * topic is anchor-bound, so a roster change moves it.
87
+ */ let inboxLane;
88
+ /**
89
+ * The host's app event handlers, per protocol, as the drain calls them — the same adaptation
90
+ * the live bus server is built from, so a drained frame and a pushed one reach the host by the
91
+ * same door. Built once: the handlers a host passed at construction do not change, and the
92
+ * drain outlives any one epoch's runtime (it runs mid-walk, when the app lane has been torn
93
+ * down and not yet rebuilt).
94
+ */ const appEventHandlers = new Map();
95
+ for (const [name, protocol] of Object.entries(protocols)){
96
+ appEventHandlers.set(name, adaptBusHandlers(protocol, handlers[name], suppress).eventHandlers);
97
+ }
98
+ /**
99
+ * The live epoch this peer frames commits at, seeded from the handle, not zero. Not the app
100
+ * lane's epoch (anchor-bound) but the commit lane's: `frameCommit` refuses to seal bodies once
101
+ * the live handle has moved past this. Zero is not neutral — the first lane operation (replay
102
+ * then pull) runs BEFORE this is re-read, so a peer restarted holding a journalled commit would
103
+ * have its own replay wrongly refused at startup.
68
104
  */ let epoch = crypto.epoch();
105
+ /**
106
+ * The app-lane anchor: the per-epoch secret and epoch the app-lane topic derivation is bound
107
+ * to. Seeded at genesis and rotated when an applied Commit changes the roster OR rejoins a
108
+ * member — captured from the port's own post-commit epoch secret, never the recovery secret.
109
+ *
110
+ * It sits at the last roster change because two constraints meet there and nowhere else. A
111
+ * Remove must move it: the evicted member keeps every topic ID it derived. An Add must move it
112
+ * too: MLS ratchets forward, so a member added at epoch E cannot export an earlier secret.
113
+ * `max(last add, last remove)` is the only epoch both after every removal and held by every
114
+ * current member, and every member reaches it by applying the same commit, so they agree
115
+ * natively — the joiner seeding at its own add epoch included.
116
+ *
117
+ * A REJOIN moves it too, from a member the Add/Remove diff cannot see: it changes no DID, so it
118
+ * rotates on the applied commit's own external flag instead, set from the rejoiner's own
119
+ * rejoined handle in `recover()` (a member never applies its own commit). The invariant is that
120
+ * the anchor is >= every current member's EFFECTIVE join, and a rejoiner's effective join is
121
+ * its rejoin epoch: its rejoined handle exports no secret from before it.
122
+ *
123
+ * PERSISTED, never re-derived: it is captured at an epoch the live handle then runs past, and a
124
+ * rebooted handle can never re-export that epoch's secret. Every capture writes it to
125
+ * {@link GroupPeerMLSParams.anchorStore} and construction restores it from there.
126
+ *
127
+ * Only the epoch is observable outside this scope (see {@link GroupPeer.anchorEpoch}).
128
+ */ let anchor = {
129
+ secret: new Uint8Array(),
130
+ epoch: crypto.epoch()
131
+ };
132
+ /**
133
+ * The peer's app lane: the retained-frame buffer, its durable read position, and the drain. It
134
+ * reads the anchor back through the accessor below rather than being handed one, since the
135
+ * anchor moves under it and every topic it derives belongs to the segment the anchor names.
136
+ */ const appLane = createAppLane({
137
+ mux,
138
+ crypto,
139
+ localDID,
140
+ protocols,
141
+ eventHandlers: appEventHandlers,
142
+ retentionSeconds: appLogRetentionSeconds,
143
+ anchor: ()=>anchor,
144
+ groupID: ()=>commitTopicID,
145
+ justifiedEpochCeiling: ()=>justifiedEpochCeiling(),
146
+ ...appCursorStore != null ? {
147
+ appCursorStore
148
+ } : {},
149
+ ...onAppWindowPruned != null ? {
150
+ onAppWindowPruned
151
+ } : {}
152
+ });
153
+ /**
154
+ * Capture the anchor from the port's post-commit handle and persist it. The one place the
155
+ * anchor is written from the live epoch, and the one place it is saved.
156
+ *
157
+ * KNOWN BOUND: `processCommit` is durable before this runs, so a crash between the two leaves a
158
+ * persisted anchor one rotation stale, and the restarted peer stays off the group's topic until
159
+ * the next roster change rotates it again. Closing it needs the anchor inside the same durable
160
+ * write as the handle, which this layer cannot reach.
161
+ */ const captureAnchor = async ()=>{
162
+ anchor = {
163
+ secret: await crypto.exportSecret(APP_TOPIC_LABEL),
164
+ epoch: crypto.epoch()
165
+ };
166
+ await anchorStore?.save(anchor);
167
+ // The anchor moving IS the segment boundary, so every capture ends the segment the buffer
168
+ // belongs to. AFTER the assignment above: the lane rebuilds its cursors off the live anchor.
169
+ appLane.reset();
170
+ };
171
+ /**
172
+ * The opened form of a live frame, keyed by the plaintext the open produced. Written by the
173
+ * inbound path below and read by every transport built on it, so one open serves all of them.
174
+ *
175
+ * {@link GroupUnwrapResult}, not `@kumiai/broadcast`'s `UnwrapResult`: what is stored here
176
+ * reaches `BroadcastClient.gather` as the sender it keys its quorum on, and broadcast's type
177
+ * says `senderDID?`. `crypto.unwrap` REQUIRES the field, so the narrowing below checks a promise
178
+ * already made — a frame that breaks it is refused rather than fanned out.
179
+ */ const openedFrames = new WeakMap();
180
+ /**
181
+ * The app lane's inbound path: one open per topic, fanned out as plaintext, with each frame's
182
+ * log position noted before the open. Every consumer's own `unwrap` is then a pure lookup of the
183
+ * opened result ({@link openedFrames}), and nothing downstream touches the handle.
184
+ *
185
+ * See {@link createOpenOncePath} for why a lane may only open a frame once.
186
+ */ const createInboundPath = (name, topicID)=>{
187
+ return createOpenOncePath({
188
+ mux,
189
+ topicID,
190
+ unwrap: crypto.unwrap,
191
+ project: (_message, opened)=>{
192
+ const { payload, senderDID } = opened;
193
+ if (typeof senderDID !== 'string' || senderDID === '') {
194
+ // `project` returning `undefined` drops the frame deliberately (see
195
+ // `OpenOncePathParams.project`): the app lane is always MLS-sealed, so an open that
196
+ // recovers no sender is not a frame to deliver unattributed. Fails CLOSED against the
197
+ // shared open-once signature's wider `UnwrapResult`.
198
+ return undefined;
199
+ }
200
+ openedFrames.set(payload, {
201
+ payload,
202
+ senderDID
203
+ });
204
+ return payload;
205
+ },
206
+ note: (message)=>appLane.note(name, topicID, message)
207
+ });
208
+ };
209
+ /**
210
+ * One protocol's live-lane transport: LISTENS on the topic the runtime is built for, and
211
+ * PUBLISHES to the segment that contains each frame's own seal epoch — see
212
+ * {@link sealForSegment} for why those can differ mid-rotation.
213
+ *
214
+ * The topic is decided by the SEAL and carried to the publish, since the two are separate calls
215
+ * with an anchor that can move between them: `wrap` records the topic under the ciphertext it
216
+ * produced, keyed by the bytes' own identity rather than a slot, since two transports share this
217
+ * lane and interleave their writes.
218
+ *
219
+ * The subscribe keeps the runtime's topic — a rotation rebuilds the listeners, but a topic stays
220
+ * subscribed at the mux for the member's whole life either way.
221
+ */ const segmentBoundTransport = (name, topicID, inbound)=>{
222
+ const sealedOn = new WeakMap();
223
+ return createBroadcastTransport({
224
+ topicID,
225
+ bus: {
226
+ // `builtFor` is the topic this transport was constructed with, and it is the fallback
227
+ // rather than the answer: anything published through here was sealed by the `wrap` below,
228
+ // so the recorded topic is the one that agrees with the seal.
229
+ publish: async (builtFor, payload)=>{
230
+ await mux.bus.publish(sealedOn.get(payload) ?? builtFor, payload);
231
+ },
232
+ // Already-opened plaintext, from the topic's one inbound path. The `unwrap` below only
233
+ // recovers the sender the open already authenticated.
234
+ subscribe: (_listenOn, onMessage)=>inbound(onMessage)
235
+ },
236
+ wrap: async (bytes)=>{
237
+ const sealed = await sealForSegment(name, bytes);
238
+ sealedOn.set(sealed.payload, sealed.topicID);
239
+ return sealed.payload;
240
+ },
241
+ unwrap: (payload)=>openedFrames.get(payload) ?? payload
242
+ });
243
+ };
69
244
  const buildEpoch = async ()=>{
70
- secret = await crypto.exportSecret();
71
245
  epoch = crypto.epoch();
72
246
  const next = new Map();
247
+ // ONE inbox lane for the whole peer, not one per protocol: the topic does not name a
248
+ // protocol, so every acceptor and directed client opening its own frames is the defect this
249
+ // shape prevents.
250
+ const selfInbox = inboxTopic(anchor.secret, anchor.epoch, localDID);
251
+ inboxLane = {
252
+ topicID: selfInbox,
253
+ path: createInboxPath({
254
+ mux,
255
+ topicID: selfInbox,
256
+ unwrap: crypto.unwrap
257
+ })
258
+ };
73
259
  for (const [name, protocol] of Object.entries(protocols)){
74
- const topicID = protocolTopic(secret, epoch, name);
75
- // Subscribed for the member's whole life, like the commit and rendezvous topics: a
76
- // rotation tears down the LISTENERS on an epoch it left, never the subscriptions (the mux
77
- // guarantees it — nothing there unsubscribes). Unsubscribing tells the hub to drop this
78
- // member's pending deliveries and free any frame it was the last reader of, so a peer that
79
- // gave up the subscription as it rotated would delete its own unread messages, and
80
- // everyone else's copy of them.
81
- const selfInbox = inboxTopic(secret, epoch, localDID);
260
+ // The app topic is bound to the ANCHOR, not the live epoch — see {@link sealForSegment}.
261
+ // Content stays sealed under the live epoch crypto below; only the topic ID is anchor-bound.
262
+ const topicID = protocolTopic(anchor.secret, anchor.epoch, name);
263
+ // Subscribed for the member's whole life, like the commit and rendezvous topics: the mux
264
+ // never unsubscribes on rotation, only tears down the LISTENERS on the epoch left.
265
+ // Unsubscribing would tell the hub to drop this member's pending deliveries and free any
266
+ // frame it was the last reader of — deleting unread messages for everyone.
267
+ //
268
+ // Subscribed HERE, not left to the transports below, because the subscription is also what
269
+ // asks the hub how long to hold the log; a bus is a fan-out abstraction with no such request.
270
+ mux.retainTopic(topicID, {
271
+ retention: appLogRetentionSeconds
272
+ });
273
+ // One path, two consumers: the frame is opened once here and both are given the plaintext.
274
+ const inbound = createInboundPath(name, topicID);
82
275
  const client = new BroadcastClient({
83
- transport: createBroadcastTransport({
84
- topicID,
85
- bus: mux.bus,
86
- wrap: crypto.wrap,
87
- unwrap: crypto.unwrap
88
- }),
89
- ...getRandomID != null ? {
90
- getRandomID
276
+ transport: segmentBoundTransport(name, topicID, inbound),
277
+ ...params.runtime != null ? {
278
+ runtime: params.runtime
91
279
  } : {}
92
280
  });
93
281
  const { eventHandlers, requestHandlers } = adaptBusHandlers(protocol, handlers[name], suppress);
94
282
  const busServer = createGroupBusServer({
95
- transport: createBroadcastTransport({
96
- topicID,
97
- bus: mux.bus,
98
- wrap: crypto.wrap,
99
- unwrap: crypto.unwrap
100
- }),
283
+ transport: segmentBoundTransport(name, topicID, inbound),
101
284
  from: localDID,
102
285
  eventHandlers,
103
286
  requestHandlers
@@ -106,11 +289,11 @@ export function createGroupPeer(params) {
106
289
  mux,
107
290
  localDID,
108
291
  selfInboxTopic: selfInbox,
109
- resolveSendTopic: (senderDID)=>inboxTopic(secret, epoch, senderDID),
292
+ inbound: inboxLane.path,
293
+ resolveSendTopic: (senderDID)=>inboxTopic(anchor.secret, anchor.epoch, senderDID),
110
294
  protocol: protocol,
111
295
  handlers: handlers[name],
112
- wrap: crypto.wrap,
113
- unwrap: crypto.unwrap
296
+ wrap: crypto.wrap
114
297
  });
115
298
  next.set(name, {
116
299
  client,
@@ -141,26 +324,71 @@ export function createGroupPeer(params) {
141
324
  throw new AggregateError(reasons, 'Group epoch teardown failed');
142
325
  }
143
326
  };
327
+ /**
328
+ * Seal an app frame and name the segment it belongs on, as ONE answer: a frame must land on the
329
+ * segment that CONTAINS its seal epoch, and only the live anchor knows which segment that is.
330
+ *
331
+ * Read from the live anchor and never from a `runtime`, because the two come apart exactly when
332
+ * it matters: a rotation moves the anchor and the handle together inside the commit walk, but
333
+ * runtimes rebuild only once the whole walk returns. A dispatch takes no mutex, so in that
334
+ * window it can seal under the NEW epoch — publishing to the topic the runtime still holds would
335
+ * land the frame on the segment the group just left, readable by nobody, ever.
336
+ *
337
+ * The anchor is re-read AFTER the seal and the pair thrown away if it moved — identity, not
338
+ * epoch equality, since every capture mints a fresh anchor — which is what makes the two halves
339
+ * one segment's: an anchor that did not move across the seal is one whose segment covers the
340
+ * seal epoch. A moved anchor re-seals under the one now live instead of publishing against the
341
+ * one it missed.
342
+ */ const sealForSegment = async (name, bytes)=>{
343
+ while(true){
344
+ const at = anchor;
345
+ const payload = await crypto.wrap(bytes);
346
+ if (anchor === at) return {
347
+ topicID: protocolTopic(at.secret, at.epoch, name),
348
+ payload
349
+ };
350
+ }
351
+ };
144
352
  const surfaceFor = (name)=>{
145
353
  const runtime = runtimes.get(name);
146
354
  if (runtime == null) throw new Error(`Unknown protocol: ${name}`);
147
355
  return {
148
- dispatch: (prc, data)=>runtime.client.dispatch(prc, data),
356
+ dispatch: async (prc, data)=>{
357
+ // Route by the procedure's declared retention. A `log` event goes to the app topic's log
358
+ // lane (retained, pullable); ephemeral events and RPC stay on the live mailbox lane. The
359
+ // log payload is byte-identical to what the broadcast transport would produce, so online
360
+ // subscribers still receive it through the same drain.
361
+ if (retentionOf(protocols[name], prc) === 'log') {
362
+ const { topicID, payload } = await sealForSegment(name, encodeEventFrame(prc, data ?? {}));
363
+ await mux.publish({
364
+ topicID,
365
+ payload,
366
+ retain: 'log'
367
+ });
368
+ return;
369
+ }
370
+ await runtime.client.dispatch(prc, data);
371
+ },
149
372
  request: (prc, prm, options)=>runtime.client.request(prc, prm, options),
150
373
  gather: (prc, prm, options)=>runtime.client.gather(prc, prm, options),
151
374
  to: (memberDID)=>{
152
375
  const cached = runtime.directed.get(memberDID);
153
376
  if (cached != null) return cached.client;
377
+ const lane = inboxLane;
378
+ if (lane == null) throw new Error('Peer is not started');
154
379
  const created = createDirectedClient({
155
380
  mux,
156
381
  localDID,
157
382
  memberDID,
158
- secret,
159
- epoch,
383
+ sendTopicID: inboxTopic(anchor.secret, anchor.epoch, memberDID),
384
+ // The epoch's own inbox topic and its one open path: reading replies through a path
385
+ // built for a topic this client does not receive on would spend keys opening frames for
386
+ // a lane nobody listens to.
387
+ receiveTopicID: lane.topicID,
388
+ inbound: lane.path,
160
389
  wrap: crypto.wrap,
161
- unwrap: crypto.unwrap,
162
- ...getRandomID != null ? {
163
- getRandomID
390
+ ...params.runtime != null ? {
391
+ runtime: params.runtime
164
392
  } : {}
165
393
  });
166
394
  runtime.directed.set(memberDID, created);
@@ -186,10 +414,8 @@ export function createGroupPeer(params) {
186
414
  * compare-and-sets against.
187
415
  *
188
416
  * NOT the cursor; conflating them is a defect. The cursor is what this peer PROCESSED; the head
189
- * is what the log's last accepted frame IS. They coincide only while every frame is log-class, a
190
- * property of the store not this peer — so read the head from the store's own reply, never infer
191
- * it from a cursor that happens to agree. `null` means the topic never had an accepted log
192
- * publish, which is what the first commit of a group's life compares against.
417
+ * is what the log's last accepted frame IS — read from the store's own reply, never inferred
418
+ * from the cursor. `null` means the topic never had an accepted log publish.
193
419
  */ let commitLogHead = null;
194
420
  /**
195
421
  * The sequenceID this peer ENACTED at each epoch it passed — applied from the log, or committed
@@ -197,19 +423,15 @@ export function createGroupPeer(params) {
197
423
  * holds a record for is two commits at one epoch, which the hub can only produce by showing
198
424
  * different logs to different members.
199
425
  *
200
- * An epoch with NO record is history, not a fork — a late joiner, rejoiner and re-seeded peer
201
- * all walk commits from epochs they never held, and a trigger on "an epoch I passed" would send
202
- * every one into recovery on its first pull.
203
- *
204
- * In memory, deliberately: a restart drops the record, and a peer with no record reads history
205
- * as history. It can MISS a fork, never invent one, and a miss costs nothing the trim and heal
206
- * triggers do not already cover.
426
+ * An epoch with NO record is history, not a fork — a late joiner, rejoiner or re-seeded peer all
427
+ * walk commits from epochs they never held. In memory, deliberately: a restart drops the record,
428
+ * so a peer with no record reads history as history — it can MISS a fork, never invent one.
207
429
  */ const appliedByEpoch = new Map();
208
430
  /**
209
- * The heal trigger, RECORDED and never awaited where found. `recover()` is a lane operation and
210
- * takes the commit mutex, so a pull that awaited it would wait on a tail including the pull. The
211
- * trigger only writes this flag; the pull unwinds, releases the lane, and the heal runs
212
- * afterward as its own operation. `healing` stops a second wakeup starting a concurrent one.
431
+ * The heal trigger, RECORDED and never awaited where found: `recover()` takes the commit mutex,
432
+ * so a pull that awaited it would wait on a tail including the pull. The trigger only writes
433
+ * this flag; the pull unwinds, releases the lane, and the heal runs afterward as its own
434
+ * operation. `healing` stops a second wakeup starting a concurrent one.
213
435
  */ let healRequested = false;
214
436
  let healing = false;
215
437
  /**
@@ -218,56 +440,48 @@ export function createGroupPeer(params) {
218
440
  * un-merged commit at its current epoch, or the LOSING side of a fork.
219
441
  *
220
442
  * Deliberately NOT `healRequested`: that flag only SCHEDULES the next heal and clears as
221
- * ordinary control flow (`recover()` clears it at the top of every attempt), so a heal that
222
- * finds no responder or spends its deadline leaves it false. Gating `commit()` on it would let a
223
- * peer that just failed to heal win the compare-and-set at a stale epoch and land a commit — a
224
- * Welcome among them — on a branch of one. This flag survives a failed heal: cleared ONLY when a
225
- * rejoin actually lands (`recover`), the one thing that rebuilds this peer's place in the tree.
226
- * No pull can carry a stranded peer back — the frames that would are gone, and the head sits at
227
- * an epoch it can no longer reach by applying the log.
443
+ * ordinary control flow, so a heal that finds no responder leaves it false. Gating `commit()` on
444
+ * it would let a peer that just failed to heal win the compare-and-set at a stale epoch and land
445
+ * a commit on a branch of one. This flag survives a failed heal: cleared ONLY when a rejoin
446
+ * actually lands (`recover`) — no pull can carry a stranded peer back, since the frames that
447
+ * would are gone.
228
448
  *
229
- * Set on positive evidence, NEVER on poison: a frame this peer stepped over (malformed, refused
230
- * by policy, or naming unresolvable bodies) is not evidence the group moved on, because nobody
231
- * applied it either. Gating on poison would rebuild the group-death hazard the classifier's
232
- * `poison` row refuses: every honest member would refuse to commit at an epoch a body-less frame
233
- * poisoned, and no one could publish the commit that unsticks the group.
449
+ * Set on positive evidence, NEVER on poison: a frame this peer stepped over (malformed, refused,
450
+ * or naming unresolvable bodies) is not evidence the group moved on, since nobody applied it
451
+ * either. Gating on poison would rebuild the group-death hazard the classifier's `poison` row
452
+ * refuses.
234
453
  */ let stranded = false;
235
454
  /**
236
- * A commit this peer journalled, that never landed and it cannot re-issue itself: held until a
237
- * lane operation with a return value can hand it to the host. A delivery wakeup is a lane
238
- * operation too but has nowhere to put a loss, and dropping it is the one thing that must not
239
- * happen — for an invite it loses an invitation, for a remove it leaves an admin believing a
455
+ * A commit this peer journalled that never landed and cannot re-issue itself: held until a lane
456
+ * operation with a return value can hand it to the host. Dropping it is the one thing that must
457
+ * not happen — for an invite it loses an invitation, for a remove it leaves an admin believing a
240
458
  * member was evicted when they were not.
241
459
  */ let lostCommit;
242
460
  /**
243
461
  * The ledger entries this peer held when it rejoined — snapshotted BEFORE the rejoined handle
244
- * replaces them, because a handle that rejoined by external commit holds an EMPTY ledger with
245
- * nothing left to read.
462
+ * replaces them, since a handle that rejoined by external commit holds an EMPTY ledger.
246
463
  *
247
- * The peer's own LEDGER, deliberately not its journal. The journal is always settled by the
248
- * time a heal runs (step 0 of every lane operation settles it before anything can trigger one),
249
- * so filtering it would filter nothing. What a healing peer holds that the group may not is its
250
- * ledger: entries it enacted on a branch the group discarded, or enacted and kept while the
251
- * group moved on. Filtering THAT against the group's authenticated ledger is the membership rule
252
- * as one set-difference: re-enact iff the group's ledger does not already contain it.
464
+ * The peer's own LEDGER, not its journal (always settled by the time a heal runs). What a
465
+ * healing peer holds that the group may not is its ledger: entries enacted on a discarded
466
+ * branch, or kept while the group moved on. Filtering that against the group's authenticated
467
+ * ledger is the membership rule as a set-difference: re-enact iff the group's ledger does not
468
+ * already contain it.
253
469
  *
254
- * `null` means no rejoin in progress. Survives a rejoin whose bootstrap failed, so the retry
255
- * filters the same entries rather than snapshotting an empty ledger and dropping every one.
470
+ * `null` means no rejoin in progress. Survives a failed bootstrap, so a retry filters the same
471
+ * entries rather than snapshotting an empty ledger.
256
472
  */ let inFlightEntries = null;
257
473
  /**
258
474
  * Entries a heal decided must be re-enacted, waiting for a lane operation with a return value —
259
- * same problem and answer as `lostCommit`. A heal triggered by a pull is not a host call and has
260
- * nowhere to put them; the host re-enacts with an ordinary `commit()` (a lane operation), so
261
- * they can never be handed over from inside one.
475
+ * same problem as `lostCommit`. A heal triggered by a pull has nowhere to put them; the host
476
+ * re-enacts with an ordinary `commit()`.
262
477
  */ let pendingReenact = [];
263
478
  /**
264
479
  * The group's commit mutex: every commit-lane operation serialized through one tail. The
265
480
  * compare-and-set resolves races between devices, not two callers here — two `build()` calls
266
481
  * against a single handle would both frame at that handle's epoch and diverge.
267
482
  *
268
- * NOT reentrant: a task that calls `runSerial` again waits on a tail including itself. That is
269
- * why a loss is RETURNED to the host, never handed to it under the lock — the host's answer to a
270
- * loss is to commit, and a commit takes this mutex.
483
+ * NOT reentrant: a task that calls `runSerial` again waits on a tail including itself — which is
484
+ * why a loss is RETURNED to the host, never handed to it under the lock.
271
485
  */ let commitTail = Promise.resolve();
272
486
  const runSerial = (fn)=>{
273
487
  const op = commitTail.then(()=>{
@@ -281,11 +495,10 @@ export function createGroupPeer(params) {
281
495
  * Whether the journal has been replayed in the lane operation now running. Cleared when an
282
496
  * operation takes the mutex, set by `replayJournal`, required by `pullCommits`.
283
497
  *
284
- * The ordering it enforces saves a group of one. A peer that pulls before it replays meets its
285
- * OWN un-merged commit in the log, whose classification is to heal — from a group that, at
286
- * creation, has nobody to answer. Nothing else catches it: the heal resolves without advancing
287
- * or throwing, the following replay adopts the commit anyway, and the peer converges — having
288
- * spent a rendezvous and a recovery deadline asking the void for help, silently, every restart.
498
+ * The ordering it enforces saves a group of one: a peer that pulls before it replays meets its
499
+ * OWN un-merged commit in the log, which classifies as a heal — from a group that, at creation,
500
+ * has nobody to answer. The following replay would adopt the commit anyway, so unguarded this
501
+ * peer would spend a rendezvous and a recovery deadline asking the void for help, every restart.
289
502
  */ let journalReplayed = false;
290
503
  // Recovery rendezvous state, keyed by requestID.
291
504
  const recoveryWaiters = new Map();
@@ -357,19 +570,16 @@ export function createGroupPeer(params) {
357
570
  /**
358
571
  * Responder: serve this member's WHOLE ordered ledger to a rejoined peer that holds none —
359
572
  * SEALED to the ephemeral key inside the request's signed blob, and only to a requester the
360
- * responder's own ratchet tree still holds a leaf for.
361
- *
362
- * Both halves are the port's and neither is this lane's to skip: the ledger is the group's whole
363
- * authority state on a public secretless topic, so a plaintext reply hands every role to the
364
- * hub and an unauthorized one hands them to any stranger who posts a request. The port refuses a
365
- * DID with no leaf, and this peer stays silent — a refusal is not an answer.
573
+ * responder's own ratchet tree still holds a leaf for. Both checks are the port's; the ledger is
574
+ * the group's whole authority state on a public secretless topic, so skipping either hands it to
575
+ * the hub or to any stranger who posts a request.
366
576
  *
367
577
  * Gated on completeness: a peer that itself rejoined and has not bootstrapped holds an EMPTY
368
- * ledger, and answering with it wastes a scarce responder (the requester's head check rejects
369
- * it — a wasted round trip, not a soundness hole).
578
+ * ledger, and answering with it just wastes a scarce responder (the requester's head check
579
+ * rejects it).
370
580
  *
371
- * Every responder that CAN answer does — no storm-collapse here, on purpose: a lying responder's
372
- * answer fails the head check, and the requester needs a second answer to fall through to.
581
+ * Every responder that CAN answer does — no storm-collapse here: a lying responder's answer
582
+ * fails the head check, and the requester needs a second answer to fall through to.
373
583
  */ const handleLedgerRequest = (request)=>{
374
584
  if (mls == null || rendezvousTopicID == null) return;
375
585
  const port = mls;
@@ -397,6 +607,108 @@ export function createGroupPeer(params) {
397
607
  ledgerWaiters.get(reply.requestID)?.(reply.sealed);
398
608
  };
399
609
  /**
610
+ * The highest epoch the group's OWN COMMIT LOG can justify a frame having been sealed at.
611
+ *
612
+ * A member seals at epoch E only after applying the commit that produced E, so a log whose
613
+ * furthest commit is framed at H bounds every member at H + 1. READ FRESH, never from this
614
+ * peer's own view of the log: a returning member's own view would bound the group at the epoch
615
+ * IT reached — killing exactly the frames it came back for.
616
+ *
617
+ * THIS IS THE HUB'S WORD, and it can only ever be wrong in ONE direction. A commit's framed
618
+ * epoch is cleartext — unauthenticated until applied — so a hub free to inject frames can RAISE
619
+ * this ceiling at will but never LOWER it: the honest commits are in the log too, and the
620
+ * ceiling is the max over all of them, so no injected frame can hide one. Raising it costs the
621
+ * attacker nothing; lowering it — which would destroy an honest member's frames — is
622
+ * unreachable.
623
+ *
624
+ * That asymmetry is why an untrusted field is acceptable HERE and would not be for opening a
625
+ * frame: this decides how long to WAIT, never what to believe — `unwrap` alone still decides
626
+ * what is finally read.
627
+ *
628
+ * Epochs are read pre-apply from the commit's own cleartext, and every frame is asked rather
629
+ * than only the last: the log's furthest frame may be poison or a fork loser.
630
+ */ const justifiedEpochCeiling = async ()=>{
631
+ let ceiling = crypto.epoch();
632
+ if (commitTopicID == null) return ceiling;
633
+ let after = null;
634
+ while(true){
635
+ const result = await mux.fetchTopic({
636
+ topicID: commitTopicID,
637
+ ...after != null ? {
638
+ after
639
+ } : {},
640
+ limit: COMMIT_FETCH_LIMIT
641
+ });
642
+ for (const message of result.messages){
643
+ after = asLogPosition(message.sequenceID);
644
+ let commit;
645
+ try {
646
+ const frame = decodeHandshakeFrame(message.payload);
647
+ // An unknown wire version is unreadable here and stays unreadable: this ceiling is
648
+ // built from epochs read out of commit bytes, and a frame this build cannot parse
649
+ // yields none. Not the heal signal — raising that twice would not raise it harder.
650
+ if (frame.version !== HANDSHAKE_VERSION) continue;
651
+ if (frame.kind !== HANDSHAKE_KIND.commit) continue;
652
+ commit = decodeCommitFrame(frame.payload).commit;
653
+ } catch {
654
+ continue; // not a commit frame: it says nothing about where the group got to
655
+ }
656
+ // The commit's CLEARTEXT epoch, not `readCommitHeader`: that resolves the committer
657
+ // against this handle's own epoch secret and answers `null` for every commit framed ahead
658
+ // of this peer — exactly the commits a returning member has yet to walk.
659
+ const framedAt = crypto.frameEpoch(commit);
660
+ if (framedAt != null && framedAt + 1 > ceiling) ceiling = framedAt + 1;
661
+ }
662
+ if (result.messages.length < COMMIT_FETCH_LIMIT) return ceiling;
663
+ }
664
+ };
665
+ /**
666
+ * THE ONE PATH THE HANDLE RATCHETS ON, and the invariant it holds: a handle does not ratchet
667
+ * past an epoch until that epoch's frames are read and its anchor is taken. Both are one-way
668
+ * doors — after the advance those frames are ciphertext forever, and that epoch's secret can
669
+ * never be exported again.
670
+ *
671
+ * A seam, not a rule: the peer ratchets in four far-apart places (applied from the log, authored
672
+ * by this peer, adopted from the journal on restart, and a rejoin), each free to uphold half of
673
+ * this or none of it. Routing them all through here means the fifth site cannot get it wrong.
674
+ * `advance` does the ratcheting and nothing else; everything around it is this function's.
675
+ *
676
+ * The ROSTER DIFF decides the rotation — see {@link anchor} for why. The before-read is
677
+ * unconditional, since whether the diff will be needed is not knowable until the advance has
678
+ * already destroyed the answer. `rotatesAnyway` is the one thing no diff can see: an
679
+ * external-commit rejoin by a member the roster still holds replaces that member's leaf and
680
+ * moves no DID, yet must rotate all the same (see {@link anchor}).
681
+ *
682
+ * The anchor is captured from the port's POST-advance handle — the epoch every member lands on
683
+ * by making this same advance — which is what makes it agreed rather than local.
684
+ */ const advanceHandle = async (port, advance, rotatesAnyway = ()=>false)=>{
685
+ // Read this epoch's app frames BEFORE the advance that leaves it — the last moment they can
686
+ // be read, since the advance ratchets the handle on and takes this epoch's key material with
687
+ // it. Per frame-epoch, not per rotation: a segment spanning five epochs is dispensed five
688
+ // times off the one pull.
689
+ await appLane.deliver();
690
+ const rosterBefore = await port.rosterDIDs();
691
+ const epochBefore = crypto.epoch();
692
+ const advanced = await advance();
693
+ // GATED ON THE HANDLE ACTUALLY RATCHETING: a roster diff alone is not evidence that it did. A
694
+ // commit that REMOVES this member does not advance its handle (there is no epoch to move to,
695
+ // since the commit's path excludes the dropped leaf), yet real MLS still applies proposals to
696
+ // the tree — so the roster comes back WITHOUT this member at an epoch that did not move.
697
+ // (Measured against ts-mls: `processMessage` returns without throwing, epoch stays,
698
+ // `listMembers()` has lost the leaf.) Undiscriminated, that reads as a rotation.
699
+ //
700
+ // An ungated capture would re-derive the anchor at the epoch it already names and clear the
701
+ // segment buffer for nothing: {@link captureAnchor} drops undelivered frames on the premise a
702
+ // rotation makes them unopenable, which is false here — the handle is still at the epoch those
703
+ // frames were sealed at, and a frame the live lane staged mid-walk would be thrown away
704
+ // openable.
705
+ const ratcheted = crypto.epoch() !== epochBefore;
706
+ if (ratcheted && (detectRosterChange(rosterBefore, await port.rosterDIDs()) || rotatesAnyway(advanced))) {
707
+ await captureAnchor();
708
+ }
709
+ return advanced;
710
+ };
711
+ /**
400
712
  * Read the commit log forward from the cursor, classify every frame, advance the cursor over
401
713
  * each one it is done with. Returns whether any advanced the epoch.
402
714
  *
@@ -406,25 +718,15 @@ export function createGroupPeer(params) {
406
718
  * port is asked, and the peer must heal.
407
719
  *
408
720
  * The cursor advances over a frame the peer is DONE with — applied, walked as history, or
409
- * stepped over as poison (a commit whose ledger entries will not resolve is poison: advance,
410
- * never retry). It does NOT advance over its own un-merged commit, which stops the drain. A
411
- * throw (port broke its contract on a frame it should have applied) leaves the cursor put and
412
- * the next pull re-reads that frame.
721
+ * stepped over as poison. It does NOT advance over its own un-merged commit, which stops the
722
+ * drain. A throw (port broke its contract) leaves the cursor put and the next pull re-reads it.
413
723
  *
414
- * Also the only place the log's tip is learned, taken from the store's OWN reply, never inferred
415
- * from the cursor. Recorded ONLY on a complete drain: a tip ahead of the frames it covers would
416
- * name a commit this peer has not reconciled to, and the next `commit()` would win a
417
- * compare-and-set at an epoch it had not caught up to. Only `own-unmerged` stops the pull early
418
- * and takes no tip; the `ahead` path steps OVER its frame and drains to the end, so it DOES
419
- * record the tip (the head is genuinely beyond this peer) — and the `stranded` flag, not a
420
- * withheld tip, then stops the next `commit()` racing at it.
421
- */ const pullCommits = async ()=>{
422
- if (!journalReplayed) {
423
- 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');
424
- }
425
- if (mls == null || commitTopicID == null) return false;
426
- const port = mls;
427
- const topicID = commitTopicID;
724
+ * Also the only place the log's tip is learned, from the store's OWN reply, never inferred from
725
+ * the cursor — recorded ONLY on a complete drain, since a tip ahead of the frames it covers
726
+ * would let the next `commit()` win a compare-and-set at an epoch it had not caught up to. Only
727
+ * `own-unmerged` stops early and takes no tip; `ahead` steps over its frame and drains to the
728
+ * end, so it DOES record one — the `stranded` flag, not a withheld tip, then stops `commit()`.
729
+ */ const walkCommits = async (port, topicID)=>{
428
730
  let advancedEpoch = false;
429
731
  // The tip from the SAME reply whose frames were processed, so it can never run ahead of them.
430
732
  const takeHead = (head)=>{
@@ -433,10 +735,8 @@ export function createGroupPeer(params) {
433
735
  while(true){
434
736
  const result = await mux.fetchTopic({
435
737
  topicID,
436
- // From the cursor. With no cursor (fresh member from a Welcome, trimmed backlog, just
437
- // rejoined) read from the OLDEST retained frame. Seeding from the topic's `head` would
438
- // be a guess: it names commits this peer never applied, wrong in exactly the case this
439
- // lane exists for.
738
+ // From the cursor. With no cursor (fresh member, trimmed backlog, just rejoined) read
739
+ // from the OLDEST retained frame — seeding from the topic's `head` would be a guess.
440
740
  ...reconciledHead != null ? {
441
741
  after: reconciledHead
442
742
  } : {},
@@ -444,16 +744,15 @@ export function createGroupPeer(params) {
444
744
  });
445
745
  if (result.messages.length === 0) {
446
746
  // Drained. The tip an EMPTY page reports is not redundant: a topic keeps its head when
447
- // its frames age out, so a fully swept log still has a tip — and a peer that anchored on
448
- // its own cursor here would compare-and-set against `null` on a topic whose head is a real
449
- // sequenceID, and lose forever.
747
+ // its frames age out, so anchoring on the cursor here would compare-and-set against
748
+ // `null` on a topic whose head is real, and lose forever.
450
749
  takeHead(result.head);
451
750
  return advancedEpoch;
452
751
  }
453
752
  for (const message of result.messages){
454
- // A commit this peer landed moved its cursor to that frame's position on acceptance, so an
455
- // ordinary pull starts after it (the journal carries that across a restart). A peer that
456
- // meets its own commit here is one whose journal was lost or never written.
753
+ // A commit this peer landed moved its cursor to that frame's position on acceptance (the
754
+ // journal carries that across a restart); meeting its own commit here means the journal
755
+ // was lost or never written.
457
756
  const position = asLogPosition(message.sequenceID);
458
757
  let frame;
459
758
  try {
@@ -462,37 +761,71 @@ export function createGroupPeer(params) {
462
761
  reconciledHead = position; // malformed: dropped, and the cursor still steps over it
463
762
  continue;
464
763
  }
764
+ // A wire version this build does not know, settled BEFORE the kind byte: nothing behind
765
+ // the magic means what this build thinks under an unknown version. On the commit topic —
766
+ // and only here — that is evidence in itself, so it goes to the classifier, not dropped.
767
+ if (frame.version !== HANDSHAKE_VERSION) {
768
+ const unreadable = classifyCommit(UNKNOWN_FRAME_VERSION, position, {
769
+ localDID,
770
+ epoch: crypto.epoch(),
771
+ appliedByEpoch
772
+ });
773
+ reconciledHead = position;
774
+ // Do what the classifier said, not what this branch assumes: it answers `ahead` today,
775
+ // and any other answer just steps over the frame, matching the bare advance above.
776
+ if (unreadable.row === 'ahead') {
777
+ healRequested = true;
778
+ stranded = true;
779
+ }
780
+ continue;
781
+ }
465
782
  if (frame.kind !== HANDSHAKE_KIND.commit) {
466
783
  reconciledHead = position; // the commit lane carries commits, and nothing else
467
784
  continue;
468
785
  }
469
786
  // Split the frame into the commit and the sealed blob of bodies it enacts. Reads bytes,
470
- // decrypts NOTHING: a peer walking the log reaches frames sealed under epochs it does not
471
- // hold (a late joiner reaches the commit that added it), and a blob it cannot open is
472
- // history, not poison. Opening it follows from "I can apply this commit", never precedes
473
- // reading it.
787
+ // decrypts NOTHING: a late joiner reaches frames sealed under epochs it does not hold, and
788
+ // an unopenable blob there is history, not poison.
474
789
  let commitFrame;
475
790
  try {
476
791
  commitFrame = decodeCommitFrame(frame.payload);
477
- } catch {
478
- reconciledHead = position; // malformed: dropped, and the cursor still steps over it
792
+ } catch (error) {
793
+ // Same split as the handshake version above, one layer down: an unknown COMMIT-FRAME
794
+ // version fails BEFORE the commit bytes are extracted, so there is no next frame to
795
+ // heal from — dropping it would step over the group's whole future. To the classifier.
796
+ if (isUnsupportedCommitFrameVersion(error)) {
797
+ const unreadable = classifyCommit(UNKNOWN_FRAME_VERSION, position, {
798
+ localDID,
799
+ epoch: crypto.epoch(),
800
+ appliedByEpoch
801
+ });
802
+ reconciledHead = position;
803
+ // The classifier's answer, not this branch's assumption — as above.
804
+ if (unreadable.row === 'ahead') {
805
+ healRequested = true;
806
+ stranded = true;
807
+ }
808
+ continue;
809
+ }
810
+ // Too short, or a commit length running past the end: genuinely not a frame, and
811
+ // nothing a future build would have written. Dropped, and the cursor steps over it.
812
+ reconciledHead = position;
479
813
  continue;
480
814
  }
481
815
  // The commit's OWN epoch and committer, from the commit's own bytes. Never
482
- // `message.senderDID` — the hub-authenticated publisher, the hub's word about who handed
483
- // it over, and the hub is not trusted: a hub that could name the committer could stamp
484
- // every recipient's own DID onto one poison frame and make the whole group heal at once.
485
- const disposition = classifyCommit(await port.readCommitHeader(commitFrame.commit), position, {
816
+ // `message.senderDID` — the hub's word about who handed it over, and the hub is not
817
+ // trusted: it could stamp every recipient's own DID onto one poison frame and make the
818
+ // whole group heal at once.
819
+ const header = await port.readCommitHeader(commitFrame.commit);
820
+ const disposition = classifyCommit(header, position, {
486
821
  localDID,
487
822
  epoch: crypto.epoch(),
488
823
  appliedByEpoch
489
824
  });
490
825
  if (disposition.row === 'own-unmerged') {
491
826
  // This peer's own commit, at the epoch it is still at: the hub took it, the group moved
492
- // on it, and the pending state died with its process. It can never be applied — MLS
493
- // merges a pending commit, does not process one — so the cursor stays put, the drain
494
- // stops, no tip is taken, and the peer heals. The trigger only RECORDS; `recover()`
495
- // takes the commit mutex this pull already holds.
827
+ // on, and the pending state died with its process. Cannot be applied (MLS merges a
828
+ // pending commit, never processes one), so the drain stops here and the peer heals.
496
829
  healRequested = true;
497
830
  stranded = true;
498
831
  return advancedEpoch;
@@ -506,8 +839,8 @@ export function createGroupPeer(params) {
506
839
  continue;
507
840
  }
508
841
  if (disposition.row === 'history') {
509
- // A frame from an epoch below this peer's that it holds no record for. Not a fork, not
510
- // poison, not the port's business: never handed over, its blob never touched.
842
+ // A frame from an epoch below this peer's with no record for it. Not a fork, not
843
+ // poison, not the port's business — its blob is never touched.
511
844
  reconciledHead = position;
512
845
  continue;
513
846
  }
@@ -530,14 +863,22 @@ export function createGroupPeer(params) {
530
863
  const framedEpoch = crypto.epoch();
531
864
  let applied;
532
865
  try {
533
- applied = await port.processCommit(commitFrame.commit, {
534
- senderDID: message.senderDID,
535
- // The resolver, not the bodies: the blob is opened only if the port asks for the
536
- // entries this commit names, and it asks only for a commit it is applying — framed at
537
- // this peer's epoch, which is the epoch the blob is sealed under. That makes body
538
- // delivery atomic with the commit.
539
- resolveLedgerEntries: createLedgerEntryResolver(commitFrame.sealedEntries, crypto.unwrap)
540
- });
866
+ // Through the seam, like every other site that ratchets the handle: it reads this
867
+ // epoch's app frames ahead of the apply and takes the anchor if the roster moved.
868
+ applied = await advanceHandle(port, ()=>{
869
+ return port.processCommit(commitFrame.commit, {
870
+ senderDID: message.senderDID,
871
+ // The resolver, not the bodies: the blob opens only if the port asks for entries
872
+ // this commit names, and only for a commit it applies — framed at this peer's
873
+ // epoch, the epoch the blob is sealed under, making body delivery atomic with the
874
+ // commit. Called from INSIDE the apply, so the open must not touch the handle's
875
+ // ratchet: `openEntries` reads only the epoch's exporter secret and is pure.
876
+ resolveLedgerEntries: createLedgerEntryResolver(commitFrame.sealedEntries, crypto.openEntries)
877
+ });
878
+ }, // A REJOIN rotates the anchor too, from a member the roster diff cannot see: an
879
+ // external commit by a member the roster still holds leaves every DID where it was.
880
+ // Only an APPLIED commit says anything about the group.
881
+ (result)=>result.advanced && header?.external === true);
541
882
  } catch (error) {
542
883
  if (!isMissingLedgerEntries(error)) {
543
884
  // The port broke its contract. The cursor stays and the frame is re-read — the pull is
@@ -546,16 +887,13 @@ export function createGroupPeer(params) {
546
887
  }
547
888
  // The commit names ledger entries whose bodies will not resolve. POISON: drop, advance,
548
889
  // do NOT heal. The bodies ride the commit sealed under its framed epoch, so a blob this
549
- // peer cannot open is one no member at this epoch can — nobody applies it, the group
550
- // never moves past that epoch, and the next honest commit is framed at the same epoch
551
- // and compare-and-sets behind it. Whole cost: a wasted lane slot any writer can burn
552
- // anyway.
890
+ // peer cannot open is one no member at this epoch can — nobody applies it, and the next
891
+ // honest commit is framed at the same epoch and compare-and-sets behind it.
553
892
  //
554
- // Healing here would hand any member a group-wide recovery storm for one publish (a
555
- // commit naming entries whose bodies it leaves out of the frame). Retrying, bounded or
556
- // not, only delays that. The one case where this peer really is the broken one
557
- // (everyone else resolved it and moved on) announces itself later from a different
558
- // frame: the next commit is then framed AHEAD of this peer's, and that heals it.
893
+ // Healing here would hand any member a group-wide recovery storm for one publish.
894
+ // Retrying only delays that. The one case where this peer really is the broken one
895
+ // announces itself later: the next commit is then framed AHEAD of this peer's, which
896
+ // heals it.
559
897
  reconciledHead = position;
560
898
  continue;
561
899
  }
@@ -565,19 +903,33 @@ export function createGroupPeer(params) {
565
903
  appliedByEpoch.set(framedEpoch, position);
566
904
  }
567
905
  // `{ advanced: false }` here is the port REFUSING a well-formed commit at this peer's own
568
- // epoch from another member: poison on the same terms as an unresolvable one — advances,
569
- // never retried, does not heal.
906
+ // epoch from another member: poison on the same terms as an unresolvable one.
570
907
  reconciledHead = position;
571
908
  }
572
- // A short page ends the log: every frame this reply named is processed, so its tip is one
573
- // this peer has reconciled to. A full page is not — the tip may be beyond it — so loop and
574
- // take the head from the reply that finally drains.
909
+ // A short page ends the log: every frame this reply named is processed, so its tip is
910
+ // reconciled. A full page is not — loop and take the head from the reply that finally drains.
575
911
  if (result.messages.length < COMMIT_FETCH_LIMIT) {
576
912
  takeHead(result.head);
577
913
  return advancedEpoch;
578
914
  }
579
915
  }
580
916
  };
917
+ /**
918
+ * The commit walk, with this segment's retained app frames delivered around it.
919
+ *
920
+ * The walk reads each epoch's frames ahead of the apply that leaves it; this adds the one epoch
921
+ * that has no apply after it — the head the walk stops at. Its frames are readable now and
922
+ * nothing further is coming to prompt them, so a peer whose backlog is entirely at its current
923
+ * epoch (or whose log held no commits at all) would otherwise never read a thing.
924
+ */ const pullCommits = async ()=>{
925
+ if (!journalReplayed) {
926
+ 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');
927
+ }
928
+ if (mls == null || commitTopicID == null) return false;
929
+ const advanced = await walkCommits(mls, commitTopicID);
930
+ await appLane.deliver();
931
+ return advanced;
932
+ };
581
933
  /** Pull the commit log, and rebuild the app lane if the pull moved the epoch. */ const reconcileCommits = async ()=>{
582
934
  const advanced = await pullCommits();
583
935
  if (advanced) await rebuildEpoch();
@@ -613,6 +965,10 @@ export function createGroupPeer(params) {
613
965
  } catch {
614
966
  return; // malformed frames are dropped
615
967
  }
968
+ // Dropped, exactly as before, and deliberately NOT the commit lane's heal: the rendezvous
969
+ // carries request/reply traffic, so a frame here in a format this build cannot read says
970
+ // nothing about where the group's line got to. Only the commit topic carries that evidence.
971
+ if (frame.version !== HANDSHAKE_VERSION) return;
616
972
  try {
617
973
  if (frame.kind === HANDSHAKE_KIND.recoveryRequest) {
618
974
  handleRecoveryRequest(decodeRecoveryRequest(frame.payload));
@@ -632,23 +988,21 @@ export function createGroupPeer(params) {
632
988
  const recoverySecret = await mls.exportRecoverySecret();
633
989
  commitTopicID = commitTopic(recoverySecret);
634
990
  rendezvousTopicID = rendezvousTopic(recoverySecret);
635
- // Both topics subscribed once for the peer's whole life — NOT rebuilt on resync, so a peer
636
- // stranded on a stale epoch still shares both rendezvous with the live group. Released only on
637
- // dispose. Subscribe BEFORE the first pull: the hub gates a topic fetch on the caller's own
638
- // subscription, and the subscription is also what asks it to hold the log.
991
+ // Both topics subscribed once for the peer's whole life — NOT rebuilt on resync, so a
992
+ // stranded peer still shares both rendezvous with the live group. Subscribe BEFORE the first
993
+ // pull: the hub gates a topic fetch on the caller's own subscription.
639
994
  commitUnsubscribe = mux.onInbound(commitTopicID, onCommitDelivery, {
640
995
  retention: commitLogRetentionSeconds
641
996
  });
642
997
  rendezvousUnsubscribe = mux.onInbound(rendezvousTopicID, onRendezvousMessage);
643
998
  // Then seed the cursor by READING the log — commits published before this peer subscribed are
644
- // exactly the ones no push will bring it. The seed is a lane operation, so the journal replays
645
- // AHEAD of it: a peer coming up after a crash settles its own pending commit before it reads a
646
- // log that may contain it. Neither step rebuilds the epoch — buildEpoch runs next.
999
+ // exactly the ones no push will bring it. A lane operation, so the journal replays AHEAD of
1000
+ // it. Neither step rebuilds the epoch — buildEpoch runs next.
647
1001
  await runSerial(async ()=>{
648
1002
  await replayJournal();
649
- // A peer restored with an incomplete ledger was killed between rejoining and bootstrapping:
650
- // empty ledger against a live head, nothing remembering it was mid-heal. The invariant finds
651
- // it, here and at every later lane operation, with no memory of how it got there.
1003
+ // A peer restored with an incomplete ledger was killed between rejoining and bootstrapping.
1004
+ // The invariant finds it here and at every later lane operation, with no memory of how it
1005
+ // got there.
652
1006
  await ensureLedger(Date.now() + recoveryTimeoutMs);
653
1007
  await pullCommits();
654
1008
  }).catch(()=>{
@@ -656,15 +1010,16 @@ export function createGroupPeer(params) {
656
1010
  });
657
1011
  };
658
1012
  /**
659
- * Frame a commit for the log: `[commit][wrap(bodies)]`, bodies sealed under the epoch secret the
660
- * commit is FRAMED at — the epoch every member that can apply it is at, and the one this group
661
- * stays at until the commit is adopted. A host that adopted first has rotated past it and can
662
- * seal for nobody, so it is told rather than publishing a blob no member can open.
1013
+ * Frame a commit for the log: `[commit][sealEntries(bodies)]`, bodies sealed under a key derived
1014
+ * from the epoch the commit is FRAMED at — the epoch every member that can apply it is at, and
1015
+ * the one this group stays at until the commit is adopted. A host that adopted first has rotated
1016
+ * past it and can seal for nobody, so it is told rather than publishing a blob no member can
1017
+ * open.
663
1018
  */ const frameCommit = async (commit, bodies)=>{
664
1019
  if (crypto.epoch() !== epoch) {
665
1020
  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.');
666
1021
  }
667
- const sealedEntries = await crypto.wrap(encodeLedgerEntries(bodies));
1022
+ const sealedEntries = await crypto.sealEntries(encodeLedgerEntries(bodies));
668
1023
  return encodeHandshakeFrame(HANDSHAKE_KIND.commit, encodeCommitFrame(commit, sealedEntries));
669
1024
  };
670
1025
  /**
@@ -686,21 +1041,21 @@ export function createGroupPeer(params) {
686
1041
  if (entry.acceptedAs != null) {
687
1042
  // It landed and this peer recorded that before adopting. Nothing to ask: no republish, no
688
1043
  // re-seal, no network. The recorded sequenceID is both the last position processed and the
689
- // log's tip as of that frame — a stale tip is safe (a commit racing it just loses the
690
- // compare-and-set and rebases), where a WRONG one would win a race it had no right to.
1044
+ // log's tip as of that frame — a stale tip is safe (loses a race and rebases), a WRONG one
1045
+ // would win a race it had no right to.
691
1046
  const accepted = asLogPosition(entry.acceptedAs);
692
1047
  reconciledHead = accepted;
693
1048
  commitLogHead = accepted;
694
1049
  appliedByEpoch.set(entry.epoch, accepted);
695
- await adoptJournalled(entry.journal);
1050
+ // Through the seam: the adopt ratchets the handle, so this epoch's app frames are read
1051
+ // first and the anchor is taken if the journalled commit moved the roster.
1052
+ await advanceHandle(mls, ()=>adoptJournalled(entry.journal));
696
1053
  await journal.clear(entry.publishID);
697
1054
  return true;
698
1055
  }
699
- // Republishing means RE-SEALING the bodies, sealable only under the host's current epoch. That
700
- // equals the framed epoch only while onAccepted is the sole place the host adopts — and an
701
- // entry with no recorded acceptance at any other epoch proves it is not. Sealing anyway
702
- // publishes a blob no member can open and wedges the lane for the whole group, so the peer
703
- // refuses and keeps the slot.
1056
+ // Republishing means RE-SEALING the bodies, sealable only under the host's current epoch —
1057
+ // which equals the framed epoch only while `onAccepted` is the sole place the host adopts.
1058
+ // Sealing anyway publishes a blob no member can open and wedges the lane for the whole group.
704
1059
  if (crypto.epoch() !== entry.epoch) {
705
1060
  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.`);
706
1061
  }
@@ -726,9 +1081,11 @@ export function createGroupPeer(params) {
726
1081
  await journal.clear(entry.publishID);
727
1082
  lostCommit = entry.kind === 'ledger' ? {
728
1083
  kind: 'ledger',
729
- tokens: entry.bodies
1084
+ tokens: entry.bodies,
1085
+ journal: entry.journal
730
1086
  } : {
731
- kind: entry.kind
1087
+ kind: entry.kind,
1088
+ journal: entry.journal
732
1089
  };
733
1090
  return false;
734
1091
  }
@@ -737,17 +1094,15 @@ export function createGroupPeer(params) {
737
1094
  //
738
1095
  // Record acceptance BEFORE adopting, as `commit()` does: adopting moves the handle past the
739
1096
  // framed epoch, and a crash between the two would leave a journalled commit indistinguishable
740
- // from a host that adopted out of band. Written first, replay is idempotent — the next one
741
- // adopts from the slot and never republishes.
1097
+ // from a host that adopted out of band. Written first, replay is idempotent.
742
1098
  await journal.markAccepted(entry.publishID, sequenceID);
743
- // This peer's own accepted frame is BOTH the last thing it processed and the log's tip — one
744
- // position, two names, genuinely coinciding for this one frame; otherwise a `commit()` right
745
- // after a `replay()` would anchor on a tip from before its own commit landed.
1099
+ // This peer's own accepted frame is BOTH the last thing it processed and the log's tip —
1100
+ // otherwise a `commit()` right after a `replay()` would anchor on a stale tip.
746
1101
  const accepted = asLogPosition(sequenceID);
747
1102
  reconciledHead = accepted;
748
1103
  commitLogHead = accepted;
749
1104
  appliedByEpoch.set(entry.epoch, accepted);
750
- await adoptJournalled(entry.journal);
1105
+ await advanceHandle(mls, ()=>adoptJournalled(entry.journal));
751
1106
  await journal.clear(entry.publishID);
752
1107
  return true;
753
1108
  };
@@ -771,13 +1126,12 @@ export function createGroupPeer(params) {
771
1126
  /**
772
1127
  * The ledger completeness invariant, checked before every lane operation and repaired on the
773
1128
  * spot. Purely local (the head folded from the handle's entries against the authenticated head
774
- * its own group state carries) and needs no memory of how the peer got here, which is what makes
775
- * the state it detects self-healing.
1129
+ * its own group state carries), which is what makes the state it detects self-healing.
776
1130
  *
777
1131
  * A handle that rejoined by external commit holds an EMPTY ledger against a live head, not a
778
- * neutral start: the roster folds from the entries, so with none the creator is the only admin.
779
- * Every admin promoted since is invisible and the peer REJECTS the next commit any of them
780
- * authors — it re-strands itself. A crash between rejoin and bootstrap leaves exactly that on
1132
+ * neutral start: the roster folds from the entries, so with none the creator is the only admin,
1133
+ * every admin promoted since is invisible, and the peer REJECTS the next commit any of them
1134
+ * authors — re-stranding itself. A crash between rejoin and bootstrap leaves exactly that on
781
1135
  * disk, and this finds it on the next lane operation.
782
1136
  *
783
1137
  * Returns whether the ledger is complete. Never throws: an incomplete ledger is a persistent,
@@ -788,15 +1142,14 @@ export function createGroupPeer(params) {
788
1142
  const topicID = rendezvousTopicID;
789
1143
  if (await port.isLedgerComplete()) return true;
790
1144
  // Gather the WHOLE ordered ledger — not "the missing ids", which nothing enumerates: the
791
- // authenticated head is a chain digest, not a list, and the rejoined handle has no entries to
792
- // diff. Every responder with a complete ledger answers, each answer checked against the head
793
- // this handle carries: a lying responder can withhold, never rewrite, and one that fails is
794
- // dropped for the next reply.
1145
+ // authenticated head is a chain digest, not a list. Every responder with a complete ledger
1146
+ // answers, each checked against the head this handle carries: a lying responder can withhold,
1147
+ // never rewrite, and one that fails is dropped for the next reply.
795
1148
  //
796
- // The request is the port's signed blob (same one a rejoin carries, same call). It names this
797
- // peer inside a signature (what a responder authorizes against) and carries an ephemeral
798
- // public key (the only key a responder seals to). Both matter: without the first any stranger
799
- // gets the group's whole authority state for one publish; without the second, so does the hub.
1149
+ // The request is the port's signed blob, naming this peer inside a signature (what a
1150
+ // responder authorizes against) and carrying an ephemeral public key (the only key a
1151
+ // responder seals to) — without the first any stranger gets the group's whole authority state
1152
+ // for one publish; without the second, so does the hub.
800
1153
  const requestID = newPublishID();
801
1154
  const request = await port.createRecoveryRequest(requestID);
802
1155
  return await new Promise((resolve)=>{
@@ -847,17 +1200,14 @@ export function createGroupPeer(params) {
847
1200
  if (await replayJournal()) await rebuildEpoch();
848
1201
  // 0.5. Refuse on an incomplete ledger. A rejoin whose bootstrap never finished leaves a
849
1202
  // reset roster: the fold sees only the genesis creator as admin, every promotion since
850
- // is invisible, and a commit built now acts on authority it cannot verify.
851
- // `ensureLedger` repairs it in place when a responder answers; when none does it stays
852
- // incomplete, and the peer must publish and advance NOTHING.
1203
+ // is invisible. `ensureLedger` repairs it in place when a responder answers; when none
1204
+ // does, the peer must publish and advance NOTHING.
853
1205
  //
854
- // Same refusal the `stranded` gate below makes. It THROWS rather than returning because
855
- // `commit()` returns only when the commit LANDED (onAccepted ran, epoch moved) — a peer
856
- // that cannot commit says so by throwing, as for a strand or spent deadline. `recover()`
857
- // answers `advanced: false` instead because its contract carries that flag; `commit()`'s
858
- // does not. NO heal is scheduled: this peer holds its leaf, so an external-commit rejoin
859
- // would rotate the tree for nothing — the gather that just failed for want of a
860
- // responder IS the repair, re-running at the head of the next lane operation.
1206
+ // THROWS rather than returning, since `commit()` returns only when the commit LANDED —
1207
+ // `recover()` answers `advanced: false` instead because its contract carries that flag;
1208
+ // `commit()`'s does not. NO heal is scheduled: this peer holds its leaf, so a rejoin
1209
+ // would rotate the tree for nothing — the gather that just failed IS the repair,
1210
+ // re-running at the head of the next lane operation.
861
1211
  if (!await ensureLedger(Date.now() + recoveryTimeoutMs)) {
862
1212
  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.');
863
1213
  }
@@ -866,13 +1216,11 @@ export function createGroupPeer(params) {
866
1216
  // 1. Pull the log to the end: every frame processed, and the tip to race at learned from
867
1217
  // the store's own reply.
868
1218
  await reconcileCommits();
869
- // The pull found positive evidence this peer is off the group's line (own un-merged
870
- // commit, a frame framed ahead, or the losing side of a fork), and that stands whether or
871
- // not the following heal lands. Unwind rather than race: on the `ahead` path the pull
872
- // drained to the end and took the live tip, so a commit here would win the compare-and-set
873
- // at an epoch it never caught up to. The lane releases, the heal runs as its own
874
- // operation, the host's commit is later. Gating on `stranded` not `healRequested` is what
875
- // makes this survive a heal that found no responder — a `commit()` right after must refuse.
1219
+ // The pull found positive evidence this peer is off the group's line, which stands
1220
+ // whether or not a following heal lands. Unwind rather than race: on the `ahead` path the
1221
+ // pull already took the live tip, so a commit here would win at an epoch it never caught
1222
+ // up to. Gating on `stranded`, not `healRequested`, is what survives a heal that found no
1223
+ // responder.
876
1224
  if (stranded) {
877
1225
  throw new RecoveryRequiredError('commit: the log holds a frame this peer cannot reconcile with — its own un-merged commit, or a commit from an epoch ahead of it. It must recover before it can commit again.');
878
1226
  }
@@ -882,9 +1230,8 @@ export function createGroupPeer(params) {
882
1230
  // 3. Journal BEFORE publishing, durably: from here to the hub's answer is the crash
883
1231
  // window, and the slot is the only thing that survives it.
884
1232
  //
885
- // Anchor on the log's TIP, not the cursor. The cursor names the last frame PROCESSED,
886
- // which need not be one the head can ever name — anchoring there stakes every commit on
887
- // the two never diverging, a property of the store not this peer.
1233
+ // Anchor on the log's TIP, not the cursor: the cursor names the last frame PROCESSED,
1234
+ // which need not be one the head can ever name.
888
1235
  const publishID = newPublishID();
889
1236
  const expectedHead = commitLogHead;
890
1237
  const framedEpoch = crypto.epoch();
@@ -916,32 +1263,38 @@ export function createGroupPeer(params) {
916
1263
  // operation replays it and asks the store which it was.
917
1264
  throw error;
918
1265
  }
919
- // 6. Lost the compare-and-set: someone committed first — the expected path, not an
920
- // error. Drop the pending commit untouched (costs nothing, pre-commit key material
921
- // retained), clear the slot, and go back to step 1 against the winner.
1266
+ // 6. Lost the compare-and-set: someone committed first — expected, not an error. Drop
1267
+ // the pending commit untouched, clear the slot, and go back to step 1.
922
1268
  await slot.clear(publishID);
923
1269
  if (Date.now() >= deadline) {
924
- throw new CommitDeadlineError(`commit: still rebasing after ${commitDeadlineMs}ms and ${attempt + 1} attempts`);
1270
+ // The last lost compare-and-set, carried: it is the proximate reason this attempt
1271
+ // restarted, and the deadline only names how many such losses ran out the clock.
1272
+ throw new CommitDeadlineError(`commit: still rebasing after ${commitDeadlineMs}ms and ${attempt + 1} attempts`, {
1273
+ cause: error
1274
+ });
925
1275
  }
926
1276
  continue;
927
1277
  }
928
1278
  // 5. Accepted. Record it in the slot BEFORE the host adopts, while the group is still at
929
- // the framed epoch. That ordering makes a crash legible: an entry carrying its
930
- // acceptance landed and can be adopted on restart; an entry carrying none, at an epoch
931
- // past the framed one, is a host that adopted outside `onAccepted`. Recorded after the
932
- // adopt, the two would be indistinguishable and the peer would have to re-seal a commit
933
- // it can seal for no one.
1279
+ // the framed epoch — an entry carrying its acceptance can be adopted on restart; one
1280
+ // carrying none at a later epoch is a host that adopted outside `onAccepted`. Recorded
1281
+ // after the adopt, the two would be indistinguishable.
934
1282
  await slot.markAccepted(publishID, sequenceID);
935
1283
  // The commit is the group's now — this frame is both the last position processed and the
936
1284
  // log's new tip.
937
1285
  const accepted = asLogPosition(sequenceID);
938
1286
  reconciledHead = accepted;
939
1287
  commitLogHead = accepted;
940
- // A commit this peer made and adopted was enacted at that epoch, like an applied one, so
941
- // it joins the fork record on the same terms. Without it a second commit at an epoch this
942
- // peer OWNS would read as history.
1288
+ // A commit this peer made and adopted was enacted at that epoch, like an applied one —
1289
+ // without it a second commit at an epoch this peer OWNS would read as history.
943
1290
  appliedByEpoch.set(framedEpoch, accepted);
944
- await pending.onAccepted();
1291
+ // The host adopts here, and adopting ratchets the handle — through the seam, exactly as
1292
+ // an applied commit does. A member never processes its own commit, so the apply site
1293
+ // never runs for the roster change this peer just made: without this, the author of a
1294
+ // Remove keeps publishing to a topic the removed member still holds, and the author of an
1295
+ // Add sits on a topic the new member's handle cannot derive — silently, and no restart
1296
+ // heals it.
1297
+ await advanceHandle(mls, ()=>pending.onAccepted());
945
1298
  await slot.clear(publishID);
946
1299
  await rebuildEpoch();
947
1300
  return takeLost();
@@ -1017,19 +1370,16 @@ export function createGroupPeer(params) {
1017
1370
  if (await replayJournal()) await rebuildEpoch();
1018
1371
  const deadline = Date.now() + recoveryDeadlineMs;
1019
1372
  while(Date.now() < deadline){
1020
- // 1. Pull to the end. It may resolve the strand outright (the missing frames may just be
1021
- // there), and a heal it no longer needs must NOT run: the external commit would rotate
1022
- // the tree for the whole group. Rebuild if it moved the epoch, before anything is
1023
- // framed: the peer that lost a heal race applies the winner's commit HERE, and a frame
1024
- // sealed against an app lane that had not caught up would seal under an epoch the group
1025
- // left.
1373
+ // 1. Pull to the end. It may resolve the strand outright, and a heal it no longer needs
1374
+ // must NOT run: the external commit would rotate the tree for the whole group. Rebuild
1375
+ // if it moved the epoch, before anything is framed: the peer that lost a heal race
1376
+ // applies the winner's commit HERE.
1026
1377
  healRequested = false;
1027
1378
  await reconcileCommits();
1028
1379
  // 2. The head to race at, from the store's own reply.
1029
1380
  const expectedHead = await readCommitHead(commits);
1030
1381
  // 3. Mint a request and rendezvous for a sealed GroupInfo. Fresh request per attempt: the
1031
- // ephemeral key is minted with it, and a reply to an already-used request is one this
1032
- // peer can no longer open.
1382
+ // ephemeral key is minted with it, and a reply to an already-used request is unopenable.
1033
1383
  const requestID = newPublishID();
1034
1384
  const request = await port.createRecoveryRequest(requestID);
1035
1385
  const sealed = await requestGroupInfo(request, requestID, rendezvous, deadline);
@@ -1046,14 +1396,12 @@ export function createGroupPeer(params) {
1046
1396
  }
1047
1397
  if (pending == null) continue;
1048
1398
  // 5. The entries this peer holds, snapshotted BEFORE the rejoined handle replaces them —
1049
- // the last moment they can be read (a rejoin's handle holds an EMPTY ledger). Kept
1050
- // across a failed attempt, so a retry filters the same entries rather than snapshotting
1051
- // the empty ledger a failed bootstrap left.
1399
+ // the last moment they can be read. Kept across a failed attempt, so a retry filters
1400
+ // the same entries rather than snapshotting the empty ledger a failed bootstrap left.
1052
1401
  if (inFlightEntries == null) inFlightEntries = await port.getLedger();
1053
1402
  const inFlight = inFlightEntries;
1054
- // 6. Publish the external commit, compare-and-set at the head. It changes the ratchet tree,
1055
- // so it races like any commit — publishing unconditionally would re-open the very fork
1056
- // the log's compare-and-set closes, on the worst path.
1403
+ // 6. Publish the external commit, compare-and-set at the head: it changes the ratchet
1404
+ // tree, so it races like any commit.
1057
1405
  const publishID = newPublishID();
1058
1406
  const payload = await frameCommit(pending.commit, []);
1059
1407
  let sequenceID;
@@ -1071,12 +1419,15 @@ export function createGroupPeer(params) {
1071
1419
  }
1072
1420
  // 7. Accepted: the group has this peer's new leaf. Adopt the rejoined handle — the only
1073
1421
  // place it may be adopted. Deliberately UNJOURNALLED: a crash here leaves an orphaned
1074
- // external commit in the log, which repairs itself. On restart the orphan is framed at
1075
- // the group's epoch, not this peer's, so the own-commit trigger (tests authorship AND
1076
- // current epoch) stays quiet; the original heal condition still holds, the peer rejoins
1077
- // again, and `resync` collects the leaf the orphan added. Leaves do not accumulate.
1422
+ // external commit that repairs itself — framed at the group's epoch, not this peer's,
1423
+ // so the own-commit trigger stays quiet, the heal condition still holds, and `resync`
1424
+ // later collects the leaf the orphan added.
1078
1425
  const rejoinedAtEpoch = (await port.readCommitHeader(pending.commit))?.epoch;
1079
- await pending.onAccepted();
1426
+ // Through the seam, like every other site that ratchets the handle — and it rotates
1427
+ // ANYWAY: this is the rejoin, which no roster diff can see (see {@link anchor}). The
1428
+ // anchor is the POST-commit epoch: the handle advances inside the seam and only then is
1429
+ // the anchor captured, exactly where an applying member lands.
1430
+ await advanceHandle(port, ()=>pending.onAccepted(), ()=>true);
1080
1431
  const accepted = asLogPosition(sequenceID);
1081
1432
  reconciledHead = accepted;
1082
1433
  commitLogHead = accepted;
@@ -1085,16 +1436,13 @@ export function createGroupPeer(params) {
1085
1436
  if (rejoinedAtEpoch != null) appliedByEpoch.set(rejoinedAtEpoch, sequenceID);
1086
1437
  healRequested = false;
1087
1438
  // The one place the commit gate is released: the rejoin landed, so this peer's leaf is
1088
- // back in the tree at the group's epoch and the stale-epoch fork it guards is closed. A
1089
- // bootstrap that still fails below is a roster-repair problem `commit()`'s own
1090
- // ledger-completeness check handles — not a reason to keep refusing every commit.
1439
+ // back in the tree and the stale-epoch fork it guards is closed. A bootstrap that still
1440
+ // fails below is `commit()`'s own ledger-completeness check to handle.
1091
1441
  stranded = false;
1092
1442
  await rebuildEpoch();
1093
1443
  // 8. Bootstrap: REQUIRED, not a formality. Until it runs, the ledger is empty against a
1094
- // live head — a roster reset where every admin promoted since genesis is invisible and
1095
- // the next commit is rejected. Failure here is a persistent degraded state, NOT a heal:
1096
- // keep the condition, keep the snapshotted entries, never report advanced with a ledger
1097
- // known incomplete.
1444
+ // live head — every admin promoted since genesis is invisible and the next commit is
1445
+ // rejected. Failure here is a persistent degraded state, NOT a heal.
1098
1446
  if (!await ensureLedger(deadline)) {
1099
1447
  healRequested = true;
1100
1448
  return {
@@ -1102,15 +1450,11 @@ export function createGroupPeer(params) {
1102
1450
  reenact: []
1103
1451
  };
1104
1452
  }
1105
- // 9. Re-enact by MEMBERSHIP, never by the failure that brought this peer here. Bootstrap
1106
- // just fetched the whole ordered, head-verified ledger, so the filter is local and
1107
- // free: keep only entries the group's ledger does NOT hold.
1108
- //
1109
- // An entry it DOES hold was enacted for everyone (that is what the authenticated ledger
1110
- // means), and appending it again puts it at the END of the log where the fold is
1111
- // last-write-wins by position: it would win, reverting whatever a later admin wrote over
1112
- // the same subject, with no error or signal anywhere. A token's content id is its
1113
- // digest, so token equality IS id equality and this set-difference is the id one.
1453
+ // 9. Re-enact by MEMBERSHIP, never by the failure that brought this peer here: keep only
1454
+ // entries the group's ledger does NOT hold. An entry it DOES hold was enacted for
1455
+ // everyone, and appending it again puts it at the END of the log where the fold is
1456
+ // last-write-wins — it would win, silently reverting whatever a later admin wrote over
1457
+ // the same subject.
1114
1458
  const held = new Set(await port.getLedger());
1115
1459
  const reenact = inFlight.filter((token)=>!held.has(token));
1116
1460
  inFlightEntries = null;
@@ -1150,6 +1494,22 @@ export function createGroupPeer(params) {
1150
1494
  }
1151
1495
  };
1152
1496
  const ready = (async ()=>{
1497
+ // Settle the app-lane anchor BEFORE the seed pull: a roster change the seed pull applies must
1498
+ // be able to rotate it off whatever lands here rather than have a later seed overwrite it.
1499
+ //
1500
+ // A stored anchor is RESTORED, never recomputed — see {@link anchor} for why (a rebooted
1501
+ // handle can never re-export an earlier epoch's secret).
1502
+ //
1503
+ // An empty store is first boot, and only first boot: seed at the initial epoch, as a group
1504
+ // with no roster change yet must. A member booting over a handle it was just added to seeds
1505
+ // at its own add epoch — the same epoch every existing member rotates to on applying that
1506
+ // add, so the two agree with no exchange between them.
1507
+ const stored = await anchorStore?.load();
1508
+ if (stored != null) {
1509
+ anchor = stored;
1510
+ } else {
1511
+ await captureAnchor();
1512
+ }
1153
1513
  await initControlLanes();
1154
1514
  await buildEpoch();
1155
1515
  })();
@@ -1181,18 +1541,18 @@ export function createGroupPeer(params) {
1181
1541
  await ready;
1182
1542
  await rebuildEpoch();
1183
1543
  },
1544
+ anchorEpoch: ()=>anchor.epoch,
1184
1545
  dispose: async ()=>{
1185
1546
  // Tear down even a peer whose init failed — it still holds a hub drain.
1186
1547
  await settled;
1187
1548
  commitUnsubscribe?.();
1188
1549
  rendezvousUnsubscribe?.();
1189
- // Resolve any in-flight recovery rendezvous FIRST, before clearing its timers. A `recover()`
1190
- // blocked in `requestGroupInfo` is settled by exactly two things — a reply or its timeout —
1191
- // and dispose is about to clear that timeout; drain the waiters here or the heal never
1192
- // settles, `commitTail` never resolves, and every lane operation queued behind it hangs.
1193
- // Resolve, then clear, so a fired timer cannot race a half-drained map. (The ledger gather
1194
- // needs no such drain: its timeout is a local held in none of these maps, so it fires and
1195
- // settles `ensureLedger` on its own.)
1550
+ // Resolve any in-flight recovery rendezvous FIRST, before clearing its timers: a
1551
+ // `recover()` blocked in `requestGroupInfo` is settled by exactly two things — a reply or
1552
+ // its timeout — and dispose is about to clear that timeout. Skipping this drain would hang
1553
+ // the heal, `commitTail`, and every lane operation queued behind it. Resolve, then clear, so
1554
+ // a fired timer cannot race a half-drained map. (The ledger gather needs no such drain: its
1555
+ // timeout is a local held in none of these maps.)
1196
1556
  for (const waiter of recoveryWaiters.values())waiter(null);
1197
1557
  recoveryWaiters.clear();
1198
1558
  for (const timer of recoveryTimers.values())clearTimeout(timer);