@941design/marmot-engine 0.0.0-stage → 0.2.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +434 -0
  2. package/LICENSE +49 -0
  3. package/README.md +33 -2
  4. package/dist/audit/emitter.d.ts +17 -0
  5. package/dist/audit/emitter.js +30 -0
  6. package/dist/audit/helpers.d.ts +16 -0
  7. package/dist/audit/helpers.js +103 -0
  8. package/dist/audit/index.d.ts +6 -0
  9. package/dist/audit/index.js +6 -0
  10. package/dist/audit/recorder.d.ts +13 -0
  11. package/dist/audit/recorder.js +24 -0
  12. package/dist/audit/sink.d.ts +16 -0
  13. package/dist/audit/sink.js +27 -0
  14. package/dist/audit/types-internal.d.ts +7 -0
  15. package/dist/audit/types-internal.js +1 -0
  16. package/dist/audit/types.d.ts +289 -0
  17. package/dist/audit/types.js +2 -0
  18. package/dist/core/account-identity-proof.d.ts +165 -0
  19. package/dist/core/account-identity-proof.js +277 -0
  20. package/dist/core/application-rumor.d.ts +45 -0
  21. package/dist/core/application-rumor.js +120 -0
  22. package/dist/core/auth-service.d.ts +2 -0
  23. package/dist/core/auth-service.js +52 -0
  24. package/dist/core/binary.d.ts +142 -0
  25. package/dist/core/binary.js +363 -0
  26. package/dist/core/capabilities.d.ts +51 -0
  27. package/dist/core/capabilities.js +102 -0
  28. package/dist/core/client-state.d.ts +119 -0
  29. package/dist/core/client-state.js +226 -0
  30. package/dist/core/commit-authorization.d.ts +26 -0
  31. package/dist/core/commit-authorization.js +26 -0
  32. package/dist/core/components/admin-policy.d.ts +4 -0
  33. package/dist/core/components/admin-policy.js +69 -0
  34. package/dist/core/components/agent-text-stream.d.ts +51 -0
  35. package/dist/core/components/agent-text-stream.js +112 -0
  36. package/dist/core/components/app-components-list.d.ts +17 -0
  37. package/dist/core/components/app-components-list.js +35 -0
  38. package/dist/core/components/avatar-url.d.ts +12 -0
  39. package/dist/core/components/avatar-url.js +85 -0
  40. package/dist/core/components/bytes.d.ts +5 -0
  41. package/dist/core/components/bytes.js +18 -0
  42. package/dist/core/components/dictionary.d.ts +80 -0
  43. package/dist/core/components/dictionary.js +175 -0
  44. package/dist/core/components/disband-validation.d.ts +21 -0
  45. package/dist/core/components/disband-validation.js +173 -0
  46. package/dist/core/components/encrypted-media.d.ts +44 -0
  47. package/dist/core/components/encrypted-media.js +210 -0
  48. package/dist/core/components/group-lifecycle.d.ts +10 -0
  49. package/dist/core/components/group-lifecycle.js +32 -0
  50. package/dist/core/components/group-profile.d.ts +24 -0
  51. package/dist/core/components/group-profile.js +35 -0
  52. package/dist/core/components/host-safety.d.ts +9 -0
  53. package/dist/core/components/host-safety.js +148 -0
  54. package/dist/core/components/ids.d.ts +74 -0
  55. package/dist/core/components/ids.js +73 -0
  56. package/dist/core/components/index.d.ts +14 -0
  57. package/dist/core/components/index.js +14 -0
  58. package/dist/core/components/integrity.d.ts +141 -0
  59. package/dist/core/components/integrity.js +293 -0
  60. package/dist/core/components/message-retention.d.ts +17 -0
  61. package/dist/core/components/message-retention.js +26 -0
  62. package/dist/core/components/nostr-routing.d.ts +8 -0
  63. package/dist/core/components/nostr-routing.js +92 -0
  64. package/dist/core/components/url.d.ts +26 -0
  65. package/dist/core/components/url.js +44 -0
  66. package/dist/core/convergence-status.d.ts +84 -0
  67. package/dist/core/convergence-status.js +82 -0
  68. package/dist/core/convergence.d.ts +567 -0
  69. package/dist/core/convergence.js +1150 -0
  70. package/dist/core/credential.d.ts +16 -0
  71. package/dist/core/credential.js +64 -0
  72. package/dist/core/default-capabilities.d.ts +9 -0
  73. package/dist/core/default-capabilities.js +34 -0
  74. package/dist/core/extensions.d.ts +9 -0
  75. package/dist/core/extensions.js +5 -0
  76. package/dist/core/grease.d.ts +2 -0
  77. package/dist/core/grease.js +6 -0
  78. package/dist/core/group-event.d.ts +18 -0
  79. package/dist/core/group-event.js +30 -0
  80. package/dist/core/group-lifecycle.d.ts +42 -0
  81. package/dist/core/group-lifecycle.js +66 -0
  82. package/dist/core/group-members.d.ts +37 -0
  83. package/dist/core/group-members.js +99 -0
  84. package/dist/core/group-message-classify.d.ts +42 -0
  85. package/dist/core/group-message-classify.js +57 -0
  86. package/dist/core/group-message-crypto.d.ts +53 -0
  87. package/dist/core/group-message-crypto.js +140 -0
  88. package/dist/core/group-message.d.ts +5 -0
  89. package/dist/core/group-message.js +11 -0
  90. package/dist/core/group.d.ts +45 -0
  91. package/dist/core/group.js +78 -0
  92. package/dist/core/inbound.d.ts +102 -0
  93. package/dist/core/inbound.js +79 -0
  94. package/dist/core/index.d.ts +28 -0
  95. package/dist/core/index.js +26 -0
  96. package/dist/core/key-package-eligibility.d.ts +31 -0
  97. package/dist/core/key-package-eligibility.js +116 -0
  98. package/dist/core/key-package-event-decode.d.ts +43 -0
  99. package/dist/core/key-package-event-decode.js +118 -0
  100. package/dist/core/key-package-event-delete.d.ts +16 -0
  101. package/dist/core/key-package-event-delete.js +46 -0
  102. package/dist/core/key-package-event-encode.d.ts +28 -0
  103. package/dist/core/key-package-event-encode.js +102 -0
  104. package/dist/core/key-package-event.d.ts +4 -0
  105. package/dist/core/key-package-event.js +8 -0
  106. package/dist/core/key-package.d.ts +55 -0
  107. package/dist/core/key-package.js +115 -0
  108. package/dist/core/leaf-succession.d.ts +83 -0
  109. package/dist/core/leaf-succession.js +97 -0
  110. package/dist/core/media/canonical.d.ts +34 -0
  111. package/dist/core/media/canonical.js +57 -0
  112. package/dist/core/media/crypto.d.ts +79 -0
  113. package/dist/core/media/crypto.js +215 -0
  114. package/dist/core/media/imeta.d.ts +33 -0
  115. package/dist/core/media/imeta.js +188 -0
  116. package/dist/core/media/locator.d.ts +44 -0
  117. package/dist/core/media/locator.js +69 -0
  118. package/dist/core/media/types.d.ts +83 -0
  119. package/dist/core/media/types.js +12 -0
  120. package/dist/core/media.d.ts +6 -0
  121. package/dist/core/media.js +12 -0
  122. package/dist/core/protocol.d.ts +51 -0
  123. package/dist/core/protocol.js +41 -0
  124. package/dist/core/relay-lists.d.ts +52 -0
  125. package/dist/core/relay-lists.js +86 -0
  126. package/dist/core/retained-history.d.ts +78 -0
  127. package/dist/core/retained-history.js +59 -0
  128. package/dist/core/transport.d.ts +43 -0
  129. package/dist/core/transport.js +21 -0
  130. package/dist/core/welcome-event.d.ts +61 -0
  131. package/dist/core/welcome-event.js +116 -0
  132. package/dist/core/welcome-join.d.ts +155 -0
  133. package/dist/core/welcome-join.js +243 -0
  134. package/dist/core/welcome.d.ts +3 -0
  135. package/dist/core/welcome.js +6 -0
  136. package/dist/engine/admin-policy.d.ts +58 -0
  137. package/dist/engine/admin-policy.js +137 -0
  138. package/dist/engine/auto-committer.d.ts +39 -0
  139. package/dist/engine/auto-committer.js +42 -0
  140. package/dist/engine/delivered-payloads.d.ts +61 -0
  141. package/dist/engine/delivered-payloads.js +84 -0
  142. package/dist/engine/disband-request.d.ts +41 -0
  143. package/dist/engine/disband-request.js +86 -0
  144. package/dist/engine/disband-tombstone.d.ts +14 -0
  145. package/dist/engine/disband-tombstone.js +66 -0
  146. package/dist/engine/fork-recovery.d.ts +672 -0
  147. package/dist/engine/fork-recovery.js +1615 -0
  148. package/dist/engine/group-engine.d.ts +571 -0
  149. package/dist/engine/group-engine.js +5112 -0
  150. package/dist/engine/history-tree.d.ts +232 -0
  151. package/dist/engine/history-tree.js +651 -0
  152. package/dist/engine/index.d.ts +16 -0
  153. package/dist/engine/index.js +15 -0
  154. package/dist/engine/ingest-disposition.d.ts +5 -0
  155. package/dist/engine/ingest-disposition.js +63 -0
  156. package/dist/engine/ingest.d.ts +390 -0
  157. package/dist/engine/ingest.js +1258 -0
  158. package/dist/engine/ingestion-pool.d.ts +74 -0
  159. package/dist/engine/ingestion-pool.js +95 -0
  160. package/dist/engine/message-dedup.d.ts +16 -0
  161. package/dist/engine/message-dedup.js +20 -0
  162. package/dist/engine/own-commit-stamp.d.ts +30 -0
  163. package/dist/engine/own-commit-stamp.js +71 -0
  164. package/dist/engine/retained-store.d.ts +79 -0
  165. package/dist/engine/retained-store.js +133 -0
  166. package/dist/engine/sender-ratchet.d.ts +50 -0
  167. package/dist/engine/sender-ratchet.js +196 -0
  168. package/dist/engine/state-notifications.d.ts +122 -0
  169. package/dist/engine/state-notifications.js +173 -0
  170. package/dist/engine/tree-convergence.d.ts +41 -0
  171. package/dist/engine/tree-convergence.js +90 -0
  172. package/dist/engine/types.d.ts +366 -0
  173. package/dist/engine/types.js +14 -0
  174. package/dist/engine/wire-format.d.ts +77 -0
  175. package/dist/engine/wire-format.js +120 -0
  176. package/dist/index.d.ts +12 -0
  177. package/dist/index.js +1 -0
  178. package/dist/mls.d.ts +11 -0
  179. package/dist/mls.js +11 -0
  180. package/dist/utils/debug.d.ts +3 -0
  181. package/dist/utils/debug.js +3 -0
  182. package/dist/utils/encoding.d.ts +38 -0
  183. package/dist/utils/encoding.js +91 -0
  184. package/dist/utils/key-value.d.ts +18 -0
  185. package/dist/utils/key-value.js +2 -0
  186. package/dist/utils/nostr.d.ts +35 -0
  187. package/dist/utils/nostr.js +26 -0
  188. package/dist/utils/relay-url.d.ts +10 -0
  189. package/dist/utils/relay-url.js +23 -0
  190. package/dist/utils/tag-cardinality.d.ts +50 -0
  191. package/dist/utils/tag-cardinality.js +91 -0
  192. package/dist/utils/timestamp.d.ts +50 -0
  193. package/dist/utils/timestamp.js +95 -0
  194. package/dist/version.d.ts +112 -0
  195. package/dist/version.js +112 -0
  196. package/package.json +68 -3
