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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/LICENSE +53 -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 +93 -0
  55. package/dist/core/components/ids.js +92 -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 +56 -0
  91. package/dist/core/group.js +95 -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 +29 -0
  95. package/dist/core/index.js +27 -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 +117 -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 +66 -0
  107. package/dist/core/key-package.js +147 -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-profile.d.ts +262 -0
  123. package/dist/core/protocol-profile.js +535 -0
  124. package/dist/core/protocol.d.ts +51 -0
  125. package/dist/core/protocol.js +41 -0
  126. package/dist/core/relay-lists.d.ts +52 -0
  127. package/dist/core/relay-lists.js +86 -0
  128. package/dist/core/retained-history.d.ts +78 -0
  129. package/dist/core/retained-history.js +59 -0
  130. package/dist/core/transport.d.ts +43 -0
  131. package/dist/core/transport.js +21 -0
  132. package/dist/core/welcome-event.d.ts +61 -0
  133. package/dist/core/welcome-event.js +116 -0
  134. package/dist/core/welcome-join.d.ts +155 -0
  135. package/dist/core/welcome-join.js +243 -0
  136. package/dist/core/welcome.d.ts +3 -0
  137. package/dist/core/welcome.js +6 -0
  138. package/dist/engine/admin-policy.d.ts +75 -0
  139. package/dist/engine/admin-policy.js +137 -0
  140. package/dist/engine/auto-committer.d.ts +39 -0
  141. package/dist/engine/auto-committer.js +42 -0
  142. package/dist/engine/delivered-payloads.d.ts +61 -0
  143. package/dist/engine/delivered-payloads.js +84 -0
  144. package/dist/engine/disband-request.d.ts +41 -0
  145. package/dist/engine/disband-request.js +86 -0
  146. package/dist/engine/disband-tombstone.d.ts +14 -0
  147. package/dist/engine/disband-tombstone.js +66 -0
  148. package/dist/engine/fork-recovery.d.ts +672 -0
  149. package/dist/engine/fork-recovery.js +1615 -0
  150. package/dist/engine/group-engine.d.ts +571 -0
  151. package/dist/engine/group-engine.js +5134 -0
  152. package/dist/engine/history-tree.d.ts +232 -0
  153. package/dist/engine/history-tree.js +651 -0
  154. package/dist/engine/index.d.ts +16 -0
  155. package/dist/engine/index.js +15 -0
  156. package/dist/engine/ingest-disposition.d.ts +5 -0
  157. package/dist/engine/ingest-disposition.js +63 -0
  158. package/dist/engine/ingest.d.ts +390 -0
  159. package/dist/engine/ingest.js +1258 -0
  160. package/dist/engine/ingestion-pool.d.ts +74 -0
  161. package/dist/engine/ingestion-pool.js +95 -0
  162. package/dist/engine/message-dedup.d.ts +16 -0
  163. package/dist/engine/message-dedup.js +20 -0
  164. package/dist/engine/own-commit-stamp.d.ts +30 -0
  165. package/dist/engine/own-commit-stamp.js +71 -0
  166. package/dist/engine/retained-store.d.ts +79 -0
  167. package/dist/engine/retained-store.js +133 -0
  168. package/dist/engine/sender-ratchet.d.ts +50 -0
  169. package/dist/engine/sender-ratchet.js +196 -0
  170. package/dist/engine/state-notifications.d.ts +122 -0
  171. package/dist/engine/state-notifications.js +173 -0
  172. package/dist/engine/tree-convergence.d.ts +41 -0
  173. package/dist/engine/tree-convergence.js +90 -0
  174. package/dist/engine/types.d.ts +366 -0
  175. package/dist/engine/types.js +14 -0
  176. package/dist/engine/wire-format.d.ts +77 -0
  177. package/dist/engine/wire-format.js +120 -0
  178. package/dist/index.d.ts +12 -0
  179. package/dist/index.js +1 -0
  180. package/dist/mls.d.ts +11 -0
  181. package/dist/mls.js +11 -0
  182. package/dist/utils/debug.d.ts +3 -0
  183. package/dist/utils/debug.js +3 -0
  184. package/dist/utils/encoding.d.ts +38 -0
  185. package/dist/utils/encoding.js +91 -0
  186. package/dist/utils/key-value.d.ts +18 -0
  187. package/dist/utils/key-value.js +2 -0
  188. package/dist/utils/nostr.d.ts +35 -0
  189. package/dist/utils/nostr.js +26 -0
  190. package/dist/utils/relay-url.d.ts +10 -0
  191. package/dist/utils/relay-url.js +23 -0
  192. package/dist/utils/tag-cardinality.d.ts +50 -0
  193. package/dist/utils/tag-cardinality.js +91 -0
  194. package/dist/utils/timestamp.d.ts +50 -0
  195. package/dist/utils/timestamp.js +95 -0
  196. package/dist/version.d.ts +112 -0
  197. package/dist/version.js +112 -0
  198. package/package.json +68 -3
