@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,2701 @@
1
+ import { createSimpleGroup, decryptGroupMessages, createGroupEvent, getGroupIdHex, getNostrGroupIdHex, getMarmotGroupView, getGroupMemberPubkeys, createCredential, generateKeyPackage, getPubkeyLeafNodes, getPubkeyLeafNodeIndexes, deserializeClientState, serializeClientState, } from '@941design/marmot-engine/core';
2
+ import { isAdminAccountLeaver, MarmotGroupEngine, OpaqueRecordInvalid, nextOwnApplicationGeneration } from '@941design/marmot-engine/engine';
3
+ import { ciphersuites, defaultCryptoProvider, getCiphersuiteImpl, nodeTypes, selfRemoveProposalType, } from '@941design/marmot-engine/mls';
4
+ import { accountLeafIndexes, activeAdmins, enforceStateProofs, isActiveAdmin, isLastActiveAdmin, RESTORE_ROTATION_EXTENSION, writeRestoreRotationOwed, } from '../account/index.js';
5
+ import { ownLeafOf } from './rekey.js';
6
+ import { DEFAULT_CIPHERSUITE_NAME, deviceProofSigner, ensureDeviceSigningKey, readDeviceSigningKey, withDeviceSignatureKey } from '../key-packages/index.js';
7
+ import { carriesBranch, judgeCompetingWelcome, toWelcomeOutcome } from '../invitations/index.js';
8
+ import { MarmotError, isMarmotError } from '../shared/index.js';
9
+ import { canonicalPath, successionsInWindow, EQUIVOCATION_EXTENSION, FENCE_EXTENSION, fencedError, heldBranchScore, readEquivocationNotifications, readFence, readWindow, recordedFencingError, restoreHistory, REWIND_HORIZON, tagOf, tipOnlyWindow, windowFor, writeWindow, } from '../history/index.js';
10
+ import { belongsTo, clearRemoval, readRemoval, REMOVAL_EXTENSION, settlesAt } from './group-removal.js';
11
+ import { clearOpaque, isEmptyOpaque, OPAQUE_EXTENSION, OpaqueRecordCorrupt, readOpaque } from './opaque-candidates.js';
12
+ import { assertNotInHistoryBackend, awaitHistoryCallSettled, boundedHistoryCall, issueMutation, clearSettlementRecheck, decryptMediaOp, deliverTransition, reconcileInvitesWithWindow, encryptMediaOp, planTransition, recordTransition, scheduleHistoryDrain, WITHDRAWN_DISPOSITION, stopHistoryDrain, historyOf, readSettlementRecheckRecord, SETTLEMENT_RECHECK_EXTENSION, subscribeNotifications } from './group-history.js';
13
+ import { clearRestoringRecord, GROUP_INDEX_EXTENSION, deletePendingIntentRecord, hasGroupState, listGroupIndex, listRestoringRecords, listPendingIntentRecords, listPendingIntentSummaries, listQueuedRumorRecords, RATCHET_SKIP_EXTENSION, ratchetSkipArmed, readGroupIndexEntry, readGroupState, readIngestCursor, readRatchetSkipMarker, readRestorePending, RESTORE_PENDING_EXTENSION, RESTORING_EXTENSION, writeGroupIndexEntry, writeGroupState, writeIngestCursor, writeRestorePending, writeTerminalLedgerEntry, writeRestoringRecord, } from './group-records.js';
14
+ import { DISBAND_EXTENSION, disbandedError, groupDisbandedOf, readDisband } from './group-disband.js';
15
+ import { drainConvergence, ingestEvents, requestHistoryResync, scheduleRemovalSettle, restartSyncOnRoutingChange, startGroupSync, stopGroupSync, treeFedPass } from './ingest.js';
16
+ import { clearPendingCommit, clearPendingLeaf, PENDING_COMMIT_EXTENSION, PENDING_LEAF_EXTENSION, pendingWatch, readPendingRestore, resolvePendingCommit, writePendingCommit, } from './pending-leaf.js';
17
+ import { ACCOUNT_SCOPE } from './reentrancy-guard.js';
18
+ import { advanceQueue, backoffMs, inviteIntent, proposeSelfRemoveIntent, removeLeafIntent, electionAtRest, removeMemberIntent, renameIntent, rekeyIntent, resumePendingInBackground, scheduleAwaitingFenceCleanup, scheduleDeferredReenqueueRetry, scheduleProposalDeadlineCheck, scheduleRekeyFollowUp, scheduleSelfRemoveCommit, notifySettled, ownMessage, scheduleWithdrawnRedrives, sendIntent, setAdminsIntent, } from './pipeline.js';
19
+ import { createHistorySilenceTracker, CURSOR_FUTURE_SKEW_S, CURSOR_REDELIVERY_MARGIN_S } from './transport-policy.js';
20
+ import { runConfirmHooks } from './confirm-hooks.js';
21
+ /** The group extension holding one row per invitation whose switch transaction committed: the durable proof it was written. */
22
+ const SWITCH_PROOF_EXTENSION = 'marmot.branchSwitch';
23
+ /** An error thrown by an `onConfirm` hook itself (as opposed to the store or the guard around it). */
24
+ class HookRefusal extends Error {
25
+ error;
26
+ constructor(error) {
27
+ super('an onConfirm hook refused');
28
+ this.error = error;
29
+ }
30
+ }
31
+ import { authenticateWindowSenders, openGroupSnapshot, snapshotHistory } from './group-snapshot.js';
32
+ import { engineSeams, MARMOT_CONVERGENCE_POLICY } from './client-config.js';
33
+ import { MARMOT_HIDDEN_CREDIT_POLICY } from '../history/policy.js';
34
+ const CIPHERSUITE_NAME_BY_ID = new Map(Object.entries(ciphersuites).map(([name, id]) => [id, name]));
35
+ function ciphersuiteNameFor(id) {
36
+ const name = CIPHERSUITE_NAME_BY_ID.get(id);
37
+ if (name === undefined)
38
+ throw new MarmotError('store-failed', `unknown MLS ciphersuite id ${id}`, { details: { ciphersuite: id, malformed: true } });
39
+ return name;
40
+ }
41
+ function hex(bytes) {
42
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
43
+ }
44
+ /** Every leaf of `account` in `state`: its leaf index and signature key (hex). */
45
+ export function leafInfosOf(state, account) {
46
+ const indexes = getPubkeyLeafNodeIndexes(state, account);
47
+ const nodes = getPubkeyLeafNodes(state, account);
48
+ return indexes.map((leafIndex, i) => Object.freeze({ leafIndex, leafKey: hex(nodes[i].signaturePublicKey) }));
49
+ }
50
+ // ---------------------------------------------------------------------------
51
+ // GroupRuntime — the type `pipeline.ts` and `ingest.ts` operate on.
52
+ // ---------------------------------------------------------------------------
53
+ class SerialQueue {
54
+ #tail = Promise.resolve();
55
+ run(task) {
56
+ const result = this.#tail.then(task, task);
57
+ this.#tail = result.catch(() => undefined);
58
+ return result;
59
+ }
60
+ }
61
+ async function ciphersuiteImplFor(cache, suiteId) {
62
+ let pending = cache.get(suiteId);
63
+ if (pending === undefined) {
64
+ pending = getCiphersuiteImpl(ciphersuiteNameFor(suiteId), defaultCryptoProvider);
65
+ cache.set(suiteId, pending);
66
+ }
67
+ return pending;
68
+ }
69
+ /** The seams a client's engines are built with: marmot's, as the (internal, test-only) override rewrites them. */
70
+ function effectiveSeams(ctx, ratchetTree) {
71
+ const marmotSeams = engineSeams(ratchetTree);
72
+ return ctx.engineSeamsOverride === undefined ? marmotSeams : ctx.engineSeamsOverride(marmotSeams);
73
+ }
74
+ /** A fresh copy of a state: never hand one `ClientState` object to two owners (ts-mls mutates some in place). */
75
+ function copyOf(state) {
76
+ return deserializeClientState(serializeClientState(state));
77
+ }
78
+ /** The "leaver is an active admin" predicate this client's engines run (the engine default when the seam is cleared). */
79
+ function leaverPredicateOf(ctx, state) {
80
+ return effectiveSeams(ctx, () => state.ratchetTree).isActiveAdminLeaver ?? isAdminAccountLeaver;
81
+ }
82
+ async function buildEngine(ctx, ciphersuiteCache, state, onSettleCheck, history, removal, opaque) {
83
+ const impl = await ciphersuiteImplFor(ciphersuiteCache, state.groupContext.cipherSuite);
84
+ const peeler = {
85
+ async peelGroupMessages(envelopes, s) {
86
+ const { read, unreadable } = await decryptGroupMessages(envelopes, s, impl);
87
+ return { read: read.map(({ event, message }) => ({ envelope: event, message })), unreadable };
88
+ },
89
+ wrapGroupMessage: (message, s) => createGroupEvent({ message, state: s, ciphersuite: impl }),
90
+ idOf: (e) => e.id,
91
+ };
92
+ // S8/S9: the marmot seams (client-config.ts) — ADR-012's proof gate around the same-account and
93
+ // admin receive rules, the admin + same-account `authorizeCommit` over this engine's current tree,
94
+ // the admin-leaver auto-commit predicate, and the signature-key-only equality `clientConfig`. A
95
+ // seam an (internal, test-only) override clears is the engine's own default.
96
+ let engine;
97
+ const seams = effectiveSeams(ctx, () => (engine === undefined ? state.ratchetTree : engine.state.ratchetTree));
98
+ engine = new MarmotGroupEngine({
99
+ state,
100
+ ciphersuite: impl,
101
+ peeler,
102
+ ...(seams.adminPolicyCallback === undefined ? {} : { adminPolicyCallback: seams.adminPolicyCallback }),
103
+ ...(seams.authorizeCommit === undefined ? {} : { authorizeCommit: seams.authorizeCommit }),
104
+ ...(seams.isActiveAdminLeaver === undefined ? {} : { isActiveAdminLeaver: seams.isActiveAdminLeaver }),
105
+ clientConfig: seams.clientConfig,
106
+ // S10: structural branch selection only — see MARMOT_CONVERGENCE_POLICY.
107
+ convergencePolicy: MARMOT_CONVERGENCE_POLICY,
108
+ scheduler: {
109
+ setTimer: (ms, cb) => ctx.timers.set(cb, ms),
110
+ clearTimer: (handle) => ctx.timers.clear(handle),
111
+ },
112
+ now: () => ctx.clock.now(),
113
+ // The engine retains input that arrives after a convergence deadline and releases it only through
114
+ // driveConvergence(); without this continuation that input would never be processed.
115
+ onSettleCheck,
116
+ // S10: the persisted rewind window — without it a rebuilt engine has no retained root below its tip, and a
117
+ // sibling of an already applied commit is skipped as beyond-anchor instead of converging (same-epoch fork).
118
+ ...(history === undefined ? {} : { retained: history.retained, historyTree: history.historyTree }),
119
+ // S20: a removal of the local leaf is a fork-recovery candidate like any branch, and stays revisable (its
120
+ // input fork material, never self-evicted) until the client settles it (client/group-removal.ts).
121
+ removalConvergence: true,
122
+ // ADR-016: at a node where one leaf authored two child commits (a restored stale leaf snapshot), only depth
123
+ // built by other leaves that were members there counts; ties keep the structural ordering above.
124
+ equivocationCredit: true,
125
+ // ADR-016 D6 (Accepted — in force; owner sign-off OQ-2 pending): a commit by this device's own leaf that it cannot
126
+ // open (a restored or cloned snapshot) is an opaque candidate, scored at its best case against the processable
127
+ // branches; the device fences only when that branch could win (client/opaque-candidates.ts persists the held
128
+ // candidates). The ONE opt-in site: inert unless `equivocationCredit` is on. The policy is one constant
129
+ // (history/policy.ts, OQ-1).
130
+ branchAwareFence: true,
131
+ hiddenCreditPolicy: MARMOT_HIDDEN_CREDIT_POLICY,
132
+ // ADR-017 (epic marmot-removal-finality): a removal is decisive at the node where it races a branch that keeps the
133
+ // removed leaf — that leaf's later commits there earn nothing, and a tie prefers the removal — within the rewind
134
+ // horizon of every candidate through the node. Inert unless `equivocationCredit` is on; the ONE opt-in site.
135
+ removalFinality: true,
136
+ // Internal, tests only: extra engine options (a test chooses the other hidden-credit policy here; never the
137
+ // opt-in, which is the literal above). Before `removal` and `opaque`, which are never overridden.
138
+ ...(ctx.engineOptionsForTest ?? {}),
139
+ ...(removal === undefined ? {} : { removal }),
140
+ // The held opaque candidates and `U` (client/opaque-candidates.ts): a rebuilt engine decides like the one it
141
+ // replaces. The engine ignores the record unless its opaque seam is on, so this is inert while the seam is off.
142
+ ...(opaque === undefined ? {} : { opaque }),
143
+ });
144
+ return engine;
145
+ }
146
+ /**
147
+ * {@link buildEngine} over a persisted opaque record, FAILING CLOSED (client/opaque-candidates.ts): a record the
148
+ * engine refuses (it throws `OpaqueRecordInvalid`, and only that, for one of another history, e.g. a candidate whose epoch disagrees with the
149
+ * node it names) is corrupt. The engine is then built WITHOUT it and `corrupt` carries the verdict the caller turns
150
+ * into a fence — never an engine that silently forgot a held candidate while the group goes on processing.
151
+ */
152
+ async function buildEngineFailClosed(ctx, ciphersuiteCache, state, onSettleCheck, history, removal, opaque) {
153
+ try {
154
+ return { engine: await buildEngine(ctx, ciphersuiteCache, state, onSettleCheck, history, removal, opaque) };
155
+ }
156
+ catch (error) {
157
+ if (opaque === undefined || !(error instanceof OpaqueRecordInvalid))
158
+ throw error;
159
+ return { engine: await buildEngine(ctx, ciphersuiteCache, state, onSettleCheck, history, removal), corrupt: new OpaqueRecordCorrupt(error.message) };
160
+ }
161
+ }
162
+ /** The stored opaque record: `undefined` when none is held; a corrupt one is reported, never thrown (the caller fences). */
163
+ async function loadOpaque(guard, groupId, groupStore) {
164
+ try {
165
+ const record = await guard.call(groupId, 'store', () => readOpaque(groupStore.extension(OPAQUE_EXTENSION)));
166
+ return { record: isEmptyOpaque(record) ? undefined : record };
167
+ }
168
+ catch (error) {
169
+ if (error instanceof OpaqueRecordCorrupt)
170
+ return { record: undefined, corrupt: error };
171
+ // A payload that does not decode (truncated bytes) is the same corruption as a malformed record: fail closed, never
172
+ // a failed load. A stamp of another build (`version`) stays what it was: the store's own incompatibility path.
173
+ if (isMarmotError(error, 'envelope-mismatch') && error.details?.reason === 'malformed')
174
+ return { record: undefined, corrupt: new OpaqueRecordCorrupt(`stored payload does not decode (${error.message})`) };
175
+ throw error;
176
+ }
177
+ }
178
+ export function createGroupRegistry(ctx, guard, invitations, teardown) {
179
+ const runtimes = new Map();
180
+ // Stryker disable next-line all: test seam (InternalClientOptions.exposeRuntimesForTest)
181
+ ctx.exposeRuntimesForTest?.((groupId) => runtimes.get(groupId));
182
+ const loading = new Map();
183
+ /** S9: groups purged by a teardown in this client's lifetime — never loaded again (unless re-joined). */
184
+ const abandoned = new Set();
185
+ /** S9: listeners of each group's exposed-state changes (the teardown driver's wake-up). */
186
+ const stateWatchers = new Map();
187
+ /** S10 (V1): the device port's rewind listeners (`DeviceGroupPort.onRewind`). */
188
+ const rewindListeners = new Set();
189
+ /** Epic marmot-device-key-rotation (S6): the device port's rotation listeners (`DeviceGroupPort.onRotation`). */
190
+ const rotationListeners = new Set();
191
+ /** Owner decision 13: the device port's restore listeners (`DeviceGroupPort.onRestored`). */
192
+ const restoredListeners = new Set();
193
+ function announceTo(listeners, groupId) {
194
+ for (const listener of [...listeners]) {
195
+ // A later macrotask: outside the group's queue (the listener may run group operations) and every frame.
196
+ ctx.timers.set(() => {
197
+ if (ctx.isDisposed())
198
+ return;
199
+ guard.detached(() => {
200
+ try {
201
+ listener(groupId);
202
+ }
203
+ catch {
204
+ // A listener never breaks the operation that persisted the transition.
205
+ }
206
+ });
207
+ }, 0);
208
+ }
209
+ }
210
+ function announceRewind(groupId) {
211
+ announceTo(rewindListeners, groupId);
212
+ }
213
+ function announceRotation(groupId) {
214
+ announceTo(rotationListeners, groupId);
215
+ }
216
+ function notifyState(groupId) {
217
+ for (const listener of [...(stateWatchers.get(groupId) ?? [])]) {
218
+ try {
219
+ listener();
220
+ }
221
+ catch {
222
+ // A watcher never breaks the operation that changed the state.
223
+ }
224
+ }
225
+ }
226
+ /** Listens to `groupId`'s exposed-state changes (see {@link notifyState}); returns the unregister function. */
227
+ function watchState(groupId, listener) {
228
+ let set = stateWatchers.get(groupId);
229
+ if (set === undefined)
230
+ stateWatchers.set(groupId, (set = new Set()));
231
+ set.add(listener);
232
+ return () => {
233
+ const current = stateWatchers.get(groupId);
234
+ current?.delete(listener);
235
+ if (current?.size === 0)
236
+ stateWatchers.delete(groupId);
237
+ };
238
+ }
239
+ /** Fires (once) and clears the runtime's terminal watchers (GroupRuntime.terminalWatchers). Never throws. */
240
+ function endRuntime(rt, end) {
241
+ const watchers = [...rt.terminalWatchers];
242
+ rt.terminalWatchers.clear();
243
+ for (const watcher of watchers) {
244
+ try {
245
+ watcher(end);
246
+ }
247
+ catch {
248
+ // A watcher never breaks the operation that ended the runtime.
249
+ }
250
+ }
251
+ }
252
+ /** The engine's settle-check: releases convergence-retained input on the group's queue. */
253
+ function settleCheck(groupId) {
254
+ const rt = runtimes.get(groupId);
255
+ if (rt === undefined || rt.disposed || ctx.isDisposed())
256
+ return;
257
+ rt.run('converge', (rtc) => drainConvergence(rtc))
258
+ // The engine's quiescence window ended: a `competing` Welcome waiting on `syncing` is decided next (AC-FWJ-31).
259
+ .then(() => gateMayHaveCleared(groupId))
260
+ .catch(() => {
261
+ if (!rt.disposed && !ctx.isDisposed())
262
+ requestHistoryResync(rt);
263
+ });
264
+ }
265
+ const confirmHooks = [];
266
+ /** AC-MX-2: groups being restored — by `groups.restore`, or resumed after an earlier client left them unfinished. */
267
+ const restoring = new Map();
268
+ /**
269
+ * AC-MX-2: resolves when the client is disposed. A failed restore's take-back races it: the take-back queues
270
+ * behind the group's in-flight operation (which may never end: a publish to a relay that never answers), and a
271
+ * disposed client must not hold the restore — or its reservation — on that.
272
+ */
273
+ let markClientDisposed;
274
+ const clientDisposed = new Promise((resolve) => (markClientDisposed = resolve));
275
+ /**
276
+ * AC-MX-2: reserves `groupId` for a restore (a `groups.restore` call, or a resumed unfinished one) — synchronously,
277
+ * so a second restore, a load or a Welcome adoption of the group from here on joins or refuses it.
278
+ */
279
+ function reserveRestore(groupId) {
280
+ let resolveSettled;
281
+ let rejectEnded;
282
+ let resolveDone;
283
+ /** Rejects once the restore can no longer succeed (dispose, a purge; once the runtime exists, its terminal signal). */
284
+ const ended = new Promise((_resolve, reject) => (rejectEnded = reject));
285
+ ended.catch(() => undefined);
286
+ const end = (error) => {
287
+ entry.endError ??= error;
288
+ rejectEnded(error);
289
+ };
290
+ const settle = (rt) => {
291
+ if (rt === undefined)
292
+ entry.ending = true;
293
+ else if (typeof rt.then === 'function')
294
+ void Promise.resolve(rt).then((v) => void (v === undefined && (entry.ending = true)), () => undefined);
295
+ resolveSettled(rt);
296
+ };
297
+ const entry = {
298
+ settled: new Promise((resolve) => (resolveSettled = resolve)),
299
+ done: new Promise((resolve) => (resolveDone = resolve)),
300
+ ending: false,
301
+ checkingPurge: false,
302
+ endError: undefined,
303
+ runtime: undefined,
304
+ abort: () => end(restoreEndError(groupId, { reason: 'disposed' })),
305
+ retire: () => end(restoreEndError(groupId, { reason: 'retired' })),
306
+ };
307
+ restoreDone.set(entry, resolveDone);
308
+ restoring.set(groupId, entry);
309
+ return { entry, settle, end, ended };
310
+ }
311
+ /** Each reservation's `done` resolver (called by {@link releaseRestore}). */
312
+ const restoreDone = new WeakMap();
313
+ /** Throws once `entry`'s restore was ended (a purge, dispose) — for the steps that do not race `ended`. */
314
+ function assertNotEnded(entry) {
315
+ if (entry.endError !== undefined)
316
+ throw entry.endError;
317
+ }
318
+ /** Purges of this registry in flight, by group (`teardownPort.purge`). */
319
+ const purgesInFlight = new Map();
320
+ /**
321
+ * Purges of this registry ever started, by group — bumped synchronously as a purge starts, so a check that awaits
322
+ * (the restore's watermark read) sees a purge that both started and finished meanwhile.
323
+ */
324
+ const purgeGenerations = new Map();
325
+ /**
326
+ * AC-MX-2: ends `groupId`'s restore reservation (a purge: it rejects `not-a-member`) and waits until it was
327
+ * released — its runtime retired as the last operation on its queue, so nothing it runs writes the group after
328
+ * the purge; the adoption is not cleared by the restore (the purge does it). Repeated for a reservation taken
329
+ * meanwhile. A reservation in its pre-adoption purge check (`checkingPurge`) is left alone: it waits for this
330
+ * purge itself. Returns the runtime the ended restore built, if any.
331
+ */
332
+ async function endRestoresForPurge(groupId) {
333
+ let built;
334
+ for (let entry = restoring.get(groupId); entry !== undefined && !entry.checkingPurge; entry = restoring.get(groupId)) {
335
+ entry.retire();
336
+ await entry.done;
337
+ built = entry.runtime ?? built;
338
+ if (restoring.get(groupId) === entry)
339
+ break;
340
+ }
341
+ return built;
342
+ }
343
+ /**
344
+ * Group stores this client already opened, by id: the unfinished-restore mark is read by listings and scans
345
+ * (AC-MX-2) before a load of the same group — each `groupFactory` yield is a store open (and an `onIncompatible`
346
+ * subscription), so the load reuses the one the read opened. Dropped when a purge clears the group.
347
+ */
348
+ const openedStores = new Map();
349
+ /**
350
+ * AC-MX-2: groups this client left marked unfinished (a resume or take-back that failed before it could clear the
351
+ * mark, a mark the scan could not read) — the only ones a later `resumeUnfinishedRestores` call re-reads.
352
+ */
353
+ const leftMarked = new Set();
354
+ /** AC-MX-2: restore records (group-records.ts `RESTORING_EXTENSION`) the scan could not settle — re-read likewise. */
355
+ const leftRecords = new Set();
356
+ /** Whether the creation-time scan read the whole group index; the scan in flight, if any. */
357
+ let indexScanned = false;
358
+ let resumeScan;
359
+ function groupStoreOf(groupId) {
360
+ let store = openedStores.get(groupId);
361
+ if (store === undefined)
362
+ openedStores.set(groupId, (store = ctx.stores.groupFactory(groupId)));
363
+ return store;
364
+ }
365
+ /** AC-MX-2: whether `groupId` carries the unfinished-restore mark (group-records.ts `RESTORE_PENDING_EXTENSION`). */
366
+ function restorePending(groupId, groupStore) {
367
+ return guard.call(groupId, 'store', () => readRestorePending(groupStore.extension(RESTORE_PENDING_EXTENSION)));
368
+ }
369
+ /**
370
+ * AC-MX-2: whether `groupId` is an unfinished restore an earlier client left (marked, not restoring here) — which
371
+ * is then resumed ({@link resumeRestore}). For the listings that skip a restoring group instead of waiting on it.
372
+ */
373
+ async function unfinishedRestore(groupId) {
374
+ if (restoring.has(groupId))
375
+ return true;
376
+ const cached = runtimes.get(groupId);
377
+ if (cached !== undefined && !cached.disposed)
378
+ return false;
379
+ if (!(await restorePending(groupId, groupStoreOf(groupId))))
380
+ return false;
381
+ resumeRestore(groupId);
382
+ return true;
383
+ }
384
+ /**
385
+ * Takes a restore's adoption back: the reverse of the order the adoption wrote it in, with the account restore
386
+ * record (group-records.ts `RESTORING_EXTENSION`) as the durable cleanup marker until both deletions are done —
387
+ * three separate transactions, account → group → account (never nested: group → account is the lock order):
388
+ * the record (re-)written, the group's stores cleared, then its index entry and the record deleted together. Every
389
+ * crash or failure point stays discoverable: before the clear the group is still marked (the scan resumes it);
390
+ * after it the record names an empty group store, whose index entry the scan deletes ({@link settleRestoringRecord}).
391
+ * Never continued once the client is disposed (its stores may belong to a new client by then).
392
+ */
393
+ async function clearAdoptedGroup(groupId, groupStore) {
394
+ const assertLive = () => {
395
+ if (ctx.isDisposed())
396
+ throw new MarmotError('disposed', 'groups.restore: client was disposed while taking a failed restore back');
397
+ };
398
+ await guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction((tx) => writeRestoringRecord(tx.extension(RESTORING_EXTENSION), groupId, ctx.clock.now())));
399
+ assertLive();
400
+ await guard.call(groupId, 'store', () => groupStore.clear());
401
+ assertLive();
402
+ await guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction(async (tx) => {
403
+ await tx.extension(GROUP_INDEX_EXTENSION).delete(groupId);
404
+ await clearRestoringRecord(tx.extension(RESTORING_EXTENSION), groupId);
405
+ }));
406
+ }
407
+ /**
408
+ * AC-MX-2: settles `groupId`'s restore record (group-records.ts `RESTORING_EXTENSION`) an adoption left — the
409
+ * startup scan's walk of the adoptions the group index may not name. A marked group is resumed like any
410
+ * unfinished restore ({@link resumeRestore}: one with no index entry never finished its adoption and is discarded,
411
+ * its group store wiped, then the record). An unmarked one holds nothing the adoption wrote (a crash before its
412
+ * group write, or an adoption refused `already-member`): only the record is dropped — never while this client
413
+ * restores the group itself (checked inside the account transaction its own record write queues behind). An
414
+ * unmarked group store that holds no state either (a take-back interrupted after its clear, `clearAdoptedGroup`)
415
+ * loses its index entry with the record: that entry names a group nothing holds. Decided inside a group
416
+ * transaction that awaits the account one (group → account, the lock order): a Welcome adoption writing the
417
+ * group's state meanwhile is serialized with it, so an entry a fresh state was written for is never deleted.
418
+ */
419
+ async function settleRestoringRecord(groupId) {
420
+ if (await unfinishedRestore(groupId)) {
421
+ // A record a take-back wrote before its clear outlives the resume it led to: settled again once that released
422
+ // the group (held: only the record goes; discarded: the take-back deleted it already).
423
+ void restoring.get(groupId)?.done.then(() => void (ctx.isDisposed() || abandoned.has(groupId) || leftRecords.add(groupId)));
424
+ return;
425
+ }
426
+ const groupStore = groupStoreOf(groupId);
427
+ await guard.call(groupId, 'store', () => groupStore.transaction(async (gtx) => {
428
+ const empty = !(await hasGroupState(gtx.artifact('clientState'))) && !(await readRestorePending(gtx.extension(RESTORE_PENDING_EXTENSION)));
429
+ await guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction(async (tx) => {
430
+ if (restoring.has(groupId))
431
+ return;
432
+ if (empty)
433
+ await tx.extension(GROUP_INDEX_EXTENSION).delete(groupId);
434
+ await clearRestoringRecord(tx.extension(RESTORING_EXTENSION), groupId);
435
+ }));
436
+ }));
437
+ }
438
+ /** AC-MX-2: restoring groups a Welcome adoption was deferred for — their release asks for an inbox pass. */
439
+ const deferredAdoptions = new Set();
440
+ let restoreReleased;
441
+ /** Ends `groupId`'s restore reservation `entry` (never a later one); a Welcome adoption it deferred is retried by an inbox pass at once. */
442
+ function releaseRestore(groupId, entry) {
443
+ restoreDone.get(entry)?.();
444
+ if (restoring.get(groupId) !== entry)
445
+ return;
446
+ restoring.delete(groupId);
447
+ // A `competing` Welcome waiting for the restore to end is decided by the next inbox pass (AC-FWJ-31).
448
+ gateMayHaveCleared(groupId);
449
+ if (!deferredAdoptions.delete(groupId) || ctx.isDisposed())
450
+ return;
451
+ const listener = restoreReleased;
452
+ if (listener !== undefined)
453
+ guard.detached(() => listener(groupId));
454
+ }
455
+ /**
456
+ * AC-MX-2: a Welcome adoption of a group being restored is deferred, never waited out — it runs on the inbox
457
+ * queue, and a restore stuck on unreachable group relays would freeze every other wrap behind it. Transient
458
+ * (`retryable`, never counted toward the maintenance failure cap): the invitation stays `joining` and the
459
+ * restore's release asks for the inbox pass that completes it.
460
+ */
461
+ function restoreInFlight(groupId) {
462
+ deferredAdoptions.add(groupId);
463
+ return new MarmotError('commit-pending', `invitations: group ${groupId} is being restored; its Welcome is joined once the restore settled`, {
464
+ details: { groupId, reason: 'restore-in-flight', retryable: true },
465
+ });
466
+ }
467
+ const ciphersuiteCache = new Map();
468
+ /**
469
+ * `MarmotGroup.invite`'s queue-and-deliver body, shared with `devicePort.addDevice` (S4): the public handle
470
+ * never passes `reopenedLeafKey` — only `addDevice` does, re-driving a reopened approval (enrolment.ts).
471
+ * Carries `invite()`'s own liveness and re-entrancy checks so bypassing the public handle here (to reach this
472
+ * optional third parameter, which `MarmotGroup.invite`'s public signature does not carry) does not drop them.
473
+ */
474
+ async function inviteAndDeliver(rt, keyPackages, reopenedLeafKey, approvalEpoch, origin) {
475
+ if (rt.abandoned && !ctx.isDisposed())
476
+ throw new MarmotError('not-a-member', `MarmotGroup: group ${rt.groupId} was left or abandoned`, { details: { groupId: rt.groupId } });
477
+ if (rt.disposed || ctx.isDisposed())
478
+ throw new MarmotError('disposed', 'MarmotGroup: client has been disposed');
479
+ // The Welcome deliveries below wait on account-scope surfaces: called from inside one, they would queue behind it.
480
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'invite');
481
+ const commit = await rt.run('invite', (rtc) => inviteIntent(rtc, keyPackages, reopenedLeafKey, approvalEpoch, origin));
482
+ const outcomes = await invitations.deliver(rt.groupId, commit.inviteId);
483
+ // No record yet (the handoff is blocked with the confirmation and retried with it): not attempted.
484
+ return Object.freeze(commit.invitees.map((invitee) => outcomes.find((o) => o.inviteeRef === invitee.inviteeRef) ?? toWelcomeOutcome({ ...invitee, status: 'pending', reason: 'awaiting-confirmation' })));
485
+ }
486
+ function buildHandle(rt) {
487
+ function assertLive() {
488
+ if (rt.abandoned && !ctx.isDisposed())
489
+ throw new MarmotError('not-a-member', `MarmotGroup: group ${rt.groupId} was left or abandoned`, { details: { groupId: rt.groupId } });
490
+ if (rt.disposed || ctx.isDisposed())
491
+ throw new MarmotError('disposed', 'MarmotGroup: client has been disposed');
492
+ }
493
+ function accountArg(member, account) {
494
+ if (typeof account !== 'string')
495
+ throw new MarmotError('invalid-options', `MarmotGroup.${member}: account must be a pubkey string`);
496
+ return account;
497
+ }
498
+ /** The teardown operations: account-scope records, so refused from inside an account- or group-scope surface. */
499
+ function teardownOp(operation, run) {
500
+ try {
501
+ assertLive();
502
+ guard.assertNotReentrant(ACCOUNT_SCOPE, operation);
503
+ guard.assertNotReentrant(rt.groupId, operation);
504
+ }
505
+ catch (error) {
506
+ return Promise.reject(error);
507
+ }
508
+ return run(teardown());
509
+ }
510
+ function view() {
511
+ const v = getMarmotGroupView(rt.exposedState);
512
+ if (v === null)
513
+ throw new MarmotError('store-failed', `group ${rt.groupId}: state carries no Marmot group view`, { details: { groupId: rt.groupId, malformed: true } });
514
+ return v;
515
+ }
516
+ return {
517
+ get id() {
518
+ assertLive();
519
+ return rt.groupId;
520
+ },
521
+ get nostrGroupId() {
522
+ assertLive();
523
+ return getNostrGroupIdHex(rt.exposedState);
524
+ },
525
+ get name() {
526
+ assertLive();
527
+ return view().name;
528
+ },
529
+ get description() {
530
+ assertLive();
531
+ return view().description;
532
+ },
533
+ get admins() {
534
+ assertLive();
535
+ return Object.freeze([...view().adminPubkeys]);
536
+ },
537
+ get relays() {
538
+ assertLive();
539
+ return Object.freeze([...view().relays]);
540
+ },
541
+ get epoch() {
542
+ assertLive();
543
+ return rt.exposedState.groupContext.epoch;
544
+ },
545
+ get disbanded() {
546
+ assertLive();
547
+ return rt.disbanded === undefined ? undefined : groupDisbandedOf(rt.disbanded);
548
+ },
549
+ async send(intent) {
550
+ assertLive();
551
+ const outcome = await rt.run('send', (rtc) => sendIntent(rtc, intent));
552
+ // A queued rumor (AC-INVITE-3) is awaited here, off the group's queue: the commit it waits for runs on it.
553
+ if (outcome.queued !== undefined)
554
+ await outcome.queued;
555
+ },
556
+ ingest(events) {
557
+ assertLive();
558
+ return rt.run('ingest', (rtc) => ingestEvents(rtc, events));
559
+ },
560
+ async synced() {
561
+ assertLive();
562
+ if (rt.fence !== undefined)
563
+ throw fencedError(rt.groupId, 'synced', rt.fence);
564
+ if (rt.disbanded !== undefined)
565
+ throw disbandedError(rt.groupId, 'synced', rt.disbanded);
566
+ if (rt.sendGateOpen)
567
+ return;
568
+ // ADR-013: awaited from inside a consumer surface of this group (a verifier, onProposal, a store call of the
569
+ // very ingest that would open the gate), the wait could never end — rejected `reentrant` instead.
570
+ guard.assertNotReentrant(rt.groupId, 'synced');
571
+ await new Promise((resolve, reject) => rt.syncWaiters.add({ resolve, reject }));
572
+ },
573
+ async pendingIntents() {
574
+ assertLive();
575
+ // Direct read, deliberately NOT serialised behind the group's op
576
+ // queue: AC-PIPE-1 observes the resumed record's state WHILE (not
577
+ // after) the fire-and-forget `resumePending` op set up by
578
+ // `groups.get` may still be running.
579
+ const records = await guard.call(rt.groupId, 'store', () => listPendingIntentSummaries(rt.groupStore.artifact('pendingIntents')));
580
+ // Queued rumors (AC-INVITE-3) come after every recorded intent: they go out only after them.
581
+ const queued = await guard.call(rt.groupId, 'store', () => listQueuedRumorRecords(rt.groupStore.artifact('queuedRumors')));
582
+ return [...records, ...queued.map((q) => ({ intentId: q.queueId, state: 'queued', kind: 'application' }))];
583
+ },
584
+ members() {
585
+ assertLive();
586
+ return Object.freeze(getGroupMemberPubkeys(rt.exposedState));
587
+ },
588
+ // AC-DEV-8: accounts, not leaves (ADR-003) — `members()` already lists each account once.
589
+ memberCount() {
590
+ assertLive();
591
+ return getGroupMemberPubkeys(rt.exposedState).length;
592
+ },
593
+ // AC-DEV-1: every leaf `account` holds, in leaf order, with its signature key (the device registry's `leafKey`).
594
+ leaves(account) {
595
+ assertLive();
596
+ if (typeof account !== 'string')
597
+ throw new MarmotError('invalid-options', 'MarmotGroup.leaves: account must be a pubkey string');
598
+ return Object.freeze(leafInfosOf(rt.exposedState, account));
599
+ },
600
+ invite(keyPackages) {
601
+ return inviteAndDeliver(rt, keyPackages);
602
+ },
603
+ async retryWelcome(inviteeRef) {
604
+ assertLive();
605
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'retryWelcome');
606
+ return invitations.retry(rt.groupId, inviteeRef);
607
+ },
608
+ // AC-ADMIN-2 / AC-ADMIN-8: the same functions the engine seams evaluate (account/admin.ts).
609
+ activeAdmins() {
610
+ assertLive();
611
+ return Object.freeze(activeAdmins(rt.exposedState.ratchetTree, view().adminPubkeys));
612
+ },
613
+ isActiveAdmin(account) {
614
+ assertLive();
615
+ return isActiveAdmin(rt.exposedState.ratchetTree, view().adminPubkeys, accountArg('isActiveAdmin', account));
616
+ },
617
+ isLastActiveAdmin(account) {
618
+ assertLive();
619
+ return isLastActiveAdmin(rt.exposedState.ratchetTree, view().adminPubkeys, accountArg('isLastActiveAdmin', account));
620
+ },
621
+ async setAdmins(accounts) {
622
+ assertLive();
623
+ await rt.run('setAdmins', (rtc) => setAdminsIntent(rtc, accounts));
624
+ },
625
+ async rename(name, options) {
626
+ assertLive();
627
+ await rt.run('rename', (rtc) => renameIntent(rtc, name, options));
628
+ },
629
+ async removeMember(account) {
630
+ assertLive();
631
+ await rt.run('removeMember', (rtc) => removeMemberIntent(rtc, account));
632
+ },
633
+ departAsAdmin() {
634
+ return teardownOp('departAsAdmin', (t) => t.depart(rt.groupId));
635
+ },
636
+ leave() {
637
+ return teardownOp('leave', (t) => t.leave(rt.groupId));
638
+ },
639
+ abandon() {
640
+ return teardownOp('abandon', (t) => t.abandon(rt.groupId));
641
+ },
642
+ destroy() {
643
+ return teardownOp('destroy', (t) => t.destroy(rt.groupId));
644
+ },
645
+ encryptMedia(bytes, options) {
646
+ assertLive();
647
+ return encryptMediaOp(rt, bytes, options);
648
+ },
649
+ decryptMedia(media) {
650
+ assertLive();
651
+ return decryptMediaOp(rt, media);
652
+ },
653
+ history() {
654
+ assertLive();
655
+ assertNotInHistoryBackend(rt);
656
+ return historyOf(rt);
657
+ },
658
+ onNotification(listener) {
659
+ assertLive();
660
+ return subscribeNotifications(rt, listener);
661
+ },
662
+ async equivocations() {
663
+ assertLive();
664
+ // Like pendingIntents(): a direct read of the durable records, not queued behind the group's operations.
665
+ return guard.call(rt.groupId, 'store', () => readEquivocationNotifications(rt.groupStore.extension(EQUIVOCATION_EXTENSION)));
666
+ },
667
+ };
668
+ }
669
+ function makeRuntime(groupId, groupStore, engine, joinedAtMs, persisted = {}) {
670
+ let exposed = engine.state;
671
+ let fence = persisted.fence;
672
+ const rt = {
673
+ groupId,
674
+ groupStore,
675
+ engine,
676
+ get exposedState() {
677
+ return exposed;
678
+ },
679
+ set exposedState(state) {
680
+ const changed = state !== exposed;
681
+ exposed = state;
682
+ if (changed)
683
+ notifyState(groupId);
684
+ },
685
+ joinedAtMs,
686
+ resyncNeeded: false,
687
+ resync() {
688
+ requestHistoryResync(rt);
689
+ },
690
+ checkSyncRouting() {
691
+ restartSyncOnRoutingChange(rt);
692
+ },
693
+ ctx,
694
+ guard,
695
+ confirmHooks,
696
+ settledListeners: new Set(),
697
+ terminalWatchers: new Set(),
698
+ disposed: false,
699
+ abandoned: false,
700
+ leaseLost: undefined,
701
+ selfRemoveElection: undefined,
702
+ leaverPredicate: leaverPredicateOf(ctx, engine.state),
703
+ window: persisted.window ?? tipOnlyWindow(engine.state),
704
+ get fence() {
705
+ return fence;
706
+ },
707
+ set fence(cause) {
708
+ const was = fence;
709
+ fence = cause;
710
+ if (was === undefined && cause !== undefined)
711
+ endRuntime(rt, { reason: 'fenced', cause });
712
+ },
713
+ removal: persisted.removal,
714
+ async removalSettled(actor) {
715
+ try {
716
+ if (await teardown().tearingDown(groupId))
717
+ return;
718
+ if (!ctx.isDisposed())
719
+ ctx.emit('groupRemoved', Object.freeze(actor === undefined ? { groupId } : { groupId, actor }));
720
+ }
721
+ catch {
722
+ // Best-effort notification: a failed teardown-record read loses it (documented at-most-once).
723
+ }
724
+ },
725
+ opaque: persisted.opaque,
726
+ pendingCommit: persisted.pendingCommit,
727
+ pendingLeaf: persisted.pendingLeaf,
728
+ disbanded: persisted.disbanded,
729
+ notificationListeners: new Set(),
730
+ announceRewind: () => announceRewind(groupId),
731
+ announceRotation: () => announceRotation(groupId),
732
+ historyDrain: { running: undefined, again: false, stopped: false, inFlight: undefined },
733
+ queue: new SerialQueue(),
734
+ handle: undefined,
735
+ historyTracker: createHistorySilenceTracker(ctx.historySilenceThreshold),
736
+ historyGapsReported: new Set(),
737
+ historyStalls: new Map(),
738
+ walkPasses: 0,
739
+ walkStartedAt: undefined,
740
+ catchUpSince: undefined,
741
+ syncStarted: false,
742
+ caughtUp: false,
743
+ connectivityGeneration: 0,
744
+ // AC-PIPE-15: closed only for state read back from the store (see GroupRuntime.sendGateOpen).
745
+ sendGateOpen: persisted.loaded !== true,
746
+ // AC-RATCH-1: armed for the same loaded state unless its stored skip is still undelivered (see GroupRuntime.ratchetSkipPending).
747
+ ratchetSkipPending: persisted.loaded === true && persisted.ratchetSkipArmed !== false,
748
+ syncWaiters: new Set(),
749
+ syncSubscription: undefined,
750
+ syncRouting: undefined,
751
+ syncHistoryRetryTimer: undefined,
752
+ pipelineTimers: new Set(),
753
+ reenqueueRetryArmed: new Set(),
754
+ run(operation, fn) {
755
+ try {
756
+ guard.assertNotReentrant(groupId, operation);
757
+ }
758
+ catch (err) {
759
+ return Promise.reject(err);
760
+ }
761
+ return rt.queue.run(async () => {
762
+ if (rt.abandoned && !ctx.isDisposed())
763
+ throw new MarmotError('not-a-member', `${operation}: group ${groupId} was left or abandoned`, { details: { groupId } });
764
+ if (rt.disposed || ctx.isDisposed()) {
765
+ throw new MarmotError('disposed', `${operation}: client has been disposed`);
766
+ }
767
+ if (rt.needsReload) {
768
+ await rt.reloadFromDurable();
769
+ rt.needsReload = false;
770
+ }
771
+ return fn(rt);
772
+ });
773
+ },
774
+ runLast(fn) {
775
+ return rt.queue.run(async () => {
776
+ await fn();
777
+ });
778
+ },
779
+ async rebuildEngine(state, window, opaqueFrom) {
780
+ const old = rt.engine;
781
+ // S10: a rebuild restores the durable rewind window (it describes the durable state), unless handed one.
782
+ const stored = window ?? (await guard.call(groupId, 'store', () => readWindow(groupStore.artifact('rewindTree'))));
783
+ // S20: a tombstone state is rebuilt with the removal it stands for (the durable one — the state handed in is a
784
+ // durable state or a batch's starting state, both of which `rt.removal` describes).
785
+ const removal = belongsTo(rt.removal, state) ? rt.removal : undefined;
786
+ const history = restoreHistory(stored, removal === undefined ? state : copyOf(removal.record.parentState));
787
+ const built = await buildEngineFailClosed(ctx, ciphersuiteCache, state, () => settleCheck(groupId), history, removal?.record, opaqueFrom === undefined ? rt.opaque : opaqueFrom.record);
788
+ rt.engine = built.engine;
789
+ rt.window = windowFor(stored, state);
790
+ rt.leaverPredicate = leaverPredicateOf(ctx, state);
791
+ rt.selfRemoveElection = undefined;
792
+ old.dispose();
793
+ // A record the engine refused: the group is fenced (client/opaque-candidates.ts, fail closed).
794
+ if (built.corrupt !== undefined && rt.fence === undefined)
795
+ rt.fence = built.corrupt;
796
+ },
797
+ needsReload: false,
798
+ invitations,
799
+ queueWaiters: new Map(),
800
+ queuedHint: undefined,
801
+ drainScheduled: false,
802
+ drainFailures: 0,
803
+ drainRetryTimer: undefined,
804
+ queueCommitHold: undefined,
805
+ selfRemoveElectionWait: undefined,
806
+ scheduleQueueDrain() {
807
+ const r = rt;
808
+ if (r.queuedHint === 0 || r.drainScheduled || r.disposed || ctx.isDisposed())
809
+ return;
810
+ if (r.drainRetryTimer !== undefined) {
811
+ // A real trigger while a failed drain waits for its backoff: drain now instead.
812
+ ctx.timers.clear(r.drainRetryTimer);
813
+ r.pipelineTimers.delete(r.drainRetryTimer);
814
+ r.drainRetryTimer = undefined;
815
+ }
816
+ r.drainScheduled = true;
817
+ // A later microtask: never inside the caller's own frame or transaction. `Promise.resolve().then(...)`
818
+ // does not clear Node's AsyncLocalStorage context on its own (S3 AC-RE-1) — `guard.detached` does.
819
+ void Promise.resolve()
820
+ .then(() => guard.detached(() => r.run('drainQueue', async (rtc) => {
821
+ r.drainScheduled = false;
822
+ const { commitError } = await advanceQueue(rtc);
823
+ // A commit the drain could not even build or record (a signer or store fault) is retried
824
+ // like a thrown drain. A terminal one is held by holdQueueCommit; an unpublished one is a
825
+ // durable intent whose own retry and confirmation drain the queue again.
826
+ if (commitError !== undefined && !isMarmotError(commitError, 'send-rejected') && !isMarmotError(commitError, 'publish-failed'))
827
+ throw commitError;
828
+ r.drainFailures = 0;
829
+ })))
830
+ .catch((error) => {
831
+ r.drainScheduled = false;
832
+ // The queue is durable, but nothing else may come along to drain it: retried on the
833
+ // capped backoff (like Welcome delivery) until it succeeds, the client is disposed or
834
+ // the stores lose their lease (the next holder drains on load).
835
+ if (isMarmotError(error, 'disposed') || isMarmotError(error, 'no-lease'))
836
+ return;
837
+ r.scheduleQueueDrainRetry();
838
+ });
839
+ },
840
+ scheduleQueueDrainRetry() {
841
+ const r = rt;
842
+ if (r.disposed || ctx.isDisposed() || r.drainRetryTimer !== undefined)
843
+ return;
844
+ r.drainFailures += 1;
845
+ const handle = ctx.timers.set(() => {
846
+ r.pipelineTimers.delete(handle);
847
+ r.drainRetryTimer = undefined;
848
+ r.scheduleQueueDrain();
849
+ }, backoffMs(r.drainFailures));
850
+ r.drainRetryTimer = handle;
851
+ r.pipelineTimers.add(handle);
852
+ },
853
+ async reloadFromDurable() {
854
+ const state = await guard.call(groupId, 'store', () => readGroupState(groupStore.artifact('clientState')));
855
+ if (state === undefined)
856
+ throw new MarmotError('store-failed', `group ${groupId}: persisted clientState is missing`);
857
+ const removal = await guard.call(groupId, 'store', () => readRemoval(groupStore.extension(REMOVAL_EXTENSION)));
858
+ rt.removal = belongsTo(removal, state) ? removal : undefined;
859
+ // The held opaque record, read with the state it describes (the durable one: a rolled-back batch's is gone).
860
+ const opaque = await loadOpaque(guard, groupId, groupStore);
861
+ rt.opaque = opaque.record;
862
+ const pendingRestore = await guard.call(groupId, 'store', () => readPendingRestore(groupStore));
863
+ rt.pendingCommit = pendingRestore.pendingCommit;
864
+ rt.pendingLeaf = pendingRestore.pendingLeaf;
865
+ await rt.rebuildEngine(state);
866
+ if (opaque.corrupt !== undefined && rt.fence === undefined)
867
+ rt.fence = opaque.corrupt;
868
+ rt.exposedState = rt.engine.state;
869
+ rt.checkSyncRouting();
870
+ },
871
+ };
872
+ rt.handle = buildHandle(rt);
873
+ runtimes.set(groupId, rt);
874
+ // AC-FWJ-31: an own intent settling clears "own commit pending"; the first sync's end (the send gate opening)
875
+ // clears "syncing". Both ask whether a `competing` Welcome waits for the group.
876
+ rt.settledListeners.add(() => gateMayHaveCleared(groupId));
877
+ if (!rt.sendGateOpen)
878
+ rt.syncWaiters.add({ resolve: () => gateMayHaveCleared(groupId), reject: () => undefined });
879
+ return rt;
880
+ }
881
+ async function createGroupOp(name, options) {
882
+ // Called from inside a consumer account-store (or signer) call, the nested create would queue an account
883
+ // transaction behind the one awaiting it: reject instead of deadlocking.
884
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'groups.create');
885
+ if (typeof name !== 'string' || name.length === 0)
886
+ throw new MarmotError('invalid-options', 'groups.create: name must be a non-empty string');
887
+ if (options !== undefined && (typeof options !== 'object' || options === null)) {
888
+ throw new MarmotError('invalid-options', 'groups.create: options must be an object');
889
+ }
890
+ const relaysOpt = options?.relays;
891
+ if (relaysOpt !== undefined && (!Array.isArray(relaysOpt) || !relaysOpt.every((r) => typeof r === 'string'))) {
892
+ throw new MarmotError('invalid-options', 'groups.create: options.relays must be an array of relay URLs');
893
+ }
894
+ const adminsOpt = options?.admins;
895
+ if (adminsOpt !== undefined && (!Array.isArray(adminsOpt) || !adminsOpt.every((a) => typeof a === 'string'))) {
896
+ throw new MarmotError('invalid-options', 'groups.create: options.admins must be an array of pubkeys');
897
+ }
898
+ // AC-INBOX-7: before anything else happens — a rejecting gate aborts with its own rejection.
899
+ await ctx.beforeCreateGroup.pass();
900
+ if (ctx.isDisposed())
901
+ throw new MarmotError('disposed', 'groups.create: client has been disposed');
902
+ const selfPubkey = await guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.getPublicKey());
903
+ const impl = await ciphersuiteImplFor(ciphersuiteCache, ciphersuites[DEFAULT_CIPHERSUITE_NAME]);
904
+ const credential = createCredential(selfPubkey);
905
+ // S8: the creator leaf carries this client's device signing key, like every leaf it mints.
906
+ const deviceKey = await ensureDeviceSigningKey((fn) => guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction(fn)), impl, ctx.clock.now());
907
+ const kp = await generateKeyPackage({
908
+ credential,
909
+ ciphersuiteImpl: withDeviceSignatureKey(impl, deviceKey),
910
+ isLastResort: false,
911
+ // A device key that carries its stored proof (after a rotation prepare) reuses it: no kind-450 signer call.
912
+ accountProofSigner: deviceProofSigner(deviceKey, (template) => guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.signEvent(template))),
913
+ });
914
+ const { clientState } = await createSimpleGroup(kp, impl, name, {
915
+ adminPubkeys: [selfPubkey, ...(adminsOpt ?? [])],
916
+ relays: relaysOpt !== undefined ? [...relaysOpt] : [...ctx.relays.defaults],
917
+ });
918
+ const proofFailures = enforceStateProofs(clientState);
919
+ if (proofFailures.length > 0) {
920
+ throw new MarmotError('store-failed', 'groups.create: the created group state failed its own leaf-proof check', {
921
+ details: { failures: proofFailures },
922
+ });
923
+ }
924
+ const groupId = getGroupIdHex(clientState);
925
+ // The group becomes visible (runtime cache, account index) only once it
926
+ // is durable. A concurrent `groups.get/list` for this id meanwhile joins
927
+ // this creation (via `loading`) rather than loading a half-written group.
928
+ // `groupCreated` fires only once both writes committed (AC-INBOX-6).
929
+ const rt = await ctx.lifecycle.afterCommit('groupCreated', async () => {
930
+ let settle;
931
+ const creation = new Promise((resolve) => (settle = resolve));
932
+ loading.set(groupId, creation);
933
+ let created;
934
+ try {
935
+ created = await persistCreatedGroup(groupId, clientState);
936
+ }
937
+ catch (error) {
938
+ settle(undefined);
939
+ throw error;
940
+ }
941
+ finally {
942
+ loading.delete(groupId);
943
+ }
944
+ settle(created);
945
+ startGroupSync(created);
946
+ return created;
947
+ }, () => ({ groupId }));
948
+ return rt.handle;
949
+ }
950
+ /**
951
+ * Writes the new group's state (group scope) — with the `onConfirm` hooks run as `kind: 'create'` inside that
952
+ * same transaction (AC-MX-1: a throw stores nothing and rejects the creation with the hook's error) — then its
953
+ * account index entry (account scope) — sequentially, never an account transaction awaiting a group scope —
954
+ * and only then caches its runtime. A failed index write clears the brand-new group store again (best effort:
955
+ * the state and whatever a hook wrote; an unindexed state is invisible to `groups.list`).
956
+ */
957
+ async function persistCreatedGroup(groupId, clientState) {
958
+ const groupStore = ctx.stores.groupFactory(groupId);
959
+ const createdAt = ctx.clock.now();
960
+ await guard.call(groupId, 'store', () => groupStore.transaction(async (tx) => {
961
+ await writeGroupState(tx.artifact('clientState'), clientState);
962
+ await runConfirmHooks({ groupId, guard, hooks: confirmHooks }, { intentId: groupId, kind: 'create', epoch: clientState.groupContext.epoch, tx, persisted: () => ({ state: clientState, window: tipOnlyWindow(clientState) }), notifications: [], createdAt });
963
+ }));
964
+ try {
965
+ await guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction((tx) => writeGroupIndexEntry(tx.extension(GROUP_INDEX_EXTENSION), groupId, { createdAt })));
966
+ }
967
+ catch (error) {
968
+ await guard.call(groupId, 'store', () => groupStore.clear()).catch(() => undefined);
969
+ throw error;
970
+ }
971
+ if (ctx.isDisposed())
972
+ throw new MarmotError('disposed', 'groups.create: client was disposed while creating the group');
973
+ const engine = await buildEngine(ctx, ciphersuiteCache, clientState, () => settleCheck(groupId));
974
+ if (ctx.isDisposed()) {
975
+ engine.dispose();
976
+ throw new MarmotError('disposed', 'groups.create: client was disposed while creating the group');
977
+ }
978
+ return makeRuntime(groupId, groupStore, engine, createdAt);
979
+ }
980
+ /**
981
+ * S6 join: the group's state (group scope, re-read inside the transaction —
982
+ * an existing state is never overwritten), then its account index entry
983
+ * stamped `joinedAtMs` — the Welcome's arrival, so a late accept still
984
+ * floors pre-join events at the Welcome's time (account scope: the floor
985
+ * ingest uses for undecryptable pre-join events) — sequentially, group
986
+ * then account, never an account transaction awaiting a group scope. A
987
+ * state already stored without its index entry (a join interrupted between
988
+ * the two writes) gets the entry now and reports `already-member`. Like
989
+ * `groups.create`, the group becomes visible only once durable: a
990
+ * concurrent `groups.get` joins this load.
991
+ */
992
+ async function adoptJoinedGroupOp(groupId, clientState, joinedAtMs, joinEvidence, invitationId, welcomeCreatedAtMs) {
993
+ // AC-MX-2: a restore of this group in flight decides first — it holds the group only once it succeeded; a
994
+ // failed one left nothing, and this Welcome is adopted as usual. Deferred (transient), never awaited: the
995
+ // caller is the inbox queue, and the restore may wait on unreachable group relays indefinitely.
996
+ if (restoring.has(groupId))
997
+ throw restoreInFlight(groupId);
998
+ // S9: a purge a crash (or a failing step) interrupted finishes first — before anything reads the group as
999
+ // held: its still-cached runtime would answer `already-member`, and the purge would then delete the group this
1000
+ // Welcome brings back. Then a group this client tore down comes back only through a Welcome newer than the
1001
+ // state it purged.
1002
+ if (ctx.finishPurgeBeforeJoin)
1003
+ await teardown().finishPurge(groupId);
1004
+ if (await teardown().refusesJoin(groupId, clientState.groupContext.epoch)) {
1005
+ throw new MarmotError('not-a-member', `invitations: group ${groupId} was left or abandoned by this client; this Welcome would bring its old state back`, { details: { groupId } });
1006
+ }
1007
+ const cached = runtimes.get(groupId);
1008
+ if (cached !== undefined && !cached.disposed)
1009
+ return 'already-member';
1010
+ // AC-MX-2: a restore started while the purge check above ran decides, like one in flight before it.
1011
+ if (restoring.has(groupId))
1012
+ throw restoreInFlight(groupId);
1013
+ // AC-MX-2: an unfinished restore an earlier client left is resumed, never replaced (its self-update may be on
1014
+ // the relays already, and only these stores can confirm it): this Welcome is deferred like for one in flight.
1015
+ // Checked before waiting on a load in flight: a load of such a group waits for the resume (never on this queue).
1016
+ if (await restorePending(groupId, groupStoreOf(groupId))) {
1017
+ resumeRestore(groupId);
1018
+ throw restoreInFlight(groupId);
1019
+ }
1020
+ if (restoring.has(groupId))
1021
+ throw restoreInFlight(groupId);
1022
+ if (runtimes.get(groupId)?.disposed === false)
1023
+ return 'already-member';
1024
+ const inFlight = loading.get(groupId);
1025
+ if (inFlight !== undefined) {
1026
+ assertNotWithinOwnLoad(groupId, 'invitations');
1027
+ if ((await inFlight.catch(() => undefined)) !== undefined)
1028
+ return 'already-member';
1029
+ }
1030
+ // AC-MX-2: and one started while the load above was awaited (its adoption must not be overwritten below).
1031
+ if (restoring.has(groupId))
1032
+ throw restoreInFlight(groupId);
1033
+ let settle;
1034
+ const adoption = new Promise((resolve) => (settle = resolve));
1035
+ loading.set(groupId, adoption);
1036
+ // A group this client left or abandoned earlier is joined again by a new Welcome.
1037
+ abandoned.delete(groupId);
1038
+ let rt;
1039
+ let outcome;
1040
+ // S10: the join-time window (the tip alone) — written in the same transaction as the state (below). Its root
1041
+ // carries the join evidence of a tagged Welcome (epic marmot-welcome-race-joiner): the digest of the commit that
1042
+ // produced the joined state and the committer, the held branch's only record of both when a second Welcome competes.
1043
+ const window = tipOnlyWindow(clientState, joinEvidence);
1044
+ try {
1045
+ const groupStore = groupStoreOf(groupId);
1046
+ const wrote = await guard.call(groupId, 'store', () => groupStore.transaction(async (tx) => {
1047
+ if ((await readGroupState(tx.artifact('clientState'))) !== undefined)
1048
+ return false;
1049
+ await writeGroupState(tx.artifact('clientState'), clientState);
1050
+ await writeWindow(tx.artifact('rewindTree'), window);
1051
+ // Owner decision 20 (BACKLOG engine-undecryptable-set-unbounded): the first sync fetches from the Welcome's
1052
+ // time minus the skew allowance, so the group's pre-join history (never decryptable here) neither costs the
1053
+ // fetch nor fills the branch-aware fence's undecryptable set. The Welcome's stamp is the sponsor's claim:
1054
+ // clamped to [arrival - grace, arrival] as the rebase path clamps it, so an offline invitee still fetches what
1055
+ // was sent between the Welcome's creation and its arrival, and a forged stamp cannot reach back for ever.
1056
+ // Every later `since` (history pass, live subscribe, resume window) inherits it; a fetch bound only — an
1057
+ // event below it that a relay delivers anyway is still processed.
1058
+ const cursorView = tx.artifact('ingestCursor');
1059
+ if ((await readIngestCursor(cursorView)) === undefined) {
1060
+ const welcomeMs = welcomeCreatedAtMs !== undefined && Number.isFinite(welcomeCreatedAtMs) ? welcomeCreatedAtMs : joinedAtMs;
1061
+ const floorMs = Math.min(joinedAtMs, Math.max(welcomeMs, joinedAtMs - ctx.graceWindowMs));
1062
+ await writeIngestCursor(cursorView, { since: Math.max(0, Math.floor(floorMs / 1000) - CURSOR_FUTURE_SKEW_S) });
1063
+ }
1064
+ // Epic marmot-leaf-backup-pre-publish S2: what an earlier state of this group parked or marked belongs to that state.
1065
+ await clearPendingLeaf(tx.extension(PENDING_LEAF_EXTENSION));
1066
+ await clearPendingCommit(tx.extension(PENDING_COMMIT_EXTENSION));
1067
+ // AC-MX-1: only an adoption that writes the group runs the hooks (never `already-member`); a throw
1068
+ // stores nothing — the join stays `joining` and a later inbox pass completes it.
1069
+ await runConfirmHooks({ groupId, guard, hooks: confirmHooks }, { intentId: groupId, kind: 'join', epoch: clientState.groupContext.epoch, tx, persisted: () => ({ state: clientState, window }), notifications: [], createdAt: joinedAtMs });
1070
+ return true;
1071
+ }));
1072
+ outcome = wrote ? 'joined' : 'already-member';
1073
+ try {
1074
+ await guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction(async (tx) => {
1075
+ const index = tx.extension(GROUP_INDEX_EXTENSION);
1076
+ if ((await readGroupIndexEntry(index, groupId)) === undefined)
1077
+ await writeGroupIndexEntry(index, groupId, { createdAt: joinedAtMs, ...(invitationId === undefined ? {} : { adoptedBy: invitationId }) });
1078
+ }));
1079
+ }
1080
+ catch (error) {
1081
+ // Only a group this call wrote is taken back (best effort: the state and whatever a hook wrote with it); an
1082
+ // unindexed state is invisible to `groups.list`.
1083
+ if (wrote)
1084
+ await guard.call(groupId, 'store', () => groupStore.clear()).catch(() => undefined);
1085
+ throw error;
1086
+ }
1087
+ if (ctx.isDisposed())
1088
+ throw new MarmotError('disposed', 'invitations: client was disposed while joining the group');
1089
+ if (wrote) {
1090
+ const engine = await buildEngine(ctx, ciphersuiteCache, clientState, () => settleCheck(groupId));
1091
+ if (ctx.isDisposed()) {
1092
+ engine.dispose();
1093
+ throw new MarmotError('disposed', 'invitations: client was disposed while joining the group');
1094
+ }
1095
+ rt = makeRuntime(groupId, groupStore, engine, joinedAtMs, { window });
1096
+ }
1097
+ }
1098
+ catch (error) {
1099
+ settle(undefined);
1100
+ throw error;
1101
+ }
1102
+ finally {
1103
+ loading.delete(groupId);
1104
+ }
1105
+ settle(rt);
1106
+ if (rt !== undefined) {
1107
+ startGroupSync(rt);
1108
+ // Epic marmot-device-key-rotation (AC-REKEY-11): a Welcome built on a retired-key KeyPackage lands an old-key leaf.
1109
+ scheduleRekeyFollowUp(rt);
1110
+ }
1111
+ return outcome;
1112
+ }
1113
+ /**
1114
+ * Refuses (`reentrant`) to wait on `groupId`'s load or adoption in flight from inside a consumer surface of that
1115
+ * group's own scope: that surface is (or runs inside) the very load waiting on this call — awaiting it would
1116
+ * hang both (the same rule {@link loadRuntime} applies to `groups.get`).
1117
+ */
1118
+ function assertNotWithinOwnLoad(groupId, operation) {
1119
+ if (!guard.active(groupId))
1120
+ return;
1121
+ throw new MarmotError('reentrant', `${operation}(${JSON.stringify(groupId)}): called from inside a consumer surface of that group's own load`, {
1122
+ details: { scope: groupId, operation },
1123
+ });
1124
+ }
1125
+ async function hasGroupOp(groupId) {
1126
+ // AC-MX-2: a group being restored counts as held — a Welcome for it is joined through `adoptJoinedGroup`,
1127
+ // which defers it (transient) until the restore released the group (then already-member, or adopted). A
1128
+ // failed restore still being taken back (`ending`) holds nothing any more.
1129
+ const restore = restoring.get(groupId);
1130
+ if (restore !== undefined)
1131
+ return !restore.ending;
1132
+ if (abandoned.has(groupId))
1133
+ return false;
1134
+ const cached = runtimes.get(groupId);
1135
+ if (cached !== undefined && !cached.disposed)
1136
+ return true;
1137
+ const groupStore = groupStoreOf(groupId);
1138
+ // AC-MX-2: an unfinished restore an earlier client left is resumed — and counts as held, like one in flight.
1139
+ // Checked before waiting on a load in flight: a load of such a group waits for the resume.
1140
+ if (await restorePending(groupId, groupStore)) {
1141
+ resumeRestore(groupId);
1142
+ return true;
1143
+ }
1144
+ const inFlight = loading.get(groupId);
1145
+ if (inFlight !== undefined) {
1146
+ assertNotWithinOwnLoad(groupId, 'hasGroup');
1147
+ if ((await inFlight.catch(() => undefined)) !== undefined)
1148
+ return true;
1149
+ }
1150
+ return (await guard.call(groupId, 'store', () => readGroupState(groupStore.artifact('clientState')))) !== undefined;
1151
+ }
1152
+ async function getGroupOp(groupId) {
1153
+ if (typeof groupId !== 'string' || groupId.length === 0)
1154
+ throw new MarmotError('invalid-options', 'groups.get: groupId must be a non-empty string');
1155
+ return (await loadRuntime(groupId))?.handle;
1156
+ }
1157
+ /**
1158
+ * The group's one runtime: the cached one, else the single in-flight load
1159
+ * shared by every concurrent `groups.get`/`groups.list` for that id — two
1160
+ * loads racing would each build an engine, resume pending intents and
1161
+ * start a sync loop over the same stores.
1162
+ */
1163
+ function loadRuntime(groupId) {
1164
+ // AC-MX-2: a group being restored (or resumed) is not handed out before its self-update confirmed — a load
1165
+ // waits for the restore (and finds nothing when it failed); never from inside a consumer surface (awaitRestore).
1166
+ const restore = restoring.get(groupId);
1167
+ if (restore !== undefined)
1168
+ return awaitRestore(groupId, restore);
1169
+ if (abandoned.has(groupId))
1170
+ return Promise.resolve(undefined);
1171
+ const cached = runtimes.get(groupId);
1172
+ if (cached !== undefined && !cached.disposed)
1173
+ return Promise.resolve(cached);
1174
+ const inFlight = loading.get(groupId);
1175
+ if (inFlight !== undefined) {
1176
+ // A consumer store read made by this very load, calling back into groups.get for the same group,
1177
+ // would await the promise that is waiting on it: reject instead of deadlocking.
1178
+ if (guard.active(groupId)) {
1179
+ return Promise.reject(new MarmotError('reentrant', `groups.get(${JSON.stringify(groupId)}): called from inside a consumer surface of that group's own load`, { details: { scope: groupId, operation: 'groups.get' } }));
1180
+ }
1181
+ return inFlight;
1182
+ }
1183
+ // Started on a later microtask so the load is registered in `loading` before its first consumer
1184
+ // store call runs: a call back into groups.get for this group then joins (or is rejected), never forks.
1185
+ // AC-RE-1: ONLY the fire-and-forget work below —
1186
+ // `resumePendingInBackground` through `startGroupSync`/`scheduleAwaitingFenceCleanup` — is background
1187
+ // work this load schedules, not something the caller awaits, so `guard.detached` wraps THAT. The store
1188
+ // reads and `buildEngine` ABOVE it are different: `groups.get`/`DeviceGroupPort.snapshot` (reached from
1189
+ // inside a `devices.*` operation's live DEVICE_SCOPE frame) directly AWAITS this whole function, so a
1190
+ // consumer store or engine seam that itself awaits a `devices.*` call during THESE reads must still be
1191
+ // rejected `reentrant` by `assertNotInDeviceOperation` (E1, device-deps.ts:123) — not detached, or such a
1192
+ // call would wrongly queue behind, and deadlock against, the very operation awaiting this load.
1193
+ const load = Promise.resolve()
1194
+ .then(async () => {
1195
+ const groupStore = groupStoreOf(groupId);
1196
+ // AC-MX-2: an unfinished restore an earlier client left is resumed, never loaded as held before its
1197
+ // self-update confirmed (nor discarded: that self-update may be on the relays already) — this load waits
1198
+ // for it like for a restore in flight.
1199
+ if (await restorePending(groupId, groupStore)) {
1200
+ const resumed = resumeRestore(groupId);
1201
+ // No longer a load: a later caller finds the resume's reservation (a purge never waits on this one).
1202
+ if (loading.get(groupId) === load)
1203
+ loading.delete(groupId);
1204
+ if (resumed !== undefined)
1205
+ return awaitRestore(groupId, resumed);
1206
+ // Not resumable here: the client is ending, or this client tore the group down.
1207
+ return undefined;
1208
+ }
1209
+ const rt = await readLoadedRuntime(groupId, groupStore);
1210
+ if (rt === undefined)
1211
+ return undefined;
1212
+ // Scheduled, not awaited: AC-PIPE-1's crash-recovery flow resumes in the background while the caller
1213
+ // already holds the handle; a transient whole-run failure is retried on the backoff. Detached (AC-RE-1):
1214
+ // this whole block never runs on the caller's own await chain, so none of it may
1215
+ // inherit whatever surface frame (e.g. a `devices.*` op's DEVICE_SCOPE) was live at the scheduling
1216
+ // call site above.
1217
+ guard.detached(() => startLoadedRuntime(rt));
1218
+ return rt;
1219
+ })
1220
+ .finally(() => {
1221
+ if (loading.get(groupId) === load)
1222
+ loading.delete(groupId);
1223
+ });
1224
+ loading.set(groupId, load);
1225
+ return load;
1226
+ }
1227
+ /**
1228
+ * AC-MX-2: a restore's handle as `groups.get` waits for it. That can take as long as the group's first sync
1229
+ * (offline: indefinitely), so it is never awaited from inside a consumer surface some group's or the account's
1230
+ * queue is waiting on (an `onConfirm` hook — of the restore's own self-update, where the wait could never end —, a
1231
+ * store call, an inbox handler): rejected `reentrant` instead of holding that queue.
1232
+ */
1233
+ function awaitRestore(groupId, restore) {
1234
+ const frame = guard.withinConsumerScope();
1235
+ if (frame !== undefined) {
1236
+ return Promise.reject(new MarmotError('reentrant', `groups.get(${JSON.stringify(groupId)}): the group is being restored; not awaited from inside a consumer surface (${frame.surface} on ${JSON.stringify(frame.scope)})`, {
1237
+ details: { scope: frame.scope, operation: 'groups.get', surface: frame.surface },
1238
+ }));
1239
+ }
1240
+ return restore.settled;
1241
+ }
1242
+ /**
1243
+ * A stored group's runtime as a load builds it (`loaded`: the AC-PIPE-15 send gate closed until its first sync):
1244
+ * its state, index entry, rewind window, fence marker, revisable removal and ratchet-skip marker, read with the
1245
+ * state they describe. `undefined` when no state is stored. Nothing is started ({@link startLoadedRuntime}).
1246
+ */
1247
+ async function readLoadedRuntime(groupId, groupStore) {
1248
+ const state = await guard.call(groupId, 'store', () => readGroupState(groupStore.artifact('clientState')));
1249
+ if (state === undefined)
1250
+ return undefined;
1251
+ // Framed on the group scope too, so a re-entrant groups.get for this group from inside the read is detected.
1252
+ const indexEntry = await guard.call(groupId, 'store', () => guard.call(ACCOUNT_SCOPE, 'store', () => readGroupIndexEntry(ctx.stores.account.extension(GROUP_INDEX_EXTENSION), groupId)));
1253
+ // S10: the rewind window and the fence marker, read with the state they describe.
1254
+ const stored = await guard.call(groupId, 'store', () => readWindow(groupStore.artifact('rewindTree')));
1255
+ const fence = await guard.call(groupId, 'store', () => readFence(groupStore.extension(FENCE_EXTENSION)));
1256
+ const disbanded = await guard.call(groupId, 'store', () => readDisband(groupStore.extension(DISBAND_EXTENSION)));
1257
+ // S20: a stored tombstone keeps its revisable removal (the retained tip and history are the removal's parent).
1258
+ const storedRemoval = await guard.call(groupId, 'store', () => readRemoval(groupStore.extension(REMOVAL_EXTENSION)));
1259
+ const removal = belongsTo(storedRemoval, state) ? storedRemoval : undefined;
1260
+ // AC-RATCH-1: the last post-load skip, read with the state it describes.
1261
+ const skipMarker = await guard.call(groupId, 'store', () => readRatchetSkipMarker(groupStore.extension(RATCHET_SKIP_EXTENSION)));
1262
+ // The held opaque candidates and `U` (client/opaque-candidates.ts), read with the state they describe. A record that
1263
+ // is corrupt — unreadable here, or refused by the engine — fences the group (fail closed), unless it is fenced already.
1264
+ const opaque = await loadOpaque(guard, groupId, groupStore);
1265
+ // Epic marmot-leaf-backup-pre-publish S2: the pending adoption's marker and the parked pending node, read with the state they describe.
1266
+ const pendingRestore = await guard.call(groupId, 'store', () => readPendingRestore(groupStore));
1267
+ const history = restoreHistory(stored, removal === undefined ? state : copyOf(removal.record.parentState));
1268
+ const built = await buildEngineFailClosed(ctx, ciphersuiteCache, state, () => settleCheck(groupId), history, removal?.record, opaque.record);
1269
+ const engine = built.engine;
1270
+ const corrupt = opaque.corrupt ?? built.corrupt;
1271
+ if (ctx.isDisposed()) {
1272
+ engine.dispose();
1273
+ throw new MarmotError('disposed', 'groups.get: client was disposed while loading the group');
1274
+ }
1275
+ return makeRuntime(groupId, groupStore, engine, indexEntry?.createdAt, {
1276
+ loaded: true,
1277
+ ratchetSkipArmed: ratchetSkipArmed(skipMarker, state.groupContext.epoch, tagOf(state), nextOwnApplicationGeneration(state)),
1278
+ window: windowFor(stored, state),
1279
+ ...(removal === undefined ? {} : { removal }),
1280
+ ...(corrupt !== undefined || opaque.record === undefined ? {} : { opaque: opaque.record }),
1281
+ ...(fence !== undefined ? { fence: recordedFencingError(fence) } : corrupt === undefined ? {} : { fence: corrupt }),
1282
+ ...(disbanded === undefined ? {} : { disbanded }),
1283
+ ...pendingRestore,
1284
+ });
1285
+ }
1286
+ /** A loaded runtime's background work (call detached — AC-RE-1). */
1287
+ function startLoadedRuntime(rt) {
1288
+ resumePendingInBackground(rt);
1289
+ // S15 (AC-INVITE-4): a deferral deadline that passed while the group was not loaded is honoured now.
1290
+ scheduleProposalDeadlineCheck(rt);
1291
+ // S20: a revisable removal re-arms its settle (its window runs on the client clock across the reload).
1292
+ scheduleRemovalSettle(rt);
1293
+ // S9 (Z2): SelfRemoves staged by a persisted ingest whose commit was never recorded — re-elected at rest.
1294
+ const election = electionAtRest(rt.engine.state, rt.leaverPredicate);
1295
+ if (election !== undefined)
1296
+ scheduleSelfRemoveCommit(rt, election);
1297
+ // S5: Welcome deliveries of this group interrupted by the reload, and rumors still queued.
1298
+ // Reconciled with the stored window first (a rewind whose withdrawal a crash lost), then resumed.
1299
+ void reconcileInvitesWithWindow(rt, rt.window).then(() => invitations.resumeGroup(rt.groupId));
1300
+ rt.scheduleQueueDrain();
1301
+ // S10: history backend updates a crash left undelivered (their transitions are durable) go out now.
1302
+ void scheduleHistoryDrain(rt);
1303
+ // AC-HIST-4: a fenced group does not sync (nothing it fetches can be processed). AC-PIPE-15:
1304
+ // awaiting-sync intents a crash left behind the fence marker fail `fenced` now (never encrypted).
1305
+ // A disbanded group does not sync either: the group is over (client/group-disband.ts).
1306
+ if (rt.fence === undefined) {
1307
+ if (rt.disbanded === undefined)
1308
+ startGroupSync(rt);
1309
+ }
1310
+ else
1311
+ scheduleAwaitingFenceCleanup(rt);
1312
+ }
1313
+ /** AC-MX-2 / AC-RE-2: refused from inside a live group-scope `onConfirm` frame — that group's confirmation transaction waits on it. */
1314
+ function assertNotInGroupOnConfirm(operation) {
1315
+ const frame = guard.withinGroupScope('onConfirm');
1316
+ if (frame === undefined)
1317
+ return;
1318
+ throw new MarmotError('reentrant', `${operation}: re-entrant call from inside group ${JSON.stringify(frame.scope)}'s onConfirm surface`, {
1319
+ details: { scope: frame.scope, operation, surface: frame.surface },
1320
+ });
1321
+ }
1322
+ /**
1323
+ * AC-MX-2: `groups.restore`'s pre-adoption purge check — like a Welcome join, an interrupted purge is finished
1324
+ * first (`finishPurge`), then whether a group this client tore down refuses the snapshot's `epoch`
1325
+ * (`refusesJoin`). Runs flagged `checkingPurge` (a purge neither ends nor waits for the restore meanwhile: the
1326
+ * check may be waiting on that very purge), and repeats until no purge of the group is in flight at its end and
1327
+ * none started during the watermark read (one that started and finished meanwhile may not be in that read), so
1328
+ * the adoption that follows never races a purge's clear and reads the watermark that purge committed.
1329
+ */
1330
+ async function refusedAfterPurges(groupId, entry, epoch) {
1331
+ entry.checkingPurge = true;
1332
+ try {
1333
+ for (;;) {
1334
+ if (ctx.finishPurgeBeforeJoin)
1335
+ await teardown().finishPurge(groupId);
1336
+ const purging = purgesInFlight.get(groupId);
1337
+ if (purging !== undefined) {
1338
+ await purging.catch(() => undefined);
1339
+ continue;
1340
+ }
1341
+ const generation = purgeGenerations.get(groupId);
1342
+ const refused = await teardown().refusesJoin(groupId, epoch);
1343
+ if (!purgesInFlight.has(groupId) && purgeGenerations.get(groupId) === generation)
1344
+ return refused;
1345
+ }
1346
+ }
1347
+ finally {
1348
+ entry.checkingPurge = false;
1349
+ }
1350
+ }
1351
+ /** What a restore of `groupId` rejects with when its runtime ended for good ({@link RuntimeEnd}). */
1352
+ function restoreEndError(groupId, end) {
1353
+ if (end.reason === 'fenced')
1354
+ return fencedError(groupId, 'groups.restore', end.cause);
1355
+ if (end.reason === 'disposed')
1356
+ return new MarmotError('disposed', 'groups.restore: client was disposed while restoring the group');
1357
+ if (end.reason === 'no-lease') {
1358
+ return new MarmotError('no-lease', `groups.restore: the stores lost their lease while restoring group ${groupId}; the next lease holder resumes it`, { cause: end.cause, details: { groupId } });
1359
+ }
1360
+ return new MarmotError('not-a-member', `groups.restore: group ${groupId} was torn down while being restored`, { details: { groupId } });
1361
+ }
1362
+ /**
1363
+ * AC-MX-2 `groups.restore(groupId, snapshot)`. Refused `reentrant` from inside an account-scope surface, a
1364
+ * group's `onConfirm` hook, or any consumer surface of `groupId`'s own scope (e.g. a store read of that group's
1365
+ * load in flight, which the restore would otherwise wait on while the load waits on the read). Checked before anything is written, in this order: the snapshot itself
1366
+ * (`envelope-mismatch`, pure — a malformed payload included: a state of another group than the payload names, a
1367
+ * rewind window with a cycle, a dangling link, a node not connected to the tip's tree, a node below the horizon or a node without the serialized
1368
+ * state or commit restoring it needs, or naming a sender for a link other than its commit's authenticated sender), that its serialized MLS state is
1369
+ * `groupId`'s (`invalid-options`, AC-BAK-10), that the group is not held or being
1370
+ * restored (`already-member`), then — like a Welcome join — an interrupted purge is finished and a group this
1371
+ * client tore down only comes back with a newer state (`not-a-member`). The snapshot is then adopted as a LOADED
1372
+ * state with the rewind window it carries (the AC-PIPE-15 send gate closed: its first sync replays every commit
1373
+ * since, rewinding within that window when a competing commit won convergence; the AC-RATCH-1 skip armed), and
1374
+ * once the gate opens a self-update is committed. The handle resolves only once that self-update confirmed.
1375
+ *
1376
+ * Every wait races the runtime's terminal signal (GroupRuntime.terminalWatchers): a fence (`fenced`), a teardown
1377
+ * purge (`not-a-member`) or dispose (`disposed`) ends the restore at once. Any failure after the adoption removes
1378
+ * the adopted group again (all-or-nothing) — on dispose without waiting for the group's queue: the adoption is
1379
+ * marked unfinished until its self-update confirms, and a later client over the same stores discards a group so
1380
+ * marked before reading it as held (also after a crash mid-restore).
1381
+ */
1382
+ async function restoreGroupOp(groupId, snapshot) {
1383
+ guard.assertNotReentrant(ACCOUNT_SCOPE, 'groups.restore');
1384
+ assertNotInGroupOnConfirm('groups.restore');
1385
+ if (typeof groupId !== 'string' || groupId.length === 0)
1386
+ throw new MarmotError('invalid-options', 'groups.restore: groupId must be a non-empty string');
1387
+ // Nor from inside any consumer surface of this group's own scope: whatever invoked that surface — a load
1388
+ // (`groups.get`), a Welcome adoption, a purge, another restore — is what the checks below would wait on.
1389
+ guard.assertNotReentrant(groupId, 'groups.restore');
1390
+ // Opened in full before anything is written: a payload whose serialized state is of another group than it
1391
+ // names, or whose rewind window is no tree below its tip within the horizon or lacks a node's state or commit, is
1392
+ // `envelope-mismatch` (malformed) — as is a window that would still restore to no engine history: the history
1393
+ // is built here, before anything is written, so a restore never adopts a state without the window it advertises.
1394
+ const opened = openGroupSnapshot(snapshot);
1395
+ let content = opened;
1396
+ let history = snapshotHistory(content);
1397
+ // AC-BAK-10: the serialized MLS state's own group id — the payload's, as opened — decides which group this is.
1398
+ const snapshotGroupId = getGroupIdHex(content.state);
1399
+ if (snapshotGroupId !== groupId) {
1400
+ throw new MarmotError('invalid-options', `groups.restore: the snapshot is of group ${snapshotGroupId}, not ${groupId}`, { details: { groupId, snapshotGroupId } });
1401
+ }
1402
+ const alreadyMember = () => new MarmotError('already-member', `groups.restore: group ${groupId} is already held by this client`, { details: { groupId } });
1403
+ const cached = runtimes.get(groupId);
1404
+ const pending = restoring.get(groupId);
1405
+ // A failed restore still being taken back: transient — the group is free once its adoption was removed.
1406
+ if (pending?.ending === true) {
1407
+ throw new MarmotError('commit-pending', `groups.restore: an earlier restore of group ${groupId} failed and is still being taken back; retry once it was`, {
1408
+ details: { groupId, reason: 'restore-ending', retryable: true },
1409
+ });
1410
+ }
1411
+ if (pending !== undefined || (cached !== undefined && !cached.disposed))
1412
+ throw alreadyMember();
1413
+ // Reserved synchronously: a second restore (or a load, or a Welcome adoption) of this group from here on joins or refuses this one.
1414
+ const { entry, settle, end, ended } = reserveRestore(groupId);
1415
+ let rt;
1416
+ /** Whether this call wrote the group's restore record, and whether the group-store adoption was written. */
1417
+ let announced = false;
1418
+ let adopted = false;
1419
+ let resumeEarlier = false;
1420
+ try {
1421
+ // Every window link's sender re-derived from its commit at its parent, never the snapshot's stored claim
1422
+ // (ADR-016 D4a): a mismatching claim refuses the snapshot (`envelope-mismatch`, malformed) before anything is
1423
+ // written, and only derived senders reach the engine and the window store. After the synchronous reservation
1424
+ // (the re-resolution is async), so a `groups.get` racing this call waits on it; the history is rebuilt over them.
1425
+ if (history !== undefined) {
1426
+ content = await authenticateWindowSenders(opened, await ciphersuiteImplFor(ciphersuiteCache, opened.state.groupContext.cipherSuite), effectiveSeams(ctx, () => opened.state.ratchetTree).clientConfig);
1427
+ history = snapshotHistory(content);
1428
+ }
1429
+ const groupStore = groupStoreOf(groupId);
1430
+ // An unfinished restore an earlier client left (disposed or crashed mid-restore) is resumed, never replaced
1431
+ // — its self-update may be on the relays already, and only these stores can confirm it — and this call is
1432
+ // refused like any second restore of a group being restored. Checked before waiting on a load in flight:
1433
+ // that load, finding the mark, waits on this reservation (handed over to the resume below).
1434
+ if (await restorePending(groupId, groupStore)) {
1435
+ resumeEarlier = true;
1436
+ throw alreadyMember();
1437
+ }
1438
+ // A load already in flight (a `groups.get` racing this call) decides whether the group is held.
1439
+ const inFlight = loading.get(groupId);
1440
+ if (inFlight !== undefined && (await inFlight.catch(() => undefined)) !== undefined)
1441
+ throw alreadyMember();
1442
+ assertNotEnded(entry);
1443
+ if (await refusedAfterPurges(groupId, entry, content.state.groupContext.epoch)) {
1444
+ throw new MarmotError('not-a-member', `groups.restore: group ${groupId} was left or abandoned by this client; this snapshot would bring its old state back`, { details: { groupId } });
1445
+ }
1446
+ // A purge from here on ends this restore (`not-a-member`) and waits for it; every step below that does not
1447
+ // race `ended` re-checks.
1448
+ assertNotEnded(entry);
1449
+ // The window the snapshot carries (AC-RACE-1: what a rewind below the snapshot's tip needs), else the tip alone.
1450
+ const window = windowFor(content.window, content.state);
1451
+ const pendingMarker = content.pending === undefined ? undefined : { digest: content.pending.digest, parentTag: content.pending.parentTag, tipTag: tagOf(content.state) };
1452
+ // Discoverable before anything of the group is written: the startup scan walks the group index, written only
1453
+ // after the group store, so a crash in between would orphan the snapshot's key material. Three separate
1454
+ // transactions, account → group → account (never nested: group → account is the lock order) — every crash
1455
+ // point leaves what the next client's scan settles (group-records.ts `RESTORING_EXTENSION`).
1456
+ await guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction((tx) => writeRestoringRecord(tx.extension(RESTORING_EXTENSION), groupId, ctx.clock.now())));
1457
+ announced = true;
1458
+ assertNotEnded(entry);
1459
+ const wrote = await guard.call(groupId, 'store', () => groupStore.transaction(async (tx) => {
1460
+ if ((await readGroupState(tx.artifact('clientState'))) !== undefined)
1461
+ return false;
1462
+ // Marked unfinished until its self-update confirms (cleared in that confirmation's transaction).
1463
+ await writeRestorePending(tx.extension(RESTORE_PENDING_EXTENSION), ctx.clock.now());
1464
+ await writeGroupState(tx.artifact('clientState'), content.state);
1465
+ await writeWindow(tx.artifact('rewindTree'), window);
1466
+ // The restored engine is built with no opaque record (nothing was handed to the snapshot's state yet); a
1467
+ // `marmot.opaque` left by an earlier state of this group belongs to that state, so it goes in this transaction:
1468
+ // a reload must not rehydrate candidates that describe another history.
1469
+ await clearOpaque(tx.extension(OPAQUE_EXTENSION));
1470
+ // Epic marmot-leaf-backup-pre-publish S2: a record an earlier state of this group left never survives a new
1471
+ // adoption; a pending-tagged snapshot then writes its own marker (cleared once its commit was seen or the
1472
+ // first sync's resolution step ran — client/pending-leaf.ts).
1473
+ await clearPendingLeaf(tx.extension(PENDING_LEAF_EXTENSION));
1474
+ await clearPendingCommit(tx.extension(PENDING_COMMIT_EXTENSION));
1475
+ if (pendingMarker !== undefined)
1476
+ await writePendingCommit(tx.extension(PENDING_COMMIT_EXTENSION), pendingMarker);
1477
+ if (content.since !== undefined)
1478
+ await writeIngestCursor(tx.artifact('ingestCursor'), { since: content.since });
1479
+ return true;
1480
+ }));
1481
+ if (!wrote)
1482
+ throw alreadyMember();
1483
+ adopted = true;
1484
+ assertNotEnded(entry);
1485
+ const createdAt = content.createdAt ?? ctx.clock.now();
1486
+ // The index entry and the record's removal together: from here the index alone makes the adoption found.
1487
+ await guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction(async (tx) => {
1488
+ const index = tx.extension(GROUP_INDEX_EXTENSION);
1489
+ if ((await readGroupIndexEntry(index, groupId)) === undefined)
1490
+ await writeGroupIndexEntry(index, groupId, { createdAt });
1491
+ await clearRestoringRecord(tx.extension(RESTORING_EXTENSION), groupId);
1492
+ }));
1493
+ announced = false;
1494
+ // Synchronously with the clear below: a purge that started meanwhile marked the group abandoned — kept so.
1495
+ assertNotEnded(entry);
1496
+ abandoned.delete(groupId);
1497
+ if (ctx.isDisposed())
1498
+ throw new MarmotError('disposed', 'groups.restore: client was disposed while restoring the group');
1499
+ const engine = await buildEngine(ctx, ciphersuiteCache, content.state, () => settleCheck(groupId), history);
1500
+ if (ctx.isDisposed()) {
1501
+ engine.dispose();
1502
+ throw new MarmotError('disposed', 'groups.restore: client was disposed while restoring the group');
1503
+ }
1504
+ // A load, not a join: the snapshot may be older than what the relays hold (AC-PIPE-15, AC-RATCH-1).
1505
+ rt = makeRuntime(groupId, groupStore, engine, createdAt, { loaded: true, window, ...(pendingMarker === undefined ? {} : { pendingCommit: pendingMarker }) });
1506
+ entry.runtime = rt;
1507
+ const runtime = rt;
1508
+ runtime.terminalWatchers.add((ending) => end(restoreEndError(groupId, ending)));
1509
+ assertNotEnded(entry);
1510
+ guard.detached(() => startGroupSync(runtime));
1511
+ // The first sync: every relay answered (or was excluded as silent) and every commit since was replayed.
1512
+ await Promise.race([new Promise((resolve, reject) => (runtime.sendGateOpen ? resolve() : runtime.syncWaiters.add({ resolve, reject }))), ended]);
1513
+ await resolvePendingRestore(runtime, ended);
1514
+ await commitRestoreSelfUpdate(runtime, ended);
1515
+ }
1516
+ catch (error) {
1517
+ // Settled at once: a `groups.get` waiting on this restore learns "not held" without waiting for the
1518
+ // retirement below, which queues behind an operation still in flight (a slow signer or publish). The
1519
+ // reservation itself is held until the stores are cleared: released earlier, a Welcome would be adopted
1520
+ // (or a load would read the restored state back) and then be wiped by the clear. Except on dispose: the
1521
+ // client is ending and that operation may never finish (a publish no relay answers), so the restore
1522
+ // rejects at once; the stores are left to the unfinished-restore mark, which the next client over them
1523
+ // discards before it reads the group as held (see `undoRestore`).
1524
+ if (resumeEarlier) {
1525
+ // Whoever waits on this reservation (a load that found the mark) follows the resume instead.
1526
+ releaseRestore(groupId, entry);
1527
+ settle(resumeRestore(groupId)?.settled);
1528
+ throw error;
1529
+ }
1530
+ settle(undefined);
1531
+ if (adopted)
1532
+ await Promise.race([undoRestore(groupId, rt), clientDisposed]);
1533
+ else if (announced && !ctx.isDisposed()) {
1534
+ // Nothing of the group written by this call (refused, or ended before its group write): only the record goes
1535
+ // — while the reservation is held, so no restore of the group here writes one meanwhile. Left on a failure
1536
+ // (or once disposed: a new client may own the record by now) for the next scan, which drops it alike.
1537
+ await guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction((tx) => clearRestoringRecord(tx.extension(RESTORING_EXTENSION), groupId))).catch(() => undefined);
1538
+ }
1539
+ releaseRestore(groupId, entry);
1540
+ // Ended by a teardown purge (which waited for the release above): rejects once that purge removed the group —
1541
+ // stores, then index entry. The purge, not this take-back, clears it: it commits the purged epoch's watermark
1542
+ // from the stored state first.
1543
+ if (adopted && abandoned.has(groupId) && !ctx.isDisposed())
1544
+ await Promise.race([teardown().finishPurge(groupId).catch(() => undefined), clientDisposed]);
1545
+ // A fence ends the restore `fenced` whichever wait noticed it first.
1546
+ if (rt?.fence !== undefined && !isMarmotError(error, 'disposed'))
1547
+ throw fencedError(groupId, 'groups.restore', rt.fence);
1548
+ throw error;
1549
+ }
1550
+ releaseRestore(groupId, entry);
1551
+ settle(rt);
1552
+ // AC-REKEY-11: a restored leaf may sit on a retired key (a backup older than a rotation).
1553
+ scheduleRekeyFollowUp(rt);
1554
+ await oweRestoreRotation(groupId);
1555
+ return rt.handle;
1556
+ }
1557
+ /**
1558
+ * Epic `marmot-leaf-backup-pre-publish` S2 (Design Decision 7): the resolution of a pending-tagged snapshot's adoption,
1559
+ * run once the restore's first sync is over and before its self-update is committed. On the group's queue, gated on
1560
+ * the persisted tip and idempotent (client/pending-leaf.ts `resolvePendingCommit`); when it rewound the group onto the
1561
+ * pending commit's parent, the tree-fed convergence pass over the rebuilt tree is the structural replay, so a
1562
+ * competitor of the rewound-away tip that the sync already ledgered is weighed from the parent (no relay re-fetch).
1563
+ * A no-op for every group that carries no marker.
1564
+ */
1565
+ async function resolvePendingRestore(rt, ended) {
1566
+ if (rt.pendingCommit === undefined)
1567
+ return;
1568
+ await Promise.race([
1569
+ rt.run('restorePending', async (rtc) => {
1570
+ if (await resolvePendingCommit(rtc))
1571
+ await treeFedPass(rtc);
1572
+ }),
1573
+ ended,
1574
+ ]);
1575
+ }
1576
+ /**
1577
+ * AC-MX-2: resumes `groupId`'s unfinished restore — one an earlier client over these stores adopted but whose
1578
+ * self-update it never saw confirmed (disposed or crashed). Returns the reservation (an existing one when the
1579
+ * group is already being restored here), or `undefined` when nothing is resumed: the client is disposed, this
1580
+ * client tore the group down, or it holds the group already.
1581
+ *
1582
+ * Started by whatever first finds the mark — the startup scan ({@link GroupRegistry.resumeUnfinishedRestores},
1583
+ * on client creation and every inbox pass), `groups.get`/`list`, `hasGroup`, a Welcome adoption, `groups.restore`
1584
+ * — never by the app re-supplying the snapshot. While it runs the group behaves exactly as one being restored by
1585
+ * `groups.restore`: `groups.get` waits for it, `groups.list`/`heldGroups` skip it, a Welcome for it is deferred.
1586
+ *
1587
+ * The mark is never simply discarded: once the restore's self-update was recorded (S13: the record carries the
1588
+ * signed envelope and `pending.newState` before anything is published) a relay may hold that commit, and only
1589
+ * this record can confirm it — discarded, the commit would fence every later restore of this leaf. So the group
1590
+ * is loaded like any stored group (its rewind window, fence marker and ingest cursor as stored), whose
1591
+ * crash-recovery resume (AC-PIPE-1, `resumePending`) re-publishes the recorded envelope byte-identically (or finds
1592
+ * it on the relays) and confirms it — clearing the mark in that confirmation's transaction (pipeline.ts). Its own
1593
+ * echo is held as an own pending envelope until then (ingest.ts), never replayed as a foreign commit (no fence);
1594
+ * a competing commit that won the epoch goes through the ordinary convergence/rewind within the stored window.
1595
+ * A mark with no self-update recorded (a crash after the adoption, before the first self-update was recorded,
1596
+ * or between two attempts) continues the restore instead: its first sync, then a fresh self-update — exactly
1597
+ * what `groups.restore` would have done next, and safer than discarding (an earlier attempt's commit, if any,
1598
+ * is ledgered in these stores). Either way the resumed self-update counts as the first of
1599
+ * {@link RESTORE_SELF_UPDATE_ATTEMPTS}; when they all go terminal, or the group is fenced, the group is discarded
1600
+ * like a failed restore (its stores and index entry cleared — the terminal attempt was reported `intentFailed`).
1601
+ * A mark on a group whose adoption never finished (no state, or no index entry: nothing was ever recorded) is
1602
+ * discarded — such a group is found through its account restore record (`settleRestoringRecord`), not the index.
1603
+ * A store or engine failure before the runtime exists discards nothing: the mark stays, and the next
1604
+ * access or scan resumes again.
1605
+ */
1606
+ function resumeRestore(groupId) {
1607
+ const existing = restoring.get(groupId);
1608
+ if (existing !== undefined)
1609
+ return existing;
1610
+ if (ctx.isDisposed() || abandoned.has(groupId))
1611
+ return undefined;
1612
+ const cached = runtimes.get(groupId);
1613
+ if (cached !== undefined && !cached.disposed)
1614
+ return undefined;
1615
+ const reservation = reserveRestore(groupId);
1616
+ guard.detached(() => void driveResumedRestore(groupId, reservation));
1617
+ return reservation.entry;
1618
+ }
1619
+ async function driveResumedRestore(groupId, r) {
1620
+ const groupStore = groupStoreOf(groupId);
1621
+ let rt;
1622
+ /** Whether a failure takes the adoption back (else the mark stays for the next resume). */
1623
+ let discard = false;
1624
+ try {
1625
+ if (!(await restorePending(groupId, groupStore))) {
1626
+ // Finished (or taken back) since the mark was read: an ordinary load decides.
1627
+ releaseRestore(groupId, r.entry);
1628
+ r.settle(loadRuntime(groupId).catch(() => undefined));
1629
+ return;
1630
+ }
1631
+ // A purge from here on ends this resume and waits for it; every step that does not race `ended` re-checks.
1632
+ assertNotEnded(r.entry);
1633
+ const indexed = await guard.call(ACCOUNT_SCOPE, 'store', () => readGroupIndexEntry(ctx.stores.account.extension(GROUP_INDEX_EXTENSION), groupId));
1634
+ assertNotEnded(r.entry);
1635
+ const records = await guard.call(groupId, 'store', () => listPendingIntentRecords(groupStore.artifact('pendingIntents')));
1636
+ assertNotEnded(r.entry);
1637
+ const recorded = records.find((record) => record.kind === 'self-update');
1638
+ if (indexed === undefined && recorded === undefined) {
1639
+ // The adoption never finished (the index entry is written before anything is recorded): nothing to resume.
1640
+ discard = true;
1641
+ throw new MarmotError('not-a-member', `groups.restore: group ${groupId}'s unfinished restore never completed its adoption`, { details: { groupId } });
1642
+ }
1643
+ rt = await readLoadedRuntime(groupId, groupStore);
1644
+ if (rt === undefined) {
1645
+ discard = true;
1646
+ throw new MarmotError('not-a-member', `groups.restore: group ${groupId}'s unfinished restore holds no state`, { details: { groupId } });
1647
+ }
1648
+ r.entry.runtime = rt;
1649
+ const runtime = rt;
1650
+ runtime.terminalWatchers.add((ending) => r.end(restoreEndError(groupId, ending)));
1651
+ // Before anything is started on the runtime: a purge that ran while it was read leaves the group torn down
1652
+ // (and its stores cleared) — the runtime is only retired, nothing written back.
1653
+ assertNotEnded(r.entry);
1654
+ if (abandoned.has(groupId))
1655
+ throw restoreEndError(groupId, { reason: 'retired' });
1656
+ if (!(await restorePending(groupId, groupStore))) {
1657
+ // The mark vanished while the group was read: nothing to resume — retired; the next access loads what is stored.
1658
+ throw new MarmotError('not-a-member', `groups.restore: group ${groupId}'s unfinished restore was settled elsewhere`, { details: { groupId } });
1659
+ }
1660
+ assertNotEnded(r.entry);
1661
+ if (abandoned.has(groupId))
1662
+ throw restoreEndError(groupId, { reason: 'retired' });
1663
+ discard = true;
1664
+ if (runtime.fence !== undefined)
1665
+ throw restoreEndError(groupId, { reason: 'fenced', cause: runtime.fence });
1666
+ // Collected from before the load's resume starts: the recorded self-update may settle at once.
1667
+ const early = [];
1668
+ const collect = (event) => void early.push(event);
1669
+ runtime.settledListeners.add(collect);
1670
+ try {
1671
+ guard.detached(() => startLoadedRuntime(runtime));
1672
+ // A pending adoption an earlier client left unresolved resolves identically (its marker survived the crash): after
1673
+ // this load's first sync, before the self-update. The tree-fed pass runs too whenever anything of the pending
1674
+ // machinery is in play (a marker, a parked node, an own-leaf fork node): a crash between the resolution's or the
1675
+ // reinstatement's transaction and its pass leaves no marker to say the pass is owed, and the pass is idempotent.
1676
+ // With a self-update already recorded the resolution ran before it was staged, so nothing waits here.
1677
+ if (recorded === undefined && pendingWatch(runtime) !== undefined) {
1678
+ await Promise.race([new Promise((resolve, reject) => (runtime.sendGateOpen ? resolve() : runtime.syncWaiters.add({ resolve, reject }))), r.ended]);
1679
+ await resolvePendingRestore(runtime, r.ended);
1680
+ await Promise.race([runtime.run('restorePending', (rtc) => treeFedPass(rtc)), r.ended]);
1681
+ }
1682
+ await commitRestoreSelfUpdate(runtime, r.ended, recorded === undefined ? undefined : { intentId: recorded.reenqueuedFrom ?? recorded.intentId, early });
1683
+ }
1684
+ finally {
1685
+ runtime.settledListeners.delete(collect);
1686
+ }
1687
+ }
1688
+ catch {
1689
+ // No caller to reject: a waiting `groups.get` learns "not held"; the self-update's own failure was reported.
1690
+ r.settle(undefined);
1691
+ await Promise.race([undoRestore(groupId, rt, discard), clientDisposed]);
1692
+ releaseRestore(groupId, r.entry);
1693
+ return;
1694
+ }
1695
+ releaseRestore(groupId, r.entry);
1696
+ r.settle(rt);
1697
+ if (rt !== undefined) {
1698
+ scheduleRekeyFollowUp(rt);
1699
+ // A restore resumed after a crash owes the rotation as the uninterrupted one does.
1700
+ await oweRestoreRotation(groupId);
1701
+ }
1702
+ }
1703
+ /**
1704
+ * Owner decision 13: a successful restore owes a device-key rotation (the old device may still hold the backed-up key).
1705
+ * The marker is durable before the device service is told; a failed write only loses the prompt rotation, never the
1706
+ * restore (the handle is already the caller's). A crash between the restore's success and this write loses it too.
1707
+ */
1708
+ async function oweRestoreRotation(groupId) {
1709
+ if (ctx.disableRestoreRotationForTest)
1710
+ return;
1711
+ await guard
1712
+ .call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction((tx) => writeRestoreRotationOwed(tx.extension(RESTORE_ROTATION_EXTENSION), groupId, ctx.clock.now())))
1713
+ .then(() => announceTo(restoredListeners, groupId))
1714
+ .catch(() => undefined);
1715
+ }
1716
+ /** Most self-updates a restore attempts when each one goes terminal (a foreign commit won its epoch, …). */
1717
+ const RESTORE_SELF_UPDATE_ATTEMPTS = 3;
1718
+ /**
1719
+ * First delay (ms) before a self-update the group refused `commit-pending` (retryable: an elected SelfRemove
1720
+ * wait, a deferred proposal, another own commit pending) is re-driven when nothing woke the restore sooner (an
1721
+ * own intent settling, the group's state changing); doubles per round up to {@link RESTORE_REDRIVE_MAX_MS}.
1722
+ */
1723
+ const RESTORE_REDRIVE_BASE_MS = 250;
1724
+ const RESTORE_REDRIVE_MAX_MS = 30_000;
1725
+ /** Throws when the restored runtime can no longer make progress: fenced, torn down, disposed. */
1726
+ function assertRestorable(rt) {
1727
+ if (rt.fence !== undefined)
1728
+ throw restoreEndError(rt.groupId, { reason: 'fenced', cause: rt.fence });
1729
+ if (ctx.isDisposed())
1730
+ throw restoreEndError(rt.groupId, { reason: 'disposed' });
1731
+ if (rt.abandoned || rt.disposed)
1732
+ throw restoreEndError(rt.groupId, { reason: 'retired' });
1733
+ }
1734
+ /**
1735
+ * Commits a self-update on the restored group and resolves once it is confirmed — matched by the driven
1736
+ * record's id (or a re-enqueue of it, AC-RACE-1), whatever else settles meanwhile; it may be retried in the
1737
+ * background before that. A self-update that goes terminal is re-driven, up to {@link RESTORE_SELF_UPDATE_ATTEMPTS}.
1738
+ * A `commit-pending` refusal that recorded nothing (`details.retryable`) is re-driven once its condition may
1739
+ * have cleared — an own intent settled, the group's state changed, or the backoff passed — without counting as
1740
+ * an attempt. Every wait races `ended` (the runtime's terminal signal, dispose); every pass re-checks the runtime.
1741
+ *
1742
+ * `resumed` (a resumed unfinished restore): the self-update an earlier client recorded — driven by the load's own
1743
+ * crash-recovery resume, not here — is awaited as the first attempt; `early` holds what settled before this call.
1744
+ * A fresh drive waits for the group's first post-load sync (AC-PIPE-15) — already open for `groups.restore`.
1745
+ */
1746
+ async function commitRestoreSelfUpdate(rt, ended, resumed) {
1747
+ const settled = [];
1748
+ let wake;
1749
+ const poke = () => {
1750
+ const w = wake;
1751
+ wake = undefined;
1752
+ w?.();
1753
+ };
1754
+ const onSettled = (event) => {
1755
+ settled.push(event);
1756
+ poke();
1757
+ };
1758
+ let timer;
1759
+ const clearTimer = () => {
1760
+ if (timer === undefined)
1761
+ return;
1762
+ ctx.timers.clear(timer);
1763
+ timer = undefined;
1764
+ };
1765
+ /** Until the next wake-up (or `ms` passed), or rejects when the restore ended. */
1766
+ const pause = async (ms) => {
1767
+ try {
1768
+ await Promise.race([
1769
+ new Promise((resolve) => {
1770
+ wake = resolve;
1771
+ if (ms !== undefined)
1772
+ timer = ctx.timers.set(poke, ms);
1773
+ }),
1774
+ ended,
1775
+ ]);
1776
+ }
1777
+ finally {
1778
+ wake = undefined;
1779
+ clearTimer();
1780
+ }
1781
+ };
1782
+ rt.settledListeners.add(onSettled);
1783
+ if (resumed !== undefined)
1784
+ settled.push(...resumed.early);
1785
+ const unwatch = watchState(rt.groupId, poke);
1786
+ try {
1787
+ let failures = 0;
1788
+ let refusals = 0;
1789
+ let carried = resumed?.intentId;
1790
+ for (;;) {
1791
+ assertRestorable(rt);
1792
+ let driven = carried;
1793
+ let sendError;
1794
+ if (carried !== undefined) {
1795
+ carried = undefined;
1796
+ }
1797
+ else {
1798
+ settled.length = 0;
1799
+ if (!rt.sendGateOpen)
1800
+ await Promise.race([new Promise((resolve, reject) => (rt.sendGateOpen ? resolve() : rt.syncWaiters.add({ resolve, reject }))), ended]);
1801
+ try {
1802
+ await Promise.race([rt.run('restore', (rtc) => sendIntent(rtc, { type: 'self-update' }, { onRecorded: (intentId) => (driven = intentId) })), ended]);
1803
+ }
1804
+ catch (error) {
1805
+ assertRestorable(rt);
1806
+ if (driven === undefined) {
1807
+ // Refused before anything was recorded, for a condition that clears by itself: waited out, uncounted.
1808
+ if (isMarmotError(error, 'commit-pending') && error.details?.['retryable'] === true) {
1809
+ await pause(Math.min(RESTORE_REDRIVE_BASE_MS * 2 ** refusals, RESTORE_REDRIVE_MAX_MS));
1810
+ refusals += 1;
1811
+ continue;
1812
+ }
1813
+ throw error;
1814
+ }
1815
+ // Recorded and still on its way (retried in the background), or already reported terminal below.
1816
+ const pending = isMarmotError(error, 'publish-failed') || isMarmotError(error, 'confirm-blocked') || isMarmotError(error, 'commit-pending') || isMarmotError(error, 'send-rejected');
1817
+ if (!pending)
1818
+ throw error;
1819
+ sendError = error;
1820
+ }
1821
+ refusals = 0;
1822
+ }
1823
+ const ours = (event) => event.intentId === driven || event.rootIntentId === driven;
1824
+ let outcome;
1825
+ while ((outcome = settled.find(ours)) === undefined) {
1826
+ assertRestorable(rt);
1827
+ await pause();
1828
+ }
1829
+ if (outcome.error === undefined)
1830
+ return;
1831
+ failures += 1;
1832
+ if (failures >= RESTORE_SELF_UPDATE_ATTEMPTS)
1833
+ throw sendError ?? outcome.error;
1834
+ }
1835
+ }
1836
+ finally {
1837
+ rt.settledListeners.delete(onSettled);
1838
+ unwatch();
1839
+ clearTimer();
1840
+ }
1841
+ }
1842
+ /**
1843
+ * Takes a failed restore's adoption back (best effort): the runtime retired — as the last operation on its
1844
+ * queue, so an operation in flight finishes first and nothing it writes outlives the clear — unless a teardown
1845
+ * purge or dispose already did; then the group's stores cleared and its index entry removed.
1846
+ *
1847
+ * Never once the client is disposed: its stores may already belong to a new client over the same backend, which
1848
+ * may hold (or be restoring) the group by now — a late clear from here would wipe that. The group adopted here
1849
+ * stays marked unfinished instead (`RESTORE_PENDING_EXTENSION`, cleared only by a confirmed own self-update), and
1850
+ * that next client resumes it before reading it as held (`resumeRestore`). A failed clear leaves the mark too, so
1851
+ * the same holds for it. `clear: false` (a resume that failed before it could decide) only retires the runtime.
1852
+ */
1853
+ async function undoRestore(groupId, rt, clear = true) {
1854
+ if (rt !== undefined) {
1855
+ await rt
1856
+ .runLast(() => {
1857
+ if (!rt.disposed)
1858
+ retireRuntime(rt, 'could not be restored');
1859
+ })
1860
+ .catch(() => undefined);
1861
+ if (runtimes.get(groupId) === rt)
1862
+ runtimes.delete(groupId);
1863
+ }
1864
+ if (ctx.isDisposed())
1865
+ return;
1866
+ // A purge of the group owns its clear (it waits for this take-back, then clears and drops the store it opened —
1867
+ // a clear from here would open and cache that store again).
1868
+ if (abandoned.has(groupId))
1869
+ return;
1870
+ if (!clear) {
1871
+ // Left marked: the next scan retries it (`resumeUnfinishedRestores`).
1872
+ leftMarked.add(groupId);
1873
+ return;
1874
+ }
1875
+ // Left to the restore record the take-back wrote first (or, when even that failed, to the mark): the next scan
1876
+ // settles it (`settleRestoringRecord` resumes a marked group, completes an interrupted clear).
1877
+ await clearAdoptedGroup(groupId, groupStoreOf(groupId)).catch(() => {
1878
+ if (!abandoned.has(groupId))
1879
+ leftRecords.add(groupId);
1880
+ });
1881
+ }
1882
+ /**
1883
+ * Every held group's handle. AC-MX-2: a group being restored (or resumed) is not held yet — it is skipped (never
1884
+ * waited for), so one restore that cannot finish (offline) never blocks the list; it appears once its restore
1885
+ * resolved. An unfinished restore an earlier client left is resumed here, and skipped likewise.
1886
+ */
1887
+ async function listGroupsOp() {
1888
+ const ids = await guard.call(ACCOUNT_SCOPE, 'store', () => listGroupIndex(ctx.stores.account.extension(GROUP_INDEX_EXTENSION)));
1889
+ const out = [];
1890
+ for (const id of ids) {
1891
+ if (await unfinishedRestore(id))
1892
+ continue;
1893
+ const handle = await getGroupOp(id);
1894
+ if (handle !== undefined)
1895
+ out.push(handle);
1896
+ }
1897
+ return Object.freeze(out);
1898
+ }
1899
+ const devicePort = {
1900
+ // AC-MX-2: a group being restored (or resumed) is not held yet (as for `groups.list`): device operations never wait on it.
1901
+ // Nor is an index entry whose group store holds no state (a take-back or purge interrupted between its clear and
1902
+ // the entry's deletion, settled by the next scan) — as `groups.list`, whose load finds nothing there.
1903
+ async heldGroups() {
1904
+ const held = [];
1905
+ for (const id of await guard.call(ACCOUNT_SCOPE, 'store', () => listGroupIndex(ctx.stores.account.extension(GROUP_INDEX_EXTENSION)))) {
1906
+ if (await unfinishedRestore(id))
1907
+ continue;
1908
+ const live = runtimes.get(id);
1909
+ if ((live === undefined || live.disposed) && !(await guard.call(id, 'store', () => hasGroupState(groupStoreOf(id).artifact('clientState')))))
1910
+ continue;
1911
+ held.push(id);
1912
+ }
1913
+ return held;
1914
+ },
1915
+ async snapshot(groupId) {
1916
+ const rt = await loadRuntime(groupId);
1917
+ if (rt === undefined)
1918
+ return undefined;
1919
+ const self = await guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.getPublicKey());
1920
+ // A purge may retire the runtime after it was taken here (its last operation queued first): the group is then
1921
+ // not held — DeviceGroupPort.snapshot's `undefined` — although its index entry is dropped only after the purge.
1922
+ const notHeld = (error) => {
1923
+ if (rt.abandoned && isMarmotError(error, 'not-a-member'))
1924
+ return undefined;
1925
+ throw error;
1926
+ };
1927
+ if (rt.abandoned)
1928
+ return undefined;
1929
+ // On the group's queue: whatever was delivered before this read (a competing commit a live
1930
+ // subscription handed over while an own commit was being published) is ingested first.
1931
+ return rt.run('snapshot', async (rtc) => {
1932
+ const summaries = await guard.call(groupId, 'store', () => listPendingIntentSummaries(rtc.groupStore.artifact('pendingIntents')));
1933
+ // S20 follow-up: the settlement-recheck marker read on the same queue step as the tree, so a reopen decided
1934
+ // from this snapshot sees the withdrawn-leaf evidence as of THIS tree — never one read before later
1935
+ // transitions (a re-add pruned it) went in (VQ-S20-P14).
1936
+ const recheck = await guard.call(groupId, 'store', () => readSettlementRecheckRecord(rtc.groupStore.extension(SETTLEMENT_RECHECK_EXTENSION)));
1937
+ const state = rtc.exposedState;
1938
+ // The local account's signature-key successions on the canonical path (read with the tree, on the queue): what
1939
+ // the device service unites with its recorded links. `account` is each succession's own (the leaf's credential).
1940
+ const successions = successionsInWindow(rtc.window, state)
1941
+ .filter((s) => s.account === self)
1942
+ .map(({ account, leafIndex, fromLeafKey, toLeafKey, commitDigest }) => ({ account, leafIndex, fromLeafKey, toLeafKey, commitDigest }));
1943
+ const ownLeaf = ownLeafOf(state);
1944
+ return {
1945
+ groupId,
1946
+ member: state.groupActiveState.kind !== 'removedFromGroup',
1947
+ accountLeaves: leafInfosOf(state, self),
1948
+ ...(ownLeaf === undefined ? {} : { ownLeaf }),
1949
+ successions,
1950
+ recheck,
1951
+ ownCommitPending: summaries.some((r) => r.kind === 'commit' || r.kind === 'self-update' || r.kind === 'proposal'),
1952
+ // The engine's `convergenceStatuses.syncing` (not exported by marmot-engine's barrels).
1953
+ syncing: rtc.engine.convergenceStatus === 'Syncing',
1954
+ };
1955
+ }).catch(notHeld);
1956
+ },
1957
+ async addDevice(groupId, keyPackageEvent, reopenedLeafKey, approvalEpoch, origin) {
1958
+ const rt = await loadRuntime(groupId);
1959
+ if (rt === undefined)
1960
+ throw new MarmotError('not-a-member', `devices: group ${groupId} is not held`, { details: { groupId } });
1961
+ await inviteAndDeliver(rt, [keyPackageEvent], reopenedLeafKey, approvalEpoch, origin);
1962
+ },
1963
+ async groupTip(groupId) {
1964
+ const rt = await loadRuntime(groupId);
1965
+ if (rt === undefined || rt.abandoned)
1966
+ return undefined;
1967
+ return `${Number(rt.exposedState.groupContext.epoch)}:${tagOf(rt.exposedState)}`;
1968
+ },
1969
+ async groupEpoch(groupId) {
1970
+ const rt = await loadRuntime(groupId);
1971
+ if (rt === undefined || rt.abandoned)
1972
+ return undefined;
1973
+ // A plain read of the exposed state (same as the public `MarmotGroup.epoch` getter) — never `rt.run(...)`,
1974
+ // so this never touches `pendingIntents` or any other queued read.
1975
+ return Number(rt.exposedState.groupContext.epoch);
1976
+ },
1977
+ async removeLeaf(groupId, leafKey) {
1978
+ const rt = await loadRuntime(groupId);
1979
+ if (rt === undefined)
1980
+ throw new MarmotError('not-a-member', `devices: group ${groupId} is not held`, { details: { groupId } });
1981
+ return rt.run('forget', (rtc) => removeLeafIntent(rtc, leafKey));
1982
+ },
1983
+ // The whole device chain in ONE commit (Design Decision 8): every leaf carrying any of the keys.
1984
+ async removeLeaves(groupId, leafKeys) {
1985
+ const rt = await loadRuntime(groupId);
1986
+ if (rt === undefined)
1987
+ throw new MarmotError('not-a-member', `devices: group ${groupId} is not held`, { details: { groupId } });
1988
+ return rt.run('forget', (rtc) => removeLeafIntent(rtc, leafKeys));
1989
+ },
1990
+ // AC-REKEY-9/10: on the group's queue; rt.run rejects `reentrant` from a consumer surface like removeLeaf.
1991
+ async rekey(groupId, target) {
1992
+ const rt = await loadRuntime(groupId);
1993
+ if (rt === undefined)
1994
+ throw new MarmotError('not-a-member', `devices: group ${groupId} is not held`, { details: { groupId } });
1995
+ return rt.run('rekey', (rtc) => rekeyIntent(rtc, target));
1996
+ },
1997
+ // The views carry `successions` and the registry may be told of a new one by `onRotation`.
1998
+ reportsSuccessions: true,
1999
+ onRotation(listener) {
2000
+ rotationListeners.add(listener);
2001
+ return () => {
2002
+ rotationListeners.delete(listener);
2003
+ };
2004
+ },
2005
+ async settlementRechecks() {
2006
+ const out = [];
2007
+ const ids = await guard.call(ACCOUNT_SCOPE, 'store', () => listGroupIndex(ctx.stores.account.extension(GROUP_INDEX_EXTENSION)));
2008
+ for (const groupId of ids) {
2009
+ if (abandoned.has(groupId))
2010
+ continue;
2011
+ const marker = await guard.call(groupId, 'store', () => readSettlementRecheckRecord(ctx.stores.groupFactory(groupId).extension(SETTLEMENT_RECHECK_EXTENSION)));
2012
+ if (marker !== undefined)
2013
+ out.push({ groupId, token: marker.token, ...(marker.withdrawnLeaves === undefined ? {} : { withdrawnLeaves: marker.withdrawnLeaves }) });
2014
+ }
2015
+ return out;
2016
+ },
2017
+ async leafOnBranches(groupId, leafKey) {
2018
+ const rt = await loadRuntime(groupId);
2019
+ if (rt === undefined || rt.abandoned)
2020
+ return undefined;
2021
+ const self = await guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.getPublicKey());
2022
+ const keys = typeof leafKey === 'string' ? [leafKey] : leafKey;
2023
+ const holds = (state) => leafInfosOf(state, self).some((l) => keys.includes(l.leafKey));
2024
+ return rt
2025
+ .run('leafOnBranches', async (rtc) => {
2026
+ const window = rtc.window;
2027
+ const path = new Set(canonicalPath(window).map((n) => n.tag));
2028
+ let canonical = holds(rtc.exposedState);
2029
+ let abandoned = false;
2030
+ for (const node of window.nodes.values()) {
2031
+ if (node.tag === window.tipTag || node.snapshot === undefined || !holds(deserializeClientState(node.snapshot)))
2032
+ continue;
2033
+ if (path.has(node.tag))
2034
+ canonical = true;
2035
+ else
2036
+ abandoned = true;
2037
+ }
2038
+ return { canonical, abandoned };
2039
+ })
2040
+ .catch((error) => {
2041
+ if (rt.abandoned && isMarmotError(error, 'not-a-member'))
2042
+ return undefined;
2043
+ throw error;
2044
+ });
2045
+ },
2046
+ async clearSettlementRecheck(groupId, token) {
2047
+ const store = ctx.stores.groupFactory(groupId);
2048
+ await guard.call(groupId, 'store', () => store.transaction((tx) => clearSettlementRecheck(tx.extension(SETTLEMENT_RECHECK_EXTENSION), token)));
2049
+ },
2050
+ onRewind(listener) {
2051
+ rewindListeners.add(listener);
2052
+ return () => {
2053
+ rewindListeners.delete(listener);
2054
+ };
2055
+ },
2056
+ onRestored(listener) {
2057
+ restoredListeners.add(listener);
2058
+ return () => {
2059
+ restoredListeners.delete(listener);
2060
+ };
2061
+ },
2062
+ };
2063
+ /** What `leave()` reads from the group's exposed state (account/teardown.ts). */
2064
+ function leaveViewOf(state, self, ownIntentPending, removalSettlesAt) {
2065
+ const member = state.groupActiveState.kind !== 'removedFromGroup';
2066
+ const ownLeaf = Number(state.privatePath.leafIndex);
2067
+ let occupied = 0;
2068
+ for (let i = 0; i < state.ratchetTree.length; i += 2)
2069
+ if (state.ratchetTree[i]?.nodeType === nodeTypes.leaf)
2070
+ occupied += 1;
2071
+ const admins = getMarmotGroupView(state)?.adminPubkeys ?? [];
2072
+ return {
2073
+ member,
2074
+ soleMember: member && occupied === 1,
2075
+ admin: admins.includes(self),
2076
+ accountHasOtherLeaf: accountLeafIndexes(state.ratchetTree, self).some((i) => i !== ownLeaf),
2077
+ lastActiveAdmin: isLastActiveAdmin(state.ratchetTree, admins, self),
2078
+ selfRemoveStaged: Object.values(state.unappliedProposals).some((p) => p.proposal.proposalType === selfRemoveProposalType && p.senderLeafIndex !== undefined && Number(p.senderLeafIndex) === ownLeaf),
2079
+ ownIntentPending,
2080
+ ...(member || removalSettlesAt === undefined ? {} : { removalSettlesAt }),
2081
+ };
2082
+ }
2083
+ /**
2084
+ * Retires a group's runtime for good — inside its last operation (an abandoned group's purge, a failed restore
2085
+ * taken back): no sync, no timers, no engine; its handle and operations answer `not-a-member`; waiting queued
2086
+ * sends and `synced()` callers learn `not-a-member` ("group X {@link what} before …"); its terminal watchers fire.
2087
+ */
2088
+ function retireRuntime(rt, what) {
2089
+ rt.abandoned = true;
2090
+ rt.disposed = true;
2091
+ for (const handle of rt.pipelineTimers)
2092
+ ctx.timers.clear(handle);
2093
+ rt.pipelineTimers.clear();
2094
+ rt.reenqueueRetryArmed.clear();
2095
+ for (const waiter of rt.queueWaiters.values())
2096
+ waiter.reject(new MarmotError('not-a-member', `send: group ${rt.groupId} ${what} before the queued rumor was published`, { details: { groupId: rt.groupId } }));
2097
+ rt.queueWaiters.clear();
2098
+ for (const waiter of rt.syncWaiters)
2099
+ waiter.reject(new MarmotError('not-a-member', `synced: group ${rt.groupId} ${what} before its first sync`, { details: { groupId: rt.groupId } }));
2100
+ rt.syncWaiters.clear();
2101
+ endRuntime(rt, { reason: 'retired' });
2102
+ try {
2103
+ stopGroupSync(rt);
2104
+ }
2105
+ catch {
2106
+ // the transport's unsubscribe failed: the runtime is retired regardless
2107
+ }
2108
+ rt.engine.dispose();
2109
+ }
2110
+ async function heldRuntime(groupId, operation) {
2111
+ const rt = await loadRuntime(groupId);
2112
+ if (rt === undefined)
2113
+ throw new MarmotError('not-a-member', `${operation}: group ${groupId} is not held`, { details: { groupId } });
2114
+ return rt;
2115
+ }
2116
+ const teardownPort = {
2117
+ async view(groupId) {
2118
+ const rt = await loadRuntime(groupId);
2119
+ if (rt === undefined)
2120
+ return undefined;
2121
+ const self = await guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.getPublicKey());
2122
+ // On the group's queue: whatever was delivered before this read is ingested first.
2123
+ return rt.run('leaveView', async (rtc) => {
2124
+ const summaries = await guard.call(groupId, 'store', () => listPendingIntentSummaries(rtc.groupStore.artifact('pendingIntents')));
2125
+ const removalSettlesAt = belongsTo(rtc.removal, rtc.exposedState) ? settlesAt(rtc.removal, ctx.removalSettleMs) : undefined;
2126
+ return leaveViewOf(rtc.exposedState, self, summaries.some((r) => r.kind !== 'application'), removalSettlesAt);
2127
+ });
2128
+ },
2129
+ async proposeSelfRemove(groupId) {
2130
+ const rt = await heldRuntime(groupId, 'leave');
2131
+ await rt.run('leave', (rtc) => proposeSelfRemoveIntent(rtc));
2132
+ },
2133
+ async demote(groupId) {
2134
+ const rt = await heldRuntime(groupId, 'departAsAdmin');
2135
+ const self = await guard.call(ACCOUNT_SCOPE, 'signer', () => ctx.signer.getPublicKey());
2136
+ await rt.run('departAsAdmin', (rtc) => {
2137
+ const admins = (getMarmotGroupView(rtc.engine.state)?.adminPubkeys ?? []).filter((a) => a !== self);
2138
+ return setAdminsIntent(rtc, admins, 'departAsAdmin');
2139
+ });
2140
+ },
2141
+ purge(groupId, beforeClear) {
2142
+ purgeGenerations.set(groupId, (purgeGenerations.get(groupId) ?? 0) + 1);
2143
+ const run = purgeGroup(groupId, beforeClear);
2144
+ purgesInFlight.set(groupId, run);
2145
+ void run
2146
+ .finally(() => {
2147
+ if (purgesInFlight.get(groupId) === run)
2148
+ purgesInFlight.delete(groupId);
2149
+ })
2150
+ .catch(() => undefined);
2151
+ return run;
2152
+ },
2153
+ watch: watchState,
2154
+ };
2155
+ /** {@link TeardownGroupPort.purge}. */
2156
+ async function purgeGroup(groupId, beforeClear) {
2157
+ abandoned.add(groupId);
2158
+ leftMarked.delete(groupId);
2159
+ // AC-MX-2: a restore (or resume) of the group is ended first and its take-back awaited — before it has a
2160
+ // runtime it is in neither map below, and left running it would continue over the cleared stores (and hold its
2161
+ // reservation forever: the self-update record it waits on is gone). A resume is never started from here on.
2162
+ const restored = await endRestoresForPurge(groupId);
2163
+ const rt = runtimes.get(groupId) ?? (await loading.get(groupId)?.catch(() => undefined)) ?? restored;
2164
+ // F2: the stored epoch is read, and its watermark committed, in the same serialized step as the clear; then
2165
+ // AC-ADMIN-5: every artifact AND every extension namespace of the group, in one backend transaction.
2166
+ const deleteAll = async (store, live) => {
2167
+ // S10 (AC-ADMIN-7): the history backend's retained rumors go first — a failure leaves the group stored and
2168
+ // the purge is retried, never a purged group whose history survives in the backend. The group's history
2169
+ // worker is stopped first (no update is started after the purge); a purge that does not settle within the
2170
+ // history call timeout counts as failed, so a hanging backend never wedges the group's queue; the purge (and
2171
+ // the teardown) is retried at the teardown backoff until the backend answers.
2172
+ const history = ctx.history;
2173
+ if (history !== undefined) {
2174
+ // The worker's last call must have settled first, so a stalled append never lands after the purge.
2175
+ if (live !== undefined) {
2176
+ await stopHistoryDrain(live);
2177
+ await awaitHistoryCallSettled(live);
2178
+ await issueMutation(live, () => history.purge(groupId));
2179
+ }
2180
+ else {
2181
+ // No runtime in this client instance: none of its history calls can be outstanding.
2182
+ await boundedHistoryCall(ctx, guard, groupId, () => history.purge(groupId));
2183
+ }
2184
+ }
2185
+ const epoch = (await guard.call(groupId, 'store', () => readGroupState(store.artifact('clientState'))))?.groupContext.epoch;
2186
+ if (epoch !== undefined)
2187
+ await guard.call(ACCOUNT_SCOPE, 'store', () => beforeClear(epoch));
2188
+ await guard.call(groupId, 'store', () => store.clear());
2189
+ };
2190
+ if (rt !== undefined && !rt.abandoned && !rt.disposed) {
2191
+ // Last operation on the group's queue: every operation queued before it finishes first, none after it runs.
2192
+ await rt.run('abandon', async (rtc) => {
2193
+ await deleteAll(rtc.groupStore, rtc);
2194
+ retireRuntime(rtc, 'was left or abandoned');
2195
+ });
2196
+ }
2197
+ else {
2198
+ // A runtime this client retired or never loaded: any history call it issued is still waited for.
2199
+ await deleteAll(ctx.stores.groupFactory(groupId), rt);
2200
+ }
2201
+ if (rt !== undefined && runtimes.get(groupId) === rt)
2202
+ runtimes.delete(groupId);
2203
+ openedStores.delete(groupId);
2204
+ notifyState(groupId);
2205
+ }
2206
+ // ---------------------------------------------------------------------------
2207
+ // The competing-Welcome ports (epic marmot-welcome-race-joiner)
2208
+ // ---------------------------------------------------------------------------
2209
+ /** The listener {@link GroupRegistry.onGateMayHaveCleared} set. */
2210
+ let gateClearedListener;
2211
+ /** Tells the client that a condition the gate reports may have cleared for `groupId`. Never throws. */
2212
+ function gateMayHaveCleared(groupId) {
2213
+ const listener = gateClearedListener;
2214
+ if (listener === undefined || ctx.isDisposed())
2215
+ return;
2216
+ guard.detached(() => {
2217
+ try {
2218
+ listener(groupId);
2219
+ }
2220
+ catch {
2221
+ // A listener never breaks the operation that cleared the condition.
2222
+ }
2223
+ });
2224
+ }
2225
+ /**
2226
+ * `competingGate` (Design Decision 6): open only when nothing is changing the group's state under the decision.
2227
+ * Closed, with the first reason that holds: a restore in flight, a purge, a group torn down, a group not loaded
2228
+ * (a load is started: its first sync ending asks for the pass that decides), a retired runtime, a fenced or
2229
+ * disbanded group (over for good: reported `fenced`), an own commit, self-update or proposal pending, or the
2230
+ * group still syncing — its engine inside the quiescence window, or its first sync since the load not ended.
2231
+ */
2232
+ async function competingGateOp(groupId) {
2233
+ if (restoring.has(groupId))
2234
+ return { open: false, reason: 'restoring' };
2235
+ if (purgesInFlight.has(groupId))
2236
+ return { open: false, reason: 'purging' };
2237
+ if (abandoned.has(groupId))
2238
+ return { open: false, reason: 'abandoned' };
2239
+ const rt = runtimes.get(groupId);
2240
+ if (rt === undefined || (rt.disposed && !rt.abandoned)) {
2241
+ // Stored but not loaded: loaded now, so its first sync can end and ask for the pass that decides.
2242
+ if (!ctx.isDisposed())
2243
+ loadRuntime(groupId).catch(() => undefined);
2244
+ return { open: false, reason: 'not-loaded' };
2245
+ }
2246
+ if (rt.abandoned)
2247
+ return { open: false, reason: 'abandoned' };
2248
+ if (rt.fence !== undefined || rt.disbanded !== undefined)
2249
+ return { open: false, reason: 'fenced' };
2250
+ const summaries = await guard.call(groupId, 'store', () => listPendingIntentSummaries(rt.groupStore.artifact('pendingIntents')));
2251
+ if (summaries.some((r) => r.kind === 'commit' || r.kind === 'self-update' || r.kind === 'proposal'))
2252
+ return { open: false, reason: 'own-commit-pending' };
2253
+ // The engine's `convergenceStatuses.syncing` (not exported by marmot-engine's barrels).
2254
+ if (rt.engine.convergenceStatus === 'Syncing' || !rt.sendGateOpen)
2255
+ return { open: false, reason: 'syncing' };
2256
+ return { open: true };
2257
+ }
2258
+ /** The held branch of a stored or live state: its window-derived score, join facts and the tip's leaf accounts. */
2259
+ function heldViewOf(state, window, adoptedBy) {
2260
+ const epoch = Number(state.groupContext.epoch);
2261
+ // The window's root is the join root while it can be told from a root the horizon pruned to: a pruned root sits
2262
+ // exactly `REWIND_HORIZON` below the tip, so a root above that floor is the join (or creation) state, and one
2263
+ // carrying join evidence is the join state wherever it sits. A bare root at the floor is treated as pruned: an
2264
+ // untagged join exactly `REWIND_HORIZON` back is indistinguishable from it. That loses nothing: the decision's
2265
+ // bound (`tipEpoch - (joinEpoch - 1) <= REWIND_HORIZON`, the members' fork-parent bound) already puts a join root
2266
+ // that far back beyond the horizon.
2267
+ const root = canonicalPath(window)[0];
2268
+ const joinRoot = root !== undefined && (root.joinEvidence !== undefined || root.epoch > epoch - REWIND_HORIZON) ? root : undefined;
2269
+ const own = state.ratchetTree[Number(state.privatePath.leafIndex) * 2];
2270
+ return {
2271
+ epoch,
2272
+ tag: tagOf(state),
2273
+ joinEpoch: joinRoot?.epoch,
2274
+ joinTag: joinRoot?.tag,
2275
+ adoptedBy,
2276
+ pathTags: new Set(canonicalPath(window).map((n) => n.tag)),
2277
+ horizon: REWIND_HORIZON,
2278
+ score: heldBranchScore(window, state),
2279
+ ownLeafSignatureKey: own !== undefined && own !== null && own.nodeType === nodeTypes.leaf ? hex(own.leaf.signaturePublicKey) : undefined,
2280
+ memberAccounts: new Set(getGroupMemberPubkeys(state)),
2281
+ };
2282
+ }
2283
+ /** The group's account index entry (read through the group scope too, like a load does). */
2284
+ function indexEntryOf(groupId) {
2285
+ return guard.call(groupId, 'store', () => guard.call(ACCOUNT_SCOPE, 'store', () => readGroupIndexEntry(ctx.stores.account.extension(GROUP_INDEX_EXTENSION), groupId)));
2286
+ }
2287
+ /**
2288
+ * AC-FWJ-29: the keys of THIS device's directed ancestry for the held view's `ownLeafChain`: `deviceRegistry/self` and the
2289
+ * leaf the tip holds, each with every key from which it is reached along the recorded links (`DeviceLineage.ancestorsOf`,
2290
+ * not the lineage component: a live sibling installation sharing an origin key is another device). `undefined` when the
2291
+ * chain holds nothing beyond the held key, and when the account store cannot be read: the check then compares the
2292
+ * held key alone, as before, and the Welcome path is never blocked.
2293
+ *
2294
+ * The lineage and `self` are account-store reads made HERE, on their own, after the group reads and outside any group
2295
+ * transaction (lock order group -> account): the held view is built from frozen values.
2296
+ */
2297
+ async function ownLeafChainOf(groupId, held) {
2298
+ const read = ctx.deviceLineage.read;
2299
+ if (read === undefined)
2300
+ return undefined;
2301
+ try {
2302
+ const { lineage, self } = await guard.call(groupId, 'store', () => guard.call(ACCOUNT_SCOPE, 'store', async () => ({ lineage: await read(), self: await readDeviceSigningKey((fn) => ctx.stores.account.transaction(fn)) })));
2303
+ const chain = new Set();
2304
+ for (const key of [self?.leafKey, held.ownLeafSignatureKey]) {
2305
+ if (key === undefined)
2306
+ continue;
2307
+ chain.add(key);
2308
+ for (const ancestor of lineage.ancestorsOf(key))
2309
+ chain.add(ancestor);
2310
+ }
2311
+ // Nothing beyond the key the tip holds (the held key is self and has no ancestors): the check is unchanged.
2312
+ return [...chain].some((key) => key !== held.ownLeafSignatureKey) ? chain : undefined;
2313
+ }
2314
+ catch {
2315
+ return undefined;
2316
+ }
2317
+ }
2318
+ /** `CompetingWelcomePorts.withOwnLeafChain`: `held` with the device chain (see {@link ownLeafChainOf}) when it has one. */
2319
+ async function withOwnLeafChain(groupId, held) {
2320
+ const ownLeafChain = await ownLeafChainOf(groupId, held);
2321
+ return ownLeafChain === undefined ? held : { ...held, ownLeafChain };
2322
+ }
2323
+ /**
2324
+ * `heldBranch`: the stored group's branch, loaded or not (a loaded runtime's exposed state and window are the
2325
+ * stored ones). `undefined` ONLY while a restore of the group is in flight or marked unfinished, and when nothing
2326
+ * is stored.
2327
+ */
2328
+ async function heldBranchOp(groupId) {
2329
+ if (restoring.has(groupId))
2330
+ return undefined;
2331
+ const live = runtimes.get(groupId);
2332
+ if (live !== undefined && !live.disposed && !live.abandoned && !live.needsReload)
2333
+ return heldViewOf(live.exposedState, windowFor(live.window, live.exposedState), (await indexEntryOf(groupId))?.adoptedBy);
2334
+ if (abandoned.has(groupId))
2335
+ return undefined;
2336
+ const groupStore = groupStoreOf(groupId);
2337
+ if (await restorePending(groupId, groupStore))
2338
+ return undefined;
2339
+ const state = await guard.call(groupId, 'store', () => readGroupState(groupStore.artifact('clientState')));
2340
+ if (state === undefined)
2341
+ return undefined;
2342
+ const stored = await guard.call(groupId, 'store', () => readWindow(groupStore.artifact('rewindTree')));
2343
+ return heldViewOf(state, windowFor(stored, state), (await indexEntryOf(groupId))?.adoptedBy);
2344
+ }
2345
+ /** Where invitation `invitationId`'s switch to `to` stands in the STORED group (see `CompetingWelcomePorts.switchState`). */
2346
+ async function switchStateOp(groupId, to, invitationId) {
2347
+ if (abandoned.has(groupId))
2348
+ return 'absent';
2349
+ const groupStore = groupStoreOf(groupId);
2350
+ const state = await guard.call(groupId, 'store', () => readGroupState(groupStore.artifact('clientState')));
2351
+ if (state === undefined)
2352
+ return 'absent';
2353
+ if ((await guard.call(groupId, 'store', () => groupStore.extension(SWITCH_PROOF_EXTENSION).get(invitationId))) !== undefined)
2354
+ return 'written';
2355
+ const stored = await guard.call(groupId, 'store', () => readWindow(groupStore.artifact('rewindTree')));
2356
+ return carriesBranch(heldViewOf(state, windowFor(stored, state), undefined), to) ? 'foreign' : 'absent';
2357
+ }
2358
+ /**
2359
+ * The rest of a switch once the group state carries C (on the group's queue): the in-memory runtime follows the
2360
+ * durable state — reloaded when its window does not carry C yet (a failed rebuild, a crash recovered by a reload) —
2361
+ * its pre-join floor is read back from the index entry, and a history sync runs for the new branch. Idempotent. The
2362
+ * notifications of the switch were delivered by the process that ran the transaction (a restart loses them: the
2363
+ * ledger, the history outbox and the recheck marker are the durable record).
2364
+ */
2365
+ async function finishRebase(rt, to) {
2366
+ if (!rt.window.nodes.has(to) || rt.needsReload)
2367
+ await rt.reloadFromDurable();
2368
+ const entry = await indexEntryOf(rt.groupId);
2369
+ if (entry !== undefined)
2370
+ rt.joinedAtMs = entry.createdAt;
2371
+ rt.checkSyncRouting();
2372
+ requestHistoryResync(rt);
2373
+ // AC-REKEY-11: the competing Welcome's state may carry an old-key leaf as well.
2374
+ scheduleRekeyFollowUp(rt);
2375
+ }
2376
+ /** The switch itself, on the group's queue (Design Decision 8): re-validated, then one group transaction. */
2377
+ async function rebaseOnQueue(rt, request) {
2378
+ const { groupId } = rt;
2379
+ const store = rt.groupStore;
2380
+ const stored = await guard.call(groupId, 'store', () => readGroupState(store.artifact('clientState')));
2381
+ if (stored === undefined)
2382
+ return 'stale';
2383
+ const storedWindow = windowFor(await guard.call(groupId, 'store', () => readWindow(store.artifact('rewindTree'))), stored);
2384
+ const held = heldViewOf(stored, storedWindow, undefined);
2385
+ // A crash after the transaction: this invitation's switch committed (its durable proof), whatever the tip is by
2386
+ // now. Nothing is validated or written again. A group that carries C WITHOUT that proof reached it by ordinary
2387
+ // ingest: not a switch to run (the Welcome service keeps it out as the group's own lineage).
2388
+ const proven = (await guard.call(groupId, 'store', () => store.extension(SWITCH_PROOF_EXTENSION).get(request.invitationId))) !== undefined;
2389
+ if (proven) {
2390
+ await finishRebase(rt, request.to);
2391
+ return 'switched';
2392
+ }
2393
+ if (carriesBranch(held, request.to))
2394
+ return 'stale';
2395
+ // The decision was made against another tip than the stored one: re-decided next pass.
2396
+ if (held.tag !== request.from)
2397
+ return 'stale';
2398
+ // The gate, the classification and the decision, against the tip as it is NOW: a rebase never runs with a closed gate.
2399
+ if (!(await competingGateOp(groupId)).open)
2400
+ return 'stale';
2401
+ // The chain is read here, on the queue but before the group transaction (group -> account): a `switching` marker written
2402
+ // while the chain could not be read, or by a build without it, must not complete a switch the chain keeps out.
2403
+ if (judgeCompetingWelcome(await withOwnLeafChain(groupId, held), request.competing).decision !== 'switch')
2404
+ return 'stale';
2405
+ const joined = request.state;
2406
+ const epoch = joined.groupContext.epoch;
2407
+ const joinedWindow = tipOnlyWindow(joined, request.joinEvidence);
2408
+ // What the abandoned branch applied is diffed against C's tip with the window floor lowered to H's root: a
2409
+ // tip-only window floors at C's own epoch, which would count every state of H below it as pruned, not abandoned.
2410
+ const joinedTip = joinedWindow.nodes.get(joinedWindow.tipTag);
2411
+ const hRoot = canonicalPath(storedWindow)[0];
2412
+ const diffWindow = { tipTag: joinedWindow.tipTag, nodes: new Map([[joinedTip.tag, { ...joinedTip, epoch: Math.min(joinedTip.epoch, hRoot?.epoch ?? joinedTip.epoch) }]]) };
2413
+ const transition = await planTransition(rt, storedWindow, stored, joinedWindow, joined, [], new Set(), diffWindow);
2414
+ // Own application messages minted on the abandoned branch that are still on their way (published, not confirmed):
2415
+ // no member on C can read them, and confirmed later against C's tip-only window they would read as canonical. They
2416
+ // are withdrawn with the branch (ledgered, announced `message-withdrawn`) and their records dropped.
2417
+ const inFlight = (await guard.call(groupId, 'store', () => listPendingIntentRecords(store.artifact('pendingIntents')))).filter((r) => r.kind === 'application' && r.envelope !== undefined);
2418
+ // The state each went out under: its staged ordering key, else read from its envelope over H's engine (as the
2419
+ // confirmation does) — before the engine is rebuilt.
2420
+ const lost = [];
2421
+ for (const r of inFlight) {
2422
+ const envelope = r.envelope;
2423
+ const digest = r.ordering?.acceptedDigest ?? (await ownMessage(rt, r, envelope))?.orderingKey.acceptedDigest ?? '';
2424
+ lost.push({ type: 'message-withdrawn', eventId: envelope.id, acceptedDigest: digest });
2425
+ }
2426
+ const plan = lost.length === 0 ? transition : { ...transition, notifications: [...transition.notifications, ...lost], withdrawn: [...transition.withdrawn, ...lost] };
2427
+ // The pre-join ingest floor (what the index entry and `joinedAtMs` hold) goes down to C's Welcome, and the ingest
2428
+ // cursor with it, so what was sent on C before the switch is fetched again and delivered. The Welcome's stamp is
2429
+ // the sponsor's claim: clamped to [joinedAt - grace, now] so a forged one cannot reach back for ever.
2430
+ const nowMs = ctx.clock.now();
2431
+ const welcomeMs = Math.min(Math.max(request.welcomeCreatedAtMs, (rt.joinedAtMs ?? nowMs) - ctx.graceWindowMs), nowMs);
2432
+ const floorMs = rt.joinedAtMs === undefined ? undefined : Math.min(rt.joinedAtMs, welcomeMs);
2433
+ const cursorFloor = Math.floor(welcomeMs / 1000) - CURSOR_FUTURE_SKEW_S;
2434
+ let restored = [];
2435
+ await guard.call(groupId, 'store', () => store.transaction(async (tx) => {
2436
+ await writeGroupState(tx.artifact('clientState'), joined);
2437
+ await writeWindow(tx.artifact('rewindTree'), joinedWindow);
2438
+ // What the abandoned state held belongs to it: exactly what a Welcome adoption clears.
2439
+ await clearOpaque(tx.extension(OPAQUE_EXTENSION));
2440
+ await clearRemoval(tx.extension(REMOVAL_EXTENSION));
2441
+ await clearPendingLeaf(tx.extension(PENDING_LEAF_EXTENSION));
2442
+ await clearPendingCommit(tx.extension(PENDING_COMMIT_EXTENSION));
2443
+ for (const [i, record] of inFlight.entries()) {
2444
+ const envelope = record.envelope;
2445
+ await writeTerminalLedgerEntry(tx.artifact('terminalLedger'), envelope.id, {
2446
+ disposition: WITHDRAWN_DISPOSITION,
2447
+ at: ctx.clock.now(),
2448
+ createdAt: envelope.created_at,
2449
+ ...(lost[i].acceptedDigest === '' ? {} : { node: lost[i].acceptedDigest }),
2450
+ });
2451
+ await deletePendingIntentRecord(tx.artifact('pendingIntents'), record.intentId);
2452
+ }
2453
+ // The abandoned branch's messages withdrawn, its self-updates re-enqueued, the settlement-recheck marker
2454
+ // written (the switch is a rewind), the history backend's updates queued — one transition, one transaction.
2455
+ restored = await recordTransition(rt, tx, plan, epoch);
2456
+ const cursor = await readIngestCursor(tx.artifact('ingestCursor'));
2457
+ if (cursor !== undefined && (cursor.since > cursorFloor || (cursor.resume !== undefined && cursor.resume.from > cursorFloor))) {
2458
+ await writeIngestCursor(tx.artifact('ingestCursor'), {
2459
+ ...cursor,
2460
+ since: Math.min(cursor.since, cursorFloor),
2461
+ ...(cursor.resume === undefined ? {} : { resume: { ...cursor.resume, from: Math.min(cursor.resume.from, cursorFloor) } }),
2462
+ });
2463
+ }
2464
+ // The durable proof that this invitation's switch committed (it survives the window pruning the join root).
2465
+ await tx.extension(SWITCH_PROOF_EXTENSION).put(request.invitationId, { to: request.to });
2466
+ // The account's backup follows the new branch. A throw rolls the whole switch back; one raised by a hook itself is
2467
+ // reported as a hook refusal, which the Welcome service retries every pass without counting it toward its give-up.
2468
+ try {
2469
+ await runConfirmHooks({
2470
+ groupId,
2471
+ guard,
2472
+ hooks: confirmHooks.map((hook) => async (context) => {
2473
+ try {
2474
+ await hook(context);
2475
+ }
2476
+ catch (error) {
2477
+ throw new HookRefusal(error);
2478
+ }
2479
+ }),
2480
+ }, { intentId: groupId, kind: 'join', epoch, tx, persisted: () => ({ state: joined, window: joinedWindow }), notifications: [], createdAt: floorMs });
2481
+ }
2482
+ catch (cause) {
2483
+ if (!(cause instanceof HookRefusal))
2484
+ throw cause;
2485
+ throw new MarmotError('confirm-blocked', `rebaseToWelcome: an onConfirm hook refused the switch of group ${groupId}`, { cause: cause.error, details: { groupId, reason: 'hook', retryable: true } });
2486
+ }
2487
+ // Last, so a failure above leaves the floor where it was (a floor lowered for a switch that did not happen only refetches).
2488
+ if (floorMs !== undefined && floorMs < (rt.joinedAtMs ?? Infinity)) {
2489
+ await guard.call(ACCOUNT_SCOPE, 'store', () => ctx.stores.account.transaction(async (atx) => {
2490
+ const index = atx.extension(GROUP_INDEX_EXTENSION);
2491
+ const entry = await readGroupIndexEntry(index, groupId);
2492
+ if (entry !== undefined && entry.createdAt > floorMs)
2493
+ await writeGroupIndexEntry(index, groupId, { ...entry, createdAt: floorMs });
2494
+ }));
2495
+ }
2496
+ }));
2497
+ // Committed: the runtime follows. A failure from here leaves the durable state C's and the runtime reloaded
2498
+ // before its next operation; the next pass finds the stored group carrying C and finishes. The notifications and
2499
+ // the re-enqueues happen whatever the rebuild did (delivering never throws).
2500
+ let failure;
2501
+ try {
2502
+ rt.opaque = undefined;
2503
+ rt.removal = undefined;
2504
+ rt.pendingLeaf = undefined;
2505
+ rt.pendingCommit = undefined;
2506
+ await rt.rebuildEngine(copyOf(joined), joinedWindow);
2507
+ rt.exposedState = rt.engine.state;
2508
+ if (floorMs !== undefined)
2509
+ rt.joinedAtMs = floorMs;
2510
+ // Not caught up on the new branch until the sync below ran (a pass that began earlier proves nothing).
2511
+ rt.caughtUp = false;
2512
+ rt.connectivityGeneration += 1;
2513
+ }
2514
+ catch (error) {
2515
+ rt.needsReload = true;
2516
+ failure = { error };
2517
+ }
2518
+ await deliverTransition(rt, plan);
2519
+ const gone = new MarmotError('send-rejected', `group ${groupId} switched branch before the message was confirmed`, { details: { groupId, reason: 'branch-switched' } });
2520
+ for (const record of inFlight)
2521
+ notifySettled(rt, record, gone);
2522
+ scheduleWithdrawnRedrives(rt, plan);
2523
+ for (const intentId of restored)
2524
+ scheduleDeferredReenqueueRetry(rt, intentId);
2525
+ if (failure !== undefined)
2526
+ throw failure.error;
2527
+ // The lowered floor reaches the next pass even if a live event advances the stored cursor first (nextCursor would
2528
+ // recompute `since` from `high`): the catch-up floor is read afresh by that pass (BACKLOG welcome-race-rebase-lowers-only-stored).
2529
+ // Set before anything can start a pass. Residual: on the rebuild-failure path above the runtime reloads with no catch-up
2530
+ // floor and relies on the stored (lowered) `since` alone.
2531
+ const reachBack = cursorFloor - CURSOR_REDELIVERY_MARGIN_S;
2532
+ rt.catchUpSince = rt.catchUpSince === undefined ? reachBack : Math.min(rt.catchUpSince, reachBack);
2533
+ rt.checkSyncRouting();
2534
+ requestHistoryResync(rt);
2535
+ // AC-REKEY-11: the branch switched to may hold this device's leaf on a retired key (detached; queues only if owed).
2536
+ scheduleRekeyFollowUp(rt);
2537
+ return 'switched';
2538
+ }
2539
+ /** `rebaseToWelcome` (see {@link CompetingWelcomePorts.rebaseToWelcome}). */
2540
+ async function rebaseToWelcomeOp(request) {
2541
+ const { groupId } = request;
2542
+ // Refused without changing any store: a restore in flight decides the group first (AC-FWJ-25); a group torn down
2543
+ // is gone.
2544
+ if (restoring.has(groupId) || purgesInFlight.has(groupId) || abandoned.has(groupId))
2545
+ return 'stale';
2546
+ const rt = await loadRuntime(groupId);
2547
+ if (rt === undefined || rt.abandoned || rt.disposed)
2548
+ return 'stale';
2549
+ return rt.run('rebaseToWelcome', (rtc) => rebaseOnQueue(rtc, request)).catch((error) => {
2550
+ // A purge retired the runtime while the switch waited on the queue.
2551
+ if (rt.abandoned && isMarmotError(error, 'not-a-member'))
2552
+ return 'stale';
2553
+ throw error;
2554
+ });
2555
+ }
2556
+ const competingPorts = {
2557
+ competingGate: competingGateOp,
2558
+ heldBranch: heldBranchOp,
2559
+ withOwnLeafChain,
2560
+ rebaseToWelcome: rebaseToWelcomeOp,
2561
+ switchState: switchStateOp,
2562
+ onBranchSwitched(switched) {
2563
+ ctx.emit('groupBranchSwitched', { invitationId: switched.invitationId, groupId: switched.groupId, from: switched.from, to: switched.to });
2564
+ },
2565
+ };
2566
+ return {
2567
+ devicePort,
2568
+ teardownPort,
2569
+ groups: {
2570
+ create: createGroupOp,
2571
+ get: getGroupOp,
2572
+ list: listGroupsOp,
2573
+ restore: restoreGroupOp,
2574
+ },
2575
+ adoptJoinedGroup: adoptJoinedGroupOp,
2576
+ competing: competingPorts,
2577
+ onGateMayHaveCleared(listener) {
2578
+ gateClearedListener = listener;
2579
+ },
2580
+ hasGroup: hasGroupOp,
2581
+ onRestoreReleased(listener) {
2582
+ restoreReleased = listener;
2583
+ },
2584
+ onConfirm(hook) {
2585
+ if (typeof hook !== 'function')
2586
+ throw new MarmotError('invalid-options', 'extensions.onConfirm: hook must be a function');
2587
+ confirmHooks.push(hook);
2588
+ return () => {
2589
+ const i = confirmHooks.indexOf(hook);
2590
+ if (i >= 0)
2591
+ confirmHooks.splice(i, 1);
2592
+ };
2593
+ },
2594
+ checkProposalDeadlines() {
2595
+ for (const rt of runtimes.values())
2596
+ if (!rt.disposed && !rt.abandoned)
2597
+ scheduleProposalDeadlineCheck(rt);
2598
+ },
2599
+ resumeUnfinishedRestores() {
2600
+ if (ctx.isDisposed() || resumeScan !== undefined)
2601
+ return;
2602
+ if (indexScanned && leftMarked.size === 0 && leftRecords.size === 0)
2603
+ return;
2604
+ guard.detached(() => {
2605
+ const scan = (async () => {
2606
+ let ids;
2607
+ let records;
2608
+ if (indexScanned) {
2609
+ ids = [...leftMarked];
2610
+ leftMarked.clear();
2611
+ records = [...leftRecords];
2612
+ leftRecords.clear();
2613
+ }
2614
+ else {
2615
+ // The adoptions the index may not name yet first (a crash mid-adoption), then the whole index.
2616
+ records = await guard.call(ACCOUNT_SCOPE, 'store', () => listRestoringRecords(ctx.stores.account.extension(RESTORING_EXTENSION)));
2617
+ ids = await guard.call(ACCOUNT_SCOPE, 'store', () => listGroupIndex(ctx.stores.account.extension(GROUP_INDEX_EXTENSION)));
2618
+ indexScanned = true;
2619
+ }
2620
+ for (const id of records) {
2621
+ if (ctx.isDisposed())
2622
+ return;
2623
+ try {
2624
+ await settleRestoringRecord(id);
2625
+ }
2626
+ catch {
2627
+ if (!abandoned.has(id))
2628
+ leftRecords.add(id);
2629
+ }
2630
+ }
2631
+ for (const id of ids) {
2632
+ if (ctx.isDisposed())
2633
+ return;
2634
+ try {
2635
+ await unfinishedRestore(id);
2636
+ }
2637
+ catch {
2638
+ if (!abandoned.has(id))
2639
+ leftMarked.add(id);
2640
+ }
2641
+ }
2642
+ })();
2643
+ resumeScan = scan;
2644
+ void scan
2645
+ .catch(() => undefined)
2646
+ .finally(() => {
2647
+ if (resumeScan === scan)
2648
+ resumeScan = undefined;
2649
+ });
2650
+ });
2651
+ },
2652
+ dispose() {
2653
+ // Every runtime is torn down even when a step throws (a transport
2654
+ // unsubscribe, an engine dispose): the errors are returned, not thrown.
2655
+ const errors = [];
2656
+ for (const rt of runtimes.values()) {
2657
+ rt.disposed = true;
2658
+ for (const handle of rt.pipelineTimers) {
2659
+ try {
2660
+ ctx.timers.clear(handle);
2661
+ }
2662
+ catch (error) {
2663
+ errors.push(error);
2664
+ }
2665
+ }
2666
+ rt.pipelineTimers.clear();
2667
+ rt.reenqueueRetryArmed.clear();
2668
+ for (const waiter of rt.queueWaiters.values())
2669
+ waiter.reject(new MarmotError('disposed', 'send: client was disposed before the queued rumor was published'));
2670
+ rt.queueWaiters.clear();
2671
+ for (const waiter of rt.syncWaiters)
2672
+ waiter.reject(new MarmotError('disposed', 'synced: client was disposed before the group completed its first sync'));
2673
+ rt.syncWaiters.clear();
2674
+ endRuntime(rt, { reason: 'disposed' });
2675
+ try {
2676
+ stopGroupSync(rt);
2677
+ }
2678
+ catch (error) {
2679
+ errors.push(error);
2680
+ }
2681
+ try {
2682
+ rt.engine.dispose();
2683
+ }
2684
+ catch (error) {
2685
+ errors.push(error);
2686
+ }
2687
+ }
2688
+ for (const restore of restoring.values())
2689
+ restore.abort();
2690
+ markClientDisposed();
2691
+ runtimes.clear();
2692
+ loading.clear();
2693
+ openedStores.clear();
2694
+ confirmHooks.length = 0;
2695
+ rewindListeners.clear();
2696
+ restoredListeners.clear();
2697
+ rotationListeners.clear();
2698
+ return errors;
2699
+ },
2700
+ };
2701
+ }