@@ -0,0 +1,1258 @@
1
+ /** @module @category Engine */
2
+ import { bytesToHex } from "@noble/hashes/utils.js";
3
+ import { contentTypes, encode, mlsMessageEncoder, processMessage, ValidationError, wireformats, } from "ts-mls";
4
+ import { verifyApplicationRumorAuthorship } from "../core/application-rumor.js";
5
+ import { marmotAuthService } from "../core/auth-service.js";
6
+ import { validateCommitLegality } from "../core/components/integrity.js";
7
+ import { classifyDisbandCommit } from "../core/components/disband-validation.js";
8
+ import { commitDigest, compareCommitOrderingKeys, } from "../core/convergence.js";
9
+ import { getCredentialPubkey } from "../core/credential.js";
10
+ import { deferredReasons } from "../core/inbound.js";
11
+ import { classifyLateCommit } from "../core/retained-history.js";
12
+ import { withCapturedProposals } from "./admin-policy.js";
13
+ import { authenticatedSenderOf, classifyOwnCommitPathLoss, isLostPathSecretsError, isMissingProposalReference, reconstructLostPathSecretsError, resolveCandidateParent, } from "./fork-recovery.js";
14
+ import { contentDedupId } from "./message-dedup.js";
15
+ import { deriveStateNotifications, groupWithdrawnNotificationsByCommit, } from "./state-notifications.js";
16
+ import { framedContentType, framedEpoch } from "./wire-format.js";
17
+ /**
18
+ * A decryption failure that retrying can never recover. The MLS secret tree
19
+ * only ratchets forward, so once a generation's secret has been consumed and
20
+ * deleted (forward secrecy) it is gone for good; ts-mls signals this with a
21
+ * {@link ValidationError} "Desired gen in the past". This is expected — and
22
+ * benign — for a member's own application messages replayed by a relay and for
23
+ * duplicate deliveries. Re-attempting against the same (or a further-advanced)
24
+ * state is byte-for-byte futile, so these are dropped as unreadable on the
25
+ * first pass instead of churning through the retry loop.
26
+ */
27
+ function isPermanentDecryptFailure(error) {
28
+ return (error instanceof ValidationError &&
29
+ error.message.includes("Desired gen in the past"));
30
+ }
31
+ /** Hex `commit_digest` of a commit message. */
32
+ function digestHexOf(message) {
33
+ return bytesToHex(commitDigest(encode(mlsMessageEncoder, message)));
34
+ }
35
+ /**
36
+ * Seam (convergence rejection reason): the `droppedReason` of the `past-epoch`
37
+ * skip of the pool commit `digest`, when fork recovery dropped it as a
38
+ * candidate for failing the authorization / commit-legality gate; nothing
39
+ * (the key stays absent) otherwise.
40
+ */
41
+ function droppedReasonOf(rejected, digest) {
42
+ const rejection = rejected?.get(digest);
43
+ return rejection === undefined ? {} : { droppedReason: rejection.reason };
44
+ }
45
+ /**
46
+ * Seam (`branchAwareFence`): holds a pool-replay commit judged `skipped`. It is
47
+ * not final — a later pass can find it could win and fence — so the engine
48
+ * keeps it (with its original envelope, which `opaqueDecided` takes out of the
49
+ * pool) in the held set it persists (Design Decision 6). `false` when the
50
+ * engine's held set is full: the caller fences the commit at once, with the
51
+ * cause `held` carries. `true` too when there is nothing to hold (no hook, or a
52
+ * digest `held` does not name).
53
+ */
54
+ function holdSkippedOpaque(ctx, held, digest, envelope, message) {
55
+ if (ctx.holdOpaque === undefined)
56
+ return true;
57
+ const info = held?.get(digest);
58
+ // Fail closed: a skipped digest the resolution gave no hold info for cannot
59
+ // be held, so the caller fences it.
60
+ if (info === undefined)
61
+ return false;
62
+ return (ctx.holdOpaque({
63
+ parentTag: info.parentTag,
64
+ parentEpoch: info.parentEpoch,
65
+ envelope,
66
+ message,
67
+ senderLeafIndex: info.senderLeafIndex,
68
+ cause: info.cause,
69
+ ...(info.removed === undefined ? {} : { removed: info.removed }),
70
+ }) !== false);
71
+ }
72
+ /**
73
+ * Seam (`removalFinality`): an opaque head's R-2 facts at `parent` through the
74
+ * engine's hook — `undefined` (unknown) without the hook, or without captured
75
+ * proposals.
76
+ */
77
+ function opaqueFactsOf(ctx, parent, proposals) {
78
+ return proposals === undefined
79
+ ? undefined
80
+ : ctx.opaqueRemovalFacts?.(parent, proposals);
81
+ }
82
+ /** A short, stable label for an envelope in debug logs. */
83
+ function envelopeLabel(envelope) {
84
+ if (envelope &&
85
+ typeof envelope === "object" &&
86
+ "id" in envelope &&
87
+ typeof envelope.id === "string") {
88
+ return envelope.id.slice(0, 8);
89
+ }
90
+ return "?";
91
+ }
92
+ /**
93
+ * Resolves a still-unprocessed envelope to its terminal {@link IngestResult}:
94
+ * `deferred` (retryable — missing parent / future epoch) when the batch marked
95
+ * it as such, otherwise `unreadable` (terminal). Keeping deferred inputs out of
96
+ * `unreadable` is what stops a future-epoch commit being mislabeled
97
+ * `stale: invalid_encoding` (`protocol-core/inbound-processing.md`).
98
+ */
99
+ function terminalResult(envelope, deferred, errorList, decryptFailed) {
100
+ const entry = deferred.get(envelope);
101
+ if (entry)
102
+ return {
103
+ kind: "deferred",
104
+ envelope,
105
+ message: entry.message,
106
+ reason: entry.reason,
107
+ sourceEpoch: Number(framedEpoch(entry.message) ?? 0n),
108
+ };
109
+ return {
110
+ kind: "unreadable",
111
+ envelope,
112
+ errors: errorList
113
+ .filter((e) => e.envelope === envelope)
114
+ .map((e) => e.error),
115
+ // A peel failure is retryable (the unlocking state may arrive later); the
116
+ // engine pools these rather than dropping them.
117
+ decryptFailure: decryptFailed.has(envelope) || undefined,
118
+ };
119
+ }
120
+ /**
121
+ * Whether a decrypted application message is authentic: its inner Nostr event
122
+ * id is canonical AND its `pubkey` matches the MLS-authenticated sender's
123
+ * account identity (`foundation/identity.md`, `protocol-core/group-messaging.md`).
124
+ * MLS authenticates *who* sent the bytes (the sender leaf); this binds the inner
125
+ * author to that sender so a member can't forge another account's authorship.
126
+ * A failure — including an unattributable sender (no leaf index) or a
127
+ * non-conformant payload — is `invalid_encoding`; the message is dropped, never
128
+ * delivered.
129
+ *
130
+ * Uses `result.senderCredential`, not a fresh `getCredentialFromLeafIndex`
131
+ * lookup against the *current* tree: for a past-epoch `PrivateMessage`
132
+ * ts-mls decrypts through `historicalReceiverData` and resolves the sender
133
+ * credential against *that epoch's* ratchet tree before returning it here
134
+ * (seam-application-authorship-past-epoch-credential). Re-deriving the
135
+ * credential from the current tree would misattribute the message once the
136
+ * sender's leaf index is reused by a later member (M3 continued: this is
137
+ * what keeps a late message from being attributed to whoever now occupies
138
+ * that leaf).
139
+ */
140
+ export function isAuthenticApplicationMessage(result, log, label) {
141
+ const senderLeafIndex = result
142
+ .senderLeafIndex;
143
+ if (senderLeafIndex === undefined) {
144
+ log("reject app message envelope:%s – unattributable sender", label);
145
+ return false;
146
+ }
147
+ try {
148
+ const senderPubkey = getCredentialPubkey(result.senderCredential);
149
+ verifyApplicationRumorAuthorship(result.message, senderPubkey);
150
+ return true;
151
+ }
152
+ catch (error) {
153
+ log("reject app message envelope:%s – %s", label, error.message);
154
+ return false;
155
+ }
156
+ }
157
+ /** Orders peeled commits deterministically by their convergence ordering key. */
158
+ function sortPeeledCommits(commits) {
159
+ const keyed = commits.map((pair) => {
160
+ const sourceEpoch = Number(framedEpoch(pair.message) ?? 0n);
161
+ const key = {
162
+ sourceEpoch,
163
+ commitDigest: commitDigest(encode(mlsMessageEncoder, pair.message)),
164
+ };
165
+ return { pair, key };
166
+ });
167
+ keyed.sort((a, b) => compareCommitOrderingKeys(a.key, b.key));
168
+ return keyed.map((entry) => entry.pair);
169
+ }
170
+ /**
171
+ * Seam (epic-marmot-client S20, `removalConvergence`): input for a group whose
172
+ * state is a REVISABLE removal of the local leaf. Instead of D-13's blanket
173
+ * `self-evicted`, every envelope is fork material for the removal, read
174
+ * against the state it was applied to (`parent`):
175
+ * - a commit framed at the parent's epoch that removes the local leaf too is
176
+ * a competing removal, held as a candidate (`recordRemoval`) and skipped
177
+ * `past-epoch` (evaluated);
178
+ * - any other commit or proposal framed at the parent's epoch is `deferred`
179
+ * (`missing_parent`, source epoch = the parent's): the pool's tree sweep
180
+ * grows it into the history tree at the parent node and tree-fed
181
+ * re-convergence weighs it against the removal;
182
+ * - anything else (unreadable there: a later commit of a sibling branch, an
183
+ * application message) is pooled as undecryptable — read by the sweep once
184
+ * its branch is grown, or delivered after a rewind out of the removal.
185
+ * Nothing is yielded `self-evicted`: whether the local leaf left is not
186
+ * decided yet.
187
+ */
188
+ async function* admitRemovalForkMaterial(ctx, envelopes, parent, log) {
189
+ const parentEpoch = parent.groupContext.epoch;
190
+ log("group holds a revisable removal at epoch %d – admitting %d envelope(s) as fork material", parentEpoch, envelopes.length);
191
+ const pooled = (envelope) => (ctx.undecryptable?.(envelope),
192
+ {
193
+ kind: "unreadable",
194
+ envelope,
195
+ errors: [new Error("not readable at the removal's parent state")],
196
+ decryptFailure: true,
197
+ });
198
+ // (the undecryptable hook above runs before the result is yielded)
199
+ // Seam (`branchAwareFence`): lost-path-secrets commits at the parent, held
200
+ // and decided once every envelope of the batch was classified.
201
+ const held = [];
202
+ for (const envelope of envelopes) {
203
+ let message;
204
+ try {
205
+ const peeled = await ctx.peeler.peelGroupMessages([envelope], parent);
206
+ message = peeled.read[0]?.message;
207
+ }
208
+ catch {
209
+ message = undefined;
210
+ }
211
+ if (message === undefined ||
212
+ (message.wireformat !== wireformats.mls_private_message &&
213
+ message.wireformat !== wireformats.mls_public_message)) {
214
+ yield pooled(envelope);
215
+ continue;
216
+ }
217
+ const cls = ctx.dedup.classify(message);
218
+ if (cls !== undefined) {
219
+ yield {
220
+ kind: "skipped",
221
+ envelope,
222
+ message,
223
+ reason: cls === "own-echo" ? "self-echo" : "duplicate",
224
+ };
225
+ continue;
226
+ }
227
+ const type = framedContentType(message);
228
+ if (framedEpoch(message) !== parentEpoch ||
229
+ (type !== contentTypes.commit && type !== contentTypes.proposal)) {
230
+ yield pooled(envelope);
231
+ continue;
232
+ }
233
+ if (type === contentTypes.commit) {
234
+ const resolution = await resolveCandidateParent({
235
+ ciphersuite: ctx.ciphersuite,
236
+ clientConfig: ctx.clientConfig,
237
+ parent,
238
+ message,
239
+ callback: ctx.createAdminCallback(parent),
240
+ });
241
+ switch (resolution.kind) {
242
+ case "fenced":
243
+ // Seam (`branchAwareFence`): not fenced on the spot — held, and
244
+ // decided below against the removal (and what the tree holds) once
245
+ // the whole batch was seen.
246
+ if (ctx.decideOpaque !== undefined) {
247
+ // Seam (`removalFinality`): R-2 at the parent, while it is in hand.
248
+ const removed = opaqueFactsOf(ctx, parent, resolution.proposals);
249
+ if (ctx.holdOpaque?.({
250
+ parentTag: bytesToHex(parent.confirmationTag),
251
+ parentEpoch: Number(parent.groupContext.epoch),
252
+ envelope,
253
+ message,
254
+ senderLeafIndex: resolution.senderLeafIndex,
255
+ cause: resolution.cause,
256
+ ...(removed === undefined ? {} : { removed }),
257
+ }) === false) {
258
+ // Held set full: fenced at once, the final disposition.
259
+ yield {
260
+ kind: "unreadable",
261
+ envelope,
262
+ errors: [resolution.cause],
263
+ };
264
+ ctx.opaqueDecided?.(envelope);
265
+ continue;
266
+ }
267
+ held.push({
268
+ envelope,
269
+ message,
270
+ senderLeafIndex: resolution.senderLeafIndex,
271
+ cause: resolution.cause,
272
+ ...(removed === undefined ? {} : { removed }),
273
+ });
274
+ continue;
275
+ }
276
+ // This device lost its own path secrets at the removal's parent: the
277
+ // same terminal `unreadable` the direct apply path yields.
278
+ yield { kind: "unreadable", envelope, errors: [resolution.cause] };
279
+ continue;
280
+ case "resolved":
281
+ if (resolution.result.newState.groupActiveState.kind ===
282
+ "removedFromGroup") {
283
+ ctx.recordRemoval?.(parent, message, authenticatedSenderOf(resolution.result, message), resolution.result.newState);
284
+ ctx.dedup.remember(message);
285
+ log("competing removal envelope:%s held", envelopeLabel(envelope));
286
+ yield { kind: "skipped", envelope, message, reason: "past-epoch" };
287
+ continue;
288
+ }
289
+ break;
290
+ case "authentication_mismatch":
291
+ case "missing_proposal":
292
+ case "rejected":
293
+ case "deferred":
294
+ break;
295
+ }
296
+ }
297
+ yield {
298
+ kind: "deferred",
299
+ envelope,
300
+ message,
301
+ reason: deferredReasons.missingParent,
302
+ sourceEpoch: Number(parentEpoch),
303
+ };
304
+ }
305
+ // Seam (`branchAwareFence`): the held candidates, decided against the state
306
+ // the batch reached. The decision is the engine's, shared with the tree
307
+ // sweep; every outcome reports the equivocations it saw, and is terminal for
308
+ // the envelope (a skipped one is held by the engine, not by the pool).
309
+ if (held.length > 0) {
310
+ const decision = await ctx.decideOpaque({
311
+ parent,
312
+ candidates: held,
313
+ hold: true,
314
+ });
315
+ for (const evidence of decision.equivocations)
316
+ yield { kind: "leafEquivocation", evidence };
317
+ // Release rule: a candidate leaves the engine's held set and the pool only
318
+ // immediately AFTER the yield of its own final disposition, so a consumer
319
+ // that abandons the generator earlier can still be served by the next
320
+ // entry point's settle.
321
+ for (const candidate of held) {
322
+ if (decision.fenced.has(digestHexOf(candidate.message))) {
323
+ yield {
324
+ kind: "unreadable",
325
+ envelope: candidate.envelope,
326
+ errors: [candidate.cause],
327
+ };
328
+ ctx.releaseOpaque?.(candidate.message);
329
+ }
330
+ else
331
+ // Provisional: the engine holds the candidate and a later pass may
332
+ // yield `unreadable` for the same envelope (the fence verdict).
333
+ yield {
334
+ kind: "skipped",
335
+ envelope: candidate.envelope,
336
+ message: candidate.message,
337
+ reason: "past-epoch",
338
+ };
339
+ ctx.opaqueDecided?.(candidate.envelope);
340
+ }
341
+ }
342
+ }
343
+ /**
344
+ * Ingests transport envelopes and applies MLS messages to group state
345
+ * (Marmot v2 `protocol-core/inbound-processing.md`). Decrypts (retrying against
346
+ * retained states), splits commits from non-commits, applies in-order commits,
347
+ * routes past/future-epoch commits through convergence fork recovery, and
348
+ * retries out-of-order messages only while a pass made progress.
349
+ *
350
+ * This is the engine's `message_processor/ingest` seam, extracted from
351
+ * `MarmotGroupEngine` so the 400-line pipeline can be read and tested in
352
+ * isolation from send and lifecycle.
353
+ */
354
+ export async function* ingestEnvelopes(ctx, envelopes, options) {
355
+ const log = ctx.log.extend(`ingest:${Date.now().toString(36).slice(-5)}`);
356
+ // D-04: canonical disband is an absorbing input gate. Keep this before even
357
+ // reading ClientState so direct engine callers cannot reopen crypto,
358
+ // convergence passes, timers, dedup, or application delivery.
359
+ if (ctx.isDisbanded?.()) {
360
+ for (const envelope of envelopes)
361
+ yield { kind: "skipped", envelope, reason: "group-disbanded" };
362
+ return;
363
+ }
364
+ // D-13: once canonical state is the removedFromGroup tombstone, later input
365
+ // for this group is classified `self-evicted` before any per-message work —
366
+ // no peel, no decrypt, no authentication (`protocol-core/member-departure.md`
367
+ // "Realizing removal": such input "need not be decrypted or authenticated").
368
+ // This must be the very first check in the function, ahead of the peel call,
369
+ // so a whole batch short-circuits uniformly regardless of retry state.
370
+ if (ctx.getState().groupActiveState.kind === "removedFromGroup") {
371
+ // Seam (epic-marmot-client S20): while the removal is revisable, input is
372
+ // fork material for it, not self-evicted.
373
+ const removalParent = ctx.removalParent?.();
374
+ if (removalParent !== undefined) {
375
+ yield* admitRemovalForkMaterial(ctx, envelopes, removalParent, log);
376
+ return;
377
+ }
378
+ log("group is removedFromGroup – yielding %d envelope(s) as self-evicted", envelopes.length);
379
+ for (const envelope of envelopes) {
380
+ yield { kind: "skipped", envelope, reason: "self-evicted" };
381
+ }
382
+ return;
383
+ }
384
+ const retryCount = options?.retryCount ?? 0;
385
+ const maxRetries = options?.maxRetries ?? 5;
386
+ const errorList = options?._errors ?? [];
387
+ // Envelopes deferred this batch (future-epoch / missing-parent commits). They
388
+ // ride the same retry set as `unreadable` so a later pass can apply them once
389
+ // the gap fills, but at a terminal yield they surface as `deferred`, not stale.
390
+ const deferred = options?._deferred ?? new Map();
391
+ // Envelopes whose kind-445 wrapper never opened (peel failures) — retryable,
392
+ // so they surface as `unreadable` with `decryptFailure` set for the pool.
393
+ const decryptFailedAll = options?._decryptFailed ?? new Set();
394
+ if (retryCount === 0) {
395
+ log("start – %d envelope(s), maxRetries=%d", envelopes.length, maxRetries);
396
+ }
397
+ else {
398
+ log("retry %d/%d – %d envelope(s) remaining", retryCount, maxRetries, envelopes.length);
399
+ }
400
+ if (retryCount > maxRetries) {
401
+ log("max retries exceeded – yielding %d envelope(s) as deferred/unreadable", envelopes.length);
402
+ for (const envelope of envelopes) {
403
+ yield terminalResult(envelope, deferred, errorList, decryptFailedAll);
404
+ }
405
+ return;
406
+ }
407
+ if (envelopes.length === 0)
408
+ return;
409
+ // Snapshot the state so we can tell whether this pass advanced anything.
410
+ // Every successful apply replaces it via setState, so identity inequality
411
+ // means progress. Retrying envelopes against an unchanged state is
412
+ // deterministic and can only reproduce the same failures.
413
+ const stateBeforePass = ctx.getState();
414
+ let { read, unreadable: decryptFailed } = await ctx.peeler.peelGroupMessages(envelopes, ctx.getState());
415
+ if (decryptFailed.length > 0 && ctx.retained.size > 0) {
416
+ const stillFailed = [];
417
+ for (const envelope of decryptFailed) {
418
+ let recovered = false;
419
+ for (const retained of ctx.retained.states()) {
420
+ if (retained === ctx.getState())
421
+ continue;
422
+ const retry = await ctx.peeler.peelGroupMessages([envelope], retained);
423
+ if (retry.read.length > 0) {
424
+ read = [...read, ...retry.read];
425
+ recovered = true;
426
+ break;
427
+ }
428
+ }
429
+ if (!recovered)
430
+ stillFailed.push(envelope);
431
+ }
432
+ decryptFailed = stillFailed;
433
+ }
434
+ log("decryption: %d/%d readable, %d failed", read.length, envelopes.length, decryptFailed.length);
435
+ for (const envelope of decryptFailed) {
436
+ log("decrypt failed envelope:%s", envelopeLabel(envelope));
437
+ decryptFailedAll.add(envelope);
438
+ ctx.undecryptable?.(envelope);
439
+ errorList.push({
440
+ envelope,
441
+ error: new Error("Failed to decrypt group message"),
442
+ });
443
+ }
444
+ if (read.length === 0) {
445
+ log("nothing readable – yielding %d decrypt failure(s) as unreadable", decryptFailed.length);
446
+ for (const envelope of decryptFailed) {
447
+ yield {
448
+ kind: "unreadable",
449
+ envelope,
450
+ errors: errorList
451
+ .filter((e) => e.envelope === envelope)
452
+ .map((e) => e.error),
453
+ decryptFailure: true,
454
+ };
455
+ }
456
+ return;
457
+ }
458
+ const unreadable = [...decryptFailed];
459
+ // Content-derived dedup (`inbound-processing.md`): before any MLS processing or
460
+ // convergence classification, drop a message whose content we have already
461
+ // terminally processed (`duplicate`) or that is our own send replayed back in a
462
+ // fresh transport envelope (`own-echo` → reported as `self-echo`). Keyed on the
463
+ // peeled MLS bytes, so a re-wrap with a new Nostr event id is still caught.
464
+ // Intra-batch repeats collapse to the first occurrence as well.
465
+ const batchSeen = new Set();
466
+ const fresh = [];
467
+ for (const pair of read) {
468
+ const id = contentDedupId(pair.message);
469
+ const cls = ctx.dedup.classify(pair.message);
470
+ if (cls === "own-echo") {
471
+ log("skip envelope:%s reason:self-echo (own send)", envelopeLabel(pair.envelope));
472
+ yield {
473
+ kind: "skipped",
474
+ envelope: pair.envelope,
475
+ message: pair.message,
476
+ reason: "self-echo",
477
+ };
478
+ continue;
479
+ }
480
+ if (cls === "duplicate" || batchSeen.has(id)) {
481
+ log("skip envelope:%s reason:duplicate", envelopeLabel(pair.envelope));
482
+ yield {
483
+ kind: "skipped",
484
+ envelope: pair.envelope,
485
+ message: pair.message,
486
+ reason: "duplicate",
487
+ };
488
+ continue;
489
+ }
490
+ batchSeen.add(id);
491
+ fresh.push(pair);
492
+ }
493
+ let commits = [];
494
+ const nonCommits = [];
495
+ for (const pair of fresh) {
496
+ // Commits are MLS PublicMessage under Marmot v2 (see wire-format.ts); other
497
+ // framed content (application, proposals) goes through the non-commit path.
498
+ if (framedContentType(pair.message) === contentTypes.commit) {
499
+ commits.push(pair);
500
+ }
501
+ else {
502
+ nonCommits.push(pair);
503
+ }
504
+ }
505
+ log("split: %d commit(s), %d non-commit(s)", commits.length, nonCommits.length);
506
+ for (const { envelope, message } of nonCommits) {
507
+ try {
508
+ if (message.wireformat !== wireformats.mls_private_message &&
509
+ message.wireformat !== wireformats.mls_public_message) {
510
+ log("skip envelope:%s reason:wrong-wireformat", envelopeLabel(envelope));
511
+ yield {
512
+ kind: "skipped",
513
+ envelope,
514
+ message,
515
+ reason: "wrong-wireformat",
516
+ };
517
+ continue;
518
+ }
519
+ const result = await processMessage({
520
+ context: {
521
+ cipherSuite: ctx.ciphersuite,
522
+ authService: marmotAuthService,
523
+ externalPsks: {},
524
+ clientConfig: ctx.clientConfig,
525
+ },
526
+ state: ctx.getState(),
527
+ message,
528
+ // The admin-verification callback judges standalone proposals too, so
529
+ // a caller's `adminPolicyCallback` can refuse one before it is staged
530
+ // (the vendored callback accepts every proposal: unchanged by default).
531
+ callback: ctx.createAdminCallback(),
532
+ });
533
+ if (result.kind === "newState" && result.actionTaken === "reject") {
534
+ log("proposal envelope:%s rejected by admin policy", envelopeLabel(envelope));
535
+ ctx.dedup.remember(message);
536
+ yield {
537
+ kind: "rejected",
538
+ result,
539
+ envelope,
540
+ message,
541
+ reason: "admin-policy",
542
+ };
543
+ }
544
+ else if (result.kind === "newState") {
545
+ log("proposal accepted envelope:%s epoch:%d", envelopeLabel(envelope), ctx.getState().groupContext.epoch);
546
+ ctx.setState(result.newState);
547
+ ctx.recordProposalStaged(result.newState);
548
+ ctx.dedup.remember(message);
549
+ yield { kind: "processed", result, envelope, message };
550
+ }
551
+ else if (result.kind === "applicationMessage") {
552
+ // The MLS layer has authenticated the sender; advance our ratchet to
553
+ // reflect the consumed generation even if we then drop the payload.
554
+ ctx.setState(result.newState);
555
+ if (!isAuthenticApplicationMessage(result, log, envelopeLabel(envelope))) {
556
+ // M3: forged inner id / author ⇒ invalid_encoding, never delivered.
557
+ yield {
558
+ kind: "skipped",
559
+ envelope,
560
+ message,
561
+ reason: "invalid-app-payload",
562
+ };
563
+ continue;
564
+ }
565
+ // Remember this eager delivery keyed by the branch state it decrypted
566
+ // against (epoch + confirmation tag); a later rewind abandoning this
567
+ // branch retracts it as `invalidated` (M7). An app message advances the
568
+ // ratchet but not the epoch/confirmation tag, so newState identifies the
569
+ // delivery branch.
570
+ ctx.recordDeliveredAppPayload(Number(result.newState.groupContext.epoch), bytesToHex(result.newState.confirmationTag), envelope, message, result.message);
571
+ ctx.dedup.remember(message);
572
+ log("application message envelope:%s", envelopeLabel(envelope));
573
+ yield { kind: "processed", result, envelope, message };
574
+ }
575
+ }
576
+ catch (error) {
577
+ if (isPermanentDecryptFailure(error)) {
578
+ log("non-commit permanently unreadable envelope:%s – %s", envelopeLabel(envelope), error.message);
579
+ yield { kind: "unreadable", envelope, errors: [error] };
580
+ continue;
581
+ }
582
+ // A proposal framed at a retained past epoch cannot stage onto the
583
+ // current state, but belongs on that epoch's node: a sibling commit
584
+ // built over it is only replayable there once it is staged. Deferred,
585
+ // so the pool hands it to the tree sweep (missing_parent semantics).
586
+ const proposalEpoch = framedEpoch(message);
587
+ if (framedContentType(message) === contentTypes.proposal &&
588
+ proposalEpoch !== undefined &&
589
+ proposalEpoch < ctx.getState().groupContext.epoch &&
590
+ ctx.retained.hasState(Number(proposalEpoch)))
591
+ deferred.set(envelope, {
592
+ message,
593
+ reason: deferredReasons.missingParent,
594
+ });
595
+ log("non-commit failed envelope:%s – queued for retry: %O", envelopeLabel(envelope), error);
596
+ errorList.push({ envelope, error });
597
+ unreadable.push(envelope);
598
+ }
599
+ }
600
+ commits = sortPeeledCommits(commits);
601
+ const capture = withCapturedProposals(ctx.createAdminCallback());
602
+ const forkPool = [];
603
+ // Seam (`branchAwareFence`): commits that failed the direct apply with the
604
+ // lost-path-secrets error. Not fenced where they fail: held while the rest
605
+ // of the batch is applied, and decided at its end against the state it
606
+ // reached (below).
607
+ const heldOpaque = [];
608
+ for (const [commitIndex, { envelope, message }] of commits.entries()) {
609
+ // A commit is always framed (private or public); guard narrows the type and
610
+ // defends against a non-framed message reaching the commit path.
611
+ if (message.wireformat !== wireformats.mls_private_message &&
612
+ message.wireformat !== wireformats.mls_public_message) {
613
+ log("skip commit envelope:%s reason:wrong-wireformat", envelopeLabel(envelope));
614
+ yield { kind: "skipped", envelope, message, reason: "wrong-wireformat" };
615
+ continue;
616
+ }
617
+ const commitEpoch = framedEpoch(message) ?? 0n;
618
+ const currentEpoch = ctx.getState().groupContext.epoch;
619
+ if (commitEpoch < currentEpoch) {
620
+ forkPool.push({ envelope, message, epoch: Number(commitEpoch) });
621
+ continue;
622
+ }
623
+ if (commitEpoch > currentEpoch) {
624
+ // A commit framed at an epoch ahead of the current epoch: its parent
625
+ // commit has not been applied here. A commit is framed at the epoch it
626
+ // was sent FROM, so one framed at `current + 1` already needs the
627
+ // `current -> current + 1` commit first, exactly like one further ahead.
628
+ // That parent may still arrive (this or a later batch), so this is
629
+ // retryable `deferred` (missing_parent), not a terminal error
630
+ // (`protocol-core/inbound-processing.md`). It rides `unreadable` for the
631
+ // in-batch retry but `deferred` remembers it for the terminal yield.
632
+ log("defer commit envelope:%s epoch:%d ahead of current=%d – missing parent", envelopeLabel(envelope), commitEpoch, currentEpoch);
633
+ deferred.set(envelope, {
634
+ message,
635
+ reason: deferredReasons.missingParent,
636
+ });
637
+ unreadable.push(envelope);
638
+ continue;
639
+ }
640
+ log("processing commit envelope:%s epoch:%d->%d", envelopeLabel(envelope), currentEpoch, commitEpoch);
641
+ try {
642
+ // Clear any proposals left buffered from a prior message in this loop
643
+ // before processing this one (withCapturedProposals contract).
644
+ capture.take();
645
+ const result = await processMessage({
646
+ context: {
647
+ cipherSuite: ctx.ciphersuite,
648
+ authService: marmotAuthService,
649
+ externalPsks: {},
650
+ clientConfig: ctx.clientConfig,
651
+ },
652
+ state: ctx.getState(),
653
+ message,
654
+ callback: capture.callback,
655
+ });
656
+ const capturedCommit = capture.take();
657
+ if (result.kind === "newState") {
658
+ if (result.actionTaken === "reject") {
659
+ log("commit envelope:%s rejected by admin policy", envelopeLabel(envelope));
660
+ ctx.dedup.remember(message);
661
+ yield {
662
+ kind: "rejected",
663
+ result,
664
+ envelope,
665
+ message,
666
+ reason: "admin-policy",
667
+ };
668
+ continue;
669
+ }
670
+ const parentState = ctx.getState();
671
+ // WIRE-03/CONV-01 (D-03): validate the commit's resulting GroupContext
672
+ // AFTER processMessage returns (never inside the callback — Pitfall 1),
673
+ // BEFORE canonical state advances. A violating commit is rejected here
674
+ // and never reaches ctx.setState/ctx.recordCommit.
675
+ const violation = validateCommitLegality({
676
+ parentState,
677
+ resultingState: result.newState,
678
+ proposals: capturedCommit.proposals,
679
+ committerLeafIndex: capturedCommit.committerLeafIndex,
680
+ });
681
+ if (violation) {
682
+ log("commit envelope:%s rejected reason:%s detail:%s", envelopeLabel(envelope), violation.reason, violation.detail);
683
+ ctx.dedup.remember(message);
684
+ yield {
685
+ kind: "rejected",
686
+ result,
687
+ envelope,
688
+ message,
689
+ reason: violation.reason,
690
+ };
691
+ continue;
692
+ }
693
+ const disband = classifyDisbandCommit({
694
+ parentState,
695
+ resultingState: result.newState,
696
+ proposals: capturedCommit.proposals,
697
+ committerLeafIndex: capturedCommit.committerLeafIndex,
698
+ });
699
+ if (disband.kind === "validDisband") {
700
+ const digest = commitDigest(encode(mlsMessageEncoder, message));
701
+ ctx.admitDisbandCandidate(parentState, message, result.newState, {
702
+ commitDigest: digest,
703
+ actorPubkey: disband.actorPubkey,
704
+ sourceEpoch: Number(parentState.groupContext.epoch),
705
+ parentTag: bytesToHex(parentState.confirmationTag),
706
+ terminalOutcome: "disbanded",
707
+ }, authenticatedSenderOf(result, message));
708
+ continue;
709
+ }
710
+ ctx.setState(result.newState);
711
+ // D-10/D-11: the commit's digest is computed once here and reused for
712
+ // both the notification attribution below and the `removed` branch's
713
+ // own attribution — never a second hashing path over the same bytes.
714
+ const acceptedCommitDigest = commitDigest(encode(mlsMessageEncoder, message));
715
+ const notifications = deriveStateNotifications({
716
+ parentState,
717
+ resultingState: result.newState,
718
+ commitDigest: acceptedCommitDigest,
719
+ });
720
+ // The commit removed *us* (an admin's Remove, or a peer committing our
721
+ // own self_remove). State is now the `removedFromGroup` tombstone: no
722
+ // secrets advanced, so nothing else in this batch can be decrypted and
723
+ // retained history is moot. Surface it and stop the generator — there is
724
+ // nothing left to process once we are out (member-departure.md).
725
+ if (result.newState.groupActiveState.kind === "removedFromGroup") {
726
+ log("commit envelope:%s removed us from the group", envelopeLabel(envelope));
727
+ ctx.dedup.remember(message);
728
+ // D-10/D-12: the derived list always contains a `selfRemoved` entry
729
+ // on this branch (parent was active, resulting state is the
730
+ // tombstone), alongside `epochAdvanced` and this member's own
731
+ // `memberRemoved` entry, for the same commit.
732
+ // Seam (S20): the removal is held as a candidate against its retained
733
+ // parent, and ledgered at the epoch it logically produces (its
734
+ // tombstone keeps the parent's), so a rewind out of it withdraws it.
735
+ ctx.recordRemoval?.(parentState, message, authenticatedSenderOf(result, message), result.newState);
736
+ ctx.recordStateNotifications(acceptedCommitDigest, Number(result.newState.groupContext.epoch) +
737
+ (ctx.recordRemoval === undefined ? 0 : 1), notifications);
738
+ yield {
739
+ kind: "removed",
740
+ result,
741
+ envelope,
742
+ message,
743
+ notifications,
744
+ };
745
+ // Seam (S20): the rest of the batch is fork material for the removal
746
+ // (upstream drops it with the generator).
747
+ if (ctx.removalParent !== undefined) {
748
+ const rest = [
749
+ ...commits.slice(commitIndex + 1).map((c) => c.envelope),
750
+ ...forkPool.map((p) => p.envelope),
751
+ ...unreadable,
752
+ ...heldOpaque.map((h) => h.envelope),
753
+ ];
754
+ if (rest.length > 0)
755
+ yield* ingestEnvelopes(ctx, rest);
756
+ }
757
+ else {
758
+ // Seam (`branchAwareFence`) without removal convergence: this
759
+ // device was removed, and the rest of the batch is dropped as
760
+ // upstream drops it. A held candidate is no exception, but it
761
+ // must not vanish without a result: its commit belongs to a
762
+ // group this device has left, so it is `skipped` as
763
+ // `self-evicted` (what any later input for a removed group is,
764
+ // D-13) rather than fenced, and its pooled copy is dropped.
765
+ for (const h of heldOpaque) {
766
+ yield {
767
+ kind: "skipped",
768
+ envelope: h.envelope,
769
+ message: h.message,
770
+ reason: "self-evicted",
771
+ };
772
+ ctx.releaseOpaque?.(h.message);
773
+ ctx.opaqueDecided?.(h.envelope);
774
+ }
775
+ }
776
+ return;
777
+ }
778
+ ctx.recordCommit(parentState, message, result.newState, authenticatedSenderOf(result, message));
779
+ ctx.commitAppliedInOrder?.(parentState, message, result.newState, authenticatedSenderOf(result, message));
780
+ ctx.recordStateNotifications(acceptedCommitDigest, Number(result.newState.groupContext.epoch), notifications);
781
+ ctx.dedup.remember(message);
782
+ log("commit envelope:%s applied – new epoch:%d", envelopeLabel(envelope), ctx.getState().groupContext.epoch);
783
+ yield { kind: "processed", result, envelope, message, notifications };
784
+ }
785
+ }
786
+ catch (error) {
787
+ // AC-HIST-4, sole-member shape: this device's own commit, whose empty
788
+ // `UpdatePath` fails before ts-mls's "No overlap" error. Classified here,
789
+ // where the authenticated committer is known, so the `unreadable` below
790
+ // carries an error the client fences on (`isLostPathSecretsError`).
791
+ const captured = capture.take();
792
+ const committerLeafIndex = captured.committerLeafIndex;
793
+ classifyOwnCommitPathLoss(error, committerLeafIndex, ctx.getState().privatePath.leafIndex);
794
+ if (isPermanentDecryptFailure(error)) {
795
+ log("commit permanently unreadable envelope:%s – %s", envelopeLabel(envelope), error.message);
796
+ yield { kind: "unreadable", envelope, errors: [error] };
797
+ continue;
798
+ }
799
+ // Seam (`branchAwareFence`): this device lost its own path secrets at the
800
+ // current state. The batch goes on; the commit is decided at its end.
801
+ if (ctx.opaqueDecided !== undefined && isLostPathSecretsError(error)) {
802
+ log("commit envelope:%s lost own path secrets – held for the end of the batch", envelopeLabel(envelope));
803
+ // Seam (`removalFinality`): R-2 at the current state (the parent),
804
+ // from the proposals the callback captured (none: it never ran).
805
+ const removed = opaqueFactsOf(ctx, ctx.getState(), committerLeafIndex === undefined ? undefined : captured.proposals);
806
+ if (ctx.holdOpaque?.({
807
+ parentTag: bytesToHex(ctx.getState().confirmationTag),
808
+ parentEpoch: Number(ctx.getState().groupContext.epoch),
809
+ envelope,
810
+ message,
811
+ senderLeafIndex: committerLeafIndex,
812
+ cause: error,
813
+ ...(removed === undefined ? {} : { removed }),
814
+ }) === false) {
815
+ // Held set full (the cap): fenced at once, the final disposition.
816
+ yield { kind: "unreadable", envelope, errors: [error] };
817
+ ctx.opaqueDecided?.(envelope);
818
+ continue;
819
+ }
820
+ heldOpaque.push({
821
+ envelope,
822
+ message,
823
+ epoch: Number(commitEpoch),
824
+ parent: ctx.getState(),
825
+ senderLeafIndex: committerLeafIndex,
826
+ cause: error,
827
+ ...(removed === undefined ? {} : { removed }),
828
+ });
829
+ continue;
830
+ }
831
+ // A commit by reference to a proposal not staged here yet (it has not
832
+ // arrived, or arrived out of order) is waiting for its input, not
833
+ // malformed: deferred, retried once the proposal is staged.
834
+ if (isMissingProposalReference(error))
835
+ deferred.set(envelope, {
836
+ message,
837
+ reason: deferredReasons.missingParent,
838
+ });
839
+ log("commit failed envelope:%s – queued for retry: %O", envelopeLabel(envelope), error);
840
+ errorList.push({ envelope, error });
841
+ unreadable.push(envelope);
842
+ }
843
+ }
844
+ // Seam (`branchAwareFence`): the held commits, decided against the state the
845
+ // batch reached. Where a sibling advanced the state past the commit's parent
846
+ // it is fork material like any other and pool replay decides it by the one
847
+ // rule (`fenced` only if its best case could win, `skipped` otherwise).
848
+ // Where the parent is still the tip there is no processable sibling, and the
849
+ // commit fences: the terminal `unreadable` carrying the cause, as before.
850
+ const fencedNow = [];
851
+ for (const candidate of heldOpaque) {
852
+ if (Number(ctx.getState().groupContext.epoch) > candidate.epoch) {
853
+ // Not released here: pool replay delivers its disposition below, and
854
+ // the release follows that yield.
855
+ forkPool.push({
856
+ envelope: candidate.envelope,
857
+ message: candidate.message,
858
+ epoch: candidate.epoch,
859
+ });
860
+ }
861
+ else
862
+ fencedNow.push(candidate);
863
+ }
864
+ if (forkPool.length > 0) {
865
+ const retainedPool = forkPool.filter((p) => ctx.retained.hasState(p.epoch));
866
+ const orphanPool = forkPool.filter((p) => !ctx.retained.hasState(p.epoch));
867
+ if (retainedPool.length > 0) {
868
+ const minForkEpoch = Math.min(...retainedPool.map((p) => p.epoch));
869
+ const resolution = await ctx.resolveFork(minForkEpoch, retainedPool.map((p) => p.message), decryptFailed, envelopes);
870
+ // Seam (`equivocationCredit`): selection's equivocation report, yielded
871
+ // whoever won — on a no-op (`superseded`) too. Seam (`branchAwareFence`):
872
+ // a `skip` carries the report as well (without the seam it never does).
873
+ for (const evidence of resolution.equivocations ?? [])
874
+ yield { kind: "leafEquivocation", evidence };
875
+ if (resolution.outcome === "recovered") {
876
+ log("convergence rewound to canonical branch – epoch:%d", ctx.getState().groupContext.epoch);
877
+ // Seam (`branchAwareFence`): the commit the `processed` result is
878
+ // attributed to is never one judged unable to win — that digest is
879
+ // yielded `skipped` below. Without the seam nothing is skipped here and
880
+ // this is the first pool entry. When every pool entry was skipped, the
881
+ // winning tip was not a pool commit: replay opened it from an
882
+ // undecryptable envelope of this batch (`opaqueTipEnvelope`), and the
883
+ // result is attributed to that envelope, so the notifications the
884
+ // engine already recorded as delivered are yielded (`processed`, or
885
+ // `removed` when the winner removed this device) instead of being
886
+ // lost. Each further wrapper of the same tip commit is a duplicate of
887
+ // the applied commit: `skipped` / `duplicate`, and no longer retryable.
888
+ // (The tip is always a pool commit or a wrapper: a tip from the
889
+ // applied chain alone would be a no-op, not a rewind; the
890
+ // `retainedPool[0]` fallback only keeps the notifications contract
891
+ // should that ever not hold.)
892
+ // Seam (convergence rejection reason): nor one dropped as a candidate
893
+ // for failing the authorization / commit-legality gate, which is
894
+ // yielded `skipped` with its `droppedReason` below.
895
+ const opaqueSkipped = resolution.opaqueSkipped;
896
+ const rejected = resolution.rejected;
897
+ const poolRep = opaqueSkipped === undefined && rejected === undefined
898
+ ? retainedPool[0]
899
+ : retainedPool.find((p) => {
900
+ const digest = bytesToHex(commitDigest(encode(mlsMessageEncoder, p.message)));
901
+ return !opaqueSkipped?.has(digest) && !rejected?.has(digest);
902
+ });
903
+ const tipFound = poolRep === undefined ? resolution.opaqueTipEnvelope : undefined;
904
+ const rep = poolRep ??
905
+ (tipFound === undefined
906
+ ? retainedPool[0]
907
+ : {
908
+ envelope: decryptFailed[tipFound.indices[0]],
909
+ message: tipFound.message,
910
+ });
911
+ if (tipFound !== undefined)
912
+ for (const index of tipFound.indices) {
913
+ const at = unreadable.indexOf(decryptFailed[index]);
914
+ if (at >= 0)
915
+ unreadable.splice(at, 1);
916
+ }
917
+ // The canonical branch we rewound onto may itself have removed us; the
918
+ // winning tip is now live state, so report `removed` rather than
919
+ // `processed` (member-departure.md). The rewind's `invalidated`
920
+ // retractions below are still reported — they are independent.
921
+ if (ctx.getState().groupActiveState.kind === "removedFromGroup") {
922
+ // D-10/D-12: attribute the derived notifications (including
923
+ // `selfRemoved`) to the winning branch's OWN tip commit, not
924
+ // `rep.message` (which is merely the first forkPool entry that
925
+ // triggered this resolution) — the tip commit is the one that
926
+ // actually produced the tombstone. `resolution.notifications` is
927
+ // derived (and ledger-recorded) by `#applyForkResolution`, the same
928
+ // shared rewind-apply path the direct commit branch above uses.
929
+ //
930
+ // WR-18: `notifications` here spans the WHOLE applied winner chain,
931
+ // while `message` is only `rep.message`. This is the one place the
932
+ // per-commit reading of `ProcessedIngestResult`/`RemovedIngestResult`
933
+ // does not hold — consumers must attribute by each entry's
934
+ // `commitDigest`, as those types now document.
935
+ yield {
936
+ kind: "removed",
937
+ result: resolution.result,
938
+ envelope: rep.envelope,
939
+ message: rep.message,
940
+ notifications: resolution.notifications,
941
+ };
942
+ }
943
+ else {
944
+ yield {
945
+ kind: "processed",
946
+ result: resolution.result,
947
+ envelope: rep.envelope,
948
+ message: rep.message,
949
+ notifications: resolution.notifications,
950
+ selectedTerminal: resolution.selectedTerminal,
951
+ };
952
+ }
953
+ // The winner's own wrappers leave the pool after the yield that
954
+ // delivered the result attributed to them.
955
+ if (tipFound !== undefined)
956
+ for (const index of tipFound.indices)
957
+ ctx.opaqueDecided?.(decryptFailed[index]);
958
+ for (const p of retainedPool)
959
+ if (p !== rep) {
960
+ const digest = digestHexOf(p.message);
961
+ if (opaqueSkipped?.has(digest)) {
962
+ // A skipped opaque candidate stays held (revisable); a full set
963
+ // fences it at once.
964
+ if (holdSkippedOpaque(ctx, resolution.opaqueHeld, digest, p.envelope, p.message))
965
+ yield {
966
+ kind: "skipped",
967
+ envelope: p.envelope,
968
+ message: p.message,
969
+ reason: "past-epoch",
970
+ };
971
+ else {
972
+ yield {
973
+ kind: "unreadable",
974
+ envelope: p.envelope,
975
+ errors: [
976
+ resolution.opaqueHeld?.get(digest)?.cause ??
977
+ reconstructLostPathSecretsError("candidate cannot be held"),
978
+ ],
979
+ };
980
+ ctx.releaseOpaque?.(p.message);
981
+ }
982
+ ctx.opaqueDecided?.(p.envelope);
983
+ continue;
984
+ }
985
+ yield {
986
+ kind: "skipped",
987
+ envelope: p.envelope,
988
+ message: p.message,
989
+ reason: "past-epoch",
990
+ ...droppedReasonOf(resolution.rejected, digest),
991
+ };
992
+ ctx.releaseOpaque?.(p.message);
993
+ }
994
+ if (tipFound !== undefined)
995
+ for (const index of tipFound.indices.slice(1)) {
996
+ yield {
997
+ kind: "skipped",
998
+ envelope: decryptFailed[index],
999
+ message: tipFound.message,
1000
+ reason: "duplicate",
1001
+ };
1002
+ }
1003
+ // D-11: withdrawn state notifications are yielded BEFORE the
1004
+ // app-payload `invalidated` retractions below, so the two retraction
1005
+ // streams have a deterministic relative order within this drainable
1006
+ // generator.
1007
+ for (const group of groupWithdrawnNotificationsByCommit(resolution.withdrawnNotifications)) {
1008
+ yield {
1009
+ kind: "stateInvalidated",
1010
+ commitDigest: group.commitDigest,
1011
+ forkEpoch: minForkEpoch,
1012
+ withdrawn: group.withdrawn,
1013
+ };
1014
+ }
1015
+ // App payloads delivered on the now-abandoned branch are retracted (M7).
1016
+ for (const inv of resolution.invalidated) {
1017
+ log("invalidate app payload envelope:%s", envelopeLabel(inv.envelope));
1018
+ yield {
1019
+ kind: "invalidated",
1020
+ envelope: inv.envelope,
1021
+ message: inv.message,
1022
+ payload: inv.payload,
1023
+ tag: inv.tag,
1024
+ epoch: inv.epoch,
1025
+ };
1026
+ }
1027
+ }
1028
+ else {
1029
+ const awaiting = resolution.awaitingProposal ?? new Set();
1030
+ const fenced = resolution.fenced ?? new Map();
1031
+ for (const p of retainedPool) {
1032
+ // This device lost its own path secrets replaying this commit (a
1033
+ // restored state predating a commit of its own leaf): the same
1034
+ // terminal `unreadable` the direct apply path yields for that error.
1035
+ const digest = bytesToHex(commitDigest(encode(mlsMessageEncoder, p.message)));
1036
+ if (fenced.has(digest)) {
1037
+ ctx.fencedOpaque?.(p.message);
1038
+ yield {
1039
+ kind: "unreadable",
1040
+ envelope: p.envelope,
1041
+ errors: [fenced.get(digest)],
1042
+ };
1043
+ ctx.releaseOpaque?.(p.message);
1044
+ ctx.opaqueDecided?.(p.envelope);
1045
+ continue;
1046
+ }
1047
+ // Evaluated (it lost, was refused, or duplicates a canonical
1048
+ // commit): past-epoch. One that references a proposal the fork root
1049
+ // has not staged could not be evaluated at all: deferred — the
1050
+ // pool's tree sweep grows it into the history tree once the
1051
+ // proposal is staged there, and tree-fed re-convergence then weighs
1052
+ // it like any other branch.
1053
+ if (!awaiting.has(digest)) {
1054
+ if (resolution.opaqueSkipped?.has(digest)) {
1055
+ // A skipped opaque candidate stays held (revisable); a full set
1056
+ // fences it at once.
1057
+ if (holdSkippedOpaque(ctx, resolution.opaqueHeld, digest, p.envelope, p.message))
1058
+ yield {
1059
+ kind: "skipped",
1060
+ envelope: p.envelope,
1061
+ message: p.message,
1062
+ reason: "past-epoch",
1063
+ };
1064
+ else {
1065
+ yield {
1066
+ kind: "unreadable",
1067
+ envelope: p.envelope,
1068
+ errors: [
1069
+ resolution.opaqueHeld?.get(digest)?.cause ??
1070
+ reconstructLostPathSecretsError("candidate cannot be held"),
1071
+ ],
1072
+ };
1073
+ ctx.releaseOpaque?.(p.message);
1074
+ }
1075
+ ctx.opaqueDecided?.(p.envelope);
1076
+ continue;
1077
+ }
1078
+ yield {
1079
+ kind: "skipped",
1080
+ envelope: p.envelope,
1081
+ message: p.message,
1082
+ reason: "past-epoch",
1083
+ ...droppedReasonOf(resolution.rejected, digest),
1084
+ };
1085
+ ctx.releaseOpaque?.(p.message);
1086
+ }
1087
+ else
1088
+ yield {
1089
+ kind: "deferred",
1090
+ envelope: p.envelope,
1091
+ message: p.message,
1092
+ reason: deferredReasons.missingParent,
1093
+ sourceEpoch: p.epoch,
1094
+ };
1095
+ }
1096
+ }
1097
+ // Seam (`branchAwareFence`): the decisions also bind the commits replay
1098
+ // found by decrypting this batch's undecryptable envelopes under an
1099
+ // explored state. They are no pool entry, so they would otherwise stay a
1100
+ // generic `decryptFailure` (and be retried) with the cause dropped: a
1101
+ // fenced one is the terminal `unreadable` carrying its cause (no
1102
+ // `decryptFailure`, so the client fences), a skipped one `past-epoch`.
1103
+ for (const [digest, found] of resolution.opaqueEncrypted ?? []) {
1104
+ const cause = resolution.outcome === "skip"
1105
+ ? resolution.fenced?.get(digest)
1106
+ : undefined;
1107
+ // Every wrapper that opened to the commit gets the decision. A
1108
+ // skipped commit is held through its first wrapper (the record keeps
1109
+ // that envelope); a full held set fences it at once.
1110
+ for (const [position, index] of found.indices.entries()) {
1111
+ const envelope = decryptFailed[index];
1112
+ const at = unreadable.indexOf(envelope);
1113
+ if (at >= 0)
1114
+ unreadable.splice(at, 1);
1115
+ let fenceCause = cause;
1116
+ if (fenceCause === undefined &&
1117
+ position === 0 &&
1118
+ !holdSkippedOpaque(ctx, resolution.opaqueHeld, digest, envelope, found.message))
1119
+ fenceCause =
1120
+ resolution.opaqueHeld?.get(digest)?.cause ??
1121
+ reconstructLostPathSecretsError("candidate cannot be held");
1122
+ if (fenceCause !== undefined)
1123
+ yield { kind: "unreadable", envelope, errors: [fenceCause] };
1124
+ else
1125
+ yield {
1126
+ kind: "skipped",
1127
+ envelope,
1128
+ message: found.message,
1129
+ reason: "past-epoch",
1130
+ };
1131
+ ctx.opaqueDecided?.(envelope);
1132
+ }
1133
+ }
1134
+ }
1135
+ if (orphanPool.length > 0) {
1136
+ const currentTipEpoch = Number(ctx.getState().groupContext.epoch);
1137
+ const anchorEpoch = ctx.retained.anchorEpoch() ?? currentTipEpoch;
1138
+ for (const p of orphanPool) {
1139
+ if (p.epoch >= currentTipEpoch) {
1140
+ yield {
1141
+ kind: "skipped",
1142
+ envelope: p.envelope,
1143
+ message: p.message,
1144
+ reason: "past-epoch",
1145
+ };
1146
+ ctx.releaseOpaque?.(p.message);
1147
+ continue;
1148
+ }
1149
+ const outcome = classifyLateCommit({
1150
+ sourceEpoch: p.epoch,
1151
+ anchorEpoch,
1152
+ currentTipEpoch,
1153
+ maxRewindCommits: ctx.maxRewindCommits,
1154
+ parentArrived: true,
1155
+ retainedParentStateAvailable: false,
1156
+ });
1157
+ if (outcome.kind === "missing_retained_anchor") {
1158
+ ctx.toUnrecoverable();
1159
+ log("convergence lost retained anchor – group is Unrecoverable");
1160
+ yield {
1161
+ kind: "skipped",
1162
+ envelope: p.envelope,
1163
+ message: p.message,
1164
+ reason: "missing-retained-anchor",
1165
+ };
1166
+ ctx.releaseOpaque?.(p.message);
1167
+ }
1168
+ else if (outcome.kind === "beyond_anchor") {
1169
+ yield {
1170
+ kind: "skipped",
1171
+ envelope: p.envelope,
1172
+ message: p.message,
1173
+ reason: "beyond-anchor",
1174
+ };
1175
+ ctx.releaseOpaque?.(p.message);
1176
+ }
1177
+ else {
1178
+ yield {
1179
+ kind: "skipped",
1180
+ envelope: p.envelope,
1181
+ message: p.message,
1182
+ reason: "past-epoch",
1183
+ };
1184
+ ctx.releaseOpaque?.(p.message);
1185
+ }
1186
+ }
1187
+ }
1188
+ }
1189
+ // Seam (`branchAwareFence`): the commits whose parent is still the tip, decided
1190
+ // only now that the fork material of this batch is settled. A rewind above
1191
+ // may have moved the group onto a branch the candidate cannot beat, so a
1192
+ // fence emitted earlier could outlive its reason; decided here, against
1193
+ // the state the batch reached, the engine's tree-fed rule applies (and
1194
+ // with no fork material the tip has no processable sibling: it fences).
1195
+ const byParent = new Map();
1196
+ for (const candidate of fencedNow) {
1197
+ const tag = bytesToHex(candidate.parent.confirmationTag);
1198
+ byParent.set(tag, [...(byParent.get(tag) ?? []), candidate]);
1199
+ }
1200
+ for (const group of byParent.values()) {
1201
+ const decision = await ctx.decideOpaque?.({
1202
+ parent: group[0].parent,
1203
+ candidates: group.map((c) => ({
1204
+ envelope: c.envelope,
1205
+ message: c.message,
1206
+ senderLeafIndex: c.senderLeafIndex,
1207
+ cause: c.cause,
1208
+ ...(c.removed === undefined ? {} : { removed: c.removed }),
1209
+ })),
1210
+ hold: true,
1211
+ });
1212
+ for (const evidence of decision?.equivocations ?? [])
1213
+ yield { kind: "leafEquivocation", evidence };
1214
+ for (const candidate of group) {
1215
+ if (decision === undefined ||
1216
+ decision.fenced.has(digestHexOf(candidate.message))) {
1217
+ yield {
1218
+ kind: "unreadable",
1219
+ envelope: candidate.envelope,
1220
+ errors: [candidate.cause],
1221
+ };
1222
+ ctx.releaseOpaque?.(candidate.message);
1223
+ }
1224
+ else
1225
+ yield {
1226
+ kind: "skipped",
1227
+ envelope: candidate.envelope,
1228
+ message: candidate.message,
1229
+ reason: "past-epoch",
1230
+ };
1231
+ ctx.opaqueDecided?.(candidate.envelope);
1232
+ }
1233
+ }
1234
+ log("done processing batch – epoch:%d", ctx.getState().groupContext.epoch);
1235
+ if (unreadable.length === 0) {
1236
+ log("done – no unreadable envelopes remain");
1237
+ return;
1238
+ }
1239
+ // A retry only helps when something applied this pass (e.g. a commit advanced
1240
+ // the epoch, unlocking an out-of-order message). If the pass made no progress,
1241
+ // the same envelopes against the same state would fail identically — so yield
1242
+ // them now instead of spinning to maxRetries.
1243
+ if (ctx.getState() === stateBeforePass) {
1244
+ log("no progress this pass – yielding %d envelope(s) as deferred/unreadable", unreadable.length);
1245
+ for (const envelope of unreadable) {
1246
+ yield terminalResult(envelope, deferred, errorList, decryptFailedAll);
1247
+ }
1248
+ return;
1249
+ }
1250
+ log("scheduling retry for %d unreadable envelope(s)", unreadable.length);
1251
+ yield* ingestEnvelopes(ctx, unreadable, {
1252
+ retryCount: retryCount + 1,
1253
+ maxRetries,
1254
+ _errors: errorList,
1255
+ _deferred: deferred,
1256
+ _decryptFailed: decryptFailedAll,
1257
+ });
1258
+ }