@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,1290 @@
1
+ import { createDeleteKeyPackageEvent, getKeyPackage } from '@941design/marmot-engine/core';
2
+ import { maintenanceFailureReason } from '../inbox/index.js';
3
+ import { stripWaitingRequestTimes } from '../invitations/index.js';
4
+ import { DEVICE_KEY_ENTRY, readDeviceSigningKey } from '../key-packages/index.js';
5
+ import { classifyPublish, isMarmotError, MarmotError } from '../shared/index.js';
6
+ import { DEVICE_REGISTRY_ARTIFACT, forgetDepartureTime, MAX_MAINTENANCE_FAILURES, tombstoneDepartureTime } from './device-deps.js';
7
+ import { consolidateRegistryEntries, localAccountOf, malformedRegistryRecord, chainClosure, createDeviceLineage, loadDeviceLineage, mergeRegistryEntries, persistSuccessionEdges, readRegistryEdges, readRegistryEntry, viewSuccessionEdges, } from './device-lineage.js';
8
+ import { createRotationDriver } from './device-rotation.js';
9
+ import { approveEnrolment, classifyGroupActFailure, handleEnrolmentRumor, MAX_GROUP_ATTEMPTS, pendingEnrolments, reopenApprovalsAfterRewind, requestedKeyPackages, requestEnrolment, resumeEnrolments, stopsDeviceIntent, } from './enrolment.js';
10
+ const ARTIFACT = DEVICE_REGISTRY_ARTIFACT;
11
+ const LEAF_KEY = /^[0-9a-f]{64}$/;
12
+ const MAX_LABEL_LENGTH = 128;
13
+ /** Publish attempts of a forget's kind-5 deletion before it is given up. */
14
+ const MAX_DELETION_ATTEMPTS = 10;
15
+ const forgetKey = (leafKey) => `forget:${leafKey}`;
16
+ const malformed = malformedRegistryRecord;
17
+ const readEntry = readRegistryEntry;
18
+ async function readForget(view, leafKey) {
19
+ const raw = await view.get(forgetKey(leafKey));
20
+ if (raw === undefined)
21
+ return undefined;
22
+ const r = raw;
23
+ if (r.v !== 1 || r.leafKey !== leafKey || !Array.isArray(r.groups))
24
+ throw malformed(forgetKey(leafKey));
25
+ return r;
26
+ }
27
+ async function writeForget(view, record) {
28
+ await view.put(forgetKey(record.leafKey), record);
29
+ }
30
+ // Module-level export (not re-exported from account/index.ts) for white-box unit testing of
31
+ // supersedeDeparture/bindLabel directly — the same deep-import convention account/enrolment.ts's own tests use
32
+ // (e.g. recheck-evidence.test.ts importing reopenApprovalsAfterRewind straight from enrolment.js).
33
+ export const registryBinding = {
34
+ // The entry lives at the device's lineage head (Design Decision 4): a label bound for ANY key of a chain lands there,
35
+ // and entries an earlier key of the chain still has are folded in (AC-ENR-3: nothing stays under a retired key).
36
+ async bindLabel(tx, leafKey, label, enrolledAt) {
37
+ const view = tx.artifact(ARTIFACT);
38
+ const lineage = await loadDeviceLineage(view);
39
+ const head = lineage.deviceHeadOf(leafKey);
40
+ const { entry: current } = await consolidateRegistryEntries(view, lineage, head);
41
+ const entry = current === undefined ? { v: 1, leafKey: head, label, enrolledAt } : { ...current, label };
42
+ await view.put(head, entry);
43
+ },
44
+ // AC-RECHK-2 (amended 2026-10-04): the
45
+ // enrolment finalize's supersede. The tombstone and the forget record are judged on THEIR OWN time
46
+ // (tombstoneDepartureTime / forgetDepartureTime, device-deps.ts) — never merged into one "whichever is found
47
+ // first" value (round 2's bug: a stale tombstone's time could be returned ahead of a genuinely newer, still
48
+ // live forget record, masking it). Each is cleared/deleted independently, PROVIDED its own time is not newer
49
+ // than `approvedAt`; a departure newer than the approval (e.g. a forget started after this device
50
+ // re-enrolled) is a genuinely later decision and is left untouched regardless of the other record.
51
+ // Lineage (AC-FORGET-4): the tombstone is the head entry's and a forget record may sit under any key of the chain,
52
+ // each judged on its own.
53
+ async supersedeDeparture(tx, leafKey, approvedAt) {
54
+ const view = tx.artifact(ARTIFACT);
55
+ const lineage = await loadDeviceLineage(view);
56
+ const head = lineage.deviceHeadOf(leafKey);
57
+ const { entry: current } = await consolidateRegistryEntries(view, lineage, head);
58
+ const tombstoneTime = tombstoneDepartureTime(current?.tombstone);
59
+ if (tombstoneTime !== undefined && tombstoneTime <= approvedAt) {
60
+ const { tombstone: _tombstone, ...rest } = current;
61
+ await view.put(head, rest);
62
+ }
63
+ for (const key of lineage.keysOf(head)) {
64
+ const forget = (await readForget(view, key)); // read loosely: readForget casts raw storage without deep-validating nested fields
65
+ const forgetTime = forgetDepartureTime(forget);
66
+ if (forgetTime !== undefined && forgetTime <= approvedAt)
67
+ await view.delete(forgetKey(key));
68
+ }
69
+ },
70
+ };
71
+ /**
72
+ * The own device's re-admission (a Welcome adopted under an enrolment manifest this device recorded at `recordedAt`, ms),
73
+ * run in the account transaction that fulfils the manifest: "until enrolled again" (AC-ROT-5), the counterpart of
74
+ * `supersedeDeparture` on the approving sibling's store. Every own forget record that is SETTLED (`forgotten`) or given up
75
+ * and whose own departure time (`forgetDepartureTime`) is at or before `recordedAt` ends, and so does the tombstone its
76
+ * settlement wrote on the device's entry when its own time (`tombstoneDepartureTime`) is also at or before `recordedAt`.
77
+ * A record whose kind-5 deletion is still unsettled is marked `superseded` instead of deleted, so the deletion is
78
+ * finished by the background pass, which then deletes the record. Never touched: an OPEN own forget (leaving beats
79
+ * re-keying, and its intent still needs the record), a forget that started after the request, and any row that does
80
+ * not read (rows are read loosely and a malformed one stays in place: a corrupt row must not abort the join).
81
+ */
82
+ export async function supersedeOwnForget(tx, recordedAt) {
83
+ const view = tx.artifact(ARTIFACT);
84
+ let lineage;
85
+ try {
86
+ lineage = await loadDeviceLineage(view);
87
+ }
88
+ catch {
89
+ lineage = undefined; // a malformed link row: the tombstone is looked up under the record's own key
90
+ }
91
+ for (const key of await view.keys()) {
92
+ if (!key.startsWith('forget:'))
93
+ continue;
94
+ try {
95
+ const raw = (await view.get(key));
96
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
97
+ continue;
98
+ const r = raw;
99
+ if (r.own !== true || typeof r.leafKey !== 'string' || forgetKey(r.leafKey) !== key)
100
+ continue;
101
+ if (r.status !== 'forgetting' && r.status !== 'forgotten')
102
+ continue;
103
+ if (r.status === 'forgetting' && r.gaveUp === undefined)
104
+ continue; // open
105
+ const departure = forgetDepartureTime(r);
106
+ if (departure === undefined || departure > recordedAt)
107
+ continue;
108
+ const head = lineage === undefined ? r.leafKey : lineage.deviceHeadOf(r.leafKey);
109
+ const entry = lineage === undefined ? await readEntry(view, head) : (await consolidateRegistryEntries(view, lineage, head)).entry;
110
+ const tombstoneTime = tombstoneDepartureTime(entry?.tombstone);
111
+ if (tombstoneTime !== undefined && tombstoneTime <= recordedAt) {
112
+ const { tombstone: _tombstone, ...rest } = entry;
113
+ await view.put(head, rest);
114
+ }
115
+ const unsettled = r.gaveUp === undefined && (r.deletion === undefined || r.deletion.status === 'pending');
116
+ if (unsettled)
117
+ await view.put(key, { ...raw, superseded: true });
118
+ else
119
+ await view.delete(key);
120
+ }
121
+ catch {
122
+ continue;
123
+ }
124
+ }
125
+ }
126
+ function forgetOutcomeOf(record) {
127
+ const perGroupOutcome = {};
128
+ for (const g of record.groups)
129
+ perGroupOutcome[g.groupId] = g.outcome;
130
+ return Object.freeze({ leafKey: record.leafKey, perGroupOutcome: Object.freeze(perGroupOutcome), tombstoneRecorded: record.status === 'forgotten' });
131
+ }
132
+ // ---------------------------------------------------------------------------
133
+ // The service
134
+ // ---------------------------------------------------------------------------
135
+ class SerialQueue {
136
+ #tail = Promise.resolve();
137
+ run(task) {
138
+ const result = this.#tail.then(task, task);
139
+ this.#tail = result.catch(() => undefined);
140
+ return result;
141
+ }
142
+ }
143
+ function backoffMs(count) {
144
+ return Math.min(1000 * 2 ** Math.max(0, count - 1), 60_000);
145
+ }
146
+ export function createDeviceService(deps, seams = {}) {
147
+ const queue = new SerialQueue();
148
+ let disposed = false;
149
+ let resumeTimer;
150
+ let resumeFailures = 0;
151
+ let resumeRunning = false;
152
+ function assertLive(operation) {
153
+ if (disposed || deps.isDisposed())
154
+ throw new MarmotError('disposed', `devices.${operation}: client has been disposed`);
155
+ }
156
+ function scheduleResume() {
157
+ if (disposed || deps.isDisposed() || resumeTimer !== undefined)
158
+ return;
159
+ resumeFailures += 1;
160
+ resumeTimer = deps.timers.set(() => {
161
+ resumeTimer = undefined;
162
+ resumeInBackground();
163
+ }, backoffMs(resumeFailures));
164
+ }
165
+ /**
166
+ * Whether the local device's OWN forget (`own: true`) is open (`forgetting`, not given up) — or, with `since`, started at or
167
+ * after that time (settled or not), or, with `any`, exists at all (open, settled or given up): the precedence rule of AC-ROT-5
168
+ * (leaving beats re-keying; a forgotten device must not re-key). A forget of the own device ends when the device is enrolled
169
+ * again (`supersedeOwnForget` deletes the settled record when a Welcome is adopted under an enrolment request made after it).
170
+ */
171
+ async function ownForgetOpen(options = {}) {
172
+ return deps.transaction(async (tx) => {
173
+ const view = tx.artifact(ARTIFACT);
174
+ for (const key of await view.keys()) {
175
+ if (!key.startsWith('forget:'))
176
+ continue;
177
+ const record = await readForget(view, key.slice('forget:'.length));
178
+ if (record?.own !== true || record.superseded === true)
179
+ continue;
180
+ if (record.status === 'forgetting' && record.gaveUp === undefined)
181
+ return true;
182
+ if (options.any === true)
183
+ return true;
184
+ if (options.since !== undefined && record.startedAt >= options.since)
185
+ return true;
186
+ }
187
+ return false;
188
+ });
189
+ }
190
+ const rotations = createRotationDriver(deps, { assertLive, ownForget: ownForgetOpen });
191
+ function resumeInBackground() {
192
+ if (disposed || deps.isDisposed() || resumeRunning)
193
+ return;
194
+ resumeRunning = true;
195
+ queue
196
+ .run(() => deps.inDeviceFrame(async () => {
197
+ const recheckLeft = await recheckSettlements();
198
+ // AC-LIN-5: successions the held groups' windows show are recorded, once per service lifetime (a live rotation
199
+ // arrives as a notification) and only for a port that reports successions: reading every group's view on every
200
+ // pass is not free. A group whose read or write failed is marked dirty and re-ingested by the next pass; it holds
201
+ // nothing back (every lineage reader also unites the groups' own views).
202
+ if (reportsSuccessions()) {
203
+ try {
204
+ if (!caughtUp) {
205
+ await ingestSuccessions([...(await deps.groups.heldGroups())].sort());
206
+ caughtUp = true;
207
+ }
208
+ else if (dirtyGroups.size > 0) {
209
+ await ingestSuccessions([...dirtyGroups].sort());
210
+ }
211
+ }
212
+ catch (error) {
213
+ // A failed persist never holds the rest of the pass back (approvals, forgets): the groups stay dirty and a
214
+ // later pass retries them.
215
+ if (stopsDeviceIntent(error))
216
+ throw error;
217
+ caughtUp = true;
218
+ }
219
+ if (dirtyGroups.size > 0)
220
+ scheduleResume();
221
+ }
222
+ // S7: an open rotation, the sweep toward `self` and the recorded KeyPackage retry (before the forgets, so a forget that
223
+ // began since is seen as such by the rotation: leaving beats re-keying).
224
+ let rotationLeft = false;
225
+ try {
226
+ rotationLeft = await rotations.resume();
227
+ }
228
+ catch (error) {
229
+ // A rotation pass that cannot read its records or the groups never holds the approvals and forgets back.
230
+ if (stopsDeviceIntent(error))
231
+ throw error;
232
+ rotationLeft = true;
233
+ }
234
+ const approvalsLeft = await resumeEnrolments(deps, registryBinding);
235
+ const forgetsLeft = await resumeForgets();
236
+ return recheckLeft || rotationLeft || approvalsLeft || forgetsLeft;
237
+ }))
238
+ .then((left) => {
239
+ resumeRunning = false;
240
+ if (passRequested) {
241
+ passRequested = false;
242
+ resumeInBackground();
243
+ }
244
+ else if (left)
245
+ scheduleResume();
246
+ else
247
+ resumeFailures = 0;
248
+ }, (error) => {
249
+ resumeRunning = false;
250
+ passRequested = false;
251
+ if (!isMarmotError(error, 'disposed') && !isMarmotError(error, 'no-lease'))
252
+ scheduleResume();
253
+ });
254
+ }
255
+ /**
256
+ * S10 (V1 revisable settlement): rechecks the device outcomes settled from
257
+ * the tree of every group a persisted transition rewound (the durable
258
+ * marker `DeviceGroupPort.settlementRechecks` reads). A group whose tree
259
+ * contradicts a settled `enrolled` / `removed` outcome reopens it; a group
260
+ * still converging (`syncing`, an own commit pending — the rewind's own
261
+ * withdrawal re-opens the convergence window) keeps its marker and the pass
262
+ * reports work left, so the background continuation re-arms until the
263
+ * recheck is conclusive. Only a conclusive recheck clears the marker.
264
+ * Returns whether a recheck is still owed.
265
+ */
266
+ async function recheckSettlements() {
267
+ let left = false;
268
+ for (const { groupId, token, withdrawnLeaves } of await deps.groups.settlementRechecks()) {
269
+ const [approvals, forgets] = await Promise.all([
270
+ reopenApprovalsAfterRewind(deps, groupId, withdrawnLeaves).catch(() => 'blocked'),
271
+ reopenForgetsAfterRewind(groupId).catch(() => 'blocked'),
272
+ ]);
273
+ if (approvals === 'blocked' || forgets === 'blocked') {
274
+ left = true;
275
+ continue;
276
+ }
277
+ await deps.groups.clearSettlementRecheck(groupId, token);
278
+ }
279
+ return left;
280
+ }
281
+ /** The one-time catch-up of the held groups' successions was attempted (failures are `dirtyGroups`). */
282
+ let caughtUp = false;
283
+ /** The port reports successions in its views (it says so, or announces them through `onRotation`). */
284
+ const reportsSuccessions = () => deps.groups.reportsSuccessions ?? deps.groups.onRotation !== undefined;
285
+ /** A pass was asked for while one was running: it runs again once that one ends (it may have read the markers already). */
286
+ let passRequested = false;
287
+ /**
288
+ * `DeviceGroupPort.onRewind` (detached, outside the group's queue): a prompt
289
+ * recheck pass. The marker that pass consumes is durable, so a crash before
290
+ * this notification only delays the recheck to the next pass (load, inbox
291
+ * pass, retry timer).
292
+ */
293
+ const unsubscribeRewind = deps.groups.onRewind((groupId) => {
294
+ rotations.invalidate(groupId);
295
+ if (disposed || deps.isDisposed())
296
+ return;
297
+ if (resumeRunning)
298
+ passRequested = true;
299
+ else
300
+ resumeInBackground();
301
+ });
302
+ /** Owner decision 13: a restore succeeded — a prompt pass drains the rotation it owes (its marker is durable). */
303
+ const unsubscribeRestored = deps.groups.onRestored?.(() => {
304
+ if (disposed || deps.isDisposed())
305
+ return;
306
+ if (resumeRunning)
307
+ passRequested = true;
308
+ else
309
+ resumeInBackground();
310
+ }) ?? (() => undefined);
311
+ /**
312
+ * `DeviceGroupPort.onRotation` (detached, outside the group's queue): a `leaf-key-rotated` notification of a held
313
+ * group. The group's successions are recorded on the device queue; a failure leaves the next pass to catch up
314
+ * (the feed is the window, which still holds them), and a recorded link gives a waiting forget a prompt pass.
315
+ */
316
+ const unsubscribeRotation = deps.groups.onRotation?.((groupId) => {
317
+ rotations.invalidate(groupId);
318
+ if (disposed || deps.isDisposed())
319
+ return;
320
+ queue
321
+ .run(() => deps.inDeviceFrame(() => ingestSuccessions([groupId])))
322
+ .then((wrote) => {
323
+ if (!wrote || disposed || deps.isDisposed())
324
+ return;
325
+ if (resumeRunning)
326
+ passRequested = true;
327
+ else
328
+ resumeInBackground();
329
+ }, (error) => {
330
+ // Marked dirty by the ingest itself; the next pass re-reads the group.
331
+ if (!stopsDeviceIntent(error))
332
+ scheduleResume();
333
+ });
334
+ });
335
+ /**
336
+ * Runs one durable device operation on the queue, inside the DEVICE_SCOPE frame:
337
+ * - E1: refused `reentrant` — before it could queue — when called from inside a consumer surface a device
338
+ * operation is waiting on (an `onConfirm` hook of its commit, of whatever scope): it would queue behind
339
+ * that very operation. Where no async context exists (browsers) only synchronous re-entry is detected —
340
+ * ADR-013's bounded residue.
341
+ * - S3 (AC-RE-2): refused `reentrant` — also before it could queue — when called from inside ANY group's
342
+ * own `onConfirm`/`verifier`/`onProposal` surface, even one no device operation is itself waiting on:
343
+ * that group's queue may be the very thing a concurrent device operation needs, so joining the device
344
+ * queue here would deadlock the two queues against each other (`assertNotInGroupConsumerSurface`).
345
+ * - E2 / C3: any failure that does not stop device intents (disposed, no-lease, reentrant) schedules the
346
+ * capped-backoff background pass, which continues what the operation made durable; the caller still
347
+ * gets the rejection.
348
+ */
349
+ function runOperation(operation, task) {
350
+ try {
351
+ assertLive(operation);
352
+ deps.assertNotInDeviceOperation(`devices.${operation}`);
353
+ deps.assertNotInGroupConsumerSurface(`devices.${operation}`);
354
+ }
355
+ catch (error) {
356
+ return Promise.reject(error);
357
+ }
358
+ return queue.run(() => deps.inDeviceFrame(async () => {
359
+ assertLive(operation);
360
+ try {
361
+ return await task();
362
+ }
363
+ catch (error) {
364
+ // A call refused on its input (`invalid-options`) made nothing durable: nothing to continue.
365
+ if (!stopsDeviceIntent(error) && !isMarmotError(error, 'invalid-options'))
366
+ scheduleResume();
367
+ throw error;
368
+ }
369
+ }));
370
+ }
371
+ async function readHeld() {
372
+ const leaves = new Map();
373
+ const views = new Map();
374
+ const edges = [];
375
+ for (const groupId of [...(await deps.groups.heldGroups())].sort()) {
376
+ const snapshot = await deps.groups.snapshot(groupId);
377
+ if (snapshot === undefined)
378
+ continue;
379
+ views.set(groupId, snapshot);
380
+ if (!snapshot.member)
381
+ continue;
382
+ for (const leaf of snapshot.accountLeaves)
383
+ if (!leaves.has(leaf.leafKey))
384
+ leaves.set(leaf.leafKey, leaf.leafIndex);
385
+ }
386
+ // The signer is asked for the account only when some view reports successions.
387
+ edges.push(...(await viewSuccessionEdges(deps.signer, views.values())));
388
+ return { leaves, views, edges };
389
+ }
390
+ /** The recorded lineage evidence as edges: links, then alternates (strict decode: a malformed record rejects `store-failed`). */
391
+ async function linkEdges() {
392
+ return deps.transaction((tx) => readRegistryEdges(tx.artifact(ARTIFACT)));
393
+ }
394
+ /**
395
+ * The keys of forgotten devices (an entry with a tombstone): a forgotten installation is still a distinct device, so it
396
+ * counts as a live head when telling the installations of a contested component apart — otherwise forgetting one
397
+ * installation would fold its tombstone into the other the moment its leaf leaves the groups.
398
+ */
399
+ async function tombstonedKeys() {
400
+ return deps.transaction(async (tx) => {
401
+ const view = tx.artifact(ARTIFACT);
402
+ const out = [];
403
+ for (const key of await view.keys()) {
404
+ if (!LEAF_KEY.test(key))
405
+ continue;
406
+ if ((await readEntry(view, key))?.tombstone !== undefined)
407
+ out.push(key);
408
+ }
409
+ return out;
410
+ });
411
+ }
412
+ /** Groups whose successions could not be recorded (a failed read or write): re-ingested by the next pass. */
413
+ const dirtyGroups = new Set();
414
+ /**
415
+ * AC-LIN-5 / Design Decision 7: feeds the local account's canonical-path successions of `groupIds` into the registry,
416
+ * idempotently, in one transaction. Returns whether anything was written. A failed read marks its group dirty (retried by
417
+ * the next pass) and does not stop the others; a failed write marks them all and rejects. A withdrawn rotation never
418
+ * un-records a link: nothing here deletes.
419
+ */
420
+ async function ingestSuccessions(groupIds) {
421
+ const facts = [];
422
+ const failed = [];
423
+ for (const groupId of groupIds) {
424
+ let snapshot;
425
+ try {
426
+ snapshot = await deps.groups.snapshot(groupId);
427
+ facts.push(...(await viewSuccessionEdges(deps.signer, [snapshot])));
428
+ }
429
+ catch (error) {
430
+ if (stopsDeviceIntent(error))
431
+ throw error;
432
+ dirtyGroups.add(groupId);
433
+ failed.push(groupId);
434
+ }
435
+ }
436
+ if (facts.length > 0) {
437
+ const at = deps.clock.now();
438
+ try {
439
+ const wrote = await deps.transaction((tx) => persistSuccessionEdges(tx, facts, () => at));
440
+ for (const g of groupIds)
441
+ if (!failed.includes(g))
442
+ dirtyGroups.delete(g);
443
+ return wrote;
444
+ }
445
+ catch (error) {
446
+ for (const g of groupIds)
447
+ dirtyGroups.add(g);
448
+ throw error;
449
+ }
450
+ }
451
+ for (const g of groupIds)
452
+ if (!failed.includes(g))
453
+ dirtyGroups.delete(g);
454
+ return false;
455
+ }
456
+ // -- forget ---------------------------------------------------------------
457
+ async function updateForget(leafKey, change) {
458
+ return deps.transaction(async (tx) => {
459
+ const view = tx.artifact(ARTIFACT);
460
+ const current = await readForget(view, leafKey);
461
+ if (current?.status !== 'forgetting')
462
+ return current;
463
+ const next = change(current);
464
+ if (next === undefined)
465
+ return current;
466
+ await writeForget(view, next);
467
+ return next;
468
+ });
469
+ }
470
+ function withGroup(record, groupId, patch) {
471
+ return { ...record, groups: record.groups.map((g) => (g.groupId === groupId ? { ...g, ...patch } : g)) };
472
+ }
473
+ /**
474
+ * S10 (V1 revisable settlement): reopens `groupId` of `leafKey`'s forget
475
+ * once its recorded `removed` outcome is contradicted by a rewind — the
476
+ * leaf is back on the winning branch. The group returns to `outcome:
477
+ * 'pending', inflight: true` (counted like C4 on its next drive) and a
478
+ * finalized forget returns to `forgetting`. The registry's tombstone (if
479
+ * one was already recorded) is amended in the SAME transaction so
480
+ * `devices.list()`'s projection stays consistent immediately — `groups`
481
+ * lists `groupId` as still holding the leaf again until it is removed a
482
+ * second time, when `finalizeForget` rewrites the tombstone in full.
483
+ */
484
+ async function reopenForgetGroup(leafKey, groupId, viewEdges = []) {
485
+ await deps.transaction(async (tx) => {
486
+ const view = tx.artifact(ARTIFACT);
487
+ // What the view showed is persisted before the tombstone is located by lineage (one source in reads and writes).
488
+ await persistSuccessionEdges(tx, viewEdges, () => deps.clock.now());
489
+ const current = await readForget(view, leafKey);
490
+ if (current === undefined || current.superseded === true || (current.status !== 'forgetting' && current.status !== 'forgotten'))
491
+ return;
492
+ const group = current.groups.find((g) => g.groupId === groupId);
493
+ if (group === undefined || group.outcome !== 'removed')
494
+ return;
495
+ const groups = current.groups.map((g) => (g.groupId === groupId ? { ...g, outcome: 'pending', inflight: true } : g));
496
+ await writeForget(view, { ...current, status: 'forgetting', groups });
497
+ // The tombstone is the lineage head's.
498
+ const lineage = await loadDeviceLineage(view);
499
+ const head = lineage.deviceHeadOf(leafKey);
500
+ const { entry } = await consolidateRegistryEntries(view, lineage, head);
501
+ if (entry?.tombstone !== undefined && !entry.tombstone.groups.includes(groupId)) {
502
+ const tombstone = { ...entry.tombstone, groups: [...entry.tombstone.groups, groupId].sort() };
503
+ await view.put(head, { ...entry, tombstone });
504
+ }
505
+ });
506
+ }
507
+ /**
508
+ * S10 (V1 revisable settlement): `DeviceGroupPort.onRewind`'s handler for
509
+ * device forgets, called after `groupId` rewound off a branch it had
510
+ * applied. Every forget record whose status is `forgetting` or `forgotten`
511
+ * and whose recorded outcome for `groupId` was `removed` is re-checked
512
+ * against one fresh snapshot; a leaf the rewind brought back is reopened
513
+ * ({@link reopenForgetGroup}). Returns whether anything was reopened.
514
+ */
515
+ async function reopenForgetsAfterRewind(groupId) {
516
+ const snapshot = await deps.groups.snapshot(groupId);
517
+ if (snapshot === undefined)
518
+ return 'clear'; // no longer held: nothing here to reconsider
519
+ if (snapshot.syncing || snapshot.ownCommitPending)
520
+ return 'blocked';
521
+ const candidates = await deps.transaction(async (tx) => {
522
+ const view = tx.artifact(ARTIFACT);
523
+ const out = [];
524
+ for (const key of await view.keys()) {
525
+ if (!key.startsWith('forget:'))
526
+ continue;
527
+ const record = await readForget(view, key.slice('forget:'.length));
528
+ if (record === undefined || record.superseded === true || (record.status !== 'forgetting' && record.status !== 'forgotten'))
529
+ continue;
530
+ if (record.groups.some((g) => g.groupId === groupId && g.outcome === 'removed'))
531
+ out.push(record);
532
+ }
533
+ return out;
534
+ });
535
+ if (candidates.length === 0)
536
+ return 'clear';
537
+ // The device's chain: the links and this group's successions, united with what the record knew (Design Decision 8).
538
+ const viewEdges = await viewSuccessionEdges(deps.signer, [snapshot]);
539
+ const edges = [...(await linkEdges()), ...viewEdges];
540
+ let reopened = false;
541
+ for (const record of candidates) {
542
+ const chain = chainClosure([record.leafKey, ...(record.chain ?? [])], edges, record.apart);
543
+ if (!snapshot.accountLeaves.some((l) => chain.has(l.leafKey)))
544
+ continue; // still gone: no contradiction
545
+ await reopenForgetGroup(record.leafKey, groupId, viewEdges);
546
+ reopened = true;
547
+ }
548
+ return reopened ? 'reopened' : 'clear';
549
+ }
550
+ /**
551
+ * The chain of a forget (Design Decision 8): every key of the device's lineage, over the registry's recorded links
552
+ * united with the canonical-path successions of the groups' views, and the keys the record already knew (a chain
553
+ * never shrinks while the intent lives, so a group listed because it held a chain key keeps being judged against it).
554
+ * `observe` folds in one more view; growth is persisted on the record.
555
+ */
556
+ async function forgetChain(record) {
557
+ const edges = await linkEdges();
558
+ const viewEdges = [];
559
+ const live = new Set();
560
+ let chain = chainClosure([record.leafKey, ...(record.chain ?? [])], edges, record.apart);
561
+ const persist = async () => {
562
+ const keys = [...chain].sort();
563
+ await updateForget(record.leafKey, (r) => {
564
+ const known = [...(r.chain ?? [r.leafKey])].sort();
565
+ return known.length === keys.length && keys.every((k, i) => known[i] === k) ? undefined : { ...r, chain: keys };
566
+ });
567
+ };
568
+ return {
569
+ chain: () => chain,
570
+ viewEdges: () => viewEdges,
571
+ live: () => live,
572
+ async observe(view) {
573
+ if (view === undefined)
574
+ return;
575
+ for (const l of view.accountLeaves)
576
+ live.add(l.leafKey);
577
+ const reported = await viewSuccessionEdges(deps.signer, [view]);
578
+ edges.push(...reported);
579
+ viewEdges.push(...reported);
580
+ const grown = chainClosure(chain, edges, record.apart);
581
+ if (grown.size === chain.size)
582
+ return;
583
+ chain = grown;
584
+ await persist();
585
+ },
586
+ held: (view) => [...new Set(view.accountLeaves.filter((l) => chain.has(l.leafKey)).map((l) => l.leafKey))],
587
+ };
588
+ }
589
+ /** One group commit removing every chain leaf of the group (one commit when the port can, else one per chain key). */
590
+ async function removeChainLeaves(groupId, keys) {
591
+ if (deps.groups.removeLeaves !== undefined) {
592
+ await deps.groups.removeLeaves(groupId, keys);
593
+ return;
594
+ }
595
+ for (const key of keys)
596
+ await deps.groups.removeLeaf(groupId, key);
597
+ }
598
+ /** One pass over the forget's pending groups (state decides each outcome, never the call that tried). */
599
+ async function driveForgetGroups(leafKey) {
600
+ let record = await deps.transaction((tx) => readForget(tx.artifact(ARTIFACT), leafKey));
601
+ if (record?.status !== 'forgetting')
602
+ return record;
603
+ const lineage = await forgetChain(record);
604
+ for (const group of record.groups) {
605
+ if (group.outcome !== 'pending')
606
+ continue;
607
+ assertLive('forget');
608
+ if (record.own === true) {
609
+ record = await driveOwnLeave(leafKey, group, lineage);
610
+ if (record?.status !== 'forgetting')
611
+ return record;
612
+ continue;
613
+ }
614
+ const snapshot = await deps.groups.snapshot(group.groupId);
615
+ await lineage.observe(snapshot);
616
+ let attempts = group.attempts;
617
+ let outcome;
618
+ if (snapshot === undefined || !snapshot.member)
619
+ outcome = 'timed-out';
620
+ // A competing commit may still replace what the tree shows now (a forget racing an incoming commit).
621
+ else if (snapshot.syncing)
622
+ outcome = 'wait';
623
+ else if (lineage.held(snapshot).length === 0)
624
+ outcome = 'removed';
625
+ // An issued commit still in the pipeline: its fate decides.
626
+ else if (snapshot.ownCommitPending)
627
+ outcome = 'wait';
628
+ else
629
+ outcome = 'act';
630
+ if (outcome === 'act' && group.inflight === true) {
631
+ // C4: an earlier Remove settled without removing the leaf (terminal after the call returned, or a lost
632
+ // race): it counts, exactly once.
633
+ attempts += 1;
634
+ record = await updateForget(leafKey, (r) => withGroup(r, group.groupId, { attempts, inflight: false }));
635
+ if (record?.status !== 'forgetting')
636
+ return record;
637
+ }
638
+ if (outcome === 'act' && attempts >= MAX_GROUP_ATTEMPTS)
639
+ outcome = 'timed-out';
640
+ if (outcome === 'act') {
641
+ // Persisted before the commit is issued (see ForgetGroup.inflight).
642
+ record = await updateForget(leafKey, (r) => withGroup(r, group.groupId, { inflight: true }));
643
+ if (record?.status !== 'forgetting')
644
+ return record;
645
+ let failure;
646
+ try {
647
+ await removeChainLeaves(group.groupId, lineage.held(snapshot));
648
+ }
649
+ catch (error) {
650
+ if (stopsDeviceIntent(error))
651
+ throw error;
652
+ failure = classifyGroupActFailure(error);
653
+ }
654
+ const after = await deps.groups.snapshot(group.groupId);
655
+ // A rotation that landed meanwhile extends the chain: judged against it, so a leaf that only changed its key
656
+ // is never read as gone.
657
+ await lineage.observe(after);
658
+ if (after === undefined || !after.member)
659
+ outcome = 'timed-out';
660
+ else if (after.syncing || after.ownCommitPending)
661
+ outcome = 'wait';
662
+ else if (lineage.held(after).length === 0)
663
+ outcome = 'removed';
664
+ // Every relay refused the commit: terminal.
665
+ else if (failure === 'permanent')
666
+ outcome = 'timed-out';
667
+ else if (failure === 'transient') {
668
+ // Refused before any commit existed: not an attempt.
669
+ record = await updateForget(leafKey, (r) => withGroup(r, group.groupId, { inflight: false }));
670
+ if (record?.status !== 'forgetting')
671
+ return record;
672
+ outcome = 'wait';
673
+ }
674
+ else {
675
+ // The attempt ran and the leaf is still there (a lost race, a commit that went terminal): counted.
676
+ attempts += 1;
677
+ record = await updateForget(leafKey, (r) => withGroup(r, group.groupId, { attempts, inflight: false }));
678
+ if (record?.status !== 'forgetting')
679
+ return record;
680
+ outcome = attempts >= MAX_GROUP_ATTEMPTS ? 'timed-out' : 'wait';
681
+ }
682
+ }
683
+ if (outcome === 'wait')
684
+ continue;
685
+ const settled = outcome;
686
+ record = await updateForget(leafKey, (r) => withGroup(r, group.groupId, { outcome: settled, inflight: false }));
687
+ if (record?.status !== 'forgetting')
688
+ return record;
689
+ }
690
+ return record;
691
+ }
692
+ /**
693
+ * Own-leaf forget, one group: the group's `leave()` is started (its request
694
+ * id persisted, so a resumed pass joins it rather than starting another),
695
+ * then its outcome is read back; `pending` leaves the group pending. A leave
696
+ * that reports `removed` while a leaf of the device's chain is still in the
697
+ * group (the leave removed one key, another stayed) is not `removed`: the
698
+ * group times out and the tombstone names it (AC-FORGET-5).
699
+ */
700
+ async function driveOwnLeave(leafKey, group, lineage) {
701
+ const leave = seams.ownLeaf;
702
+ if (leave === undefined)
703
+ throw new MarmotError('store-failed', 'devices.forget: no teardown service for the own leaf');
704
+ let leaveId = group.leaveId;
705
+ if (leaveId === undefined) {
706
+ const started = await leave.startLeave(group.groupId);
707
+ const record = await updateForget(leafKey, (r) => withGroup(r, group.groupId, { leaveId: started }));
708
+ if (record?.status !== 'forgetting')
709
+ return record;
710
+ leaveId = started;
711
+ }
712
+ let outcome = await leave.leaveOutcome(leaveId);
713
+ if (outcome === 'pending')
714
+ return deps.transaction((tx) => readForget(tx.artifact(ARTIFACT), leafKey));
715
+ if (outcome === 'removed') {
716
+ const view = await deps.groups.snapshot(group.groupId);
717
+ await lineage.observe(view);
718
+ if (view !== undefined && view.member && lineage.held(view).length > 0)
719
+ outcome = 'timed-out';
720
+ }
721
+ const settled = outcome;
722
+ return updateForget(leafKey, (r) => withGroup(r, group.groupId, { outcome: settled }));
723
+ }
724
+ /**
725
+ * The kind-5 deletion of the device's KeyPackages: found (every valid
726
+ * kind-30443 event of the account whose leaf carries `leafKey`, plus the
727
+ * KeyPackages its enrolment requests carried), signed outside any
728
+ * transaction and stored in the record, then published; a stored deletion
729
+ * is re-published on later passes. Returns whether it is settled.
730
+ */
731
+ async function driveDeletion(leafKey) {
732
+ let record = await deps.transaction((tx) => readForget(tx.artifact(ARTIFACT), leafKey));
733
+ if (record === undefined)
734
+ return true;
735
+ let deletion = record.deletion;
736
+ if (deletion === undefined) {
737
+ try {
738
+ record = await prepareDeletion(leafKey);
739
+ }
740
+ catch (error) {
741
+ if (stopsDeviceIntent(error))
742
+ throw error;
743
+ return countDeletionFailure(leafKey, error);
744
+ }
745
+ if (record === undefined)
746
+ return false; // the lookup timed out: an unknown, retried uncounted
747
+ deletion = record.deletion;
748
+ }
749
+ if (deletion === undefined || deletion.status !== 'pending')
750
+ return true;
751
+ let accepted = false;
752
+ try {
753
+ accepted = classifyPublish(deletion.relays, await deps.transport.publish([...deletion.relays], deletion.event)).outcome === 'accepted';
754
+ }
755
+ catch {
756
+ accepted = false;
757
+ }
758
+ const published = deletion.event;
759
+ let gaveUp = false;
760
+ const stored = await deps.transaction(async (tx) => {
761
+ const view = tx.artifact(ARTIFACT);
762
+ const current = await readForget(view, leafKey);
763
+ const d = current?.deletion;
764
+ if (current === undefined || d === undefined || d.status !== 'pending' || d.event.id !== published.id)
765
+ return d;
766
+ const attempts = d.attempts + 1;
767
+ const updated = { ...d, attempts, status: accepted ? 'published' : attempts >= MAX_DELETION_ATTEMPTS ? 'failed' : 'pending' };
768
+ gaveUp = updated.status === 'failed';
769
+ await writeForget(view, { ...current, deletion: updated });
770
+ return updated;
771
+ });
772
+ if (gaveUp)
773
+ deps.onMaintenanceFailed({ invitationId: leafKey, kind: 'keypackage-deletion', reason: 'publish-failed' });
774
+ return stored === undefined || stored.status !== 'pending';
775
+ }
776
+ /**
777
+ * Counts one failed preparation of the deletion (after the write committed, `maintenanceFailed` fires when
778
+ * it was the {@link MAX_MAINTENANCE_FAILURES}th). A transient cause is not counted and retried. Returns
779
+ * whether the deletion is settled (given up).
780
+ */
781
+ async function countDeletionFailure(leafKey, error) {
782
+ const reason = maintenanceFailureReason(error);
783
+ if (reason === undefined)
784
+ return false;
785
+ const gaveUp = await deps.transaction(async (tx) => {
786
+ const view = tx.artifact(ARTIFACT);
787
+ const current = await readForget(view, leafKey);
788
+ if (current === undefined || current.deletion !== undefined)
789
+ return false;
790
+ const deletionFailures = (current.deletionFailures ?? 0) + 1;
791
+ const failed = deletionFailures >= MAX_MAINTENANCE_FAILURES;
792
+ await writeForget(view, { ...current, deletionFailures, ...(failed ? { deletion: { status: 'failed', reason } } : {}) });
793
+ return failed;
794
+ });
795
+ if (gaveUp)
796
+ deps.onMaintenanceFailed({ invitationId: leafKey, kind: 'keypackage-deletion', reason });
797
+ return gaveUp;
798
+ }
799
+ /** Looks the device's KeyPackages up, signs the deletion OUTSIDE any transaction and stores it; `undefined` when the lookup timed out. */
800
+ async function prepareDeletion(leafKey) {
801
+ const self = await deps.signer.getPublicKey();
802
+ // Every key of the device's chain known now (AC-FORGET-3): the record's own, extended by the registry's links.
803
+ const known = await deps.transaction((tx) => readForget(tx.artifact(ARTIFACT), leafKey));
804
+ const chain = chainClosure([leafKey, ...(known?.chain ?? [])], await linkEdges(), known?.apart);
805
+ const fetched = await deps.fetchKeyPackageEvents(self);
806
+ // An incomplete answer (a relay timed out) would delete too little: retried on the next pass.
807
+ if (fetched.timedOut)
808
+ return undefined;
809
+ const byId = new Map();
810
+ for (const event of [...fetched.events, ...(await requestedKeyPackages(deps, leafKey, [...chain]))]) {
811
+ if (event.pubkey !== self || byId.has(event.id))
812
+ continue;
813
+ try {
814
+ if (chain.has(hex(getKeyPackage(event).leafNode.signaturePublicKey)))
815
+ byId.set(event.id, event);
816
+ }
817
+ catch {
818
+ // not a decodable KeyPackage
819
+ }
820
+ }
821
+ let next;
822
+ if (byId.size === 0) {
823
+ next = { status: 'none' };
824
+ }
825
+ else {
826
+ // One `a` tag per slot (every version of a slot shares its address), one `e` tag per event.
827
+ const template = createDeleteKeyPackageEvent({ events: [...byId.values()] });
828
+ const seenTags = new Set();
829
+ const tags = template.tags.filter((t) => {
830
+ const key = JSON.stringify(t);
831
+ if (seenTags.has(key))
832
+ return false;
833
+ seenTags.add(key);
834
+ return true;
835
+ });
836
+ const signed = await deps.signer.signEvent({ ...template, tags });
837
+ next = { status: 'pending', event: signed, relays: fetched.relays, attempts: 0 };
838
+ }
839
+ const stored = await deps.transaction(async (tx) => {
840
+ const view = tx.artifact(ARTIFACT);
841
+ const current = await readForget(view, leafKey);
842
+ if (current === undefined || current.deletion !== undefined)
843
+ return current;
844
+ const updated = { ...current, deletion: next, ...(chain.size > 1 ? { deletionChain: [...chain].sort() } : {}) };
845
+ await writeForget(view, updated);
846
+ return updated;
847
+ });
848
+ // Gone meanwhile: nothing to publish (a settled record).
849
+ return stored ?? { v: 1, leafKey, startedAt: 0, groups: [], status: 'forgotten', deletion: { status: 'none' } };
850
+ }
851
+ /** Records the tombstone and closes the intent once every group is terminal; `deviceForgotten` fires after that commit. */
852
+ async function finalizeForget(leafKey, leafIndex) {
853
+ // S10 (V1 revisable settlement): re-derive every `removed` group from a fresh snapshot before recording
854
+ // the tombstone — a rewind since the drive pass that settled it may have brought the leaf back. `syncing`
855
+ // / `ownCommitPending` defers the whole finalize to a later pass; a leaf back on the tree reopens the
856
+ // group (instead of tombstoning a false success) and likewise defers.
857
+ const probe = await deps.transaction((tx) => readForget(tx.artifact(ARTIFACT), leafKey));
858
+ if (probe?.status !== 'forgetting')
859
+ return;
860
+ const lineage = await forgetChain(probe);
861
+ for (const group of probe.groups) {
862
+ if (group.outcome !== 'removed')
863
+ continue;
864
+ const snapshot = await deps.groups.snapshot(group.groupId);
865
+ await lineage.observe(snapshot);
866
+ if (snapshot === undefined || !snapshot.member)
867
+ continue; // no longer held: nothing here to contradict
868
+ if (snapshot.syncing || snapshot.ownCommitPending)
869
+ return;
870
+ if (lineage.held(snapshot).length > 0) {
871
+ await reopenForgetGroup(leafKey, group.groupId, lineage.viewEdges());
872
+ return;
873
+ }
874
+ }
875
+ const ownKey = await readDeviceSigningKey((fn) => deps.transaction(fn));
876
+ const forgottenKeys = await tombstonedKeys();
877
+ const chainKeys = [...lineage.chain()].sort();
878
+ // The chain grew beyond what the deletion covers (a succession these views showed): the next pass re-prepares the
879
+ // deletion once before any tombstone is written (AC-FORGET-3).
880
+ const covered = new Set(probe.deletionChain ?? [probe.leafKey]);
881
+ if (probe.reprepared !== true && probe.deletion !== undefined && chainKeys.some((k) => !covered.has(k)))
882
+ return;
883
+ let forgottenHead = leafKey;
884
+ class AlreadyFinal extends Error {
885
+ }
886
+ try {
887
+ await deps.lifecycle.afterCommit('deviceForgotten', () => deps.transaction(async (tx) => {
888
+ const view = tx.artifact(ARTIFACT);
889
+ const current = await readForget(view, leafKey);
890
+ if (current?.status !== 'forgetting' || current.groups.some((g) => g.outcome === 'pending'))
891
+ throw new AlreadyFinal();
892
+ const stillHolding = current.groups.filter((g) => g.outcome !== 'removed').map((g) => g.groupId).sort();
893
+ // AC-RECHK-2: forgetStartedAt carries this settling forget's OWN startedAt onto
894
+ // the tombstone — the authoritative departure time, not `at` (when this settle happened).
895
+ const tombstone = { at: deps.clock.now(), groups: stillHolding, forgetStartedAt: current.startedAt };
896
+ // The tombstone is the lineage head's: it follows the device (Design Decision 8).
897
+ // The forgotten device's own keys and the other installations count as live: the tombstone stays on THIS device.
898
+ const live = new Set([...lineage.live(), ...chainKeys, ...(probe.apart ?? []), ...forgottenKeys]);
899
+ if (ownKey !== undefined)
900
+ live.add(ownKey.leafKey);
901
+ await persistSuccessionEdges(tx, lineage.viewEdges(), () => deps.clock.now(), live);
902
+ const registryLineage = await loadDeviceLineage(view, [], live);
903
+ // The entry is stored under the device's entry key; the event and the record name the key `list()` shows.
904
+ const head = registryLineage.deviceHeadOf(leafKey);
905
+ forgottenHead = registryLineage.displayHeadsOf(leafKey)[0];
906
+ const { entry } = await consolidateRegistryEntries(view, registryLineage, head);
907
+ const next = {
908
+ ...(entry ?? { v: 1, leafKey: head, label: '', enrolledAt: 0 }),
909
+ ...(leafIndex === undefined ? {} : { leafIndex }),
910
+ tombstone,
911
+ };
912
+ await view.put(head, next);
913
+ await writeForget(view, { ...current, status: 'forgotten', ...(chainKeys.length > 1 ? { chain: chainKeys } : {}) });
914
+ return stillHolding;
915
+ }), (stillHolding) => ({ leafKey: forgottenHead, groups: stillHolding }));
916
+ }
917
+ catch (error) {
918
+ if (!(error instanceof AlreadyFinal))
919
+ throw error;
920
+ }
921
+ }
922
+ /**
923
+ * AC-FORGET-3: a succession recorded for the device after its deletion was prepared (a chain key the deletion does not
924
+ * cover) re-prepares the deletion, once, for the extended chain. Returns whether it was reset.
925
+ */
926
+ async function reprepareDeletionForGrownChain(leafKey) {
927
+ const record = await deps.transaction((tx) => readForget(tx.artifact(ARTIFACT), leafKey));
928
+ if (record?.status !== 'forgetting' || record.reprepared === true || record.deletion === undefined)
929
+ return false;
930
+ const chain = chainClosure([leafKey, ...(record.chain ?? [])], await linkEdges(), record.apart);
931
+ const covered = new Set(record.deletionChain ?? [leafKey]);
932
+ if ([...chain].every((k) => covered.has(k)))
933
+ return false;
934
+ const reset = await updateForget(leafKey, (r) => {
935
+ const { deletion: _deletion, ...rest } = r;
936
+ return r.reprepared === true ? undefined : { ...rest, chain: [...chain].sort(), deletionFailures: 0, reprepared: true };
937
+ });
938
+ return reset?.reprepared === true && reset.deletion === undefined;
939
+ }
940
+ /** One pass of one forget; resolves with its record afterwards and whether work is left. */
941
+ async function driveForget(leafKey, leafIndex) {
942
+ const record = await driveForgetGroups(leafKey);
943
+ // Own leaf: leave first (AC-ADMIN-10) — the kind-5 waits until every group is terminal.
944
+ const leaving = record?.own === true && record.status === 'forgetting' && record.groups.some((g) => g.outcome === 'pending');
945
+ // A failure preparing the deletion is counted inside (W1); anything else thrown here counts for the pass.
946
+ let deletionSettled = leaving ? false : await driveDeletion(leafKey);
947
+ // The chain grew after the deletion was prepared and before the tombstone: re-prepared once (AC-FORGET-3).
948
+ if (!leaving && record?.status === 'forgetting' && !record.groups.some((g) => g.outcome === 'pending') && (await reprepareDeletionForGrownChain(leafKey))) {
949
+ deletionSettled = await driveDeletion(leafKey);
950
+ }
951
+ // The tombstone waits for a re-prepared deletion to be published or given up.
952
+ const current = await deps.transaction((tx) => readForget(tx.artifact(ARTIFACT), leafKey));
953
+ const awaitingReprepared = current?.reprepared === true && (current.deletion === undefined || current.deletion.status === 'pending');
954
+ if (record?.status === 'forgetting' && !record.groups.some((g) => g.outcome === 'pending') && !awaitingReprepared)
955
+ await finalizeForget(leafKey, leafIndex);
956
+ const after = await deps.transaction((tx) => readForget(tx.artifact(ARTIFACT), leafKey));
957
+ // A superseded record (the own device was admitted again) lives only until its kind-5 deletion settles.
958
+ if (after?.superseded === true && deletionSettled) {
959
+ await deps.transaction(async (tx) => {
960
+ const view = tx.artifact(ARTIFACT);
961
+ if ((await readForget(view, leafKey))?.superseded === true)
962
+ await view.delete(forgetKey(leafKey));
963
+ });
964
+ return { record: after, left: false };
965
+ }
966
+ return { record: after, left: after?.status === 'forgetting' || !deletionSettled };
967
+ }
968
+ async function resumeForgets() {
969
+ const keys = await deps.transaction(async (tx) => {
970
+ const view = tx.artifact(ARTIFACT);
971
+ const out = [];
972
+ for (const key of await view.keys()) {
973
+ if (!key.startsWith('forget:'))
974
+ continue;
975
+ const record = await readForget(view, key.slice('forget:'.length));
976
+ if (record === undefined)
977
+ continue;
978
+ const d = record.deletion;
979
+ // A given-up intent is never resumed again (W1).
980
+ if (record.gaveUp === undefined && (record.status === 'forgetting' || d === undefined || d.status === 'pending'))
981
+ out.push(record.leafKey);
982
+ }
983
+ return out;
984
+ });
985
+ let left = false;
986
+ for (const leafKey of keys) {
987
+ try {
988
+ const { left: more } = await driveForget(leafKey);
989
+ left ||= more;
990
+ }
991
+ catch (error) {
992
+ if (stopsDeviceIntent(error))
993
+ throw error;
994
+ // W1: a pass over this intent that keeps failing (a record that no longer reads, a store that keeps
995
+ // failing) is counted like S6's maintenance; the other intents still get their pass.
996
+ if (!(await countForgetPassFailure(leafKey, error)))
997
+ left = true;
998
+ }
999
+ }
1000
+ return left;
1001
+ }
1002
+ /** Counts a failed pass over a forget; `true` when it was the {@link MAX_MAINTENANCE_FAILURES}th (given up). */
1003
+ async function countForgetPassFailure(leafKey, error) {
1004
+ const reason = maintenanceFailureReason(error);
1005
+ if (reason === undefined)
1006
+ return false;
1007
+ const gaveUp = await deps.transaction(async (tx) => {
1008
+ const view = tx.artifact(ARTIFACT);
1009
+ const current = await readForget(view, leafKey);
1010
+ if (current === undefined)
1011
+ return false;
1012
+ const driverFailures = (current.driverFailures ?? 0) + 1;
1013
+ const failed = driverFailures >= MAX_MAINTENANCE_FAILURES;
1014
+ await writeForget(view, { ...current, driverFailures, ...(failed ? { gaveUp: reason } : {}) });
1015
+ return failed;
1016
+ });
1017
+ if (gaveUp)
1018
+ deps.onMaintenanceFailed({ invitationId: leafKey, kind: 'device-forget', reason });
1019
+ return gaveUp;
1020
+ }
1021
+ /** The forget record of a device, among the records of the keys of its chain: one in progress, else the newest. */
1022
+ async function findForget(chain) {
1023
+ return deps.transaction(async (tx) => {
1024
+ const view = tx.artifact(ARTIFACT);
1025
+ let best;
1026
+ for (const key of chain) {
1027
+ const record = await readForget(view, key);
1028
+ if (record === undefined)
1029
+ continue;
1030
+ if (best === undefined || (record.status === 'forgetting' && best.status !== 'forgetting') || (record.status === best.status && record.startedAt > best.startedAt))
1031
+ best = record;
1032
+ }
1033
+ return best;
1034
+ });
1035
+ }
1036
+ async function forgetLeaf(leafKey) {
1037
+ const held = await readHeld();
1038
+ const ownKey = await readDeviceSigningKey((fn) => deps.transaction(fn));
1039
+ // The chain of the device named, over the recorded links united with the groups' canonical-path successions. The live
1040
+ // keys (held in groups, the own key) keep two installations that share an origin key apart (contested component).
1041
+ const live = new Set([...held.leaves.keys(), ...(ownKey === undefined ? [] : [ownKey.leafKey]), ...(await tombstonedKeys())]);
1042
+ const lineage = createDeviceLineage([...(await linkEdges()), ...held.edges], live);
1043
+ const chain = lineage.keysOf(leafKey);
1044
+ const apart = lineage.apartFrom(leafKey);
1045
+ const chainSet = new Set(chain);
1046
+ // AC-ADMIN-10 (S9) / AC-FORGET-5: the own device (any key of its chain) leaves every shared group — `leave()`, not a sibling Remove.
1047
+ const own = ownKey !== undefined && lineage.sameDevice(leafKey, ownKey.leafKey);
1048
+ const existing = await findForget(chain);
1049
+ let leafIndex;
1050
+ // A settled forget is re-checked: a leaf re-admitted into a held group since — or one that reappears there under a
1051
+ // successor key — is forgotten again by a fresh intent (round 6). An intent in progress, or a given-up one, is left as it is.
1052
+ if (existing === undefined || (existing.status === 'forgotten' && existing.gaveUp === undefined)) {
1053
+ // Every held group holding a leaf of the chain NOW — the intent's fixed group list (AC-DEV-7). The own leaf: every
1054
+ // group the local leaf is still a member of (a group that removed it holds no leaf of it).
1055
+ const groups = [];
1056
+ const heldKeys = new Map();
1057
+ for (const [groupId, view] of held.views) {
1058
+ const leaves = view.member === true || !own ? view.accountLeaves.filter((l) => chainSet.has(l.leafKey)) : [];
1059
+ if (leaves.length === 0)
1060
+ continue;
1061
+ leafIndex ??= leaves[0].leafIndex;
1062
+ heldKeys.set(groupId, leaves.map((l) => l.leafKey));
1063
+ groups.push({ groupId, outcome: 'pending', attempts: 0 });
1064
+ }
1065
+ // Settled, and membership unchanged — the device is in no held group beyond those its tombstone already names as
1066
+ // still holding it (timed out) and holds nothing there outside the chain the forget knew: idempotent, nothing is
1067
+ // written or published.
1068
+ const stillHolding = new Set((existing?.groups ?? []).filter((g) => g.outcome !== 'removed').map((g) => g.groupId));
1069
+ const knownKeys = new Set(existing?.chain ?? (existing === undefined ? [] : [existing.leafKey]));
1070
+ if (existing === undefined || groups.some((g) => !stillHolding.has(g.groupId) || heldKeys.get(g.groupId).some((k) => !knownKeys.has(k)))) {
1071
+ const self = groups.length === 0 && !own ? await localAccountOf(deps.signer) : '';
1072
+ await deps.transaction(async (tx) => {
1073
+ const view = tx.artifact(ARTIFACT);
1074
+ // What the groups' views showed is persisted first: the record's key and the entries it touches are located by
1075
+ // the registry's lineage, the one source reads and writes share.
1076
+ await persistSuccessionEdges(tx, held.edges, () => deps.clock.now(), live);
1077
+ // The record is named by the key `list()` shows (the held head), like the event and the tombstone it leads to.
1078
+ const head = (await loadDeviceLineage(view, [], live)).displayHeadsOf(leafKey)[0];
1079
+ let known = false;
1080
+ for (const key of chain)
1081
+ if ((await readEntry(view, key)) !== undefined)
1082
+ known = true;
1083
+ if (groups.length === 0 && !known && !own) {
1084
+ throw new MarmotError('invalid-options', `devices.forget: ${leafKey} is not a leaf of account ${self} in any held group nor a known device`, {
1085
+ details: { reason: 'unknown-leaf', leafKey },
1086
+ });
1087
+ }
1088
+ // Started — or restarted — concurrently since `existing` was read: that one continues.
1089
+ const current = await readForget(view, head);
1090
+ if (current !== undefined && (current.status === 'forgetting' || existing === undefined || existing.leafKey !== head || current.startedAt !== existing.startedAt))
1091
+ return;
1092
+ if (existing !== undefined && existing.leafKey !== head) {
1093
+ const old = await readForget(view, existing.leafKey);
1094
+ if (old === undefined || old.status === 'forgetting' || old.startedAt !== existing.startedAt)
1095
+ return;
1096
+ }
1097
+ // The fresh intent supersedes every settled forget of the device under another key of its chain (not a newer one).
1098
+ const startedAt = deps.clock.now();
1099
+ for (const key of chain) {
1100
+ if (key === head)
1101
+ continue;
1102
+ const settled = await readForget(view, key);
1103
+ if (settled !== undefined && settled.status === 'forgotten' && settled.startedAt <= startedAt)
1104
+ await view.delete(forgetKey(key));
1105
+ }
1106
+ // A fresh intent: no deletion, failure counts or give-up carried over, so the device's CURRENT
1107
+ // KeyPackages are looked up and a new kind-5 is signed for them.
1108
+ await writeForget(view, { v: 1, leafKey: head, startedAt, groups, status: 'forgetting', ...(chain.length > 1 ? { chain: [...chain].sort() } : {}), ...(apart.length > 0 ? { apart: [...apart].sort() } : {}), ...(own ? { own: true } : {}) });
1109
+ // Leaving beats enrolling: a request made before this forget must never let a late Welcome end it (the clock may have moved).
1110
+ if (own)
1111
+ await stripWaitingRequestTimes(tx);
1112
+ });
1113
+ }
1114
+ }
1115
+ const current = await findForget(chain);
1116
+ const { record, left } = await driveForget((current ?? existing).leafKey, leafIndex);
1117
+ // Any forget work left — a group still pending, or the kind-5 deletion not settled (a KeyPackage lookup that
1118
+ // timed out, a publish no relay accepted), also after the tombstone — is retried by the capped-backoff
1119
+ // background pass: an inbox that is already running runs no pass that would pick it up (D1).
1120
+ if (left)
1121
+ scheduleResume();
1122
+ return forgetOutcomeOf(record);
1123
+ }
1124
+ return {
1125
+ async list() {
1126
+ assertLive('list');
1127
+ resumeInBackground();
1128
+ const held = await readHeld();
1129
+ const own = await readDeviceSigningKey((fn) => deps.transaction(fn));
1130
+ // One transaction: the entries, and the lineage over the recorded links united with the groups' successions.
1131
+ const { entries, lineage } = await deps.transaction(async (tx) => {
1132
+ const view = tx.artifact(ARTIFACT);
1133
+ const out = [];
1134
+ for (const key of await view.keys()) {
1135
+ if (!LEAF_KEY.test(key))
1136
+ continue;
1137
+ const entry = await readEntry(view, key);
1138
+ if (entry !== undefined)
1139
+ out.push(entry);
1140
+ }
1141
+ return { entries: out, lineage: await loadDeviceLineage(view, held.edges, new Set([...held.leaves.keys(), ...(own === undefined ? [] : [own.leafKey]), ...out.filter((e) => e.tombstone !== undefined).map((e) => e.leafKey)])) };
1142
+ });
1143
+ const byKey = new Map(entries.map((e) => [e.leafKey, e]));
1144
+ // One entry per device (AC-LIST-1): a device in the middle of a rotation is one entry, not two. Its key is the live head
1145
+ // (held in a group, else the own current key, else the device's entry key). A component with TWO live heads (two
1146
+ // installations that share an origin key) is two devices, one entry per live head, with nothing folded across them.
1147
+ const reported = new Set();
1148
+ for (const key of [...held.leaves.keys(), ...byKey.keys()])
1149
+ for (const h of lineage.displayHeadsOf(key))
1150
+ reported.add(h);
1151
+ const devices = [];
1152
+ for (const head of [...reported].sort()) {
1153
+ const chain = lineage.keysOf(head);
1154
+ const chainSet = new Set(chain);
1155
+ // The entry at the head, with whatever an older key of the device still holds folded in (nearest the head first).
1156
+ let entry = byKey.get(head);
1157
+ for (const key of [...chain].reverse()) {
1158
+ const older = key === head ? undefined : byKey.get(key);
1159
+ if (older !== undefined)
1160
+ entry = entry === undefined ? { ...older, leafKey: head } : mergeRegistryEntries(entry, older);
1161
+ }
1162
+ const isOwn = own !== undefined && lineage.sameDevice(head, own.leafKey);
1163
+ const enrolledAt = entry?.enrolledAt ?? (own !== undefined && own.leafKey === head ? own.createdAt : 0);
1164
+ let leafIndex;
1165
+ for (const view of held.views.values()) {
1166
+ if (!view.member)
1167
+ continue;
1168
+ const leaf = view.accountLeaves.find((l) => chainSet.has(l.leafKey));
1169
+ if (leaf !== undefined) {
1170
+ leafIndex = leaf.leafIndex;
1171
+ break;
1172
+ }
1173
+ }
1174
+ devices.push(Object.freeze({
1175
+ leafKey: head,
1176
+ leafIndex: leafIndex ?? entry?.leafIndex ?? -1,
1177
+ label: entry?.label ?? '',
1178
+ enrolledAt,
1179
+ ...(entry?.tombstone === undefined
1180
+ ? {}
1181
+ : {
1182
+ tombstone: Object.freeze({
1183
+ at: entry.tombstone.at,
1184
+ groups: Object.freeze([...entry.tombstone.groups]),
1185
+ ...(entry.tombstone.forgetStartedAt === undefined ? {} : { forgetStartedAt: entry.tombstone.forgetStartedAt }),
1186
+ }),
1187
+ }),
1188
+ previousLeafKeys: Object.freeze(chain.filter((k) => k !== head)),
1189
+ self: isOwn,
1190
+ }));
1191
+ }
1192
+ return Object.freeze(devices);
1193
+ },
1194
+ async lineage() {
1195
+ assertLive('lineage');
1196
+ return deps.transaction((tx) => loadDeviceLineage(tx.artifact(ARTIFACT)));
1197
+ },
1198
+ async label(leafKey, label) {
1199
+ assertLive('label');
1200
+ if (typeof leafKey !== 'string' || !LEAF_KEY.test(leafKey))
1201
+ throw new MarmotError('invalid-options', 'devices.label: leafKey must be a 64-char lower-case hex leaf key', { details: { reason: 'invalid-leaf-key' } });
1202
+ if (typeof label !== 'string' || label.length > MAX_LABEL_LENGTH)
1203
+ throw new MarmotError('invalid-options', `devices.label: label must be a string of at most ${MAX_LABEL_LENGTH} characters`, { details: { reason: 'invalid-label' } });
1204
+ const held = await readHeld();
1205
+ const own = await readDeviceSigningKey((fn) => deps.transaction(fn));
1206
+ const forgotten = await tombstonedKeys();
1207
+ // AC-DEV-10: one registry write — nothing is published, no KeyPackage changes. AC-LIST-3: bound to the lineage head.
1208
+ await deps.transaction(async (tx) => {
1209
+ const view = tx.artifact(ARTIFACT);
1210
+ // The groups' successions are persisted first: the entry is located by the registry's lineage.
1211
+ const live = new Set([...held.leaves.keys(), ...(own === undefined ? [] : [own.leafKey]), ...forgotten]);
1212
+ await persistSuccessionEdges(tx, held.edges, () => deps.clock.now(), live);
1213
+ const lineage = await loadDeviceLineage(view, [], live);
1214
+ const head = lineage.deviceHeadOf(leafKey);
1215
+ const chain = lineage.keysOf(head);
1216
+ const inGroups = chain.map((k) => held.leaves.get(k)).find((i) => i !== undefined);
1217
+ const isOwn = own !== undefined && lineage.sameDevice(head, own.leafKey);
1218
+ const { entry: current } = await consolidateRegistryEntries(view, lineage, head);
1219
+ if (current === undefined && inGroups === undefined && !isOwn) {
1220
+ throw new MarmotError('invalid-options', `devices.label: ${leafKey} is not a device of this account`, { details: { reason: 'unknown-leaf', leafKey } });
1221
+ }
1222
+ const next = current === undefined
1223
+ ? { v: 1, leafKey: head, label, enrolledAt: isOwn ? own.createdAt : 0, ...(inGroups === undefined ? {} : { leafIndex: inGroups }) }
1224
+ : { ...current, label };
1225
+ await view.put(head, next);
1226
+ });
1227
+ },
1228
+ forget(leafKey) {
1229
+ if (typeof leafKey !== 'string' || !LEAF_KEY.test(leafKey)) {
1230
+ return Promise.reject(new MarmotError('invalid-options', 'devices.forget: leafKey must be a 64-char lower-case hex leaf key', { details: { reason: 'invalid-leaf-key' } }));
1231
+ }
1232
+ return runOperation('forget', () => forgetLeaf(leafKey));
1233
+ },
1234
+ rotateKey() {
1235
+ return runOperation('rotateKey', async () => {
1236
+ const outcome = await rotations.rotateKey();
1237
+ // Groups still converging, a KeyPackage step still retrying: the capped-backoff background pass continues them.
1238
+ if (!outcome.settled)
1239
+ scheduleResume();
1240
+ return outcome;
1241
+ });
1242
+ },
1243
+ async rotation() {
1244
+ assertLive('rotation');
1245
+ return rotations.rotation();
1246
+ },
1247
+ requestEnrolment(options) {
1248
+ // On the device queue, so a background pass never publishes a request its own creation is still writing
1249
+ // (it waits on no other queue: request and manifests are one account transaction). A request recorded but
1250
+ // not published is left to the background retry — a live inbox runs no periodic pass (C3).
1251
+ return runOperation('requestEnrolment', async () => {
1252
+ // Enrolling back while leaving is contradictory: an OPEN forget of the own device refuses the request (it would be
1253
+ // answered by a Welcome that the forget's own leave is undoing).
1254
+ if (await ownForgetOpen()) {
1255
+ throw new MarmotError('invalid-options', 'devices.requestEnrolment: the local device is being forgotten', { details: { reason: 'device-forgetting' } });
1256
+ }
1257
+ return requestEnrolment(deps, options);
1258
+ });
1259
+ },
1260
+ pendingEnrolments() {
1261
+ assertLive('pendingEnrolments');
1262
+ return pendingEnrolments(deps);
1263
+ },
1264
+ approveEnrolment(requestId) {
1265
+ return runOperation('approveEnrolment', async () => {
1266
+ const outcome = await approveEnrolment(deps, registryBinding, requestId);
1267
+ if (!outcome.settled)
1268
+ scheduleResume();
1269
+ return outcome;
1270
+ });
1271
+ },
1272
+ handleEnrolmentRumor(rumor, ctx) {
1273
+ return handleEnrolmentRumor(deps, registryBinding, rumor, ctx);
1274
+ },
1275
+ resumeInBackground,
1276
+ dispose() {
1277
+ disposed = true;
1278
+ if (resumeTimer !== undefined)
1279
+ deps.timers.clear(resumeTimer);
1280
+ resumeTimer = undefined;
1281
+ unsubscribeRewind();
1282
+ unsubscribeRestored();
1283
+ unsubscribeRotation?.();
1284
+ },
1285
+ };
1286
+ }
1287
+ function hex(bytes) {
1288
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
1289
+ }
1290
+ export { DEVICE_KEY_ENTRY };