@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,196 @@
1
+ /**
2
+ * @module @category Engine
3
+ *
4
+ * Sender-ratchet advance seam (ADR-002 `seam` class).
5
+ *
6
+ * A client that loads an older snapshot of its own `ClientState` may already
7
+ * have sent application messages at generations the restored secret tree
8
+ * still treats as unused. If no relay it can read replays them, its next
9
+ * application message re-mints one of those (epoch, generation) pairs: same
10
+ * key and nonce (only the 4-byte reuse guard differs), and every member that
11
+ * read the earlier message refuses the new one (its ratchet has moved past
12
+ * that generation). Jumping the own application ratchet forward before that
13
+ * first message avoids every generation the snapshot could have missed, as
14
+ * long as the jump stays inside the receivers' forward window
15
+ * (`KeyRetentionConfig.maximumForwardRatchetSteps`).
16
+ *
17
+ * `advanceOwnApplicationRatchet` leaves the secret tree exactly as `steps`
18
+ * calls of ts-mls's internal `consumeRatchet` for the own leaf would (without
19
+ * producing any message): the own leaf's ratchets are derived first if they
20
+ * never were in this epoch, intermediate nodes on the way are consumed the
21
+ * same way, and the application ratchet's `unusedGenerations` is untouched
22
+ * (a sender keeps no secrets for generations it skipped). ts-mls does not
23
+ * export its secret-tree derivation, so RFC 9420's `ExpandWithLabel` /
24
+ * `DeriveTreeSecret` (section 8) and the left-balanced tree arithmetic
25
+ * (appendix C) are re-derived here over the exported `Kdf`.
26
+ *
27
+ * Nothing here runs unless a caller asks for it: `MarmotGroupEngine.send`
28
+ * applies it only for an `applicationMessage` intent carrying a positive
29
+ * `ratchetSkip`; without one the send path is upstream's.
30
+ */
31
+ import { defaultKeyRetentionConfig, } from "ts-mls";
32
+ const textEncoder = new TextEncoder();
33
+ /** RFC 9420 section 2.1.2 variable-length vector length prefix. */
34
+ function vectorLength(length) {
35
+ if (length < 0x40)
36
+ return Uint8Array.of(length);
37
+ if (length < 0x4000)
38
+ return Uint8Array.of(0x40 | (length >> 8), length & 0xff);
39
+ if (length < 0x40000000) {
40
+ return Uint8Array.of(0x80 | (length >>> 24), (length >> 16) & 0xff, (length >> 8) & 0xff, length & 0xff);
41
+ }
42
+ throw new RangeError("vector too long to encode");
43
+ }
44
+ function concatBytes(parts) {
45
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
46
+ let offset = 0;
47
+ for (const part of parts) {
48
+ out.set(part, offset);
49
+ offset += part.length;
50
+ }
51
+ return out;
52
+ }
53
+ /** RFC 9420 `ExpandWithLabel(Secret, Label, Context, Length)`. */
54
+ function expandWithLabel(secret, label, context, length, kdf) {
55
+ const labelBytes = textEncoder.encode(`MLS 1.0 ${label}`);
56
+ const info = concatBytes([
57
+ Uint8Array.of((length >> 8) & 0xff, length & 0xff),
58
+ vectorLength(labelBytes.length),
59
+ labelBytes,
60
+ vectorLength(context.length),
61
+ context,
62
+ ]);
63
+ return kdf.expand(secret, info, length);
64
+ }
65
+ /** RFC 9420 `DeriveTreeSecret(Secret, Label, Generation, Length)`. */
66
+ function deriveTreeSecret(secret, label, generation, length, kdf) {
67
+ const context = new Uint8Array(4);
68
+ new DataView(context.buffer).setUint32(0, generation);
69
+ return expandWithLabel(secret, label, context, length, kdf);
70
+ }
71
+ // RFC 9420 appendix C: array-represented left-balanced binary tree.
72
+ function log2(x) {
73
+ if (x === 0)
74
+ return 0;
75
+ let k = 0;
76
+ while (x >> k > 0)
77
+ k++;
78
+ return k - 1;
79
+ }
80
+ function level(node) {
81
+ if ((node & 0x01) === 0)
82
+ return 0;
83
+ let k = 0;
84
+ while (((node >> k) & 0x01) === 1)
85
+ k++;
86
+ return k;
87
+ }
88
+ function rootOf(leafWidth) {
89
+ const nodeWidth = leafWidth === 0 ? 0 : 2 * (leafWidth - 1) + 1;
90
+ return (1 << log2(nodeWidth)) - 1;
91
+ }
92
+ function leftOf(node) {
93
+ return node ^ (0x01 << (level(node) - 1));
94
+ }
95
+ function rightOf(node) {
96
+ return node ^ (0x03 << (level(node) - 1));
97
+ }
98
+ function parentOf(node) {
99
+ const k = level(node);
100
+ const b = (node >> (k + 1)) & 0x01;
101
+ return (node | (1 << k)) ^ (b << (k + 1));
102
+ }
103
+ /**
104
+ * The tree with `leafIndex`'s handshake/application ratchets derived (the
105
+ * input itself when they already are): descends from the lowest secret held
106
+ * on the leaf's direct path, replacing each consumed parent by both children.
107
+ */
108
+ async function withLeafRatchets(tree, leafIndex, kdf) {
109
+ const target = leafIndex * 2;
110
+ if (tree.leafNodes[target] !== undefined)
111
+ return tree;
112
+ const root = rootOf(tree.leafWidth);
113
+ const path = [];
114
+ for (let node = target;; node = parentOf(node)) {
115
+ path.push(node);
116
+ if (node === root)
117
+ break;
118
+ }
119
+ const nodes = { ...tree.intermediateNodes };
120
+ let start = path.length - 1;
121
+ while (start >= 0 && nodes[path[start]] === undefined)
122
+ start--;
123
+ if (start < 0)
124
+ throw new Error("secret tree holds no secret on the own leaf's direct path");
125
+ let current = path[start];
126
+ while (current !== target) {
127
+ const secret = nodes[current];
128
+ const left = leftOf(current);
129
+ const right = rightOf(current);
130
+ nodes[left] = await expandWithLabel(secret, "tree", textEncoder.encode("left"), kdf.size, kdf);
131
+ nodes[right] = await expandWithLabel(secret, "tree", textEncoder.encode("right"), kdf.size, kdf);
132
+ delete nodes[current];
133
+ current = target < current ? left : right;
134
+ }
135
+ const leafSecret = nodes[target];
136
+ delete nodes[target];
137
+ const ratchetRoot = async (label) => ({
138
+ secret: await expandWithLabel(leafSecret, label, new Uint8Array(), kdf.size, kdf),
139
+ generation: 0,
140
+ unusedGenerations: {},
141
+ });
142
+ return {
143
+ ...tree,
144
+ intermediateNodes: nodes,
145
+ leafNodes: {
146
+ ...tree.leafNodes,
147
+ [target]: { handshake: await ratchetRoot("handshake"), application: await ratchetRoot("application") },
148
+ },
149
+ };
150
+ }
151
+ /**
152
+ * The largest `ratchetSkip` a receiver configured with `clientConfig` (ts-mls
153
+ * defaults when omitted) accepts in one jump:
154
+ * `keyRetentionConfig.maximumForwardRatchetSteps`.
155
+ */
156
+ export function maxSenderRatchetSkip(clientConfig) {
157
+ return (clientConfig?.keyRetentionConfig ?? defaultKeyRetentionConfig).maximumForwardRatchetSteps;
158
+ }
159
+ /**
160
+ * The generation the own leaf's next application message uses in `state`'s
161
+ * epoch: 0 when its ratchet was never derived in this epoch.
162
+ */
163
+ export function nextOwnApplicationGeneration(state) {
164
+ return state.secretTree.leafNodes[Number(state.privatePath.leafIndex) * 2]?.application.generation ?? 0;
165
+ }
166
+ /**
167
+ * A new state whose own-leaf application ratchet is `steps` generations
168
+ * further on — the secret tree `steps` own application messages would have
169
+ * left, with no message produced. `steps` must be a safe integer in
170
+ * `[0, maxSenderRatchetSkip(clientConfig)]`; `0` returns `state` itself. The
171
+ * input state is never mutated.
172
+ */
173
+ export async function advanceOwnApplicationRatchet(state, steps, cs, clientConfig) {
174
+ const max = maxSenderRatchetSkip(clientConfig);
175
+ if (!Number.isSafeInteger(steps) || steps < 0 || steps > max) {
176
+ throw new RangeError(`ratchet skip must be an integer in [0, ${String(max)}], got ${String(steps)}`);
177
+ }
178
+ if (steps === 0)
179
+ return state;
180
+ const kdf = cs.kdf;
181
+ const node = Number(state.privatePath.leafIndex) * 2;
182
+ const tree = await withLeafRatchets(state.secretTree, Number(state.privatePath.leafIndex), kdf);
183
+ const leaf = tree.leafNodes[node];
184
+ let { secret, generation } = leaf.application;
185
+ for (let i = 0; i < steps; i++) {
186
+ secret = await deriveTreeSecret(secret, "secret", generation, kdf.size, kdf);
187
+ generation += 1;
188
+ }
189
+ return {
190
+ ...state,
191
+ secretTree: {
192
+ ...tree,
193
+ leafNodes: { ...tree.leafNodes, [node]: { ...leaf, application: { ...leaf.application, secret, generation } } },
194
+ },
195
+ };
196
+ }
@@ -0,0 +1,122 @@
1
+ import { type ClientState } from "ts-mls";
2
+ /**
3
+ * A group-state change derived from an accepted commit on the selected
4
+ * branch (`convergence.md` "Applying the selected branch"). Every variant
5
+ * carries `commitDigest` — the identity of the commit that produced it — so
6
+ * a rewind that supersedes the commit can withdraw exactly the notifications
7
+ * it derived (D-10, D-11). The notification SHAPE is implementation-defined;
8
+ * `commit_digest` attribution is the conformance requirement.
9
+ */
10
+ export type StateNotification = {
11
+ kind: "epochAdvanced";
12
+ commitDigest: Uint8Array;
13
+ from: number;
14
+ to: number;
15
+ } | {
16
+ kind: "memberAdded";
17
+ commitDigest: Uint8Array;
18
+ pubkey: string;
19
+ } | {
20
+ kind: "memberRemoved";
21
+ commitDigest: Uint8Array;
22
+ pubkey: string;
23
+ actor?: string;
24
+ } | {
25
+ kind: "componentChanged";
26
+ commitDigest: Uint8Array;
27
+ componentId: number;
28
+ } | {
29
+ kind: "selfRemoved";
30
+ commitDigest: Uint8Array;
31
+ } | {
32
+ kind: "branchRecovered";
33
+ commitDigest: Uint8Array;
34
+ forkEpoch: number;
35
+ };
36
+ /**
37
+ * Derives the {@link StateNotification}s produced by a single accepted commit
38
+ * (`convergence.md` "Applying the selected branch") — a pure before/after diff
39
+ * between `parentState` and `resultingState`, every entry attributed to
40
+ * `commitDigest`. Ported from MDK's `group_state_changes.rs` split: this
41
+ * function performs no I/O and holds no ledger; it only diffs two states.
42
+ *
43
+ * Emits in a fixed order so two calls over the same commit produce a
44
+ * byte-identical result (T-03-31): `epochAdvanced`, then `memberAdded` (sorted
45
+ * ascending by pubkey), then `memberRemoved` (sorted ascending by pubkey, no
46
+ * `actor` — the committer is not visible to this pure diff), then
47
+ * `componentChanged` (sorted ascending by component id), then `selfRemoved`
48
+ * when the resulting state is the `removedFromGroup` tombstone and the parent's
49
+ * was not.
50
+ */
51
+ export declare function deriveStateNotifications(args: {
52
+ parentState: ClientState;
53
+ resultingState: ClientState;
54
+ commitDigest: Uint8Array;
55
+ }): StateNotification[];
56
+ /**
57
+ * Groups withdrawn {@link StateNotification}s by their producing commit's hex
58
+ * digest, so a rewind site can emit exactly one {@link
59
+ * StateInvalidatedIngestResult} per superseded commit (D-11) instead of one
60
+ * per notification. Preserves each group's first-seen order; iteration order
61
+ * of groups follows first appearance in `notifications`.
62
+ */
63
+ export declare function groupWithdrawnNotificationsByCommit(notifications: readonly StateNotification[]): {
64
+ commitDigest: Uint8Array;
65
+ withdrawn: StateNotification[];
66
+ }[];
67
+ /**
68
+ * A bounded ledger of {@link StateNotification}s derived from accepted
69
+ * commits, keyed by the producing commit's hex digest — NOT by the delivery
70
+ * state's confirmation tag as {@link DeliveredPayloadLedger} is. CONV-03
71
+ * attributes notifications to the commit that produced them, so the commit
72
+ * digest (rather than a branch/state tag) is the natural withdrawal key.
73
+ *
74
+ * Structural sibling of `DeliveredPayloadLedger`: entries are pruned only
75
+ * below the oldest state still named by either retained history or the fork
76
+ * tree. A finite, pruned tree can therefore bound this ledger; with an
77
+ * unpruned full-history tree (including `maxRewindCommits: Infinity`) the
78
+ * correctness horizon deliberately implies unbounded retention.
79
+ */
80
+ export declare class StateNotificationLedger {
81
+ #private;
82
+ /** Number of remembered commit-notification entries. */
83
+ get size(): number;
84
+ /**
85
+ * Whether a commit's notifications are already recorded for `(digest,
86
+ * epoch)`.
87
+ *
88
+ * WR-14: `invalidatedByRewind` KEEPS entries whose digest is on the winning
89
+ * chain, so every prefix link that was already ledger-recorded when it was
90
+ * first applied in-order survives a rewind. Callers use this to avoid
91
+ * re-reporting those links to the application as freshly-applied.
92
+ */
93
+ has(digest: Uint8Array, epoch: number): boolean;
94
+ /**
95
+ * Remembers the notifications derived from a commit at `epoch`. Empty
96
+ * derivations are retained: their digest identity is still needed to make a
97
+ * later rewind complete and idempotent even though there is nothing to emit.
98
+ *
99
+ * Idempotent on `(digest, epoch)` (WR-14): a rewind whose winning chain
100
+ * includes links that were already applied and recorded in-order would
101
+ * otherwise push a second entry with the same digest and epoch. A later
102
+ * rewind that superseded them then withdrew each of those notifications
103
+ * TWICE, breaking CONV-03's "withdraw exactly the notifications it derived"
104
+ * invariant from the other direction, and compounding the ledger's
105
+ * unbounded growth.
106
+ */
107
+ record(digest: Uint8Array, epoch: number, notifications: StateNotification[]): void;
108
+ /**
109
+ * Removes and returns the notifications withdrawn by a rewind to a
110
+ * canonical branch: those derived strictly after `forkEpoch` whose
111
+ * producing commit digest is not in `canonicalDigests`. Notifications
112
+ * produced on the canonical branch, and any at or below the fork epoch
113
+ * (shared history), are retained.
114
+ */
115
+ invalidatedByRewind(forkEpoch: number, canonicalDigests: ReadonlySet<string>): StateNotification[];
116
+ /**
117
+ * Drops entries below the caller's tree-aware correctness horizon. The
118
+ * engine supplies `min(retained anchor, oldest tree-node epoch)` so no commit
119
+ * still nameable by a fork candidate loses its withdrawal record.
120
+ */
121
+ pruneBelow(epoch: number): void;
122
+ }
@@ -0,0 +1,173 @@
1
+ /** @module @category Engine */
2
+ import { bytesToHex } from "@noble/hashes/utils.js";
3
+ import { getAppDataDictionary } from "ts-mls";
4
+ import { bytesEqual } from "../core/components/bytes.js";
5
+ import { getGroupMemberPubkeys } from "../core/group-members.js";
6
+ /**
7
+ * Derives the {@link StateNotification}s produced by a single accepted commit
8
+ * (`convergence.md` "Applying the selected branch") — a pure before/after diff
9
+ * between `parentState` and `resultingState`, every entry attributed to
10
+ * `commitDigest`. Ported from MDK's `group_state_changes.rs` split: this
11
+ * function performs no I/O and holds no ledger; it only diffs two states.
12
+ *
13
+ * Emits in a fixed order so two calls over the same commit produce a
14
+ * byte-identical result (T-03-31): `epochAdvanced`, then `memberAdded` (sorted
15
+ * ascending by pubkey), then `memberRemoved` (sorted ascending by pubkey, no
16
+ * `actor` — the committer is not visible to this pure diff), then
17
+ * `componentChanged` (sorted ascending by component id), then `selfRemoved`
18
+ * when the resulting state is the `removedFromGroup` tombstone and the parent's
19
+ * was not.
20
+ */
21
+ export function deriveStateNotifications(args) {
22
+ const { parentState, resultingState, commitDigest } = args;
23
+ const notifications = [];
24
+ const fromEpoch = Number(parentState.groupContext.epoch);
25
+ const toEpoch = Number(resultingState.groupContext.epoch);
26
+ if (toEpoch !== fromEpoch) {
27
+ notifications.push({
28
+ kind: "epochAdvanced",
29
+ commitDigest,
30
+ from: fromEpoch,
31
+ to: toEpoch,
32
+ });
33
+ }
34
+ const beforeMembers = new Set(getGroupMemberPubkeys(parentState));
35
+ const afterMembers = new Set(getGroupMemberPubkeys(resultingState));
36
+ const added = [...afterMembers]
37
+ .filter((pubkey) => !beforeMembers.has(pubkey))
38
+ .sort();
39
+ for (const pubkey of added)
40
+ notifications.push({ kind: "memberAdded", commitDigest, pubkey });
41
+ const removed = [...beforeMembers]
42
+ .filter((pubkey) => !afterMembers.has(pubkey))
43
+ .sort();
44
+ for (const pubkey of removed)
45
+ notifications.push({ kind: "memberRemoved", commitDigest, pubkey });
46
+ const beforeDict = getAppDataDictionary(parentState.groupContext.extensions);
47
+ const afterDict = getAppDataDictionary(resultingState.groupContext.extensions);
48
+ const allComponentIds = new Set();
49
+ for (const entry of beforeDict ?? [])
50
+ allComponentIds.add(entry.componentId);
51
+ for (const entry of afterDict ?? [])
52
+ allComponentIds.add(entry.componentId);
53
+ const changedComponentIds = [...allComponentIds]
54
+ .filter((componentId) => {
55
+ const before = beforeDict?.find((c) => c.componentId === componentId)?.data;
56
+ const after = afterDict?.find((c) => c.componentId === componentId)?.data;
57
+ return !bytesEqual(before, after);
58
+ })
59
+ .sort((a, b) => a - b);
60
+ for (const componentId of changedComponentIds)
61
+ notifications.push({ kind: "componentChanged", commitDigest, componentId });
62
+ if (resultingState.groupActiveState.kind === "removedFromGroup" &&
63
+ parentState.groupActiveState.kind !== "removedFromGroup") {
64
+ notifications.push({ kind: "selfRemoved", commitDigest });
65
+ }
66
+ return notifications;
67
+ }
68
+ /**
69
+ * Groups withdrawn {@link StateNotification}s by their producing commit's hex
70
+ * digest, so a rewind site can emit exactly one {@link
71
+ * StateInvalidatedIngestResult} per superseded commit (D-11) instead of one
72
+ * per notification. Preserves each group's first-seen order; iteration order
73
+ * of groups follows first appearance in `notifications`.
74
+ */
75
+ export function groupWithdrawnNotificationsByCommit(notifications) {
76
+ const order = [];
77
+ const byDigest = new Map();
78
+ for (const notification of notifications) {
79
+ const key = bytesToHex(notification.commitDigest);
80
+ let group = byDigest.get(key);
81
+ if (!group) {
82
+ group = { commitDigest: notification.commitDigest, withdrawn: [] };
83
+ byDigest.set(key, group);
84
+ order.push(key);
85
+ }
86
+ group.withdrawn.push(notification);
87
+ }
88
+ return order.map((key) => byDigest.get(key));
89
+ }
90
+ /**
91
+ * A bounded ledger of {@link StateNotification}s derived from accepted
92
+ * commits, keyed by the producing commit's hex digest — NOT by the delivery
93
+ * state's confirmation tag as {@link DeliveredPayloadLedger} is. CONV-03
94
+ * attributes notifications to the commit that produced them, so the commit
95
+ * digest (rather than a branch/state tag) is the natural withdrawal key.
96
+ *
97
+ * Structural sibling of `DeliveredPayloadLedger`: entries are pruned only
98
+ * below the oldest state still named by either retained history or the fork
99
+ * tree. A finite, pruned tree can therefore bound this ledger; with an
100
+ * unpruned full-history tree (including `maxRewindCommits: Infinity`) the
101
+ * correctness horizon deliberately implies unbounded retention.
102
+ */
103
+ export class StateNotificationLedger {
104
+ #entries = new Map();
105
+ static #key(digest, epoch) {
106
+ return `${bytesToHex(digest)}:${epoch}`;
107
+ }
108
+ /** Number of remembered commit-notification entries. */
109
+ get size() {
110
+ return this.#entries.size;
111
+ }
112
+ /**
113
+ * Whether a commit's notifications are already recorded for `(digest,
114
+ * epoch)`.
115
+ *
116
+ * WR-14: `invalidatedByRewind` KEEPS entries whose digest is on the winning
117
+ * chain, so every prefix link that was already ledger-recorded when it was
118
+ * first applied in-order survives a rewind. Callers use this to avoid
119
+ * re-reporting those links to the application as freshly-applied.
120
+ */
121
+ has(digest, epoch) {
122
+ return this.#entries.has(StateNotificationLedger.#key(digest, epoch));
123
+ }
124
+ /**
125
+ * Remembers the notifications derived from a commit at `epoch`. Empty
126
+ * derivations are retained: their digest identity is still needed to make a
127
+ * later rewind complete and idempotent even though there is nothing to emit.
128
+ *
129
+ * Idempotent on `(digest, epoch)` (WR-14): a rewind whose winning chain
130
+ * includes links that were already applied and recorded in-order would
131
+ * otherwise push a second entry with the same digest and epoch. A later
132
+ * rewind that superseded them then withdrew each of those notifications
133
+ * TWICE, breaking CONV-03's "withdraw exactly the notifications it derived"
134
+ * invariant from the other direction, and compounding the ledger's
135
+ * unbounded growth.
136
+ */
137
+ record(digest, epoch, notifications) {
138
+ if (this.has(digest, epoch))
139
+ return;
140
+ this.#entries.set(StateNotificationLedger.#key(digest, epoch), {
141
+ digest: bytesToHex(digest),
142
+ epoch,
143
+ notifications,
144
+ });
145
+ }
146
+ /**
147
+ * Removes and returns the notifications withdrawn by a rewind to a
148
+ * canonical branch: those derived strictly after `forkEpoch` whose
149
+ * producing commit digest is not in `canonicalDigests`. Notifications
150
+ * produced on the canonical branch, and any at or below the fork epoch
151
+ * (shared history), are retained.
152
+ */
153
+ invalidatedByRewind(forkEpoch, canonicalDigests) {
154
+ const invalidated = [];
155
+ for (const [key, entry] of this.#entries) {
156
+ if (entry.epoch > forkEpoch && !canonicalDigests.has(entry.digest)) {
157
+ invalidated.push(...entry.notifications);
158
+ this.#entries.delete(key);
159
+ }
160
+ }
161
+ return invalidated;
162
+ }
163
+ /**
164
+ * Drops entries below the caller's tree-aware correctness horizon. The
165
+ * engine supplies `min(retained anchor, oldest tree-node epoch)` so no commit
166
+ * still nameable by a fork candidate loses its withdrawal record.
167
+ */
168
+ pruneBelow(epoch) {
169
+ for (const [key, entry] of this.#entries)
170
+ if (entry.epoch < epoch)
171
+ this.#entries.delete(key);
172
+ }
173
+ }
@@ -0,0 +1,41 @@
1
+ /** @module @category Engine */
2
+ import type { BranchCandidate, ConvergencePolicy } from "../core/convergence.js";
3
+ import type { GroupHistoryTree } from "./history-tree.js";
4
+ /**
5
+ * The candidate set for a tree-fed re-convergence pass: the shared fork root plus
6
+ * one {@link BranchCandidate} per branch tip reachable from it (including the
7
+ * current tip), scored later by {@link selectCanonicalBranch}.
8
+ */
9
+ export interface TreeBranchSet {
10
+ /** The single fork root all candidates are measured from (its hex node tag). */
11
+ rootTag: string;
12
+ /** One candidate per tip descending from the root (the current tip included). */
13
+ candidates: BranchCandidate[];
14
+ }
15
+ /**
16
+ * Builds the candidate branch set for re-scoring the persisted fork history
17
+ * against the current tip, sourcing everything from the {@link GroupHistoryTree}
18
+ * (Marmot v2 `protocol-core/convergence.md`). Unlike `ForkRecovery`, which
19
+ * replays the incoming commit pool, this reads the tree's already-retained fork
20
+ * snapshots, so a competing branch known only on disk is re-evaluated without the
21
+ * transport re-delivering it.
22
+ *
23
+ * Construction is fully synchronous and structural: every datum a candidate needs
24
+ * (epoch, tip digest) is in the tree's light index — `tipDigest` is the stored
25
+ * `edge.commitDigest`, byte-identical to the `sha256` of the commit MLS bytes that
26
+ * scoring expects. App-payload witnesses are layered on by the caller when
27
+ * available; on load there are none, and the structural keys
28
+ * (depth + lower tip digest) still pick a deterministic, member-independent
29
+ * winner.
30
+ *
31
+ * A single shared fork root is chosen — the eligible competing tip's fork point at
32
+ * the *minimum* epoch (the current tip's path is linear, so its ancestor at that
33
+ * epoch is unique). Every tip descending from that root becomes a candidate at the
34
+ * shared `forkEpoch`, mirroring the pool path's single-root semantics
35
+ * (`ingest.ts` `minForkEpoch`). Including the current tip makes "already
36
+ * canonical" a clean no-op for the selector.
37
+ *
38
+ * @returns the candidate set, or `undefined` when no eligible competing tip exists
39
+ * (no fork within the rollback horizon — nothing to switch to).
40
+ */
41
+ export declare function buildTreeBranchSet(tree: GroupHistoryTree, currentTipTag: string, policy: ConvergencePolicy): TreeBranchSet | undefined;
@@ -0,0 +1,90 @@
1
+ import { isBranchEligible } from "../core/convergence.js";
2
+ /** Shared empty digest for the horizon-only eligibility probe (never scored). */
3
+ const EMPTY = new Uint8Array();
4
+ /**
5
+ * Builds the candidate branch set for re-scoring the persisted fork history
6
+ * against the current tip, sourcing everything from the {@link GroupHistoryTree}
7
+ * (Marmot v2 `protocol-core/convergence.md`). Unlike `ForkRecovery`, which
8
+ * replays the incoming commit pool, this reads the tree's already-retained fork
9
+ * snapshots, so a competing branch known only on disk is re-evaluated without the
10
+ * transport re-delivering it.
11
+ *
12
+ * Construction is fully synchronous and structural: every datum a candidate needs
13
+ * (epoch, tip digest) is in the tree's light index — `tipDigest` is the stored
14
+ * `edge.commitDigest`, byte-identical to the `sha256` of the commit MLS bytes that
15
+ * scoring expects. App-payload witnesses are layered on by the caller when
16
+ * available; on load there are none, and the structural keys
17
+ * (depth + lower tip digest) still pick a deterministic, member-independent
18
+ * winner.
19
+ *
20
+ * A single shared fork root is chosen — the eligible competing tip's fork point at
21
+ * the *minimum* epoch (the current tip's path is linear, so its ancestor at that
22
+ * epoch is unique). Every tip descending from that root becomes a candidate at the
23
+ * shared `forkEpoch`, mirroring the pool path's single-root semantics
24
+ * (`ingest.ts` `minForkEpoch`). Including the current tip makes "already
25
+ * canonical" a clean no-op for the selector.
26
+ *
27
+ * @returns the candidate set, or `undefined` when no eligible competing tip exists
28
+ * (no fork within the rollback horizon — nothing to switch to).
29
+ */
30
+ export function buildTreeBranchSet(tree, currentTipTag, policy) {
31
+ const currentTipEpoch = tree.epochOf(currentTipTag);
32
+ if (currentTipEpoch === undefined)
33
+ return undefined;
34
+ // The deepest eligible divergence: the smallest fork epoch among competing
35
+ // tips still inside the rollback horizon. That fork node is the shared root.
36
+ let rootTag;
37
+ let rootEpoch = Number.POSITIVE_INFINITY;
38
+ for (const tip of tree.tips()) {
39
+ if (tip === currentTipTag)
40
+ continue;
41
+ const forkTag = tree.lowestCommonAncestor(tip, currentTipTag);
42
+ if (forkTag === undefined)
43
+ continue;
44
+ const forkEpoch = tree.epochOf(forkTag);
45
+ const tipEpoch = tree.epochOf(tip);
46
+ if (forkEpoch === undefined || tipEpoch === undefined)
47
+ continue;
48
+ // Horizon eligibility — same predicate the selector applies; only forkEpoch
49
+ // is read, so a minimal candidate suffices.
50
+ const eligible = isBranchEligible(currentTipEpoch, { id: tip, forkEpoch, tipEpoch, tipDigest: EMPTY, appWitnesses: [] }, policy);
51
+ if (!eligible)
52
+ continue;
53
+ if (forkEpoch < rootEpoch) {
54
+ rootEpoch = forkEpoch;
55
+ rootTag = forkTag;
56
+ }
57
+ }
58
+ if (rootTag === undefined)
59
+ return undefined;
60
+ // Every tip reachable from the root is a candidate at the shared fork epoch.
61
+ // The current tip descends from the root (the root is its ancestor), so it is
62
+ // enumerated here too.
63
+ const candidates = [];
64
+ const stack = [rootTag];
65
+ const seen = new Set();
66
+ while (stack.length > 0) {
67
+ const tag = stack.pop();
68
+ if (seen.has(tag))
69
+ continue;
70
+ seen.add(tag);
71
+ const children = tree.childrenOf(tag);
72
+ if (children.length === 0) {
73
+ const tipEpoch = tree.epochOf(tag);
74
+ if (tipEpoch === undefined)
75
+ continue;
76
+ candidates.push({
77
+ id: tag,
78
+ forkEpoch: rootEpoch,
79
+ tipEpoch,
80
+ tipDigest: tree.node(tag)?.edge?.commitDigest ?? EMPTY,
81
+ appWitnesses: [],
82
+ });
83
+ }
84
+ else {
85
+ for (const child of children)
86
+ stack.push(child);
87
+ }
88
+ }
89
+ return { rootTag, candidates };
90
+ }