@@ -0,0 +1,567 @@
1
+ /**
2
+ * Deterministic convergence primitives (Marmot v2 `protocol-core/convergence.md`).
3
+ *
4
+ * Convergence chooses one canonical branch from unordered group input using only
5
+ * MLS-valid bytes, retained state, decrypted app payloads, and the group's
6
+ * convergence policy — never transport arrival order, timestamps, outer event
7
+ * ids, or local receive order. Every member processing the same epoch with the
8
+ * same policy MUST select the same branch, so this logic is byte-for-byte
9
+ * deterministic and ported directly from darkmatter `cgka-engine/src/convergence.rs`.
10
+ *
11
+ * This module is the pure selection/scoring core; candidate-branch construction
12
+ * (replaying commits from retained states) and disposition assignment live in
13
+ * the inbound/retained-history layers.
14
+ */
15
+ /** The signed convergence policy governing branch selection for a group. */
16
+ export interface ConvergencePolicy {
17
+ /**
18
+ * The pinned convergence-policy profile this set of constants names
19
+ * (`convergence.md`). Not a wire field — it identifies the profile; profile
20
+ * `1` is the values in {@link DEFAULT_CONVERGENCE_POLICY}.
21
+ */
22
+ policyVersion: number;
23
+ /** How far back from the current tip a branch MAY fork and stay eligible. */
24
+ maxRewindCommits: number;
25
+ /**
26
+ * The width of the retained app-payload window: an MLS application message is
27
+ * inside the window iff `reference_tip_epoch - message_epoch <= this`
28
+ * (`retained-history.md` "App-payload retention"). Messages outside it expire
29
+ * and MUST NOT count as convergence witnesses.
30
+ */
31
+ appPayloadPastEpochLimit: number;
32
+ /**
33
+ * The minimum quiescent time (ms) without new convergence-relevant input
34
+ * before a convergence pass MAY be treated as settled and queued outbound work
35
+ * released (`convergence.md`). Carried for completeness; the settle-window
36
+ * state machine itself (B5) is not yet wired.
37
+ */
38
+ settlementQuiescenceMs: number;
39
+ /** Maximum duration (ms) of one immutable convergence collection window. */
40
+ maxConvergencePassMs: number;
41
+ /** Distinct senders needed for one branch epoch to count toward witness quorum. */
42
+ witnessQuorumSendersPerEpoch: number;
43
+ /** Number of branch epochs that MUST meet sender quorum. */
44
+ witnessQuorumEpochs: number;
45
+ /** Maximum commit-depth boost a branch MAY receive from witness quorum. */
46
+ maxWitnessOverrideDepth: number;
47
+ }
48
+ /**
49
+ * The default Marmot convergence policy — profile version 1 (`convergence.md`).
50
+ * Groups without explicit policy bytes MUST treat this as active.
51
+ */
52
+ export declare const DEFAULT_CONVERGENCE_POLICY: ConvergencePolicy;
53
+ /** Input accepted from pre-bounded-pass callers that omit the v1 field. */
54
+ export type CompatibleConvergencePolicy = Omit<ConvergencePolicy, "maxConvergencePassMs"> & Partial<Pick<ConvergencePolicy, "maxConvergencePassMs">>;
55
+ /** Supplies the pinned v1 pass bound when decoding/configuring older policy input. */
56
+ export declare function normalizeConvergencePolicy(policy: CompatibleConvergencePolicy): ConvergencePolicy;
57
+ /**
58
+ * Validates the witness-override invariant: a witness-quorum boost must never be
59
+ * able to push a branch past the rollback horizon, so
60
+ * `maxWitnessOverrideDepth <= maxRewindCommits`. Throws on violation.
61
+ */
62
+ export declare function validateConvergencePolicy(policy: ConvergencePolicy): void;
63
+ /**
64
+ * An app-payload witness: an MLS application message whose Marmot app payload
65
+ * decrypts against a candidate branch state. `sender` is the account identity
66
+ * authenticated by the MLS leaf credential (not a transport/leaf identity).
67
+ */
68
+ export interface AppWitness {
69
+ epoch: number;
70
+ sender: Uint8Array;
71
+ }
72
+ /**
73
+ * Whether an app-payload witness counts toward a candidate branch's score
74
+ * (`convergence.md` "App-payload witnesses", `retained-history.md`
75
+ * "App-payload retention"). A witness MUST decrypt strictly after the branch's
76
+ * `forkEpoch` (a message at/before the fork is not a witness for any candidate)
77
+ * AND be inside the retained app-payload window evaluated with the candidate's
78
+ * `tipEpoch` as the reference tip. Stale or pre-fork app payloads MUST NOT
79
+ * influence branch selection.
80
+ */
81
+ export declare function isWitnessEligible(witness: AppWitness, forkEpoch: number, tipEpoch: number, policy: ConvergencePolicy): boolean;
82
+ /** A candidate branch produced by replaying commits from a retained state. */
83
+ export interface BranchCandidate {
84
+ /** Caller-supplied identifier for the branch (not used in scoring). */
85
+ id: string;
86
+ /** The epoch where the branch diverged from retained canonical state. */
87
+ forkEpoch: number;
88
+ /** The epoch reached after replaying the branch's valid commits. */
89
+ tipEpoch: number;
90
+ /** SHA-256 (32 bytes) of the branch's tip commit MLS message bytes. */
91
+ tipDigest: Uint8Array;
92
+ /** Authenticated account identity of the tip commit's member sender. */
93
+ tipCommitter?: Uint8Array;
94
+ /** App-payload witnesses that decrypt on candidate states in the branch. */
95
+ appWitnesses: AppWitness[];
96
+ /**
97
+ * Seam (`equivocationCredit`): the commit edges from the selection call's
98
+ * shared root to this candidate's tip, root→tip. `undefined` when the seam
99
+ * is off, which keeps selection on today's code path. Read only by
100
+ * {@link equivocationNodesOf} / {@link selectCanonicalBranchCredited}.
101
+ */
102
+ path?: readonly CandidatePathEdge[];
103
+ }
104
+ /**
105
+ * Seam (`equivocationCredit`): one commit edge of a candidate's
106
+ * {@link BranchCandidate.path}. Node ids are hex confirmation tags, so the same
107
+ * commit yields the same edge at every site and on every member. Deliberately
108
+ * carries no epoch, timestamp, sequence or event id: a node's epoch is
109
+ * `forkEpoch + position`.
110
+ */
111
+ export interface CandidatePathEdge {
112
+ /** Hex confirmation tag of the edge's parent state. */
113
+ parentId: string;
114
+ /**
115
+ * Hex confirmation tag of the child state, or `removal:<digestHex>` /
116
+ * `terminal:<digestHex>` for a virtual removal / disband-terminal leaf.
117
+ */
118
+ childId: string;
119
+ /** SHA-256 of the commit MLS bytes. */
120
+ commitDigest: Uint8Array;
121
+ /** The authenticated member sender's leaf index; `undefined` for a non-member or unknown sender. */
122
+ senderLeafIndex: number | undefined;
123
+ /**
124
+ * Seam (`removalFinality`, ADR-017 R-1 / R-2): the leaves this edge removes, each as occupied in the edge's PARENT
125
+ * state, strictly ascending by `leafIndex` with no duplicates; no epoch, time, event id or arrival order. Absent:
126
+ * unknown (never evidence); `[]`: resolved, removes nothing. Shells set it only when the seam is effective, and the
127
+ * core reads it only when `credit.removalFinality === true` (stray facts are inert). Readers use the merged
128
+ * candidate-tree entry, never one candidate's own path copy: copies of one edge merge (a present copy wins over an
129
+ * absent one; two present copies that differ as sets of leaves make the tree unbuildable).
130
+ */
131
+ removed?: readonly RemovedLeaf[];
132
+ }
133
+ /** Seam (`removalFinality`): one leaf an edge removes, as occupied in the edge's PARENT state. */
134
+ export interface RemovedLeaf {
135
+ /** The leaf index in the parent state. */
136
+ readonly leafIndex: number;
137
+ /** Lowercase hex leaf signature key in the parent (same encoding as {@link EquivocationNodeContext.members}). */
138
+ readonly leafKey: string;
139
+ }
140
+ /**
141
+ * Seam (`equivocationCredit`): the ratchet-tree facts of one equivocation node,
142
+ * resolved by the shell against that node's own state.
143
+ */
144
+ export interface EquivocationNodeContext {
145
+ /** Occupied leaf index → hex leaf signature key at the node. */
146
+ members: ReadonlyMap<number, string>;
147
+ /**
148
+ * Occupied leaf index → hex account credential pubkey at the node (report only).
149
+ * Invariant: accounts ⊆ members (`equivocationNodeContextOf` guarantees it); a
150
+ * member with a non-Marmot credential has no account.
151
+ */
152
+ accounts: ReadonlyMap<number, string>;
153
+ }
154
+ /**
155
+ * Seam (key rotation): the part of a `LeafKeySuccession` (`leaf-succession.ts`) the credit lineage reads. Declared here so the
156
+ * selection core imports nothing but `retained-history` and `@noble/hashes`; a `LeafKeySuccession` is assignable to it.
157
+ */
158
+ export interface EdgeKeySuccession {
159
+ readonly leafIndex: number;
160
+ readonly fromKey: string;
161
+ readonly toKey: string;
162
+ readonly source: "commit" | "update";
163
+ }
164
+ /**
165
+ * Seam (`equivocationCredit`): the shell-resolved input of credited selection
166
+ * (phase 2), keyed by the node ids {@link equivocationNodesOf} returned.
167
+ */
168
+ export interface EquivocationCreditInput {
169
+ /**
170
+ * One entry per candidate node {@link equivocationNodesOf} returned (hex
171
+ * confirmation tag). A missing entry resolves that node by today's ordering
172
+ * and reports nothing there (per-node fallback); other nodes keep credit.
173
+ */
174
+ nodes: ReadonlyMap<string, EquivocationNodeContext>;
175
+ /**
176
+ * Hex commit digest → hex sender leaf signature key in that edge's parent
177
+ * state, for every edge below a candidate node. A missing entry earns no
178
+ * credit and is no cross-subtree evidence (fail-closed).
179
+ */
180
+ senderKeys: ReadonlyMap<string, string>;
181
+ /**
182
+ * Seam (key rotation, lineage clause of ADR-016 D2 rule 4): hex commit digest
183
+ * → the signature-key successions (`LeafKeySuccession`s of `leaf-succession.ts`) the shell read
184
+ * between that edge's parent state and its child state. Selection reads only
185
+ * the entry of the committing leaf itself with source `commit` and a `fromKey`
186
+ * equal to the key the edge was signed under, and only to extend the keys that
187
+ * leaf's LATER edges on the same candidate path may be credited under (see
188
+ * `creditAt`); it never touches evidence, equivocation detection or the
189
+ * report. Absent, or an edge without an entry (its parent or child state was
190
+ * unavailable, or the commit rotated nothing): credit is the pre-fix credit
191
+ * for that edge's successors (fail-closed, never wider).
192
+ */
193
+ successions?: ReadonlyMap<string, readonly EdgeKeySuccession[]>;
194
+ /**
195
+ * Seam (`removalFinality`): present exactly when the engine's removalFinality is effective. Absent → ADR-016 byte
196
+ * for byte. With it, selection reads {@link CandidatePathEdge.removed} and applies ADR-017's rule at every rule node
197
+ * (`nodes` then carries a context for every branching node, see {@link phaseOneNodesOf}).
198
+ */
199
+ removalFinality?: true;
200
+ }
201
+ /**
202
+ * Seam (`equivocationCredit`): evidence that one leaf authored two or more
203
+ * distinct child commits of one node (a direct equivocation, `EqDirect`).
204
+ * Cross-subtree-only evidence is never reported. Report only — never a
205
+ * selection input.
206
+ */
207
+ export interface LeafEquivocation {
208
+ /** Hex confirmation tag of the equivocation node. */
209
+ nodeTag: string;
210
+ /** The node's MLS epoch. */
211
+ epoch: number;
212
+ /** The equivocating leaf at the node. */
213
+ leafIndex: number;
214
+ /** Hex leaf signature key of that leaf at the node. */
215
+ leafKey: string;
216
+ /** Hex account credential pubkey of that leaf at the node. */
217
+ account: string;
218
+ /** Hex digests of the leaf's child commits at the node (two or more, ascending). */
219
+ commitDigests: readonly string[];
220
+ }
221
+ /** Seam (`equivocationCredit`): the outcome of {@link selectCanonicalBranchCredited}. */
222
+ export interface CanonicalSelection {
223
+ /** The selected branch; `undefined` exactly when no candidate is eligible. */
224
+ winner?: BranchCandidate;
225
+ /** One entry per (resolvable equivocation node, directly equivocating leaf), sorted by (epoch, nodeTag, leafIndex). */
226
+ equivocations: LeafEquivocation[];
227
+ /**
228
+ * Whether credit changed the local outcome at a resolvable equivocation node
229
+ * on the winner's path: the credit filter removed the representative today's
230
+ * ordering over all of that node's representatives would have returned.
231
+ */
232
+ decidedByCredit: boolean;
233
+ /**
234
+ * Seam (`removalFinality`): present iff the credit input carries `removalFinality`. Whether ADR-017's rule changed
235
+ * the local outcome at a rule node on the winner's path: the rule's representative differs from ADR-016's choice
236
+ * there (the `Rm` exclusion or the tie preference decided). A rule node where both agree reports nothing.
237
+ */
238
+ decidedByRemoval?: boolean;
239
+ }
240
+ /** The derived comparison keys for a {@link BranchCandidate}. */
241
+ export interface BranchScore {
242
+ validCommitDepth: number;
243
+ effectiveCommitDepth: number;
244
+ witnessQuorumMet: boolean;
245
+ appWitnessScore: number;
246
+ tipDigest: Uint8Array;
247
+ tipCommitter: Uint8Array;
248
+ }
249
+ /** Computes the {@link BranchScore} for a candidate under a policy. */
250
+ export declare function scoreBranch(branch: BranchCandidate, policy: ConvergencePolicy): BranchScore;
251
+ /**
252
+ * Compares two branch scores per `convergence.md` "Branch selection": higher
253
+ * effectiveCommitDepth, then witness quorum beats none, then higher
254
+ * rawCommitDepth, then higher appWitnessScore, then LOWER tipDigest. Returns a
255
+ * positive number when `a` ranks above `b` (so the canonical branch is the
256
+ * maximum under this ordering).
257
+ */
258
+ export declare function compareBranchScores(a: BranchScore, b: BranchScore): number;
259
+ /**
260
+ * A branch is eligible only inside the rollback horizon:
261
+ * `currentTipEpoch - forkEpoch <= maxRewindCommits` (`convergence.md`
262
+ * "Eligibility").
263
+ *
264
+ * This predicate is intentionally horizon-only and takes no retained anchor.
265
+ * `convergence.md` lists a second eligibility rule — "a branch that needs a
266
+ * retained state older than the retained anchor MUST NOT be selected" — but that
267
+ * guard is deliberately kept **separate** from this predicate, mirroring the
268
+ * reference engine's two-layer structure (`is_branch_eligible` is horizon-only;
269
+ * the anchor check lives in candidate admission + late-commit classification,
270
+ * always anchor-first). Keeping the anchor out of here lets the predicate be
271
+ * reused for horizon-only purposes (e.g. eligibility counts) and keeps it a pure
272
+ * function of policy + branch, with no dependency on retained-store state. The
273
+ * anchor guard is applied operationally: {@link classifyLateCommit} emits
274
+ * `beyond_anchor` for a sub-anchor commit (ingest), and fork recovery cannot
275
+ * build a branch whose `forkEpoch` state is no longer retained.
276
+ */
277
+ export declare function isBranchEligible(currentTipEpoch: number, branch: BranchCandidate, policy: ConvergencePolicy): boolean;
278
+ /**
279
+ * Selects the canonical branch from candidates: filters to eligible branches and
280
+ * returns the maximum under {@link compareBranchScores}. On a full tie the later
281
+ * candidate wins (matching Rust `max_by`). Returns undefined if none eligible.
282
+ *
283
+ * Seam (`equivocationCredit`): with `credit` present this returns
284
+ * {@link selectCanonicalBranchCredited}'s winner; without it the body below runs
285
+ * unchanged.
286
+ */
287
+ export declare function selectCanonicalBranch(currentTipEpoch: number, candidates: BranchCandidate[], policy: ConvergencePolicy, credit?: EquivocationCreditInput): BranchCandidate | undefined;
288
+ /**
289
+ * Seam (`equivocationCredit`), phase 1: the candidate nodes of the candidate
290
+ * tree `T` — the union of the eligible candidates' {@link BranchCandidate.path}s
291
+ * — each a node with some child edge whose defined sender leaf index is also
292
+ * carried by an edge in another child subtree of the node (keys unchecked),
293
+ * with those child edges' sender indices ascending. Ordered by distance from
294
+ * the shared root, then node id.
295
+ *
296
+ * This is a superset of the equivocation nodes: phase 2 applies the key clause
297
+ * and may still resolve a node by today's ordering (SC-3 rule 3b — no context,
298
+ * no anchored child edge after the key clause, or an equivocator without
299
+ * membership there). Empty
300
+ * exactly when {@link selectCanonicalBranchCredited} falls back globally (rule
301
+ * 3a): no eligible candidate, or `T` cannot be built — an eligible candidate
302
+ * without a non-empty chained path, eligible paths with different roots or
303
+ * `forkEpoch`s, two paths disagreeing on the edge into one node, or two child
304
+ * edges of one node with one digest (see `candidateTreeOf`) — or `T` has no
305
+ * candidate node. Pure: the shell resolves an {@link EquivocationCreditInput}
306
+ * only when this is non-empty, and needs node contexts for these nodes and
307
+ * sender keys for every edge below them.
308
+ */
309
+ export declare function equivocationNodesOf(currentTipEpoch: number, candidates: readonly BranchCandidate[], policy: ConvergencePolicy): {
310
+ nodeId: string;
311
+ leafIndices: number[];
312
+ }[];
313
+ /**
314
+ * Seam (`removalFinality`): every node of `T` with at least two child edges, ordered by (depth, node id) — the
315
+ * structural phase 1 of ADR-017 (architecture.md SC-R3). `[]` exactly when `T` cannot be built (nothing eligible
316
+ * included, or two present `removed` facts of one edge differ) or no node branches; a node with one child edge is
317
+ * never a rule node, and a tip at a node competes there as a zero-length entry. Shells call {@link phaseOneNodesOf}.
318
+ */
319
+ export declare function branchingNodesOf(currentTipEpoch: number, candidates: readonly BranchCandidate[], policy: ConvergencePolicy): {
320
+ nodeId: string;
321
+ }[];
322
+ /**
323
+ * Seam (`removalFinality`): the only phase-1 entry point for shells (architecture.md SC-R3): with the seam effective
324
+ * the structural {@link branchingNodesOf}, else ADR-016's {@link equivocationNodesOf}. Empty means "call the
325
+ * 3-argument {@link selectCanonicalBranch}" in both cases.
326
+ */
327
+ export declare function phaseOneNodesOf(effective: boolean, currentTipEpoch: number, candidates: readonly BranchCandidate[], policy: ConvergencePolicy): {
328
+ nodeId: string;
329
+ }[];
330
+ /**
331
+ * Seam (`removalFinality`) test seam: one node's local outcome in flagged credited selection — `m` (`maxOf`), `c`
332
+ * (ADR-016's choice) and `r` (the rule's choice at a rule node, else `c`).
333
+ * @internal
334
+ */
335
+ export interface RemovalFinalityNodeTrace {
336
+ readonly nodeId: string;
337
+ readonly ruleNode: boolean;
338
+ readonly m: BranchCandidate;
339
+ readonly c: BranchCandidate;
340
+ readonly r: BranchCandidate;
341
+ }
342
+ /**
343
+ * Seam (`removalFinality`) test seam: runs `run` and hands `sink` the per-node outcome of every flagged
344
+ * {@link selectCanonicalBranchCredited} call made inside it. Synchronous and scoped; no production caller sets a
345
+ * sink, and no result ever depends on one.
346
+ * @internal
347
+ */
348
+ export declare function traceRemovalFinality<T>(sink: (trace: RemovalFinalityNodeTrace) => void, run: () => T): T;
349
+ /**
350
+ * Seam (`removalFinality`) test seam: what the rule sees at `nodeId` of the flagged candidate tree under its visible
351
+ * regime — the rule-node verdict, the guard, `⋃Rm`, `Rm(N, e)`, the preferred edges and, per eligible candidate
352
+ * through the node, `creditAt`, the number of steps the R-3 walk credits and `finality_N`. `undefined` when the tree
353
+ * cannot be built, the node is not in it, or R-6 (b) / (c) fails there.
354
+ * @internal
355
+ */
356
+ export declare function removalFinalityProbeOf(currentTipEpoch: number, candidates: readonly BranchCandidate[], policy: ConvergencePolicy, credit: EquivocationCreditInput, nodeId: string): {
357
+ readonly ruleNode: boolean;
358
+ readonly guard: boolean;
359
+ readonly union: readonly number[];
360
+ readonly rm: ReadonlyMap<string, readonly number[]>;
361
+ readonly preferred: readonly string[];
362
+ readonly entries: readonly {
363
+ readonly candidate: BranchCandidate;
364
+ readonly credit: number;
365
+ readonly walkCredited: number;
366
+ readonly finality: number;
367
+ }[];
368
+ } | undefined;
369
+ /**
370
+ * Seam (`equivocationCredit`), phase 2: canonical selection with other-leaf
371
+ * credited depth at equivocation nodes (ADR-016 D1–D3, architecture.md SC-3).
372
+ *
373
+ * Global fallback (rule 3a) — the unmodified 3-argument
374
+ * {@link selectCanonicalBranch} over `candidates` (`legacyMax`), with an empty
375
+ * report — whenever {@link equivocationNodesOf} is empty (its doc lists every
376
+ * structural trigger), and likewise when no candidate node is resolvable.
377
+ * Per-node fallback (rule 3b): a candidate node that `credit` lacks, with no
378
+ * anchored child edge after the key clause (`Eq(N)` empty), or where an index
379
+ * of `Eq(N)` lacks membership or account, is resolved by today's ordering and
380
+ * reports nothing; resolvable nodes elsewhere keep credit. Otherwise `T` is
381
+ * resolved bottom-up: a node's representative is `legacyMax` over its
382
+ * children's representatives (and any candidate whose tip is the node) in input
383
+ * order; at a resolvable equivocation node only the representatives with
384
+ * maximal credit compete, so a credit tie keeps today's ordering. Credit is
385
+ * head-anchored (rule 2): a leaf heading a child subtree of the node while
386
+ * also committing in another earns nothing inside the subtree it heads, but
387
+ * its commits deep in a subtree headed by another leaf earn as any other's. Only direct equivocations (`EqDirect`, two child
388
+ * edges of one node by one leaf) are reported; cross-subtree-only evidence
389
+ * feeds credit but is never reported (AC-FLAG-3, AR-8). `decidedByCredit`:
390
+ * credit changed the local outcome at a resolvable node on the winner's path.
391
+ * Pure, total and deterministic: `winner` is `undefined` exactly when no
392
+ * candidate is eligible.
393
+ *
394
+ * Seam (`removalFinality`, ADR-017): with `credit.removalFinality`, `T` merges
395
+ * the edges' `removed` facts, and at every rule node (R-6: two or more child
396
+ * edges, a context, an ADR-016-resolvable anchoring, a counting non-inert
397
+ * removal, and the node-local guard) the node's ADR-016 choice is replaced by
398
+ * the rule's ({@link CanonicalSelection.decidedByRemoval} records a change);
399
+ * the 3a fallback then needs no resolvable equivocation node and no rule node.
400
+ * The report and `decidedByCredit` are ADR-016's. Without the flag nothing of
401
+ * this runs and the result has no `decidedByRemoval` key.
402
+ */
403
+ export declare function selectCanonicalBranchCredited(currentTipEpoch: number, candidates: readonly BranchCandidate[], policy: ConvergencePolicy, credit: EquivocationCreditInput): CanonicalSelection;
404
+ /**
405
+ * Seam (`branchAwareFence`): a commit that authenticates at a state the device
406
+ * holds but fails with the lost-path-secrets error, as the pure core sees it.
407
+ * The device knows the parent node `N`, the head edge `e_o` (digest,
408
+ * authenticated sender and committer) and a bound on what the hidden subtree
409
+ * below `e_o` could carry; everything below `e_o` is unreachable.
410
+ */
411
+ export interface OpaqueCandidate {
412
+ /** The head edge `N → opaque:<digestHex>`: parent `N`, commit digest, authenticated sender. */
413
+ headEdge: CandidatePathEdge;
414
+ /**
415
+ * The commit edges from the selection call's shared root to `N`, root→`N`
416
+ * (empty when `N` is the root). Must start at the root the processable
417
+ * candidates' paths start at, or selection falls back to today's ordering.
418
+ */
419
+ pathToParent: readonly CandidatePathEdge[];
420
+ /** The MLS epoch of `N`. */
421
+ parentEpoch: number;
422
+ /** `U`, the depth bound: the group's undecryptable count (a safe integer `>= 0`). */
423
+ hiddenDepthBound: number;
424
+ /**
425
+ * `H`, the hidden-credit bound: how many of the hidden edges can earn credit
426
+ * (a safe integer `>= 0`, at most `hiddenDepthBound`; `U` under the
427
+ * conservative policy). Each hidden edge earns at most 1.
428
+ */
429
+ hiddenCreditBound: number;
430
+ /**
431
+ * The authenticated committer (account identity) of `headEdge`, as the
432
+ * processable candidates' {@link BranchCandidate.tipCommitter}. Read only at
433
+ * `U = 0`, where `e_o` itself is the tip; absent it is the empty (minimal) key.
434
+ */
435
+ headCommitter?: Uint8Array;
436
+ }
437
+ /**
438
+ * Seam (`branchAwareFence`), OQ-1: the hidden-credit policy for a head edge by
439
+ * the device's own leaf that is anchored at `N`. `conservative`: `H` is the
440
+ * candidate's `hiddenCreditBound`. `anchored-zero`: `H = 0` at every node
441
+ * whose toward edge is anchored with the own leaf as sender (always `N`: D2
442
+ * rule 2 discounts the own leaf's edges inside that subtree; other leaves are
443
+ * assumed not to have built on the clone's branch). At a node above `N` whose
444
+ * toward edge is not so anchored, the clone's own-leaf burst still earns, so
445
+ * `H` stays. Every other head keeps its `hiddenCreditBound` everywhere.
446
+ */
447
+ export type HiddenCreditPolicy = "conservative" | "anchored-zero";
448
+ /** Seam (`branchAwareFence`): options of {@link opaqueCouldWin}. */
449
+ export interface OpaqueScoringOptions {
450
+ /** Default `conservative`; any other value fails closed (`true`). */
451
+ hiddenCreditPolicy?: HiddenCreditPolicy;
452
+ /** The device's own leaf `ℓ`; read only by `anchored-zero`. */
453
+ ownLeafIndex?: number;
454
+ /**
455
+ * Seam (`removalFinality`, architecture.md SC-R7): the site holds another authenticated opaque head (decided or
456
+ * held) by the same sender at the same parent — a direct equivocation the device sees. When `true` the core scores
457
+ * the head as anchored at `N` in every regime: its visible edge earns 0, its removal is inert, and hidden credit is
458
+ * `Hpol(N)` for an anchored head (0 under `anchored-zero` for the own leaf, `min(H, ·)` under `conservative`).
459
+ * Anchoring goes through `resolveNode`'s forced path, which requires the sender to hold an account at `N`: a sender
460
+ * without one there is not anchored. That is a fail-closed fence-side approximation, costing liveness only. Read
461
+ * only when `credit.removalFinality === true`.
462
+ */
463
+ headEquivocated?: boolean;
464
+ }
465
+ /**
466
+ * Seam (`branchAwareFence`): the best case `o*` of an opaque candidate, a
467
+ * single candidate whose path ends at the head edge. Depth bound: its tip
468
+ * epoch is `parentEpoch + 1 + U`. Tiebreak: at `U >= 1` the hidden tip's
469
+ * committer and digest are unknown, so both are the empty (minimal) byte
470
+ * string and lower wins; at `U = 0` the tip is the head edge and its exact
471
+ * digest and committer are used. No witnesses (ADR-015). The credit bound is
472
+ * not a field of the candidate: {@link opaqueCouldWin} adds it in the credit
473
+ * contest. Its `forkEpoch` is `parentEpoch - pathToParent.length`, the epoch
474
+ * of the shared root.
475
+ */
476
+ export declare function opaqueBestCase(opaque: OpaqueCandidate): BranchCandidate;
477
+ /**
478
+ * Seam (`branchAwareFence`): whether the best case `o*` of `opaque` would be
479
+ * the selected branch among `processable` plus `o*` alone — the device fences
480
+ * on the opaque candidate iff this is `true` (or no processable candidate is
481
+ * eligible, which the caller decides). Pure, total and deterministic; reads no
482
+ * witnesses (the processable candidates' `appWitnesses` are ignored: ADR-015)
483
+ * and never anything hidden.
484
+ *
485
+ * `o*` is appended last, so an exact tie goes to the opaque side (LD-4).
486
+ * Without `credit`, or when the candidate tree cannot be built, the contest is
487
+ * today's ordering over the same field. With it, selection is the cascade of
488
+ * {@link selectCanonicalBranchCredited} with three bounds on `o*`:
489
+ *
490
+ * - depth: {@link opaqueBestCase}; credit: at every resolved node on `o*`'s
491
+ * path its visible credit plus `min(H, U)` (hidden edges earn at most 1
492
+ * each). Under `anchored-zero` an own-leaf head anchored at `N` has `H = 0`
493
+ * at `N` and at every node whose toward edge is anchored with the own leaf.
494
+ * - anchoring: hidden edges are evidence (ADR-016 D1), so when `U >= 1` a hidden
495
+ * edge by the sender of a visible child edge `h` at a node on the path
496
+ * anchors `h`: `h`'s sender then earns nothing inside `sub(h)`, and the node
497
+ * resolves by credit. The device cannot see the hidden senders, so at each
498
+ * node on the path (`N` included) the best case takes the better of the
499
+ * node's visible regime and the regime in which every child edge with a
500
+ * member sender, except the one on `o*`'s path, is anchored. The better of
501
+ * the two is needed: anchoring everything also switches a node that nothing
502
+ * anchors from today's ordering (where `o*`'s depth wins) to the credit
503
+ * contest (where it can lose), so a single forced regime is not conservative.
504
+ * The regimes of different nodes are independent, which relaxes "at most `U`
505
+ * distinct senders" (it may be tightened, never loosened). A third regime
506
+ * applies where a child edge is headed by a member without an account (a
507
+ * hidden edge by it anchors that head, and a node anchoring a sender without
508
+ * an account resolves by today's ordering): today's ordering at that node.
509
+ * The override acts in this function only; selection over `processable` is
510
+ * unchanged.
511
+ * - Soundness holds relative to the contexts supplied: a node of the path
512
+ * whose context `credit` lacks resolves by today's ordering, as in selection.
513
+ * The caller supplies a context for the parent of every `pathToParent` edge
514
+ * and for `N`, a sender key for every visible edge's digest (the head edge
515
+ * included), and consistent bounds (`H <= U`).
516
+ *
517
+ * Fails closed (`true`, the fence of today) on a bound that is not a
518
+ * non-negative safe integer and on an unknown policy value. `false` when `o*`
519
+ * is not eligible (the horizon is the one every member applies).
520
+ *
521
+ * Seam (`removalFinality`, ADR-017's fourth site, architecture.md SC-R7): with
522
+ * `credit.removalFinality` the head's merged `removed` fact is read (absent:
523
+ * `true`), every node is decided under the guard regimes — Gr (the rule,
524
+ * through the same rule function as selection, with `o*` at `u_r` hidden
525
+ * edges) and Ga (today's cascade) — combined with the anchoring regimes above,
526
+ * and `options.headEquivocated` anchors the head at `N` in every regime. Hidden
527
+ * edges carry no removal facts.
528
+ */
529
+ export declare function opaqueCouldWin(currentTipEpoch: number, processable: readonly BranchCandidate[], opaque: OpaqueCandidate, policy: ConvergencePolicy, credit?: EquivocationCreditInput, options?: OpaqueScoringOptions): boolean;
530
+ /**
531
+ * Seam (`branchAwareFence`): the outcome of `selectCanonicalBranchWithOpaque`.
532
+ * @internal
533
+ */
534
+ export interface OpaqueSelection {
535
+ /** Selection over the processable candidates, exactly as without opaque input. */
536
+ selection: CanonicalSelection;
537
+ /** `couldWin[i]` is {@link opaqueCouldWin} of `opaque[i]` against the processable candidates alone. */
538
+ couldWin: readonly boolean[];
539
+ }
540
+ /**
541
+ * Seam (`branchAwareFence`): selection over the processable candidates
542
+ * (credited when `credit` is present, today's otherwise), then each opaque
543
+ * candidate decided separately against them with {@link opaqueCouldWin}. With
544
+ * no opaque candidate this is exactly the selection without the entry point.
545
+ * Test seam: the engine's production sites decide through the shared per-digest
546
+ * decision (`decideOpaqueDrafts`); this entry point is exported for the
547
+ * property tests that pin the core against it.
548
+ * @internal
549
+ */
550
+ export declare function selectCanonicalBranchWithOpaque(currentTipEpoch: number, processable: readonly BranchCandidate[], opaque: readonly OpaqueCandidate[], policy: ConvergencePolicy, credit?: EquivocationCreditInput, options?: OpaqueScoringOptions): OpaqueSelection;
551
+ /**
552
+ * The content-derived ordering key for same-epoch races
553
+ * (`convergence.md` "Same-epoch races"). `commitDigest` is `SHA-256` over the
554
+ * commit's MLS message bytes; for equal `sourceEpoch`, the lower digest wins.
555
+ */
556
+ export interface CommitOrderingKey {
557
+ sourceEpoch: number;
558
+ commitDigest: Uint8Array;
559
+ }
560
+ /** Computes the `commit_digest`: SHA-256 (32 bytes) of the commit MLS bytes. */
561
+ export declare function commitDigest(mlsBytes: Uint8Array): Uint8Array;
562
+ /**
563
+ * Compares two commit ordering keys: lower sourceEpoch first, then lower
564
+ * commitDigest. Negative when `a` orders before `b`. This is for branch choice
565
+ * only; the stored message id used to mark a losing commit stays separate.
566
+ */
567
+ export declare function compareCommitOrderingKeys(a: CommitOrderingKey, b: CommitOrderingKey): number;