@941design/marmot 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 (192) hide show
  1. package/CHANGELOG.md +709 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -2
  4. package/dist/account/admin.d.ts +72 -0
  5. package/dist/account/admin.js +209 -0
  6. package/dist/account/device-deps.d.ts +379 -0
  7. package/dist/account/device-deps.js +36 -0
  8. package/dist/account/device-lineage.d.ts +199 -0
  9. package/dist/account/device-lineage.js +390 -0
  10. package/dist/account/device-registry.d.ts +93 -0
  11. package/dist/account/device-registry.js +1290 -0
  12. package/dist/account/device-rotation.d.ts +61 -0
  13. package/dist/account/device-rotation.js +827 -0
  14. package/dist/account/enrolment.d.ts +339 -0
  15. package/dist/account/enrolment.js +1247 -0
  16. package/dist/account/identity-proof.d.ts +79 -0
  17. package/dist/account/identity-proof.js +264 -0
  18. package/dist/account/index.d.ts +17 -0
  19. package/dist/account/index.js +16 -0
  20. package/dist/account/restore-rotation.d.ts +21 -0
  21. package/dist/account/restore-rotation.js +22 -0
  22. package/dist/account/same-account-authorization.d.ts +86 -0
  23. package/dist/account/same-account-authorization.js +180 -0
  24. package/dist/account/teardown.d.ts +127 -0
  25. package/dist/account/teardown.js +856 -0
  26. package/dist/client/before-create-group.d.ts +18 -0
  27. package/dist/client/before-create-group.js +65 -0
  28. package/dist/client/before-publish-hooks.d.ts +121 -0
  29. package/dist/client/before-publish-hooks.js +180 -0
  30. package/dist/client/client-config.d.ts +42 -0
  31. package/dist/client/client-config.js +13 -0
  32. package/dist/client/commit-redrive.d.ts +68 -0
  33. package/dist/client/commit-redrive.js +221 -0
  34. package/dist/client/component-update.d.ts +43 -0
  35. package/dist/client/component-update.js +53 -0
  36. package/dist/client/confirm-hooks.d.ts +50 -0
  37. package/dist/client/confirm-hooks.js +59 -0
  38. package/dist/client/create-client.d.ts +1022 -0
  39. package/dist/client/create-client.js +1125 -0
  40. package/dist/client/group-disband.d.ts +28 -0
  41. package/dist/client/group-disband.js +64 -0
  42. package/dist/client/group-history.d.ts +435 -0
  43. package/dist/client/group-history.js +1295 -0
  44. package/dist/client/group-profile.d.ts +31 -0
  45. package/dist/client/group-profile.js +62 -0
  46. package/dist/client/group-records.d.ts +485 -0
  47. package/dist/client/group-records.js +1034 -0
  48. package/dist/client/group-removal.d.ts +36 -0
  49. package/dist/client/group-removal.js +127 -0
  50. package/dist/client/group-remove-member.d.ts +49 -0
  51. package/dist/client/group-remove-member.js +163 -0
  52. package/dist/client/group-runtime.d.ts +388 -0
  53. package/dist/client/group-runtime.js +2701 -0
  54. package/dist/client/group-snapshot.d.ts +98 -0
  55. package/dist/client/group-snapshot.js +453 -0
  56. package/dist/client/history-pages.d.ts +107 -0
  57. package/dist/client/history-pages.js +194 -0
  58. package/dist/client/inbox-send.d.ts +19 -0
  59. package/dist/client/inbox-send.js +71 -0
  60. package/dist/client/index.d.ts +21 -0
  61. package/dist/client/index.js +13 -0
  62. package/dist/client/ingest.d.ts +82 -0
  63. package/dist/client/ingest.js +1550 -0
  64. package/dist/client/lifecycle-events.d.ts +63 -0
  65. package/dist/client/lifecycle-events.js +35 -0
  66. package/dist/client/opaque-candidates.d.ts +81 -0
  67. package/dist/client/opaque-candidates.js +169 -0
  68. package/dist/client/own-change-outbox.d.ts +66 -0
  69. package/dist/client/own-change-outbox.js +156 -0
  70. package/dist/client/pending-leaf.d.ts +116 -0
  71. package/dist/client/pending-leaf.js +378 -0
  72. package/dist/client/permissions.d.ts +9 -0
  73. package/dist/client/permissions.js +12 -0
  74. package/dist/client/pipeline.d.ts +554 -0
  75. package/dist/client/pipeline.js +3545 -0
  76. package/dist/client/reentrancy-guard.d.ts +96 -0
  77. package/dist/client/reentrancy-guard.js +153 -0
  78. package/dist/client/rekey.d.ts +58 -0
  79. package/dist/client/rekey.js +149 -0
  80. package/dist/client/transport-policy.d.ts +181 -0
  81. package/dist/client/transport-policy.js +214 -0
  82. package/dist/history/equivocation.d.ts +55 -0
  83. package/dist/history/equivocation.js +113 -0
  84. package/dist/history/fencing.d.ts +25 -0
  85. package/dist/history/fencing.js +61 -0
  86. package/dist/history/hex.d.ts +3 -0
  87. package/dist/history/hex.js +10 -0
  88. package/dist/history/index.d.ts +73 -0
  89. package/dist/history/index.js +31 -0
  90. package/dist/history/notifications.d.ts +270 -0
  91. package/dist/history/notifications.js +264 -0
  92. package/dist/history/ordering-key.d.ts +24 -0
  93. package/dist/history/ordering-key.js +101 -0
  94. package/dist/history/own-change-fork.d.ts +112 -0
  95. package/dist/history/own-change-fork.js +196 -0
  96. package/dist/history/own-change.d.ts +106 -0
  97. package/dist/history/own-change.js +146 -0
  98. package/dist/history/policy.d.ts +48 -0
  99. package/dist/history/policy.js +52 -0
  100. package/dist/history/retained-window.d.ts +215 -0
  101. package/dist/history/retained-window.js +565 -0
  102. package/dist/inbox/demux.d.ts +90 -0
  103. package/dist/inbox/demux.js +78 -0
  104. package/dist/inbox/handler-registry.d.ts +42 -0
  105. package/dist/inbox/handler-registry.js +37 -0
  106. package/dist/inbox/index.d.ts +11 -0
  107. package/dist/inbox/index.js +10 -0
  108. package/dist/inbox/seen-set.d.ts +82 -0
  109. package/dist/inbox/seen-set.js +202 -0
  110. package/dist/inbox/subscription.d.ts +236 -0
  111. package/dist/inbox/subscription.js +644 -0
  112. package/dist/index.d.ts +10 -0
  113. package/dist/index.js +9 -0
  114. package/dist/invitations/competing-welcome.d.ts +223 -0
  115. package/dist/invitations/competing-welcome.js +128 -0
  116. package/dist/invitations/decline.d.ts +61 -0
  117. package/dist/invitations/decline.js +143 -0
  118. package/dist/invitations/expect-welcome.d.ts +66 -0
  119. package/dist/invitations/expect-welcome.js +138 -0
  120. package/dist/invitations/index.d.ts +16 -0
  121. package/dist/invitations/index.js +16 -0
  122. package/dist/invitations/invite.d.ts +303 -0
  123. package/dist/invitations/invite.js +966 -0
  124. package/dist/invitations/offers.d.ts +79 -0
  125. package/dist/invitations/offers.js +115 -0
  126. package/dist/invitations/on-proposal.d.ts +47 -0
  127. package/dist/invitations/on-proposal.js +40 -0
  128. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  129. package/dist/invitations/pending-proposal-policy.js +139 -0
  130. package/dist/invitations/proposal-deadline.d.ts +133 -0
  131. package/dist/invitations/proposal-deadline.js +164 -0
  132. package/dist/invitations/relay-planes.d.ts +43 -0
  133. package/dist/invitations/relay-planes.js +70 -0
  134. package/dist/invitations/welcome-processor.d.ts +253 -0
  135. package/dist/invitations/welcome-processor.js +1180 -0
  136. package/dist/key-packages/device-key.d.ts +131 -0
  137. package/dist/key-packages/device-key.js +272 -0
  138. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  139. package/dist/key-packages/device-rotation-records.js +173 -0
  140. package/dist/key-packages/group-refs.d.ts +40 -0
  141. package/dist/key-packages/group-refs.js +79 -0
  142. package/dist/key-packages/index.d.ts +18 -0
  143. package/dist/key-packages/index.js +18 -0
  144. package/dist/key-packages/key-package-ref.d.ts +16 -0
  145. package/dist/key-packages/key-package-ref.js +21 -0
  146. package/dist/key-packages/observation-stream.d.ts +4 -0
  147. package/dist/key-packages/observation-stream.js +120 -0
  148. package/dist/key-packages/offer-rumor.d.ts +26 -0
  149. package/dist/key-packages/offer-rumor.js +69 -0
  150. package/dist/key-packages/publisher.d.ts +174 -0
  151. package/dist/key-packages/publisher.js +1247 -0
  152. package/dist/key-packages/select-key-package.d.ts +24 -0
  153. package/dist/key-packages/select-key-package.js +90 -0
  154. package/dist/key-packages/slot-manager.d.ts +167 -0
  155. package/dist/key-packages/slot-manager.js +327 -0
  156. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  157. package/dist/key-packages/validate-key-package-event.js +49 -0
  158. package/dist/media/cache.d.ts +14 -0
  159. package/dist/media/cache.js +10 -0
  160. package/dist/media/index.d.ts +52 -0
  161. package/dist/media/index.js +71 -0
  162. package/dist/mls.d.ts +15 -0
  163. package/dist/mls.js +15 -0
  164. package/dist/shared/account-pubkey.d.ts +4 -0
  165. package/dist/shared/account-pubkey.js +10 -0
  166. package/dist/shared/errors.d.ts +21 -0
  167. package/dist/shared/errors.js +85 -0
  168. package/dist/shared/hex.d.ts +4 -0
  169. package/dist/shared/hex.js +13 -0
  170. package/dist/shared/index.d.ts +14 -0
  171. package/dist/shared/index.js +14 -0
  172. package/dist/shared/kinds.d.ts +8 -0
  173. package/dist/shared/kinds.js +28 -0
  174. package/dist/shared/publish-classification.d.ts +26 -0
  175. package/dist/shared/publish-classification.js +31 -0
  176. package/dist/storage/envelope.d.ts +39 -0
  177. package/dist/storage/envelope.js +201 -0
  178. package/dist/storage/index.d.ts +227 -0
  179. package/dist/storage/index.js +459 -0
  180. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  181. package/dist/storage/indexeddb/idb-types.js +1 -0
  182. package/dist/storage/indexeddb/index.d.ts +17 -0
  183. package/dist/storage/indexeddb/index.js +141 -0
  184. package/dist/storage/lease.d.ts +41 -0
  185. package/dist/storage/lease.js +117 -0
  186. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  187. package/dist/storage/memory/deterministic-signer.js +65 -0
  188. package/dist/storage/memory/index.d.ts +32 -0
  189. package/dist/storage/memory/index.js +87 -0
  190. package/dist/storage/memory/lock-manager.d.ts +8 -0
  191. package/dist/storage/memory/lock-manager.js +71 -0
  192. package/package.json +66 -3
