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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/CHANGELOG.md +739 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -2
  4. package/dist/account/admin.d.ts +72 -0
  5. package/dist/account/admin.js +209 -0
  6. package/dist/account/device-deps.d.ts +379 -0
  7. package/dist/account/device-deps.js +36 -0
  8. package/dist/account/device-lineage.d.ts +199 -0
  9. package/dist/account/device-lineage.js +390 -0
  10. package/dist/account/device-registry.d.ts +93 -0
  11. package/dist/account/device-registry.js +1290 -0
  12. package/dist/account/device-rotation.d.ts +61 -0
  13. package/dist/account/device-rotation.js +827 -0
  14. package/dist/account/enrolment.d.ts +339 -0
  15. package/dist/account/enrolment.js +1247 -0
  16. package/dist/account/identity-proof.d.ts +79 -0
  17. package/dist/account/identity-proof.js +264 -0
  18. package/dist/account/index.d.ts +17 -0
  19. package/dist/account/index.js +16 -0
  20. package/dist/account/restore-rotation.d.ts +21 -0
  21. package/dist/account/restore-rotation.js +22 -0
  22. package/dist/account/same-account-authorization.d.ts +86 -0
  23. package/dist/account/same-account-authorization.js +180 -0
  24. package/dist/account/teardown.d.ts +190 -0
  25. package/dist/account/teardown.js +878 -0
  26. package/dist/client/admission-cleanup.d.ts +197 -0
  27. package/dist/client/admission-cleanup.js +635 -0
  28. package/dist/client/adoption-proof.d.ts +39 -0
  29. package/dist/client/adoption-proof.js +102 -0
  30. package/dist/client/before-create-group.d.ts +18 -0
  31. package/dist/client/before-create-group.js +65 -0
  32. package/dist/client/before-publish-hooks.d.ts +121 -0
  33. package/dist/client/before-publish-hooks.js +182 -0
  34. package/dist/client/client-config.d.ts +42 -0
  35. package/dist/client/client-config.js +13 -0
  36. package/dist/client/commit-redrive.d.ts +92 -0
  37. package/dist/client/commit-redrive.js +274 -0
  38. package/dist/client/component-update.d.ts +43 -0
  39. package/dist/client/component-update.js +53 -0
  40. package/dist/client/confirm-hooks.d.ts +55 -0
  41. package/dist/client/confirm-hooks.js +74 -0
  42. package/dist/client/create-client.d.ts +1126 -0
  43. package/dist/client/create-client.js +1232 -0
  44. package/dist/client/group-availability.d.ts +182 -0
  45. package/dist/client/group-availability.js +301 -0
  46. package/dist/client/group-disband.d.ts +28 -0
  47. package/dist/client/group-disband.js +64 -0
  48. package/dist/client/group-history.d.ts +461 -0
  49. package/dist/client/group-history.js +1365 -0
  50. package/dist/client/group-profile.d.ts +31 -0
  51. package/dist/client/group-profile.js +62 -0
  52. package/dist/client/group-records.d.ts +522 -0
  53. package/dist/client/group-records.js +1117 -0
  54. package/dist/client/group-removal.d.ts +36 -0
  55. package/dist/client/group-removal.js +127 -0
  56. package/dist/client/group-remove-member.d.ts +49 -0
  57. package/dist/client/group-remove-member.js +163 -0
  58. package/dist/client/group-runtime.d.ts +415 -0
  59. package/dist/client/group-runtime.js +2811 -0
  60. package/dist/client/group-snapshot.d.ts +104 -0
  61. package/dist/client/group-snapshot.js +474 -0
  62. package/dist/client/history-pages.d.ts +107 -0
  63. package/dist/client/history-pages.js +194 -0
  64. package/dist/client/inbox-send.d.ts +19 -0
  65. package/dist/client/inbox-send.js +71 -0
  66. package/dist/client/index.d.ts +24 -0
  67. package/dist/client/index.js +13 -0
  68. package/dist/client/ingest.d.ts +82 -0
  69. package/dist/client/ingest.js +1584 -0
  70. package/dist/client/invitation-outcomes.d.ts +50 -0
  71. package/dist/client/invitation-outcomes.js +135 -0
  72. package/dist/client/lifecycle-events.d.ts +63 -0
  73. package/dist/client/lifecycle-events.js +35 -0
  74. package/dist/client/opaque-candidates.d.ts +82 -0
  75. package/dist/client/opaque-candidates.js +170 -0
  76. package/dist/client/own-change-outbox.d.ts +66 -0
  77. package/dist/client/own-change-outbox.js +158 -0
  78. package/dist/client/pending-leaf.d.ts +116 -0
  79. package/dist/client/pending-leaf.js +378 -0
  80. package/dist/client/permissions.d.ts +9 -0
  81. package/dist/client/permissions.js +12 -0
  82. package/dist/client/pipeline.d.ts +583 -0
  83. package/dist/client/pipeline.js +3666 -0
  84. package/dist/client/reentrancy-guard.d.ts +102 -0
  85. package/dist/client/reentrancy-guard.js +159 -0
  86. package/dist/client/rekey.d.ts +58 -0
  87. package/dist/client/rekey.js +149 -0
  88. package/dist/client/transport-policy.d.ts +181 -0
  89. package/dist/client/transport-policy.js +214 -0
  90. package/dist/history/admission-lineage.d.ts +186 -0
  91. package/dist/history/admission-lineage.js +589 -0
  92. package/dist/history/equivocation.d.ts +55 -0
  93. package/dist/history/equivocation.js +113 -0
  94. package/dist/history/fencing.d.ts +66 -0
  95. package/dist/history/fencing.js +121 -0
  96. package/dist/history/hex.d.ts +3 -0
  97. package/dist/history/hex.js +10 -0
  98. package/dist/history/index.d.ts +74 -0
  99. package/dist/history/index.js +32 -0
  100. package/dist/history/notifications.d.ts +270 -0
  101. package/dist/history/notifications.js +264 -0
  102. package/dist/history/ordering-key.d.ts +24 -0
  103. package/dist/history/ordering-key.js +101 -0
  104. package/dist/history/own-change-fork.d.ts +112 -0
  105. package/dist/history/own-change-fork.js +196 -0
  106. package/dist/history/own-change.d.ts +118 -0
  107. package/dist/history/own-change.js +146 -0
  108. package/dist/history/policy.d.ts +48 -0
  109. package/dist/history/policy.js +52 -0
  110. package/dist/history/retained-window.d.ts +215 -0
  111. package/dist/history/retained-window.js +565 -0
  112. package/dist/inbox/demux.d.ts +90 -0
  113. package/dist/inbox/demux.js +78 -0
  114. package/dist/inbox/handler-registry.d.ts +42 -0
  115. package/dist/inbox/handler-registry.js +37 -0
  116. package/dist/inbox/index.d.ts +11 -0
  117. package/dist/inbox/index.js +10 -0
  118. package/dist/inbox/seen-set.d.ts +82 -0
  119. package/dist/inbox/seen-set.js +202 -0
  120. package/dist/inbox/subscription.d.ts +236 -0
  121. package/dist/inbox/subscription.js +644 -0
  122. package/dist/index.d.ts +10 -0
  123. package/dist/index.js +9 -0
  124. package/dist/invitations/competing-welcome.d.ts +223 -0
  125. package/dist/invitations/competing-welcome.js +128 -0
  126. package/dist/invitations/decline.d.ts +67 -0
  127. package/dist/invitations/decline.js +149 -0
  128. package/dist/invitations/delivery-evidence.d.ts +288 -0
  129. package/dist/invitations/delivery-evidence.js +766 -0
  130. package/dist/invitations/expect-welcome.d.ts +66 -0
  131. package/dist/invitations/expect-welcome.js +138 -0
  132. package/dist/invitations/index.d.ts +18 -0
  133. package/dist/invitations/index.js +18 -0
  134. package/dist/invitations/invitation-outcome.d.ts +110 -0
  135. package/dist/invitations/invitation-outcome.js +210 -0
  136. package/dist/invitations/invite.d.ts +358 -0
  137. package/dist/invitations/invite.js +1102 -0
  138. package/dist/invitations/offers.d.ts +79 -0
  139. package/dist/invitations/offers.js +115 -0
  140. package/dist/invitations/on-proposal.d.ts +47 -0
  141. package/dist/invitations/on-proposal.js +40 -0
  142. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  143. package/dist/invitations/pending-proposal-policy.js +139 -0
  144. package/dist/invitations/proposal-deadline.d.ts +133 -0
  145. package/dist/invitations/proposal-deadline.js +164 -0
  146. package/dist/invitations/relay-planes.d.ts +43 -0
  147. package/dist/invitations/relay-planes.js +70 -0
  148. package/dist/invitations/welcome-processor.d.ts +272 -0
  149. package/dist/invitations/welcome-processor.js +1241 -0
  150. package/dist/key-packages/device-key.d.ts +131 -0
  151. package/dist/key-packages/device-key.js +272 -0
  152. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  153. package/dist/key-packages/device-rotation-records.js +173 -0
  154. package/dist/key-packages/group-refs.d.ts +40 -0
  155. package/dist/key-packages/group-refs.js +79 -0
  156. package/dist/key-packages/index.d.ts +18 -0
  157. package/dist/key-packages/index.js +18 -0
  158. package/dist/key-packages/key-package-ref.d.ts +16 -0
  159. package/dist/key-packages/key-package-ref.js +21 -0
  160. package/dist/key-packages/observation-stream.d.ts +4 -0
  161. package/dist/key-packages/observation-stream.js +120 -0
  162. package/dist/key-packages/offer-rumor.d.ts +26 -0
  163. package/dist/key-packages/offer-rumor.js +69 -0
  164. package/dist/key-packages/publisher.d.ts +174 -0
  165. package/dist/key-packages/publisher.js +1247 -0
  166. package/dist/key-packages/select-key-package.d.ts +24 -0
  167. package/dist/key-packages/select-key-package.js +90 -0
  168. package/dist/key-packages/slot-manager.d.ts +167 -0
  169. package/dist/key-packages/slot-manager.js +327 -0
  170. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  171. package/dist/key-packages/validate-key-package-event.js +49 -0
  172. package/dist/media/cache.d.ts +14 -0
  173. package/dist/media/cache.js +10 -0
  174. package/dist/media/index.d.ts +52 -0
  175. package/dist/media/index.js +71 -0
  176. package/dist/mls.d.ts +15 -0
  177. package/dist/mls.js +15 -0
  178. package/dist/shared/account-pubkey.d.ts +4 -0
  179. package/dist/shared/account-pubkey.js +10 -0
  180. package/dist/shared/errors.d.ts +28 -0
  181. package/dist/shared/errors.js +96 -0
  182. package/dist/shared/hex.d.ts +4 -0
  183. package/dist/shared/hex.js +13 -0
  184. package/dist/shared/index.d.ts +14 -0
  185. package/dist/shared/index.js +14 -0
  186. package/dist/shared/kinds.d.ts +8 -0
  187. package/dist/shared/kinds.js +28 -0
  188. package/dist/shared/publish-classification.d.ts +26 -0
  189. package/dist/shared/publish-classification.js +31 -0
  190. package/dist/storage/envelope.d.ts +39 -0
  191. package/dist/storage/envelope.js +201 -0
  192. package/dist/storage/index.d.ts +237 -0
  193. package/dist/storage/index.js +491 -0
  194. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  195. package/dist/storage/indexeddb/idb-types.js +1 -0
  196. package/dist/storage/indexeddb/index.d.ts +17 -0
  197. package/dist/storage/indexeddb/index.js +141 -0
  198. package/dist/storage/lease.d.ts +54 -0
  199. package/dist/storage/lease.js +168 -0
  200. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  201. package/dist/storage/memory/deterministic-signer.js +65 -0
  202. package/dist/storage/memory/index.d.ts +32 -0
  203. package/dist/storage/memory/index.js +87 -0
  204. package/dist/storage/memory/lock-manager.d.ts +8 -0
  205. package/dist/storage/memory/lock-manager.js +71 -0
  206. package/package.json +66 -3
