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