@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,571 @@
1
+ import { CiphersuiteImpl, ClientState, type MlsMessage } from "ts-mls";
2
+ import type { ClientConfig } from "ts-mls";
3
+ import { decideCommitAuthorization } from "../core/commit-authorization.js";
4
+ import { type CommitIntegrityViolation } from "../core/components/integrity.js";
5
+ import { type ConvergenceStatus } from "../core/convergence-status.js";
6
+ import { type HiddenCreditPolicy } from "../core/convergence.js";
7
+ import { type GroupLifecycleState } from "../core/group-lifecycle.js";
8
+ import { type AuditContextOptions, type AuditSink } from "../audit/index.js";
9
+ import type { GenericKeyValueStore } from "../utils/key-value.js";
10
+ import { createAdminCommitPolicyCallback } from "./admin-policy.js";
11
+ import { type EdgeFacts } from "./fork-recovery.js";
12
+ import { GroupHistoryTree } from "./history-tree.js";
13
+ import { type IngestionPoolOptions } from "./ingestion-pool.js";
14
+ import { type StateNotification } from "./state-notifications.js";
15
+ import { RetainedHistoryStore } from "./retained-store.js";
16
+ import type { ConvergencePassState, DisbandCandidateEvidence, DispositionedIngestResult, GroupPeeler, PendingState, SendIntent, SendResult } from "./types.js";
17
+ import { type DisbandRequest } from "./disband-request.js";
18
+ /**
19
+ * Thrown by {@link MarmotGroupEngine.send} (`case "commit"`) when a removal
20
+ * commit's auto-coupled admin-policy update would leave the resulting epoch
21
+ * with no surviving admin account (D-07). Thrown BEFORE `createCommit` — no
22
+ * proposal is staged and the lifecycle stays `Stable`. The message names only
23
+ * the count of admins that would be orphaned, never pubkeys
24
+ * (diagnostics-privacy rule, `foundation/errors.md`).
25
+ *
26
+ * @see refs/mdk/crates/cgka-engine/src/message_processor/send.rs `do_send_remove_members` `AdminDepletion` guard
27
+ */
28
+ export declare class AdminDepletionError extends Error {
29
+ constructor(orphanedAdminCount: number);
30
+ }
31
+ /**
32
+ * Thrown when a locally-staged commit violates a Marmot component-integrity
33
+ * rule. The structured violation is retained so callers can branch on its
34
+ * stable reason without matching the human-readable diagnostic message.
35
+ */
36
+ export declare class CommitLegalityError extends Error {
37
+ readonly violation: CommitIntegrityViolation;
38
+ constructor(violation: CommitIntegrityViolation);
39
+ }
40
+ /** Typed ordinary-outbound refusal while irreversible terminal intent is pending. */
41
+ export declare class DisbandingError extends Error {
42
+ readonly reason: "disbanding";
43
+ constructor();
44
+ }
45
+ /** An opaque handle returned by {@link ConvergenceScheduler.setTimer}. */
46
+ export type TimerHandle = unknown;
47
+ /**
48
+ * Injectable timer used to fire the convergence settle-check once the quiescence
49
+ * window elapses (B5). Defaults to `setTimeout`/`clearTimeout`; tests pass a
50
+ * controllable fake so the settle moment is deterministic.
51
+ */
52
+ export interface ConvergenceScheduler {
53
+ setTimer(ms: number, cb: () => void): TimerHandle;
54
+ clearTimer(handle: TimerHandle): void;
55
+ }
56
+ export type MarmotGroupEngineOptions<TEnvelope> = {
57
+ state: ClientState;
58
+ ciphersuite: CiphersuiteImpl;
59
+ peeler: GroupPeeler<TEnvelope>;
60
+ onStateChanged?: (state: ClientState) => void;
61
+ /**
62
+ * The bounded convergence window (canonical states + applied commits within
63
+ * the rollback horizon), derived from the history tree on load. When omitted
64
+ * it is seeded with only the current tip (no past-epoch rewind until new
65
+ * commits accrue). Never persisted separately — the tree is the source.
66
+ */
67
+ retained?: RetainedHistoryStore;
68
+ /**
69
+ * A pre-populated full-fork history tree, rehydrated from persistence. When
70
+ * omitted the tree is seeded with the current tip as its root and grows as
71
+ * commits arrive.
72
+ */
73
+ historyTree?: GroupHistoryTree;
74
+ /**
75
+ * The signed convergence policy governing branch selection and the rollback
76
+ * horizon (`maxRewindCommits`). Defaults to {@link DEFAULT_CONVERGENCE_POLICY}.
77
+ * Set `maxRewindCommits` to `Infinity` to never expire old forks (the full
78
+ * history tree retains everything regardless). Validated on construction.
79
+ */
80
+ convergencePolicy?: import("../core/convergence.js").CompatibleConvergencePolicy;
81
+ /**
82
+ * Tuning for the persistent ingestion pool — undecryptable events held and
83
+ * retried as the history tree grows, instead of being dropped. Defaults to a
84
+ * size- and epoch-age-bounded pool.
85
+ */
86
+ ingestionPool?: IngestionPoolOptions;
87
+ /**
88
+ * Injectable monotonic clock (ms) for bounded convergence passes. Defaults
89
+ * to `performance.now()`; tests pass a fake clock for determinism.
90
+ */
91
+ now?: () => number;
92
+ /**
93
+ * Quiescence window (ms) before a convergence pass may be treated as settled
94
+ * (`convergence.md` `settlementQuiescenceMs`). Defaults to the profile-1 value.
95
+ */
96
+ settlementQuiescenceMs?: number;
97
+ /** Injectable timer for the settle-check; defaults to `setTimeout` (B5). */
98
+ scheduler?: ConvergenceScheduler;
99
+ /**
100
+ * Called once the quiescence window elapses after convergence-relevant input,
101
+ * so the owner can re-check {@link convergenceStatus} and release any queued
102
+ * outbound work (B5). The engine itself holds no outbound queue.
103
+ */
104
+ onSettleCheck?: () => void | Promise<void>;
105
+ /** Optional forensic audit sink. Omitted by default; audit logging is app opt-in. */
106
+ audit?: AuditSink;
107
+ /** Required when `audit` is set; contains stable engine/account/session metadata. */
108
+ auditContext?: AuditContextOptions;
109
+ /** Durable lifecycle records shared with terminal settlement. */
110
+ lifecycleStore?: GenericKeyValueStore<Uint8Array>;
111
+ /**
112
+ * Overrides the commit-authorization decision (who may commit what).
113
+ * Defaults to {@link decideCommitAuthorization}. Seam for callers with a
114
+ * different admin/authorization model (AC-VENDOR-7).
115
+ */
116
+ authorizeCommit?: typeof decideCommitAuthorization;
117
+ /**
118
+ * Overrides the incoming-message admin-verification callback constructor.
119
+ * Defaults to {@link createAdminCommitPolicyCallback}. With both this and
120
+ * `authorizeCommit` omitted, engine behaviour on the vendored admin-policy
121
+ * tests is unchanged (AC-VENDOR-7).
122
+ */
123
+ adminPolicyCallback?: typeof createAdminCommitPolicyCallback;
124
+ /**
125
+ * ts-mls `ClientConfig` threaded into every `processMessage` call this
126
+ * engine makes (ingest, fork recovery, witness collection). MUST match
127
+ * the config used to produce inbound commits — a mismatch is a silent
128
+ * fork hazard (AC-VENDOR-6). Defaults to ts-mls's own default when omitted.
129
+ */
130
+ clientConfig?: ClientConfig;
131
+ /**
132
+ * Overrides the "leaver is an active admin" predicate the `self_remove`
133
+ * auto-commit election runs per leaver ({@link decideAutoCommit}'s
134
+ * `anyLeaverIsActiveAdmin`). Defaults to {@link isAdminAccountLeaver} —
135
+ * the leaver's credential names an admin account. A caller with a
136
+ * different admin model (a multi-leaf admin account whose other leaves
137
+ * stay, epic-marmot-client AC-ADMIN-9) supplies its own; a throw counts as
138
+ * `true` (fail-closed).
139
+ */
140
+ isActiveAdminLeaver?: ActiveAdminLeaverPredicate;
141
+ /**
142
+ * Seam (epic-marmot-client S20): same-epoch convergence for a commit that
143
+ * removes the LOCAL leaf. ts-mls's `removedFromGroup` tombstone keeps its
144
+ * parent's epoch and confirmation tag, so upstream such a commit is never a
145
+ * fork-recovery candidate, never a history-tree node, and once applied D-13
146
+ * skips every later input: a member that applied the losing branch of a race
147
+ * whose branches disagree on removing it never converges. With this on, a
148
+ * removing commit is a branch candidate of its own (scored as every member
149
+ * scores it: one epoch past its parent, its digest, its committer) in pool
150
+ * replay and in tree-fed re-convergence, and while a removal is held
151
+ * ({@link MarmotGroupEngine.removal}) later input is fork material for it,
152
+ * not `self-evicted`, until the owner calls
153
+ * {@link MarmotGroupEngine.settleRemoval}. Off by default: upstream
154
+ * behaviour.
155
+ */
156
+ removalConvergence?: boolean;
157
+ /**
158
+ * Seam (epic-marmot-rewind-takeover-stale-leaf-snapshot, ADR-016):
159
+ * other-leaf credited depth at equivocation nodes. A node where one leaf
160
+ * authored two or more child commits is cryptographic evidence of a
161
+ * duplicated leaf (a restored stale snapshot); there, only the depth other
162
+ * leaves that were members at the node built on each side counts, and a
163
+ * credit tie keeps today's ordering. Every equivocation found is reported
164
+ * as a `leafEquivocation` result. Applied at all three selection sites (pool
165
+ * replay, `#reconvergeFromTree`, `#reconvergeWithRemovals`). Off by
166
+ * default: no candidate path, the 3-argument selection, no report —
167
+ * upstream behaviour.
168
+ */
169
+ equivocationCredit?: boolean;
170
+ /**
171
+ * Seam (epic-marmot-branch-aware-own-leaf-fence, ADR-016 D6): a commit that
172
+ * authenticates at a state this device holds but fails with the
173
+ * lost-path-secrets error (`isLostPathSecretsError`) is an opaque candidate —
174
+ * a head edge whose subtree the device cannot see — rather than a verdict.
175
+ * Pool-replay recovery selects over the processable branches first and fences
176
+ * only a digest whose best case under the undecryptable count could win (or
177
+ * when no processable branch is eligible); any other is yielded `skipped`.
178
+ * The opaque head joins the candidate tree, so the device reports a direct
179
+ * equivocation against its own commit, on a `skip` outcome too. The other
180
+ * sites hold the candidate instead of fencing it where it fails, and decide
181
+ * it by the same rule: the direct apply (the batch goes on; a commit whose
182
+ * parent a sibling advanced past is fork material for pool replay, one whose
183
+ * parent is still the tip fences), the removal parent and the tree sweep.
184
+ * Every candidate judged `skipped`, at any site, is held with its original
185
+ * envelope ({@link MarmotGroupEngine.opaque}) and decided again on every
186
+ * convergence pass; it leaves the held set only by a fence, the rollback
187
+ * horizon or a pruned parent. Takes effect only together with
188
+ * `equivocationCredit`. Off by default: every fenced commit fences before
189
+ * any selection, byte for byte as before.
190
+ *
191
+ * A `skipped` is provisional and only as durable as the owner makes the
192
+ * engine's `opaque` record: an owner MUST persist it with the state (in the
193
+ * batch's transaction) and hand it back through {@link opaque} when it
194
+ * rebuilds the engine, or a skip that a restart interrupts is never revised.
195
+ * The undecryptable set `U` the decision scores with lives in the same
196
+ * record; without it a rebuilt engine undercounts hidden edges and can skip
197
+ * a commit that should fence. The hidden-credit policy of the decision is
198
+ * {@link hiddenCreditPolicy}.
199
+ */
200
+ branchAwareFence?: boolean;
201
+ /**
202
+ * Seam (`branchAwareFence`), OQ-1 (spec Design Decision 7, ADR-016 D6): the
203
+ * hidden-credit policy of the fence decision, exactly one of two values.
204
+ * `"conservative"` (default): the hidden subtree of an opaque candidate is
205
+ * assumed to carry up to `U` credit; the device never stays on a branch the
206
+ * group may have abandoned, but an attacker who inflates `U` keeps the
207
+ * device fenced. `"anchored-zero"`: an opaque head by the device's own leaf
208
+ * that is anchored at its parent node earns no hidden credit there; the
209
+ * device stays on canonical whenever canonical carries other-leaf credit, at
210
+ * the price of staying behind if other members built on the clone's branch
211
+ * (it is told through its own `leaf-equivocation` record). Read only while
212
+ * the opaque seam is on (`branchAwareFence` and `equivocationCredit`):
213
+ * ignored otherwise, byte for byte as before; an unknown value is rejected
214
+ * with a `TypeError` at construction while it is on.
215
+ */
216
+ hiddenCreditPolicy?: HiddenCreditPolicy;
217
+ /**
218
+ * Seam (epic-marmot-removal-finality, ADR-017): removal finality at every
219
+ * selection site. A removal commit is decisive at the node where it races a
220
+ * branch that keeps the removed leaf: the removed leaf's later edges below
221
+ * that node earn nothing there, and on a tie a non-inert removal head is
222
+ * preferred, as long as every candidate through the node is within
223
+ * `maxRewindCommits` of it (beyond that ADR-016 selection applies). Applied at
224
+ * all four selection sites (pool replay, `#reconvergeFromTree`,
225
+ * `#reconvergeWithRemovals`, and — with `branchAwareFence` — the opaque
226
+ * fence), from removal facts the engine derives per edge (ratchet trees,
227
+ * including a removed device's tombstone) and per opaque head (its captured
228
+ * proposals). Takes effect only together with `equivocationCredit`. Off by
229
+ * default: ADR-016 selection, byte for byte. Nothing is persisted for it.
230
+ */
231
+ removalFinality?: boolean;
232
+ /**
233
+ * Seam (`branchAwareFence`, spec Design Decision 6/3a): the held opaque
234
+ * candidates and the undecryptable set `U` a previous engine of this group
235
+ * exposed ({@link MarmotGroupEngine.opaque}), so a rebuilt engine decides
236
+ * identically to one that was not rebuilt. Validated against the current
237
+ * state: ignored unless `branchAwareFence` and `equivocationCredit` are both
238
+ * on, and a malformed record (a field of the wrong type, more than
239
+ * {@link MAX_HELD_OPAQUE_CANDIDATES} candidates) is rejected with a
240
+ * `TypeError` rather than half-applied. A candidate whose parent node the
241
+ * history tree no longer holds is not dropped here: the next convergence
242
+ * pass finds it unavailable and fences it.
243
+ */
244
+ opaque?: HeldOpaqueRecord<TEnvelope>;
245
+ /**
246
+ * Seam (`branchAwareFence`): the cap on the undecryptable set `U` the engine
247
+ * tracks, default {@link MAX_UNDECRYPTABLE_IDS}. The id that would exceed it
248
+ * saturates `U` instead (see {@link HeldOpaqueRecord.undecryptableSaturated}).
249
+ * A non-negative safe integer; anything else is rejected with a `TypeError`
250
+ * at construction while the seam is on, ignored otherwise.
251
+ */
252
+ maxUndecryptableIds?: number;
253
+ /**
254
+ * Seam (S20): the removal a previous engine over this same
255
+ * `removedFromGroup` state held ({@link MarmotGroupEngine.removal}), so a
256
+ * rebuilt engine keeps treating it as revisable. Ignored without
257
+ * `removalConvergence`, or when `state` is not that removal's tombstone.
258
+ */
259
+ removal?: RemovalRecord;
260
+ };
261
+ /**
262
+ * Seam (epic-marmot-client S20): a removal of the local leaf the engine still
263
+ * treats as revisable — the state the removing commit(s) were applied to
264
+ * (staged proposals included) and every commit known to remove the local leaf
265
+ * from it. The engine's state is that removal's `removedFromGroup` tombstone.
266
+ * `commits[0]` is the commit that tombstone came from (a competing removal is
267
+ * appended; a re-convergence onto another removing commit puts it first) —
268
+ * what {@link MarmotGroupEngine.removalActor} names the committer of.
269
+ */
270
+ export interface RemovalRecord {
271
+ readonly parentState: ClientState;
272
+ readonly commits: readonly MlsMessage[];
273
+ }
274
+ /**
275
+ * Seam (`branchAwareFence`): the most opaque candidates the engine holds at a
276
+ * time. An attacker can mint many heads from one cloned leaf; a candidate
277
+ * beyond the cap is fenced conservatively (spec Design Decision 6).
278
+ */
279
+ export declare const MAX_HELD_OPAQUE_CANDIDATES = 16;
280
+ /**
281
+ * Seam (`branchAwareFence`): the most event ids the engine keeps in `U`, the
282
+ * group's undecryptable set (spec Design Decision 3a). `U` is permanent and
283
+ * every id is persisted (64 hex characters, rewritten with the record on each
284
+ * change), and ids of history no state will ever decrypt (before the device
285
+ * joined, before a restored snapshot's window, junk) never leave it. Past the
286
+ * cap the engine stops tracking ids and saturates: `U` is then treated as
287
+ * unbounded — every opaque candidate fences, today's behaviour — and the
288
+ * record carries one flag instead of the ids ({@link HeldOpaqueRecord}). The
289
+ * cap only ever turns a skip into a fence; it can never under-count.
290
+ */
291
+ export declare const MAX_UNDECRYPTABLE_IDS = 1024;
292
+ /**
293
+ * Seam (`branchAwareFence`): a held opaque candidate as the engine's persisted
294
+ * record keeps it (spec Design Decision 6) — a commit that authenticated at
295
+ * tree node `parentTag` (epoch `epoch`) but failed with the lost-path-secrets
296
+ * error, with the original envelope, since the tree sweep removes a swept
297
+ * entry from the pool and a reload loses everything in memory. Everything a
298
+ * later pass or a reload needs to decide it again and, if it now could win, to
299
+ * yield `unreadable` with this envelope: `sender` is the authenticated
300
+ * committer's leaf index at the parent (absent when unknown: it then fences),
301
+ * `errorMessage` the lost-path-secrets error's message
302
+ * ({@link reconstructLostPathSecretsError} rebuilds the error from it).
303
+ */
304
+ export interface HeldOpaqueCandidate<TEnvelope> {
305
+ /** Hex commit digest of the commit. */
306
+ readonly digest: string;
307
+ /** Hex confirmation tag of the tree node `N` it failed at. */
308
+ readonly parentTag: string;
309
+ /** The MLS epoch of `N` (what the rollback horizon and the retained-window pin are measured at). */
310
+ readonly epoch: number;
311
+ readonly sender?: number;
312
+ /** The lost-path-secrets error's message. */
313
+ readonly errorMessage: string;
314
+ /** The original transport event of the commit. */
315
+ readonly event: TEnvelope;
316
+ /**
317
+ * `"fenced"` once the engine decided the candidate fences and has not yet
318
+ * seen its `unreadable` delivered: an entry point may re-deliver exactly
319
+ * these (a fence is group state), whereas a fresh could-win decision is
320
+ * taken only inside a full pass, after that pass's material was processed.
321
+ */
322
+ readonly decided?: "fenced";
323
+ }
324
+ /**
325
+ * Seam (`branchAwareFence`): thrown by the constructor for a malformed
326
+ * `opaque` record (a `TypeError`, so existing handlers keep working). An owner
327
+ * that persists the record matches this class, and only this class, to tell a
328
+ * corrupt record from any other failure of construction.
329
+ */
330
+ export declare class OpaqueRecordInvalid extends TypeError {
331
+ constructor(message: string);
332
+ }
333
+ /**
334
+ * Seam (`branchAwareFence`): the engine's persisted opaque state — the held
335
+ * candidates (at most {@link MAX_HELD_OPAQUE_CANDIDATES}, sorted by digest) and
336
+ * `U`, the group's undecryptable set of spec Design Decision 3a: the event ids
337
+ * of every group envelope the engine was handed that no state it holds
338
+ * decrypts, sorted. An id leaves it only when its envelope decrypts; eviction,
339
+ * capacity refusal, retry exhaustion and reload never remove one. Persisted
340
+ * together so a reload cannot undercount `U`. See {@link MarmotGroupEngine.opaque}.
341
+ */
342
+ export interface HeldOpaqueRecord<TEnvelope> {
343
+ readonly candidates: readonly HeldOpaqueCandidate<TEnvelope>[];
344
+ readonly undecryptableIds: readonly string[];
345
+ /**
346
+ * `U` outgrew the engine's cap ({@link MAX_UNDECRYPTABLE_IDS}) and was
347
+ * saturated: its size is unknown and read as unbounded, `undecryptableIds`
348
+ * is empty, and every opaque candidate fences (today's behaviour). Absent
349
+ * until then. Sticky: a decrypt cannot shrink a count that is no longer
350
+ * tracked, so a saturated group stays fail-closed for the engine's life.
351
+ */
352
+ readonly undecryptableSaturated?: true;
353
+ }
354
+ /**
355
+ * One leaver of a `self_remove` auto-commit batch, as the "leaver is an
356
+ * active admin" predicate sees it: the current tree and admin set, the
357
+ * leaver's leaf, and every leaf the batch removes (so a predicate can count
358
+ * what an account keeps after the whole batch).
359
+ */
360
+ export type ActiveAdminLeaverPredicate = (args: {
361
+ ratchetTree: ClientState["ratchetTree"];
362
+ adminPubkeys: readonly string[];
363
+ leaverLeafIndex: number;
364
+ leaverLeafIndices: readonly number[];
365
+ }) => boolean;
366
+ /** The engine's default {@link ActiveAdminLeaverPredicate}: the leaver's credential names an admin account. */
367
+ export declare const isAdminAccountLeaver: ActiveAdminLeaverPredicate;
368
+ /**
369
+ * Transport-agnostic MLS group state machine: ingest, send intents, fork
370
+ * recovery, and publish-before-apply lifecycle for local commits.
371
+ *
372
+ * This class is a coordinator. The heavy concerns live in focused modules it
373
+ * composes: retained history ({@link RetainedHistoryStore}), convergence fork
374
+ * recovery ({@link ForkRecovery}), and the inbound pipeline ({@link
375
+ * ingestEnvelopes}). The engine owns only the live state and lifecycle, the
376
+ * send path, and the wiring between those modules — mirroring darkmatter's
377
+ * `cgka-engine` split across `message_processor/{ingest,send,store}`,
378
+ * `fork_recovery`, and `epoch_manager`.
379
+ */
380
+ export declare class MarmotGroupEngine<TEnvelope> {
381
+ #private;
382
+ readonly ciphersuite: CiphersuiteImpl;
383
+ readonly peeler: GroupPeeler<TEnvelope>;
384
+ constructor(options: MarmotGroupEngineOptions<TEnvelope>);
385
+ /** Number of undecryptable events currently held in the ingestion pool. */
386
+ get pendingCount(): number;
387
+ /**
388
+ * The undecryptable events currently held in the ingestion pool, oldest-first:
389
+ * received transport envelopes that have not yet decrypted/processed into the
390
+ * history tree (e.g. a newer-epoch message awaiting its commit, or a fork
391
+ * message awaiting its branch). They are retried as the tree grows; an entry
392
+ * that never clears is a received event the unlocking state never arrived for.
393
+ */
394
+ pendingEnvelopes(): TEnvelope[];
395
+ /**
396
+ * Seam (epic-marmot-client S20, `removalConvergence`): the revisable removal
397
+ * of the local leaf the current `removedFromGroup` state stands for, or
398
+ * `undefined` (a member, a settled removal, or the seam off). A new object
399
+ * whenever it changes, so an owner can persist it with the state and hand it
400
+ * to a rebuilt engine (`MarmotGroupEngineOptions.removal`).
401
+ */
402
+ get removal(): RemovalRecord | undefined;
403
+ /**
404
+ * Seam (`removalFinality`) test probe: a read-only view of the per-edge fact
405
+ * memo (hex commit digest → facts, least recently used first). Reading it
406
+ * does not refresh an entry.
407
+ * @internal
408
+ */
409
+ get edgeFactMemo(): ReadonlyMap<string, EdgeFacts>;
410
+ /**
411
+ * Seam (`removalFinality`) test probe: drops the memoised facts of the edge
412
+ * with hex commit digest `digest`, standing for its eviction; whether there
413
+ * were any. It only deletes: nothing outside the engine writes the memo.
414
+ * @internal
415
+ */
416
+ evictEdgeFactsForTest(digest: string): boolean;
417
+ /**
418
+ * Seam (S20): hex account identity of the committer of the held removal's
419
+ * selected commit (`removal.commits[0]`), read from the removal's parent
420
+ * tree — `undefined` when no removal is held or the committer cannot be
421
+ * resolved (a non-member sender, or a replay that fails on a rebuilt
422
+ * engine). An owner that reports the removal calls it before
423
+ * {@link settleRemoval}, which forgets the senders.
424
+ */
425
+ removalActor(): Promise<string | undefined>;
426
+ /**
427
+ * Seam (S20): settles the held removal — it is final from now on, and later
428
+ * input for the group is `self-evicted` again (D-13). The owner calls this
429
+ * once its convergence window for the removal has passed.
430
+ */
431
+ settleRemoval(): void;
432
+ /**
433
+ * Seam (`branchAwareFence`, spec Design Decision 6/3a): the engine's opaque
434
+ * state — the held candidates (each with its original envelope) and the
435
+ * undecryptable set `U` — or `undefined` while both are empty and with the
436
+ * seam off. A new object whenever either changes (the same object while
437
+ * neither does), so an owner can persist it with the state in the batch's
438
+ * transaction and hand it to a rebuilt engine
439
+ * ({@link MarmotGroupEngineOptions.opaque}), exactly as it does
440
+ * {@link removal}. The record is not durable by itself: an owner that does
441
+ * not persist it loses every `skipped` it would later have revised.
442
+ */
443
+ get opaque(): HeldOpaqueRecord<TEnvelope> | undefined;
444
+ /** The batch is open: a deferred step ran and no settling call has closed it yet. */
445
+ get batchOpen(): boolean;
446
+ /**
447
+ * The full-fork history tree: every group state observed — the canonical
448
+ * branch and every fork — keyed by MLS confirmation tag. Read-only structural
449
+ * access; the engine grows it as commits and proposals arrive.
450
+ */
451
+ get history(): GroupHistoryTree;
452
+ /**
453
+ * The retained canonical states within the rollback horizon, newest epoch
454
+ * first. Used for cross-epoch encrypted-media decryption: media is keyed by
455
+ * its source-epoch exporter secret, which is not carried on the wire, so a
456
+ * receiver tries each still-retained epoch's key. States older than
457
+ * `max_rewind_commits` are pruned (`retained-history.md`); media from a pruned
458
+ * epoch can no longer be decrypted.
459
+ */
460
+ retainedStates(): ClientState[];
461
+ get state(): ClientState;
462
+ set state(newState: ClientState);
463
+ /**
464
+ * The group's lifecycle state (`group-state.md`). A new local commit may only
465
+ * be prepared while `Stable`; the commit flow moves through `PendingPublish`
466
+ * (commit prepared, publish unconfirmed) and `Merging` (publish acked, staged
467
+ * commit applying) and back to `Stable`.
468
+ */
469
+ get lifecycle(): GroupLifecycleState;
470
+ /**
471
+ * The derived convergence status (`group-state.md` §Convergence status, B5):
472
+ * `Syncing` while the quiescence window since the last convergence-relevant
473
+ * input has not elapsed, then `Resolving` / `Blocked` / `Settled` per the last
474
+ * pass. Recomputed on every read against the injected clock, so it advances to
475
+ * `Settled` as wall-clock time passes even with no new input.
476
+ */
477
+ get convergenceStatus(): ConvergenceStatus;
478
+ /** Snapshot of the active immutable pass, exposed for scheduler diagnostics. */
479
+ get convergencePass(): ConvergencePassState | undefined;
480
+ /** Canonical terminal evidence retained until the client persists its tombstone. */
481
+ get selectedDisbandEvidence(): DisbandCandidateEvidence | undefined;
482
+ /** Number of envelopes retained but not yet admitted to a convergence pass. */
483
+ get retainedConvergenceInputCount(): number;
484
+ /** Opens or refreshes the current collection pass from the monotonic clock. */
485
+ admitConvergencePass(): ConvergencePassState;
486
+ /** Current durable irreversible request, hydrated before this promise resolves. */
487
+ disbandRequest(): Promise<DisbandRequest | undefined>;
488
+ /** Flushes restart-critical terminal candidate/pass evidence. */
489
+ persistDisbandConvergence(): Promise<void>;
490
+ /** Persist irreversible intent, then prepare its exact candidate against this epoch. */
491
+ requestDisband(): Promise<SendResult<TEnvelope> | undefined>;
492
+ /** Atomically enables lifecycle-v1 for a legacy group when every leaf supports it. */
493
+ enableGroupDisbanding(): Promise<SendResult<TEnvelope> | undefined>;
494
+ /** Executes a local send intent and returns the wrapped transport envelope. */
495
+ send(intent: SendIntent): Promise<SendResult<TEnvelope>>;
496
+ /**
497
+ * Applies staged state after publish confirmation (publish-before-apply).
498
+ *
499
+ * CR-09: `selfUpdate` takes the identical path to `commit` — it is a commit
500
+ * in every sense that matters here (it advances the epoch and produces a new
501
+ * confirmation tag), so it must be recorded into retained history and the
502
+ * fork tree. Recording it only via `#setState` left `RetainedHistoryStore`
503
+ * with no `stateAt(newEpoch)` (so `resolveFork` could never rebuild across a
504
+ * selfUpdate) and the tree with no node for the new tip (so the next
505
+ * `GroupRegistry.#loadHistory` discarded the entire persisted fork history).
506
+ * Since `refs/marmot/protocol-core/joining.md` tells clients to selfUpdate
507
+ * immediately after joining from a Welcome, the normal join path destroyed
508
+ * its own convergence persistence.
509
+ */
510
+ confirmPublished(pending: PendingState): StateNotification[];
511
+ /**
512
+ * Reverts lifecycle when a staged commit publish fails or is abandoned.
513
+ * Covers both commit-producing seams (CR-09/WR-17): a selfUpdate now also
514
+ * transitions to `PendingPublish`, so a failed publish must roll it back or
515
+ * the engine would be stuck unable to prepare any further commit.
516
+ */
517
+ publishFailed(pending: PendingState): void;
518
+ /**
519
+ * Ingests transport envelopes and applies MLS messages to group state.
520
+ *
521
+ * Caller contract: the engine accepts any envelope and does not route by
522
+ * group. Routing by the transport's group tag (the Nostr `h` tag) is the
523
+ * caller's job (the `@941design/marmot` client does it), so hand a group's
524
+ * engine only that group's traffic. An envelope for another group cannot be
525
+ * read here and is pooled as undecryptable until the pool evicts it, where
526
+ * upstream's engine classes it stale (`StaleReason::UnknownGroup`) at once.
527
+ * The engine does not filter on the tag itself because the group's routing
528
+ * id can change (a routing-component update), which would make an early
529
+ * check skip own-group input for good.
530
+ *
531
+ * @yields DispositionedIngestResult - processing result plus inbound
532
+ * {@link Disposition}.
533
+ */
534
+ ingest(envelopes: TEnvelope[], options?: {
535
+ maxRetries?: number;
536
+ settle?: boolean;
537
+ }): AsyncGenerator<DispositionedIngestResult<TEnvelope>>;
538
+ /**
539
+ * Admits retained input into a later pass once lifecycle and the prior fixed
540
+ * deadline permit it. Each call is a deterministic one-shot scheduler edge.
541
+ * Settling admitted disband candidates first, its `leafEquivocation` report
542
+ * (seam `equivocationCredit`) leads the returned results.
543
+ */
544
+ driveConvergence(): Promise<DispositionedIngestResult<TEnvelope>[]>;
545
+ /**
546
+ * Releases engine resources — currently the pending settle-check timer.
547
+ * Called on group teardown (destroy/unload) so no timer outlives the group.
548
+ */
549
+ dispose(): void;
550
+ /**
551
+ * Drives one tree-fed re-convergence pass to completion, switching to the
552
+ * canonical branch if the persisted history now favors a competing fork. Public
553
+ * entry for the load path (after the engine hydrates from the tree) and any
554
+ * caller wanting an explicit re-evaluation. Witness-free — the structural keys
555
+ * decide; witnesses refine on the next live ingest/sweep.
556
+ *
557
+ * Returns every result the pass produced, dispositioned and audited exactly
558
+ * as {@link ingest} does, so a caller can route them through the identical
559
+ * handler.
560
+ *
561
+ * CR-06: these results MUST reach the caller. `#reconvergeFromTree` is the
562
+ * only site that can yield the `stateInvalidated` withdrawal proving a
563
+ * rewind superseded the commit that removed us, and that withdrawal is what
564
+ * clears the persisted removed-inactive marker (CONV-03, D-12). While this
565
+ * method drained into `void _`, a client that was removed on a losing fork,
566
+ * restarted, and re-converged onto a branch where it is still a member ended
567
+ * up with canonical membership restored AND a stale marker still set —
568
+ * silently suppressing the next genuine removal.
569
+ */
570
+ reconvergeFromHistory(): Promise<DispositionedIngestResult<TEnvelope>[]>;
571
+ }