@@ -0,0 +1,878 @@
1
+ /**
2
+ * Group teardown (S9; AC-ADMIN-3, -5, -6, -7, -10): `leave()`, `abandon()`,
3
+ * `destroy()` and `departAsAdmin()` as ONE durable intent per group, and the
4
+ * per-group `leave()` that `devices.forget(ownLeafKey)` runs on every held
5
+ * group.
6
+ *
7
+ * The intent is an account record (extension `marmot.teardown`, keyed by a
8
+ * random request id) written before any effect — the group store is exactly
9
+ * what the teardown deletes, so the record cannot live there. Its phases:
10
+ *
11
+ * 1. `leaving` (leave only): the local leaf's SelfRemove proposal goes out
12
+ * through the pipeline's durable intents (re-proposed whenever an epoch
13
+ * change drops it); a leaf that is its admin account's last first
14
+ * commits the account's demotion (`departAsAdmin`). The phase ends when
15
+ * the group's own state shows the leaf removed — a peer's confirmed
16
+ * commit, the engine's SelfRemove auto-commit on some other member —
17
+ * or at the absolute `deadline` (`leaveTimeoutMs` after the request, on
18
+ * the client clock; re-armed after a reload), or at once when the leaf
19
+ * is the group's only member (nothing is sent). A leaf that is (or
20
+ * becomes, while this runs) the last leaf of the group's last active
21
+ * admin cannot leave: the intent ends `last-admin` straight to `done`,
22
+ * WITHOUT the purge — the group keeps its admin and stays held.
23
+ * 2. `purging` (every kind — this IS `abandon()`): the group runtime is
24
+ * retired and every artifact of the group's `GroupStore` deleted
25
+ * (nothing is published), then ONE account transaction drops what the
26
+ * account keeps per group — `invites` (Welcome deliveries),
27
+ * `enrolmentManifests`, still-`pending` invitations, received KeyPackage
28
+ * offers, `keyPackageGroupRefs`, and the group's index entry — and, for
29
+ * `destroy()`, the retained (grace-window) init keys of the KeyPackages
30
+ * the group's Welcomes consumed.
31
+ * 3. `deleting` (destroy only): S4's `forget()` — a durable kind-5 on the
32
+ * KeyPackage's slot — for every KeyPackage the account minted for the
33
+ * group (captured when the destroy was requested, before the purge
34
+ * deleted the refs): `keyPackages.offer({ groupId })` KeyPackages and
35
+ * the per-group KeyPackages of an enrolment request.
36
+ *
37
+ * `abandon()` / `destroy()` requested while a `leave()` runs take the
38
+ * record over (outcome `abandoned`); a second `leave()` joins the running
39
+ * one. A request joins only a record still in `leaving` or `purging` — the
40
+ * group's FRONT intent, at most one per group. A record past its purge
41
+ * (`deleting`) no longer stands for the group: the state it deleted is gone,
42
+ * and a group held again was re-joined through a newer Welcome (S11's join
43
+ * barrier lets none through earlier), so a request records a FRESH intent
44
+ * beside it (`succeeds` names it) instead of resolving on the old one's
45
+ * progress (S16). The front intent runs on one driver per group; each
46
+ * past-purge record's kind-5 pass on its own driver — the two settle
47
+ * independently: the fresh intent never waits on the old destroy's signer or
48
+ * relays, and the old one's deletions are neither dropped nor issued twice
49
+ * (the fresh destroy's KeyPackage capture skips refs an older record of the
50
+ * group still deletes). A driver re-reads its record inside every
51
+ * transaction and never holds one across a group operation, signer or relay
52
+ * call. Failures a pass counts (not explicitly transient,
53
+ * `maintenanceFailureReason`) — each charged to the record its driver was
54
+ * driving — give that intent up after {@link MAX_MAINTENANCE_FAILURES}
55
+ * (`maintenanceFailed`, kind `teardown`); any work left is retried by a
56
+ * background pass, each driver at its own capped backoff, and the
57
+ * next inbox pass or `groups.list()/get()` resumes intents a reload
58
+ * interrupted.
59
+ */
60
+ import { indexEntryView, isMalformedRowError, manifestRefsOfGroup, purgeGroupInvitations, purgeGroupInvites, purgeGroupManifests, purgeGroupOffers, stampAdoptions } from '../invitations/index.js';
61
+ import { maintenanceFailureReason } from '../inbox/index.js';
62
+ import { keyPackageRefsOfGroup, purgeKeyPackageGroupRefs, purgeRetainedKeyPackageKeys } from '../key-packages/index.js';
63
+ import { isMarmotError, MarmotError } from '../shared/index.js';
64
+ import { MAX_MAINTENANCE_FAILURES } from './device-deps.js';
65
+ /** Account extension namespace of teardown intents. */
66
+ export const TEARDOWN_EXTENSION = 'marmot.teardown';
67
+ /** Default `leaveTimeoutMs`: how long `leave()` waits for a peer's commit before purging anyway. */
68
+ export const DEFAULT_LEAVE_TIMEOUT_MS = 60_000;
69
+ /** Settled intents are kept this long (a `devices.forget` reads its groups' outcomes from them). */
70
+ const SETTLED_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
71
+ // ---------------------------------------------------------------------------
72
+ // Records
73
+ // ---------------------------------------------------------------------------
74
+ const PHASES = new Set(['leaving', 'purging', 'deleting', 'done']);
75
+ const KINDS = new Set(['leave', 'abandon', 'destroy']);
76
+ function malformed(key) {
77
+ return new MarmotError('store-failed', `${TEARDOWN_EXTENSION}/${key}: malformed record`, { details: { key, malformed: true } });
78
+ }
79
+ function decodeRecord(key, raw) {
80
+ const r = raw;
81
+ if (typeof r !== 'object' || r === null || r.v !== 1 || r.requestId !== key || typeof r.groupId !== 'string')
82
+ throw malformed(key);
83
+ if (typeof r.kind !== 'string' || !KINDS.has(r.kind) || typeof r.phase !== 'string' || !PHASES.has(r.phase) || typeof r.startedAt !== 'number')
84
+ throw malformed(key);
85
+ if (r.keyPackages !== undefined && !Array.isArray(r.keyPackages))
86
+ throw malformed(key);
87
+ return r;
88
+ }
89
+ async function readRecord(view, requestId) {
90
+ const raw = await view.get(requestId);
91
+ return raw === undefined ? undefined : decodeRecord(requestId, raw);
92
+ }
93
+ async function writeRecord(view, record) {
94
+ await view.put(record.requestId, record);
95
+ }
96
+ /**
97
+ * Every record. A malformed one is skipped (it cannot be driven, and must not block the others); a storage failure
98
+ * is NOT (F1) — it propagates, so a resume pass retries rather than concluding there is nothing to resume, and a
99
+ * request fails rather than miss an active intent and record a duplicate.
100
+ */
101
+ async function listRecords(view) {
102
+ const out = [];
103
+ for (const key of await view.keys()) {
104
+ const raw = await view.get(key);
105
+ if (raw === undefined)
106
+ continue;
107
+ try {
108
+ out.push(decodeRecord(key, raw));
109
+ }
110
+ catch {
111
+ // malformed: skipped
112
+ }
113
+ }
114
+ return out;
115
+ }
116
+ const isActive = (r) => r.phase !== 'done' && r.gaveUp === undefined;
117
+ /** The group's front intent: active and not yet past its purge (a request joins it; at most one per group). */
118
+ const isFront = (r) => isActive(r) && (r.phase === 'leaving' || r.phase === 'purging');
119
+ /** Active and past its purge: only a destroy's kind-5 deletions remain; it no longer stands for the group. */
120
+ const isPastPurge = (r) => isActive(r) && r.phase === 'deleting';
121
+ /** The group's front intent and its past-purge records, from one read of every record. */
122
+ function ofGroup(records, groupId) {
123
+ const mine = records.filter((r) => r.groupId === groupId);
124
+ return { front: mine.find(isFront), pastPurge: mine.filter(isPastPurge) };
125
+ }
126
+ function randomId() {
127
+ const bytes = new Uint8Array(16);
128
+ globalThis.crypto.getRandomValues(bytes);
129
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
130
+ }
131
+ function backoffMs(count) {
132
+ return Math.min(1000 * 2 ** Math.max(0, count - 1), 60_000);
133
+ }
134
+ /** Errors after which a driver stops (the next pass or client resumes the record). */
135
+ function stops(error) {
136
+ return isMarmotError(error, 'disposed') || isMarmotError(error, 'no-lease') || isMarmotError(error, 'reentrant');
137
+ }
138
+ /** A group operation refused for a reason that clears by itself (an own commit in flight, a blocked confirmation, a publish the pipeline retries). */
139
+ function transientGroupFailure(error) {
140
+ return isMarmotError(error, 'commit-pending') || isMarmotError(error, 'confirm-blocked') || maintenanceFailureReason(error) === undefined;
141
+ }
142
+ // ---------------------------------------------------------------------------
143
+ // Purge watermarks (F3)
144
+ // ---------------------------------------------------------------------------
145
+ /**
146
+ * Account extension of per-group purge watermarks: `groupId` → `{ epoch, at }`, the highest epoch this client
147
+ * purged of the group. Kept apart from the teardown records (pruned after 7 days) so a delayed Welcome of the old
148
+ * group is refused for as long as one could still be joined: a Welcome needs its KeyPackage's private key, and a
149
+ * KeyPackage lives at most `MAX_KEY_PACKAGE_LIFETIME` (engine: 7 261 200 s ≈ 84 days) — so a watermark is pruned
150
+ * after {@link WATERMARK_RETENTION_MS} (90 days, with margin); a later purge of the group replaces it.
151
+ */
152
+ export const PURGE_WATERMARK_EXTENSION = 'marmot.purged';
153
+ export const WATERMARK_RETENTION_MS = 90 * 24 * 60 * 60 * 1000;
154
+ async function readWatermark(t, groupId) {
155
+ const raw = (await t.extension(PURGE_WATERMARK_EXTENSION).get(groupId));
156
+ return typeof raw?.epoch === 'bigint' ? raw.epoch : undefined;
157
+ }
158
+ async function writeWatermark(t, groupId, epoch, nowMs) {
159
+ const view = t.extension(PURGE_WATERMARK_EXTENSION);
160
+ for (const key of await view.keys()) {
161
+ const at = (await view.get(key))?.at;
162
+ if (key !== groupId && (typeof at !== 'number' || at + WATERMARK_RETENTION_MS < nowMs))
163
+ await view.delete(key);
164
+ }
165
+ const current = await readWatermark(t, groupId);
166
+ await view.put(groupId, { epoch: current !== undefined && current > epoch ? current : epoch, at: nowMs });
167
+ }
168
+ function throwFailure(outcome) {
169
+ if (outcome.failure !== undefined)
170
+ throw outcome.failure.error;
171
+ }
172
+ export function createTeardownService(deps) {
173
+ let disposed = false;
174
+ /** One driver per group for its front intent. */
175
+ const running = new Map();
176
+ /** One kind-5 pass per past-purge record (by request id), apart from the group's front driver. */
177
+ const deleting = new Map();
178
+ /**
179
+ * Retry backoff per driver key (`front:<groupId>`, `delete:<requestId>`, `scan`): consecutive passes of that
180
+ * driver that failed or left work pending. A driver that settles clean drops its key; one that never settles
181
+ * (a kind-5 waiting on a signer) holds nobody else's back.
182
+ */
183
+ const backoff = new Map();
184
+ /** One purge per group at a time — the driver's and `finishPurge`'s (AB1). */
185
+ const purging = new Map();
186
+ const sleepers = new Map();
187
+ /**
188
+ * The armed resume timers, each with the host delay it was armed with (AC-HYG-1). Host timers run on the host's
189
+ * clock, not the client clock, so no client-clock comparison can tell which fires first after a clock jump; an
190
+ * armed timer covers a new request only when its own delay is no longer than the new one. The first to fire runs
191
+ * the resume pass and clears the rest. Each added timer is strictly shorter than every one still armed, so there
192
+ * are at most as many as distinct backoff delays.
193
+ */
194
+ const resumeTimers = new Map();
195
+ /** A scan found no unfinished intent and none was recorded since: `resumeInBackground` has nothing to do. */
196
+ let idle = false;
197
+ function assertLive(operation) {
198
+ if (disposed || deps.isDisposed())
199
+ throw new MarmotError('disposed', `${operation}: client has been disposed`);
200
+ }
201
+ function tx(fn) {
202
+ return deps.transaction((t) => fn(t.extension(TEARDOWN_EXTENSION), t));
203
+ }
204
+ function wakeGroup(groupId) {
205
+ for (const s of sleepers.get(groupId) ?? [])
206
+ s.wake();
207
+ }
208
+ // -- requests ---------------------------------------------------------------
209
+ /**
210
+ * The KeyPackages minted for `groupId` (`keyPackageGroupRefs`: offers, enrolment requests) and the refs whose
211
+ * retained keys go with the group — those plus every KeyPackageRef a manifest or an invitation of the group
212
+ * names (read before the purge deletes them). Only the minted ones get a kind-5: a manifest may name an
213
+ * ordinary KeyPackage (`expectWelcome` of a routine one), whose slot is not the group's to delete. A ref an
214
+ * older record of the group still deletes (`owned`) is left to it — one kind-5 per KeyPackage.
215
+ */
216
+ async function captureRefs(t, groupId, owned) {
217
+ const minted = (await keyPackageRefsOfGroup(t, groupId)).filter((ref) => !owned.has(ref));
218
+ const consumed = [...(await manifestRefsOfGroup(t, groupId))];
219
+ for (const key of await t.artifact('pendingInvitations').keys()) {
220
+ const raw = (await t.artifact('pendingInvitations').get(key));
221
+ if (typeof raw === 'object' && raw !== null && raw.groupId === groupId && typeof raw.keyPackageRef === 'string')
222
+ consumed.push(raw.keyPackageRef);
223
+ }
224
+ return { keyPackages: minted.map((ref) => ({ ref, status: 'pending', failures: 0 })), retainedRefs: [...new Set([...minted, ...consumed])] };
225
+ }
226
+ /**
227
+ * Records a teardown of `kind` for `groupId` — or joins / takes over the
228
+ * group's front intent — in ONE transaction; resolves with the record now
229
+ * active. A record past its purge is never joined (S16): the group it tore
230
+ * down is gone, and one held now was re-joined — a fresh record is written
231
+ * beside it (`succeeds`), and the old one keeps deleting on its own.
232
+ *
233
+ * `refused`: a leave refused up front (`startLeave`'s last-admin pre-check) — recorded settled, so an own-leaf
234
+ * forget reads its outcome, and never driven. A front intent of the group is still joined instead.
235
+ */
236
+ function request(groupId, kind, refused) {
237
+ idle = false;
238
+ const now = deps.clock.now();
239
+ return tx(async (view, t) => {
240
+ const records = await listRecords(view);
241
+ for (const r of records)
242
+ if (!isActive(r) && (r.settledAt ?? r.startedAt) + SETTLED_RETENTION_MS < now)
243
+ await view.delete(r.requestId);
244
+ const { front: active, pastPurge } = ofGroup(records, groupId);
245
+ const owned = new Set(pastPurge.flatMap((r) => (r.keyPackages ?? []).filter((k) => k.status === 'pending').map((k) => k.ref)));
246
+ if (active !== undefined) {
247
+ // A leave joins whatever runs; abandon joins an abandon or destroy; destroy joins a destroy.
248
+ if (kind === 'leave' || active.kind === 'destroy' || (kind === 'abandon' && active.kind === 'abandon'))
249
+ return active;
250
+ const refs = kind === 'destroy' && active.keyPackages === undefined ? await captureRefs(t, groupId, owned) : undefined;
251
+ const next = {
252
+ ...active,
253
+ kind,
254
+ ...(active.phase === 'leaving' ? { phase: 'purging', outcome: 'abandoned', settledAt: now } : {}),
255
+ ...(refs === undefined ? {} : refs),
256
+ };
257
+ await writeRecord(view, next);
258
+ return next;
259
+ }
260
+ const record = {
261
+ v: 1,
262
+ requestId: randomId(),
263
+ groupId,
264
+ kind,
265
+ phase: refused !== undefined ? 'done' : kind === 'leave' ? 'leaving' : 'purging',
266
+ startedAt: now,
267
+ ...(refused === undefined ? {} : { outcome: refused, settledAt: now }),
268
+ ...(kind === 'leave' ? { deadline: now + deps.leaveTimeoutMs } : {}),
269
+ ...(kind === 'destroy' ? await captureRefs(t, groupId, owned) : {}),
270
+ ...(pastPurge.length === 0 ? {} : { succeeds: pastPurge.map((r) => r.requestId) }),
271
+ };
272
+ await writeRecord(view, record);
273
+ return record;
274
+ });
275
+ }
276
+ /** Re-reads `requestId` and applies `change` only while it is still active (identity-checked settle). */
277
+ function update(requestId, change) {
278
+ return tx(async (view) => {
279
+ const current = await readRecord(view, requestId);
280
+ if (current === undefined || !isActive(current))
281
+ return current;
282
+ const next = change(current);
283
+ if (next === undefined)
284
+ return current;
285
+ await writeRecord(view, next);
286
+ return next;
287
+ });
288
+ }
289
+ function recordsOf(groupId) {
290
+ return tx(async (view) => ofGroup(await listRecords(view), groupId));
291
+ }
292
+ // -- sleeping -----------------------------------------------------------------
293
+ /**
294
+ * Arms a wake-up BEFORE the pass reads the group, so a change landing
295
+ * between the read and the wait is not missed. `wait(ms)` resolves on the
296
+ * first of: a state change of the group, a new request, `ms` (the deadline
297
+ * or a backoff); rejects `disposed` on dispose.
298
+ */
299
+ function arm(groupId) {
300
+ let woken = false;
301
+ let resolveWait;
302
+ let rejectWait;
303
+ let failed;
304
+ const sleeper = {
305
+ wake() {
306
+ woken = true;
307
+ resolveWait?.();
308
+ },
309
+ fail(error) {
310
+ failed = error;
311
+ rejectWait?.(error);
312
+ },
313
+ };
314
+ let set = sleepers.get(groupId);
315
+ if (set === undefined)
316
+ sleepers.set(groupId, (set = new Set()));
317
+ set.add(sleeper);
318
+ const unwatch = deps.groups.watch(groupId, () => sleeper.wake());
319
+ let timer;
320
+ const release = () => {
321
+ unwatch();
322
+ sleepers.get(groupId)?.delete(sleeper);
323
+ if (timer !== undefined)
324
+ deps.timers.clear(timer);
325
+ timer = undefined;
326
+ };
327
+ return {
328
+ release,
329
+ wait(ms) {
330
+ if (failed !== undefined)
331
+ return Promise.reject(failed);
332
+ if (woken)
333
+ return Promise.resolve();
334
+ return new Promise((resolve, reject) => {
335
+ resolveWait = resolve;
336
+ rejectWait = reject;
337
+ if (ms !== undefined)
338
+ timer = deps.timers.set(() => sleeper.wake(), Math.max(0, ms));
339
+ });
340
+ },
341
+ };
342
+ }
343
+ // -- the phases -----------------------------------------------------------------
344
+ /** One `leaving` pass: `wait` (with an optional backoff) or the record after it settled. */
345
+ async function leaveStep(record) {
346
+ const now = deps.clock.now();
347
+ // `last-admin` ends the intent WITHOUT the purge: the leaf stays, so the group keeps its last active admin
348
+ // (AC-ADMIN-3) — the caller's leave() rejects `last-admin`, an own-leaf forget lists the group as still holding.
349
+ const conclude = async (outcome) => {
350
+ const phase = outcome === 'last-admin' ? 'done' : 'purging';
351
+ await update(record.requestId, (r) => (r.phase === 'leaving' ? { ...r, phase, outcome, settledAt: deps.clock.now() } : undefined));
352
+ deps.onSettled(record.groupId);
353
+ return undefined;
354
+ };
355
+ const view = await deps.groups.view(record.groupId);
356
+ // Not held any more (its state is gone): nothing is left to leave, and nothing tells whether the leaf left.
357
+ if (view === undefined)
358
+ return conclude('timed-out');
359
+ if (!view.member) {
360
+ // S20: not before the removal settled — a winning sibling inside the window rewinds the leaf back (a state
361
+ // change wakes this pass), and concluding now would purge a leaf the group still holds: a zombie leave. The
362
+ // leave's own deadline does not cut this short: the leaf left, only whether that is final is open.
363
+ if (view.removalSettlesAt !== undefined && now < view.removalSettlesAt)
364
+ return { wait: view.removalSettlesAt - now };
365
+ return conclude('removed');
366
+ }
367
+ if (view.soleMember)
368
+ return conclude('sole-member');
369
+ const admin = view.admin && !view.accountHasOtherLeaf;
370
+ // Checked before the deadline and before an own intent's fate: the condition may arise after the request (the
371
+ // other admin left or was demoted before this leaf's demotion landed — that demotion is then stale and dropped
372
+ // by the pipeline), and a pass running after the deadline (a resumed leave, a slow read) must not purge the
373
+ // group's last active admin's leaf.
374
+ if (admin && view.lastActiveAdmin)
375
+ return conclude('last-admin');
376
+ const deadline = record.deadline ?? now;
377
+ if (now >= deadline)
378
+ return conclude('timed-out');
379
+ // An own intent still recorded: its confirmation changes the state (a wake-up), but a stale one the pipeline drops
380
+ // does not — re-checked on the base backoff.
381
+ if (view.ownIntentPending)
382
+ return { wait: Math.min(deadline - now, backoffMs(1)) };
383
+ if (!admin && view.selfRemoveStaged)
384
+ return { wait: deadline - now };
385
+ try {
386
+ // An admin account's last leaf first drops the admin role (its SelfRemove would be refused, ADR-006).
387
+ if (admin)
388
+ await deps.groups.demote(record.groupId);
389
+ else
390
+ await deps.groups.proposeSelfRemove(record.groupId);
391
+ return { wait: deadline - now };
392
+ }
393
+ catch (error) {
394
+ if (stops(error))
395
+ throw error;
396
+ if (isMarmotError(error, 'not-a-member'))
397
+ return conclude('removed');
398
+ if (transientGroupFailure(error))
399
+ return { wait: Math.min(deadline - now, backoffMs(1)) };
400
+ const counted = await update(record.requestId, (r) => ({ ...r, failures: (r.failures ?? 0) + 1 }));
401
+ const failures = counted?.failures ?? MAX_MAINTENANCE_FAILURES;
402
+ if (failures >= MAX_MAINTENANCE_FAILURES) {
403
+ deps.onMaintenanceFailed({ invitationId: record.groupId, kind: 'teardown', reason: maintenanceFailureReason(error) ?? 'unknown-error' });
404
+ return conclude('timed-out');
405
+ }
406
+ return { wait: Math.min(deadline - now, backoffMs(failures)) };
407
+ }
408
+ }
409
+ /**
410
+ * The group's index entry as the outcome classification reads it. A corrupt entry — its payload or its storage
411
+ * envelope — is no adoption evidence: it is read as absent here, so it never blocks the purge that deletes it. A
412
+ * version mismatch or a backend failure still propagates.
413
+ */
414
+ async function indexEntryOf(t, groupId) {
415
+ try {
416
+ return indexEntryView(groupId, await t.extension(deps.groupIndexExtension).get(groupId));
417
+ }
418
+ catch (error) {
419
+ if (isMalformedRowError(error))
420
+ return undefined;
421
+ throw error;
422
+ }
423
+ }
424
+ async function purgeStep(record) {
425
+ // F2/F3: the epoch actually purged, committed before the clear — on the record and as the group's watermark.
426
+ // Epic marmot-invitation-outcomes S2 (A1, ADR-019 D8): in the same transaction, every invitation the group's proofs
427
+ // (or the legacy index entry) make `joined` is stamped, before the clear deletes those proofs.
428
+ await deps.groups.purge(record.groupId, (epoch, proofs) => tx(async (view, t) => {
429
+ const current = await readRecord(view, record.requestId);
430
+ if (current?.phase === 'purging' && (current.purgedEpoch === undefined || current.purgedEpoch < epoch))
431
+ await writeRecord(view, { ...current, purgedEpoch: epoch });
432
+ await writeWatermark(t, record.groupId, epoch, deps.clock.now());
433
+ if (proofs !== undefined)
434
+ await stampAdoptions(t, record.groupId, proofs, await indexEntryOf(t, record.groupId), deps.clock.now());
435
+ }));
436
+ await tx(async (view, t) => {
437
+ const current = await readRecord(view, record.requestId);
438
+ if (current === undefined || current.phase !== 'purging' || !isActive(current))
439
+ return;
440
+ // S2 (A2): stamped before the index entry (the legacy proof, rule 3) and the records' purge go — a group store
441
+ // a crash emptied before A1 ran (or a pre-upgrade purge) still keeps its adopter's outcome.
442
+ await stampAdoptions(t, current.groupId, 'no-group', await indexEntryOf(t, current.groupId), deps.clock.now());
443
+ await purgeGroupInvites(t, current.groupId);
444
+ await purgeGroupManifests(t, current.groupId);
445
+ await purgeGroupInvitations(t, current.groupId);
446
+ await purgeGroupOffers(t, current.groupId);
447
+ await purgeKeyPackageGroupRefs(t, current.groupId);
448
+ if (current.kind === 'destroy')
449
+ await purgeRetainedKeyPackageKeys(t, await exclusiveRefs(t, current.groupId, current.retainedRefs ?? []), deps.clock.now());
450
+ await t.extension(deps.groupIndexExtension).delete(current.groupId);
451
+ const deleting = current.kind === 'destroy' && (current.keyPackages ?? []).some((k) => k.status === 'pending');
452
+ await writeRecord(view, { ...current, phase: deleting ? 'deleting' : 'done', settledAt: current.settledAt ?? deps.clock.now() });
453
+ });
454
+ }
455
+ /** Runs the purging phase of `record` once per group at a time (a concurrent caller joins the running purge). */
456
+ function purgeOnce(record) {
457
+ const current = purging.get(record.groupId);
458
+ if (current !== undefined)
459
+ return current;
460
+ const run = purgeStep(record)
461
+ .then(() => deps.onSettled(record.groupId))
462
+ .finally(() => purging.delete(record.groupId));
463
+ purging.set(record.groupId, run);
464
+ return run;
465
+ }
466
+ /**
467
+ * AA1: the refs among `refs` whose retained key serves the destroyed group only. A key another invitation still
468
+ * relies on — pending, joining, competing, or joined within the grace window, for any other group (a Welcome built on the
469
+ * same KeyPackage may still be in flight) — is left to lapse with the ordinary grace window. (Last-resort
470
+ * KeyPackages, shared by design, are never touched: `purgeRetainedKeyPackageKeys`.)
471
+ */
472
+ async function exclusiveRefs(t, groupId, refs) {
473
+ const nowMs = deps.clock.now();
474
+ const shared = new Set();
475
+ const invitations = t.artifact('pendingInvitations');
476
+ for (const key of await invitations.keys()) {
477
+ const raw = (await invitations.get(key));
478
+ if (typeof raw !== 'object' || raw === null || raw.groupId === groupId || typeof raw.keyPackageRef !== 'string')
479
+ continue;
480
+ const live = raw.status === 'pending' || raw.status === 'joining' || raw.status === 'competing' || (raw.status === 'joined' && typeof raw.receivedAt === 'number' && raw.receivedAt + deps.graceWindowMs > nowMs);
481
+ if (live)
482
+ shared.add(raw.keyPackageRef);
483
+ }
484
+ return refs.filter((ref) => !shared.has(ref));
485
+ }
486
+ /** One `deleting` pass; returns whether a KeyPackage is still pending (retried by the background pass). */
487
+ async function deleteStep(record) {
488
+ // A kind-5 already installed on its slot is re-published by S4's own resume.
489
+ await deps.resumeKeyPackageIntents();
490
+ for (const entry of record.keyPackages ?? []) {
491
+ if (entry.status !== 'pending')
492
+ continue;
493
+ assertLive('destroy');
494
+ let status = await deps.keyPackageStatus(entry.ref);
495
+ let failure;
496
+ if (status === 'present') {
497
+ try {
498
+ await deps.forgetKeyPackage(entry.ref);
499
+ }
500
+ catch (error) {
501
+ if (stops(error))
502
+ throw error;
503
+ failure = error;
504
+ }
505
+ status = await deps.keyPackageStatus(entry.ref);
506
+ }
507
+ if (status === 'deleting')
508
+ continue; // durable on the slot; S4's resume publishes it
509
+ let gaveUp = false;
510
+ await update(record.requestId, (r) => ({
511
+ ...r,
512
+ keyPackages: (r.keyPackages ?? []).map((k) => {
513
+ if (k.ref !== entry.ref || k.status !== 'pending')
514
+ return k;
515
+ if (status === 'absent')
516
+ return { ...k, status: 'done' };
517
+ const reason = maintenanceFailureReason(failure);
518
+ if (reason === undefined)
519
+ return k; // transient: retried uncounted
520
+ const failures = k.failures + 1;
521
+ gaveUp = failures >= MAX_MAINTENANCE_FAILURES;
522
+ return { ...k, failures, status: gaveUp ? 'failed' : 'pending' };
523
+ }),
524
+ }));
525
+ if (gaveUp)
526
+ deps.onMaintenanceFailed({ invitationId: entry.ref, kind: 'keypackage-deletion', reason: maintenanceFailureReason(failure) ?? 'unknown-error' });
527
+ }
528
+ const after = await update(record.requestId, (r) => ((r.keyPackages ?? []).some((k) => k.status === 'pending') ? undefined : { ...r, phase: 'done' }));
529
+ return after !== undefined && after.phase === 'deleting';
530
+ }
531
+ const frontKey = (groupId) => `front:${groupId}`;
532
+ const deleteKey = (requestId) => `delete:${requestId}`;
533
+ /**
534
+ * The group's front-intent driver: drives it until none is left (past its purge, done, or none). One per group.
535
+ * Never rejects: a failure resolves with the request id of the record it was driving (none when it failed before
536
+ * reading one), schedules this driver's own retry and is counted against that record — here, once per run: a run
537
+ * the background joins on several passes (or a caller awaits) is never counted again.
538
+ */
539
+ function runFront(groupId) {
540
+ const current = running.get(groupId);
541
+ if (current !== undefined)
542
+ return current;
543
+ const run = deps
544
+ .detached(async () => {
545
+ for (;;) {
546
+ let record;
547
+ let alarm;
548
+ try {
549
+ assertLive('teardown');
550
+ alarm = arm(groupId);
551
+ record = (await recordsOf(groupId)).front;
552
+ if (record === undefined) {
553
+ recovered(frontKey(groupId));
554
+ return {};
555
+ }
556
+ if (record.phase === 'leaving') {
557
+ const step = await leaveStep(record);
558
+ if (step !== undefined)
559
+ await alarm.wait(step.wait);
560
+ }
561
+ else {
562
+ await purgeOnce(record);
563
+ }
564
+ }
565
+ catch (error) {
566
+ const failure = { requestId: record?.requestId, error };
567
+ if (!stops(error)) {
568
+ retry(frontKey(groupId));
569
+ await countFailure(frontKey(groupId), groupId, failure);
570
+ }
571
+ return { failure };
572
+ }
573
+ finally {
574
+ alarm?.release();
575
+ }
576
+ }
577
+ })
578
+ .finally(() => running.delete(groupId));
579
+ running.set(groupId, run);
580
+ return run;
581
+ }
582
+ /**
583
+ * One kind-5 pass of a past-purge record — its own driver, never the group's front one. Never rejects: a failure
584
+ * resolves with THIS record's request id and is counted against it once, here. A KeyPackage still pending (or a
585
+ * failure) schedules this driver's retry at its own backoff; a clean pass with nothing pending resets it.
586
+ */
587
+ function runDeletion(record) {
588
+ const current = deleting.get(record.requestId);
589
+ if (current !== undefined)
590
+ return current;
591
+ const key = deleteKey(record.requestId);
592
+ const run = deps
593
+ .detached(async () => {
594
+ try {
595
+ assertLive('destroy');
596
+ if (await deleteStep(record))
597
+ retry(key);
598
+ else
599
+ recovered(key);
600
+ return {};
601
+ }
602
+ catch (error) {
603
+ const failure = { requestId: record.requestId, error };
604
+ if (!stops(error)) {
605
+ retry(key);
606
+ await countFailure(key, record.groupId, failure);
607
+ }
608
+ return { failure };
609
+ }
610
+ })
611
+ .finally(() => deleting.delete(record.requestId));
612
+ deleting.set(record.requestId, run);
613
+ return run;
614
+ }
615
+ /**
616
+ * Runs `requestId` for its caller: rejects like the driver (the driver scheduled its own retry; the work
617
+ * continues in the background), resolves once it is past its purge — after one kind-5 pass of its own for a
618
+ * destroy (a deletion still pending is left to the background retry). The group's front driver, if it was just
619
+ * finishing an earlier intent when this one was recorded, is followed by a fresh one; another record's kind-5
620
+ * pass is never waited for.
621
+ */
622
+ async function settle(groupId, requestId) {
623
+ const read = async () => {
624
+ try {
625
+ return await tx((view) => readRecord(view, requestId));
626
+ }
627
+ catch (error) {
628
+ if (!stops(error))
629
+ armResume(backoffMs(1));
630
+ throw error;
631
+ }
632
+ };
633
+ for (;;) {
634
+ throwFailure(await runFront(groupId));
635
+ const record = await read();
636
+ if (record === undefined || !isActive(record))
637
+ return record;
638
+ if (record.phase === 'deleting') {
639
+ throwFailure(await runDeletion(record));
640
+ return (await read()) ?? record;
641
+ }
642
+ }
643
+ }
644
+ // -- background -----------------------------------------------------------------
645
+ /** A resume pass is due within `ms` (host time) at the latest: covered by an armed timer no longer than `ms`, or armed now. */
646
+ function armResume(ms) {
647
+ idle = false;
648
+ if (disposed || deps.isDisposed())
649
+ return;
650
+ for (const armed of resumeTimers.values())
651
+ if (armed <= ms)
652
+ return;
653
+ const handle = deps.timers.set(() => {
654
+ clearResumeTimers();
655
+ resumeInBackground();
656
+ }, ms);
657
+ resumeTimers.set(handle, ms);
658
+ }
659
+ function clearResumeTimers() {
660
+ for (const handle of resumeTimers.keys())
661
+ deps.timers.clear(handle);
662
+ resumeTimers.clear();
663
+ }
664
+ /** Driver `key` failed or left work pending: its backoff grows, and a resume is due by then at the latest. */
665
+ function retry(key) {
666
+ const count = (backoff.get(key) ?? 0) + 1;
667
+ backoff.set(key, count);
668
+ armResume(backoffMs(count));
669
+ }
670
+ /** Driver `key` settled clean with nothing pending: its next retry starts from the base delay again. */
671
+ function recovered(key) {
672
+ backoff.delete(key);
673
+ }
674
+ /**
675
+ * A driver run's failure, counted once — by the run itself, as it settles — against the record the driver carried
676
+ * (never inferred from the error); a failure before any record was read is not counted (its retry is scheduled).
677
+ * A record given up no longer stands behind driver `key`: its backoff is dropped with it (AC-HYG-1), so a fresh
678
+ * record driven under the same key (a new teardown of the group) retries from the base delay — including one
679
+ * recorded while this run was failing (its request joined this run and got this failure): a resume pass at the
680
+ * base delay picks it up.
681
+ */
682
+ async function countFailure(key, groupId, failure) {
683
+ if (failure.requestId === undefined || stops(failure.error))
684
+ return;
685
+ const reason = maintenanceFailureReason(failure.error);
686
+ if (reason === undefined)
687
+ return;
688
+ let gaveUp = false;
689
+ const committed = await update(failure.requestId, (r) => {
690
+ const driverFailures = (r.driverFailures ?? 0) + 1;
691
+ gaveUp = driverFailures >= MAX_MAINTENANCE_FAILURES;
692
+ return { ...r, driverFailures, ...(gaveUp ? { gaveUp: reason } : {}) };
693
+ }).then(() => true, () => false);
694
+ if (!committed || !gaveUp)
695
+ return;
696
+ recovered(key);
697
+ armResume(backoffMs(1));
698
+ deps.onMaintenanceFailed({ invitationId: groupId, kind: 'teardown', reason });
699
+ }
700
+ /**
701
+ * Starts everything the group has to do, each part independently: a kind-5 pass of each of its past-purge
702
+ * records, and its front intent — followed by the kind-5 pass of a front intent that reached `deleting`.
703
+ */
704
+ function launch(groupId, pastPurge) {
705
+ const started = new Set();
706
+ const deletions = (records) => {
707
+ for (const r of records) {
708
+ if (started.has(r.requestId))
709
+ continue;
710
+ started.add(r.requestId);
711
+ void runDeletion(r);
712
+ }
713
+ };
714
+ deletions(pastPurge);
715
+ // Each run counts its own failure; joining a run already in flight attaches nothing that could count it again.
716
+ void runFront(groupId).then(async (outcome) => {
717
+ if (outcome.failure !== undefined)
718
+ return;
719
+ try {
720
+ deletions((await recordsOf(groupId)).pastPurge);
721
+ }
722
+ catch (error) {
723
+ if (!stops(error))
724
+ retry(frontKey(groupId));
725
+ }
726
+ });
727
+ }
728
+ function resumeInBackground() {
729
+ if (disposed || deps.isDisposed() || idle)
730
+ return;
731
+ void deps.detached(async () => {
732
+ let groups;
733
+ try {
734
+ groups = await tx(async (view) => {
735
+ const out = new Map();
736
+ for (const r of (await listRecords(view)).filter(isActive)) {
737
+ const list = out.get(r.groupId) ?? [];
738
+ if (isPastPurge(r))
739
+ list.push(r);
740
+ out.set(r.groupId, list);
741
+ }
742
+ return out;
743
+ });
744
+ }
745
+ catch (error) {
746
+ if (!stops(error))
747
+ retry('scan');
748
+ return;
749
+ }
750
+ recovered('scan');
751
+ // Keys of drivers with nothing left to drive (a record done or given up) are dropped.
752
+ const live = new Set();
753
+ for (const [groupId, pastPurge] of groups) {
754
+ live.add(frontKey(groupId));
755
+ for (const r of pastPurge)
756
+ live.add(deleteKey(r.requestId));
757
+ }
758
+ for (const key of [...backoff.keys()])
759
+ if (!live.has(key))
760
+ backoff.delete(key);
761
+ if (groups.size === 0 && running.size === 0 && deleting.size === 0)
762
+ idle = true;
763
+ for (const [groupId, pastPurge] of groups)
764
+ launch(groupId, pastPurge);
765
+ });
766
+ }
767
+ // -- operations -----------------------------------------------------------------
768
+ async function viewOrThrow(groupId, operation) {
769
+ const view = await deps.groups.view(groupId);
770
+ if (view === undefined)
771
+ throw new MarmotError('not-a-member', `${operation}: group ${groupId} is not held`, { details: { groupId } });
772
+ return view;
773
+ }
774
+ /** leave()'s pre-check: the local leaf is the last leaf of the group's last active admin (it cannot leave). */
775
+ function cannotLeave(view) {
776
+ return view.member && !view.soleMember && view.admin && !view.accountHasOtherLeaf && view.lastActiveAdmin;
777
+ }
778
+ /** Awaits the caller's intent; a leave that ended `last-admin` (the condition arose while it ran) rejects. */
779
+ async function settleLeave(groupId, requestId, operation) {
780
+ const record = await settle(groupId, requestId);
781
+ if (record?.outcome === 'last-admin')
782
+ throw lastAdmin(operation, groupId);
783
+ }
784
+ function lastAdmin(operation, groupId) {
785
+ return new MarmotError('last-admin', `${operation}: the local account is the last active admin of group ${groupId}; name another admin first (setAdmins)`, { details: { groupId } });
786
+ }
787
+ return {
788
+ async leave(groupId) {
789
+ assertLive('leave');
790
+ const view = await viewOrThrow(groupId, 'leave');
791
+ if (cannotLeave(view))
792
+ throw lastAdmin('leave', groupId);
793
+ const record = await request(groupId, 'leave');
794
+ wakeGroup(groupId);
795
+ await settleLeave(groupId, record.requestId, 'leave');
796
+ },
797
+ async depart(groupId) {
798
+ assertLive('departAsAdmin');
799
+ const view = await viewOrThrow(groupId, 'departAsAdmin');
800
+ if (view.lastActiveAdmin)
801
+ throw lastAdmin('departAsAdmin', groupId);
802
+ if (view.accountHasOtherLeaf) {
803
+ throw new MarmotError('use-forget', `departAsAdmin: the local account holds another leaf of group ${groupId}; forget this device (devices.forget) instead`, { details: { groupId } });
804
+ }
805
+ if (!view.admin)
806
+ throw new MarmotError('invalid-options', `departAsAdmin: the local account is not an admin of group ${groupId}`, { details: { groupId, reason: 'not-admin' } });
807
+ const record = await request(groupId, 'leave');
808
+ wakeGroup(groupId);
809
+ await settleLeave(groupId, record.requestId, 'departAsAdmin');
810
+ },
811
+ async abandon(groupId) {
812
+ assertLive('abandon');
813
+ const record = await request(groupId, 'abandon');
814
+ wakeGroup(groupId);
815
+ await settle(groupId, record.requestId);
816
+ },
817
+ async destroy(groupId) {
818
+ assertLive('destroy');
819
+ const record = await request(groupId, 'destroy');
820
+ wakeGroup(groupId);
821
+ await settle(groupId, record.requestId);
822
+ },
823
+ async startLeave(groupId) {
824
+ assertLive('devices.forget');
825
+ // leave()'s pre-check: the last leaf of the last active admin is not left (the group keeps it; the forget's
826
+ // tombstone lists the group as still holding the leaf).
827
+ const view = await deps.groups.view(groupId);
828
+ const record = await request(groupId, 'leave', view !== undefined && cannotLeave(view) ? 'last-admin' : undefined);
829
+ wakeGroup(groupId);
830
+ // Its front intent only (a leave has no kind-5; a past-purge record's pass is the background's): uncounted.
831
+ void runFront(groupId);
832
+ return record.requestId;
833
+ },
834
+ async refusesJoin(groupId, epoch) {
835
+ // F3: the group's purge watermark, which outlives the pruned teardown records. None: nothing is refused.
836
+ const watermark = await deps.transaction((t) => readWatermark(t, groupId));
837
+ return watermark !== undefined && epoch <= watermark;
838
+ },
839
+ // AB1: ONLY the purging phase, on the caller's (the inbox queue's) time — a destroy's kind-5 deletions (signer,
840
+ // relays) are left to the background driver, never awaited here.
841
+ // S16: the group's FRONT intent — a past-purge record of the same group (a destroy still deleting) neither
842
+ // hides an interrupted purge nor is driven here; its deletions are left to the background.
843
+ async tearingDown(groupId) {
844
+ // Any record still in its leaving or purging phase, including one its driver gave up on (`gaveUp`): the
845
+ // device asked for the teardown either way (the give-up was reported as `maintenanceFailed`).
846
+ return tx(async (view) => (await listRecords(view)).some((r) => r.groupId === groupId && (r.phase === 'leaving' || r.phase === 'purging')));
847
+ },
848
+ async finishPurge(groupId) {
849
+ for (;;) {
850
+ const { front, pastPurge } = await recordsOf(groupId);
851
+ if (front?.phase !== 'purging') {
852
+ if (pastPurge.length > 0)
853
+ armResume(backoffMs(1));
854
+ return;
855
+ }
856
+ await purgeOnce(front);
857
+ }
858
+ },
859
+ async leaveOutcome(requestId) {
860
+ const record = await tx((view) => readRecord(view, requestId));
861
+ if (record === undefined)
862
+ return 'timed-out';
863
+ if (record.phase === 'leaving' && record.gaveUp === undefined)
864
+ return 'pending';
865
+ return record.outcome === 'removed' || record.outcome === 'sole-member' ? 'removed' : 'timed-out';
866
+ },
867
+ resumeInBackground,
868
+ dispose() {
869
+ disposed = true;
870
+ clearResumeTimers();
871
+ const error = new MarmotError('disposed', 'teardown: client has been disposed');
872
+ for (const set of sleepers.values())
873
+ for (const s of set)
874
+ s.fail(error);
875
+ sleepers.clear();
876
+ },
877
+ };
878
+ }