@@ -0,0 +1,388 @@
1
+ /**
2
+ * Per-group runtime (S3): one `MarmotGroupEngine` + a serial operation queue
3
+ * per (client, groupId), cached for the client's lifetime, plus the client-
4
+ * level group registry `groups.create/get/list`, `extensions.onConfirm` and
5
+ * dispose wiring `create-client.ts` mounts onto `MarmotClient`.
6
+ *
7
+ * Every call into consumer-supplied code (the ADR-007 stores, the signer,
8
+ * `onConfirm` hooks, the transport) goes through the client's
9
+ * `ReentrancyGuard` (ADR-013 / DD13, AC-PIPE-11) — see `reentrancy-guard.ts`.
10
+ * `GroupRuntime.run` additionally serialises every mutating group operation
11
+ * on the group's own queue and re-checks disposal before starting.
12
+ */
13
+ import type { NostrEvent } from '@941design/nostr-events/event';
14
+ import type { Unsubscribable } from '@941design/nostr-events/transport/contract';
15
+ import { MarmotGroupEngine, type ActiveAdminLeaverPredicate } from '@941design/marmot-engine/engine';
16
+ import { type ClientState } from '@941design/marmot-engine/mls';
17
+ import { type DeviceGroupPort, type TeardownGroupPort, type TeardownService } from '../account/index.js';
18
+ import { type CompetingWelcomePorts, type InvitationsService } from '../invitations/index.js';
19
+ import { MarmotError } from '../shared/index.js';
20
+ import type { GroupStore } from '../storage/index.js';
21
+ import { type GroupNotification, type JoinEvidence, type RetainedWindow } from '../history/index.js';
22
+ import { type HeldRemoval } from './group-removal.js';
23
+ import { type OpaqueRecord } from './opaque-candidates.js';
24
+ import type { ClientContext, ConfirmHook, GroupIntent, LeafInfo, MarmotGroup, MarmotClient } from './create-client.js';
25
+ import { type DisbandRecord } from './group-disband.js';
26
+ import { type PendingCommitMarker, type PendingLeaf } from './pending-leaf.js';
27
+ import { type ReentrancyGuard } from './reentrancy-guard.js';
28
+ import { type SelfRemoveElection } from './pipeline.js';
29
+ import { type HistorySilenceTracker } from './transport-policy.js';
30
+ /** Every leaf of `account` in `state`: its leaf index and signature key (hex). */
31
+ export declare function leafInfosOf(state: ClientState, account: string): LeafInfo[];
32
+ export interface GroupRuntime {
33
+ readonly groupId: string;
34
+ readonly groupStore: GroupStore;
35
+ engine: MarmotGroupEngine<NostrEvent>;
36
+ readonly ctx: ClientContext;
37
+ readonly guard: ReentrancyGuard;
38
+ /** Registered `onConfirm` hooks, in registration order — shared, mutable (the registry owns additions/removals). */
39
+ readonly confirmHooks: ConfirmHook[];
40
+ /**
41
+ * AC-MX-2: told whenever an own intent of this group confirmed (pipeline.ts `confirmRecord`, after the state is
42
+ * applied) or went terminal (`error` set) — through `terminalFail` with a caller, else pipeline.ts
43
+ * `reportIntentFailed`, the one path every caller-less terminal failure takes (a background drive, a stranded
44
+ * re-enqueue, an awaiting-sync intent a fence dropped), which also emits `intentFailed` — and a linked self-update
45
+ * dropped with the staged-Adds commit it followed (its caller gets the commit's error). How `groups.restore`
46
+ * waits for its self-update, matched by intent id.
47
+ */
48
+ readonly settledListeners: Set<(settled: IntentSettled) => void>;
49
+ /**
50
+ * AC-MX-2: told ONCE, synchronously, when this runtime ends for good — fenced (assigning {@link fence}), retired
51
+ * (a teardown purge, a failed restore taken back), disposed, or its stores lost their lease (`no-lease`) — then cleared. Whatever waits on the group making
52
+ * progress (`groups.restore`) races it, so no such wait outlives the runtime. Never throws into the caller.
53
+ */
54
+ readonly terminalWatchers: Set<(end: RuntimeEnd) => void>;
55
+ disposed: boolean;
56
+ /** S9: the group was abandoned (left, destroyed): its handle and operations answer `not-a-member`. */
57
+ abandoned: boolean;
58
+ /**
59
+ * The `no-lease` error that ended this runtime (pipeline.ts `backgroundRetryEnds`), kept so a check made after the
60
+ * terminal signal fired still sees it; `undefined` while the stores hold their lease.
61
+ */
62
+ leaseLost: MarmotError | undefined;
63
+ readonly handle: MarmotGroup;
64
+ /** Per-group consecutive history-timeout tracker (AC-PIPE-14) — one instance for the runtime's lifetime. */
65
+ readonly historyTracker: HistorySilenceTracker;
66
+ /** `relay␟created_at` of every history gap already reported (`historyGap` fires once per relay and second per session). */
67
+ readonly historyGapsReported: Set<string>;
68
+ /** Per relay: consecutive history passes whose walk of it was incomplete without a single in-window event (see `relaySilent` `no-progress`). */
69
+ readonly historyStalls: Map<string, number>;
70
+ /** History passes since the current backlog walk began (0 when none is in progress): the live subscription starts after a bound even mid-walk. */
71
+ walkPasses: number;
72
+ /** Local clock (unix seconds) when the current or last backlog walk began: the catch-up pass after subscribing reaches back to it. */
73
+ walkStartedAt: number | undefined;
74
+ /** `since` override for the next ordinary history pass (the post-subscribe catch-up), consumed by it. */
75
+ catchUpSince: number | undefined;
76
+ /** Whether `startGroupSync` has been called and `stopGroupSync`/dispose hasn't torn it down yet. */
77
+ syncStarted: boolean;
78
+ /**
79
+ * "Caught up since the last connectivity gap": `false` when this runtime
80
+ * is built (load, reload, create, join) and again whenever the group's live
81
+ * kind-445 subscription is lost — the transport ended it (with raw-ws: every
82
+ * relay socket of the plane closed), the routing changed, or the sync
83
+ * stopped (ingest.ts `dropLiveSubscription` / the subscription's `ended`).
84
+ * Set only by the next complete history pass (ingest.ts `runHistoryPass`:
85
+ * the window ingested and no backlog walk left to continue) that BEGAN
86
+ * after the last gap: every clear bumps {@link connectivityGeneration}, a
87
+ * pass captures it when it starts, and sets `caughtUp` only if it is
88
+ * unchanged when the pass completes (a pass whose fetch predates the gap
89
+ * proves nothing about what arrived during it). In memory only.
90
+ *
91
+ * S15 gates deferral-deadline expiry on it (AC-INVITE-4: a peer admin's
92
+ * commit of the proposal, which a catch-up fetches, resolves it first).
93
+ * S18's general first-post-load-sync gate for sends is meant to reuse it;
94
+ * NOTE for S18: a group that never history-syncs (a fenced group, or a
95
+ * harness feeding events by manual `group.ingest()` with no relay) never
96
+ * becomes caught up — S18 must decide how such a group is gated; S15 only
97
+ * leaves its deferrals unexpired.
98
+ */
99
+ caughtUp: boolean;
100
+ /** Bumped on every `caughtUp` clear (a connectivity gap); see {@link caughtUp}. Reuse it with `caughtUp` (S18). */
101
+ connectivityGeneration: number;
102
+ /**
103
+ * S18 (AC-PIPE-15), the send gate: whether own envelopes may be minted. `false` for a runtime built by a LOAD
104
+ * of stored state — that state may be a restored snapshot whose sender ratchet was rolled back (key and
105
+ * nonce reuse) — until the first time {@link caughtUp} is set after that load (ingest.ts `runHistoryPass`).
106
+ * `true` from the start for a runtime built by `groups.create` or a Welcome join (state just minted). It
107
+ * latches: a later connectivity gap does not close it again — a rollback can only come with a load.
108
+ * In memory only, deliberately: a persisted "synced" flag would be restored with the snapshot it must
109
+ * distrust. While closed, `send()` records `awaiting-sync` intents and nothing is encrypted (pipeline.ts).
110
+ */
111
+ sendGateOpen: boolean;
112
+ /**
113
+ * S8 (AC-RATCH-1): the one-shot own-ratchet skip. `true` for a runtime built by a LOAD (like {@link sendGateOpen}
114
+ * starting closed) — unless the stored skip marker (group-records.ts `ratchetSkipArmed`) shows the loaded state
115
+ * already holds a skip no relay has accepted a message at or after, so restarts while nothing gets out never add
116
+ * skip on top of skip: the first own application message encrypted after that load asks the engine to skip
117
+ * `ctx.ratchetSkipMargin` generations first (pipeline.ts `driveIntent`, the only mint site, which runs only with
118
+ * the gate open). Cleared only once that message's staging transaction committed — the skipped ratchet is
119
+ * persisted with the envelope, never without it. In memory only, deliberately: the loaded state is the one it
120
+ * distrusts. Handshake messages (proposals, commits, self-updates) are MLS PublicMessages and consume no
121
+ * sender ratchet, so they neither apply nor clear it.
122
+ */
123
+ ratchetSkipPending: boolean;
124
+ /** `group.synced()` callers waiting for {@link sendGateOpen}: resolved when it opens, rejected `fenced` / on dispose or abandon. */
125
+ readonly syncWaiters: Set<{
126
+ resolve(): void;
127
+ reject(error: unknown): void;
128
+ }>;
129
+ /** The live kind-445 subscription, once the first history pass succeeds; `undefined` before then or after `stopGroupSync`. */
130
+ syncSubscription: Unsubscribable | undefined;
131
+ /** The routing (`h` + relay plane) `syncSubscription` was opened with; `undefined` whenever it is. */
132
+ syncRouting: string | undefined;
133
+ /** Pending history-retry timer handle (backoff after a `timedOut` history pass), if any. */
134
+ syncHistoryRetryTimer: unknown;
135
+ /** Pending pipeline retry timers (publish, confirm, background resume); cleared on dispose. */
136
+ readonly pipelineTimers: Set<unknown>;
137
+ /** S5 (AC-RACE-1): originals whose re-enqueue backoff timer (`armReenqueueRetry`, pipeline.ts) is pending. */
138
+ readonly reenqueueRetryArmed: Set<string>;
139
+ /**
140
+ * The state the handle's getters read (`epoch`, `members()`, `name`, …):
141
+ * the last state that passed the ADR-012 proof gate and was persisted (or
142
+ * confirmed). `engine.state` may briefly hold an unverified post-apply
143
+ * state while an ingest is in flight; it is never exposed (AC-PROOF-2).
144
+ * Assigning a different state notifies the group's state watchers (S9:
145
+ * a `leave()` waiting for its removal).
146
+ */
147
+ exposedState: ClientState;
148
+ /**
149
+ * Local create/join time (client clock, ms) — the account group index
150
+ * entry's `createdAt` — or `undefined` when unknown. An undecryptable event
151
+ * stamped well before it is provably pre-join and holds no cursor. A switch to a competing Welcome's branch lowers
152
+ * it to that Welcome's `created_at` (epic marmot-welcome-race-joiner): what was sent on that branch before the
153
+ * switch is then no longer pre-join.
154
+ */
155
+ joinedAtMs: number | undefined;
156
+ /** Set when sync-delivered events were dropped as `group-busy`; cleared by the next history pass. */
157
+ resyncNeeded: boolean;
158
+ /** Runs a history pass from the persisted cursor now (when syncing and none is already scheduled). */
159
+ resync(): void;
160
+ /**
161
+ * Called whenever `exposedState` changes: when the group's routing (relay
162
+ * plane or Nostr group id) no longer matches the live subscription's, the
163
+ * sync restarts on the new routing (history from the cursor, then a new
164
+ * subscription). Never throws.
165
+ */
166
+ checkSyncRouting(): void;
167
+ /**
168
+ * `guard.assertNotReentrant(groupId, operation)` synchronously, then
169
+ * enqueues `fn` on the group's serial queue; a disposed check runs
170
+ * immediately before `fn` starts. Never throws synchronously — a
171
+ * re-entrant call returns a rejected promise (AC-PIPE-11).
172
+ */
173
+ run<T>(operation: string, fn: (rt: GroupRuntime) => Promise<T>): Promise<T>;
174
+ /**
175
+ * Enqueues `fn` behind every operation already on the group's serial queue, WITHOUT `run`'s re-entrancy,
176
+ * disposed and abandoned checks: for what ends the runtime itself (a failed restore's retirement), which
177
+ * must run after an in-flight operation however the runtime ended. Rejects with what `fn` threw.
178
+ */
179
+ runLast(fn: () => void | Promise<void>): Promise<void>;
180
+ /**
181
+ * Disposes the current engine and replaces it with a fresh one built over
182
+ * `state`, with the history of `window` (default: the durable rewind
183
+ * window) — an in-batch rollback hands the history the engine held at
184
+ * `state`, which the durable window (still the pre-batch tip) cannot name.
185
+ *
186
+ * `opaque` (epic marmot-branch-aware-own-leaf-fence, LD-2): the held opaque record the rebuilt engine starts
187
+ * from — default {@link GroupRuntime.opaque}, the persisted one. An in-batch rollback hands the record the
188
+ * engine held where the rolled-back drain began (`{ record }`; an empty record is `undefined`), the same
189
+ * point `state` and `window` describe: what the rolled-back drain learned does not survive it, what the
190
+ * batch's earlier steps learned does.
191
+ */
192
+ rebuildEngine(state: ClientState, window?: RetainedWindow, opaque?: {
193
+ readonly record: OpaqueRecord | undefined;
194
+ }): Promise<void>;
195
+ /**
196
+ * Set when a failed operation could not roll the engine back: the in-memory
197
+ * state is untrusted, and `run` reloads the durable state before the next
198
+ * operation starts (see {@link reloadFromDurable}).
199
+ */
200
+ needsReload: boolean;
201
+ /**
202
+ * Replaces the engine with one built over the persisted `clientState` and
203
+ * re-exposes it. Every group op persists before returning, so this is the
204
+ * state the engine held at the last op boundary.
205
+ */
206
+ reloadFromDurable(): Promise<void>;
207
+ /** The client's Welcome delivery service (S5). */
208
+ readonly invitations: InvitationsService;
209
+ /**
210
+ * `send()` callers waiting for their queued rumor's publication (S5,
211
+ * AC-INVITE-3), by queueId. In memory only: after a reload a queued rumor
212
+ * still goes out, with no caller left to settle.
213
+ */
214
+ readonly queueWaiters: Map<string, {
215
+ resolve(): void;
216
+ reject(error: unknown): void;
217
+ }>;
218
+ /** Queued rumors as last counted (`undefined` = not known yet): lets a drain be skipped when the queue is known empty. */
219
+ queuedHint: number | undefined;
220
+ /** Schedules one queue drain on the group's queue (a no-op when the queue is known empty or a drain is already scheduled). Never throws. */
221
+ scheduleQueueDrain(): void;
222
+ /** Schedules a queue drain after the capped backoff (a drain that failed); a real trigger cancels it and drains at once. Never throws. */
223
+ scheduleQueueDrainRetry(): void;
224
+ /**
225
+ * The queue's own commit held after a terminal own commit at `epoch`, while
226
+ * `timer` (capped backoff) is pending (see `holdQueueCommit`, pipeline.ts).
227
+ */
228
+ queueCommitHold: {
229
+ readonly epoch: bigint;
230
+ readonly failures: number;
231
+ readonly timer: unknown;
232
+ } | undefined;
233
+ /**
234
+ * S5 (AC-RACE-2): when the staged proposals are exactly a SelfRemove batch another member is elected to
235
+ * commit, the client-clock instant that election was first observed (`startedAt`) and the manual-timer handle
236
+ * (`timer`) that releases the wait after `ctx.selfRemoveElectionWaitMs` — `awaitingElectedSelfRemove`,
237
+ * pipeline.ts. Cleared (without blocking a fresh evaluation) whenever the staged set genuinely changes.
238
+ */
239
+ selfRemoveElectionWait: {
240
+ readonly epoch: bigint;
241
+ readonly refs: string;
242
+ readonly startedAt: number;
243
+ readonly timer: unknown;
244
+ } | undefined;
245
+ /** S9: the engine's SelfRemove auto-commit election seen by the ingest in progress (published after it, AC-ADMIN-9). */
246
+ selfRemoveElection: SelfRemoveElection | undefined;
247
+ /** S9: the "leaver is an active admin" predicate this group's engines run — for re-running their election at rest (re-derived with every engine). */
248
+ leaverPredicate: ActiveAdminLeaverPredicate;
249
+ /**
250
+ * S10: the persisted rewind window whose tip is `exposedState` — what every
251
+ * engine of this group is rebuilt with, and the "before" of the next
252
+ * transition's notifications (history/retained-window.ts).
253
+ */
254
+ window: RetainedWindow;
255
+ /**
256
+ * S20: the revisable removal of the local leaf the persisted tombstone state stands for — exactly what the group
257
+ * extension `marmot.removal` holds (client/group-removal.ts); `undefined` while a member, or once settled.
258
+ * Every engine of the group is built with it, so a rebuilt engine keeps treating the removal as revisable.
259
+ */
260
+ removal: HeldRemoval | undefined;
261
+ /**
262
+ * Called once after the transaction that settled the local leaf's removal for good (client/ingest.ts
263
+ * `settleDueRemoval`): emits `groupRemoved` unless this device is tearing the group down itself. `actor` is the
264
+ * remover the engine named before the settle (`removalActor()`). Never throws.
265
+ */
266
+ readonly removalSettled: (actor: string | undefined) => Promise<void>;
267
+ /**
268
+ * The held opaque candidates and the undecryptable set `U` the engine exposed when the last batch committed —
269
+ * exactly what the group extension `marmot.opaque` holds (client/opaque-candidates.ts); `undefined` while both
270
+ * are empty (and always while the engine's opaque seam is off). Advanced only after the transaction that wrote
271
+ * it committed, so it is the PRE-batch record for every rollback of a batch in flight (LD-2). Every engine of the
272
+ * group is built with it.
273
+ */
274
+ opaque: OpaqueRecord | undefined;
275
+ /**
276
+ * Epic `marmot-leaf-backup-pre-publish` S2 (client/pending-leaf.ts): the adoption of a pending-tagged snapshot whose
277
+ * commit no ingest transaction has recognised yet — exactly what the group extension `marmot.restorePendingCommit`
278
+ * holds. Advanced only after the transaction that wrote or cleared it committed. `undefined` for every group but one
279
+ * restored from a pending-tagged snapshot, and again once its first sync's resolution step ran.
280
+ */
281
+ pendingCommit?: PendingCommitMarker | undefined;
282
+ /**
283
+ * The same epic: the rewound-away pending node (extension `marmot.pendingLeaf`), parked outside the rewind window and
284
+ * the engine's history tree until a relay delivers its commit. `undefined` when nothing is parked.
285
+ */
286
+ pendingLeaf?: PendingLeaf | undefined;
287
+ /**
288
+ * The selected peer disband (client/group-disband.ts, group extension `marmot.disband`): set once the convergence
289
+ * settlement selected it, or on load from the marker. From then on the group does not sync, rejects input and
290
+ * refuses own operations.
291
+ */
292
+ disbanded: DisbandRecord | undefined;
293
+ /**
294
+ * S10 (AC-HIST-4): set once the group is fenced — the `cause` every further operation's `fenced` carries.
295
+ * Assigning it (ingest.ts, group-history.ts `fenceGroup`) fires {@link terminalWatchers}.
296
+ */
297
+ fence: Error | undefined;
298
+ /** S10: `onNotification` listeners, in registration order. */
299
+ readonly notificationListeners: Set<(notification: GroupNotification) => void>;
300
+ /** S10 (V1): tells the device port's rewind listeners this group rewound — detached, never throws. */
301
+ announceRewind(): void;
302
+ /** Epic marmot-device-key-rotation (S6): tells the device port's rotation listeners this group applied a `leaf-key-rotated` — detached, never throws. */
303
+ announceRotation(): void;
304
+ /** S10: the group's history worker (group-history.ts `scheduleHistoryDrain`) — outside the operation queue. */
305
+ readonly historyDrain: {
306
+ running: Promise<void> | undefined;
307
+ again: boolean;
308
+ stopped: boolean;
309
+ inFlight: Promise<void> | undefined;
310
+ };
311
+ }
312
+ /** An own intent that confirmed (`error` absent) or went terminal (`error` = its `send-rejected` / `fenced`). */
313
+ export interface IntentSettled {
314
+ readonly intentId: string;
315
+ /** The intent id a caller saw: `intentId` itself, or for a re-enqueue (AC-RACE-1) the original it re-drives. */
316
+ readonly rootIntentId: string;
317
+ readonly kind: GroupIntent['type'];
318
+ readonly error?: MarmotError;
319
+ }
320
+ /** Why a runtime ended for good ({@link GroupRuntime.terminalWatchers}). */
321
+ export type RuntimeEnd = {
322
+ readonly reason: 'fenced';
323
+ readonly cause: Error;
324
+ } | {
325
+ readonly reason: 'retired';
326
+ } | {
327
+ readonly reason: 'disposed';
328
+ }
329
+ /** The stores lost their lease under the live client (pipeline.ts `backgroundRetryEnds`): no own intent can settle here any more. */
330
+ | {
331
+ readonly reason: 'no-lease';
332
+ readonly cause: MarmotError;
333
+ };
334
+ export interface GroupRegistry {
335
+ readonly groups: MarmotClient['groups'];
336
+ onConfirm(hook: ConfirmHook): () => void;
337
+ /**
338
+ * S6: persists a group joined from a Welcome (already proof-checked) — the
339
+ * join counterpart of `groups.create`. `already-member` when the group's
340
+ * state is already stored (nothing is overwritten): a second, competing
341
+ * Welcome of a same-epoch race never reaches this method for a held group
342
+ * before it was classified and decided (`competing`, below; epic
343
+ * `marmot-welcome-race-joiner`, ADR-018) — the joined branch is kept only
344
+ * when the members' own rule ranks it higher, else the group is rebased onto
345
+ * the Welcome's branch (`rebaseToWelcome`).
346
+ * `joinEvidence` (epic marmot-welcome-race-joiner): the Welcome's commit digest and the account that signed its
347
+ * GroupInfo, written on the root of the join-time window; absent for an untagged Welcome.
348
+ */
349
+ adoptJoinedGroup(groupId: string, state: ClientState, joinedAtMs: number, joinEvidence?: JoinEvidence, invitationId?: string, welcomeCreatedAtMs?: number): Promise<'joined' | 'already-member'>;
350
+ /**
351
+ * The ports of the competing-Welcome decision (epic marmot-welcome-race-joiner): the group's gate, its held
352
+ * branch, the rebase onto a competing Welcome's state and the switch report.
353
+ */
354
+ readonly competing: CompetingWelcomePorts;
355
+ /**
356
+ * Sets the one listener told that a condition `competing.competingGate` reports may have cleared for a group (its
357
+ * first sync ended, an own commit settled, the engine's quiescence ended, a restore was released): the client asks
358
+ * whether a `competing` record waits for the group and, if so, runs an inbox pass at once (AC-FWJ-31).
359
+ */
360
+ onGateMayHaveCleared(listener: (groupId: string) => void): void;
361
+ /** Whether a group state is stored (or being stored) for `groupId`. */
362
+ hasGroup(groupId: string): Promise<boolean>;
363
+ /**
364
+ * AC-MX-2: sets the one listener called when a restore that deferred a Welcome adoption
365
+ * (`adoptJoinedGroup` threw `commit-pending`, `reason: 'restore-in-flight'`) released the group — succeeded
366
+ * or failed and taken back. The client runs an inbox pass at once, so the deferred `joining` invitation
367
+ * resolves without waiting out the inbox backoff. Never called from inside the registry's own frames.
368
+ */
369
+ onRestoreReleased(listener: (groupId: string) => void): void;
370
+ /** S8: the group operations the device registry and enrolment run (`account` never imports `client`). */
371
+ readonly devicePort: DeviceGroupPort;
372
+ /** S9: the group operations teardown (leave/abandon/destroy) runs. */
373
+ readonly teardownPort: TeardownGroupPort;
374
+ /** S15: schedules the deferral-deadline check (AC-INVITE-4) on every loaded group's queue (the inbox pass). Never throws. */
375
+ checkProposalDeadlines(): void;
376
+ /**
377
+ * AC-MX-2: resumes (in the background) every unfinished restore an earlier client over these stores left
378
+ * (`resumeRestore`), so a restore interrupted by a crash or dispose completes without the app re-supplying its
379
+ * snapshot. The first call (client creation) scans the account's whole group index once; every later call (each
380
+ * inbox pass) retries only the groups THIS client left marked — a resume or take-back that failed before it could
381
+ * clear the mark, or a group whose mark could not be read — never re-reading the marks of unmarked groups (any
382
+ * access to a group still checks its mark). A scan whose index read failed is redone by the next call. Never throws.
383
+ */
384
+ resumeUnfinishedRestores(): void;
385
+ /** Tears every runtime down, each step isolated; returns the errors of the steps that threw (never throws itself). */
386
+ dispose(): unknown[];
387
+ }
388
+ export declare function createGroupRegistry(ctx: ClientContext, guard: ReentrancyGuard, invitations: InvitationsService, teardown: () => TeardownService): GroupRegistry;