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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/CHANGELOG.md +709 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -2
  4. package/dist/account/admin.d.ts +72 -0
  5. package/dist/account/admin.js +209 -0
  6. package/dist/account/device-deps.d.ts +379 -0
  7. package/dist/account/device-deps.js +36 -0
  8. package/dist/account/device-lineage.d.ts +199 -0
  9. package/dist/account/device-lineage.js +390 -0
  10. package/dist/account/device-registry.d.ts +93 -0
  11. package/dist/account/device-registry.js +1290 -0
  12. package/dist/account/device-rotation.d.ts +61 -0
  13. package/dist/account/device-rotation.js +827 -0
  14. package/dist/account/enrolment.d.ts +339 -0
  15. package/dist/account/enrolment.js +1247 -0
  16. package/dist/account/identity-proof.d.ts +79 -0
  17. package/dist/account/identity-proof.js +264 -0
  18. package/dist/account/index.d.ts +17 -0
  19. package/dist/account/index.js +16 -0
  20. package/dist/account/restore-rotation.d.ts +21 -0
  21. package/dist/account/restore-rotation.js +22 -0
  22. package/dist/account/same-account-authorization.d.ts +86 -0
  23. package/dist/account/same-account-authorization.js +180 -0
  24. package/dist/account/teardown.d.ts +127 -0
  25. package/dist/account/teardown.js +856 -0
  26. package/dist/client/before-create-group.d.ts +18 -0
  27. package/dist/client/before-create-group.js +65 -0
  28. package/dist/client/before-publish-hooks.d.ts +121 -0
  29. package/dist/client/before-publish-hooks.js +180 -0
  30. package/dist/client/client-config.d.ts +42 -0
  31. package/dist/client/client-config.js +13 -0
  32. package/dist/client/commit-redrive.d.ts +68 -0
  33. package/dist/client/commit-redrive.js +221 -0
  34. package/dist/client/component-update.d.ts +43 -0
  35. package/dist/client/component-update.js +53 -0
  36. package/dist/client/confirm-hooks.d.ts +50 -0
  37. package/dist/client/confirm-hooks.js +59 -0
  38. package/dist/client/create-client.d.ts +1022 -0
  39. package/dist/client/create-client.js +1125 -0
  40. package/dist/client/group-disband.d.ts +28 -0
  41. package/dist/client/group-disband.js +64 -0
  42. package/dist/client/group-history.d.ts +435 -0
  43. package/dist/client/group-history.js +1295 -0
  44. package/dist/client/group-profile.d.ts +31 -0
  45. package/dist/client/group-profile.js +62 -0
  46. package/dist/client/group-records.d.ts +485 -0
  47. package/dist/client/group-records.js +1034 -0
  48. package/dist/client/group-removal.d.ts +36 -0
  49. package/dist/client/group-removal.js +127 -0
  50. package/dist/client/group-remove-member.d.ts +49 -0
  51. package/dist/client/group-remove-member.js +163 -0
  52. package/dist/client/group-runtime.d.ts +388 -0
  53. package/dist/client/group-runtime.js +2701 -0
  54. package/dist/client/group-snapshot.d.ts +98 -0
  55. package/dist/client/group-snapshot.js +453 -0
  56. package/dist/client/history-pages.d.ts +107 -0
  57. package/dist/client/history-pages.js +194 -0
  58. package/dist/client/inbox-send.d.ts +19 -0
  59. package/dist/client/inbox-send.js +71 -0
  60. package/dist/client/index.d.ts +21 -0
  61. package/dist/client/index.js +13 -0
  62. package/dist/client/ingest.d.ts +82 -0
  63. package/dist/client/ingest.js +1550 -0
  64. package/dist/client/lifecycle-events.d.ts +63 -0
  65. package/dist/client/lifecycle-events.js +35 -0
  66. package/dist/client/opaque-candidates.d.ts +81 -0
  67. package/dist/client/opaque-candidates.js +169 -0
  68. package/dist/client/own-change-outbox.d.ts +66 -0
  69. package/dist/client/own-change-outbox.js +156 -0
  70. package/dist/client/pending-leaf.d.ts +116 -0
  71. package/dist/client/pending-leaf.js +378 -0
  72. package/dist/client/permissions.d.ts +9 -0
  73. package/dist/client/permissions.js +12 -0
  74. package/dist/client/pipeline.d.ts +554 -0
  75. package/dist/client/pipeline.js +3545 -0
  76. package/dist/client/reentrancy-guard.d.ts +96 -0
  77. package/dist/client/reentrancy-guard.js +153 -0
  78. package/dist/client/rekey.d.ts +58 -0
  79. package/dist/client/rekey.js +149 -0
  80. package/dist/client/transport-policy.d.ts +181 -0
  81. package/dist/client/transport-policy.js +214 -0
  82. package/dist/history/equivocation.d.ts +55 -0
  83. package/dist/history/equivocation.js +113 -0
  84. package/dist/history/fencing.d.ts +25 -0
  85. package/dist/history/fencing.js +61 -0
  86. package/dist/history/hex.d.ts +3 -0
  87. package/dist/history/hex.js +10 -0
  88. package/dist/history/index.d.ts +73 -0
  89. package/dist/history/index.js +31 -0
  90. package/dist/history/notifications.d.ts +270 -0
  91. package/dist/history/notifications.js +264 -0
  92. package/dist/history/ordering-key.d.ts +24 -0
  93. package/dist/history/ordering-key.js +101 -0
  94. package/dist/history/own-change-fork.d.ts +112 -0
  95. package/dist/history/own-change-fork.js +196 -0
  96. package/dist/history/own-change.d.ts +106 -0
  97. package/dist/history/own-change.js +146 -0
  98. package/dist/history/policy.d.ts +48 -0
  99. package/dist/history/policy.js +52 -0
  100. package/dist/history/retained-window.d.ts +215 -0
  101. package/dist/history/retained-window.js +565 -0
  102. package/dist/inbox/demux.d.ts +90 -0
  103. package/dist/inbox/demux.js +78 -0
  104. package/dist/inbox/handler-registry.d.ts +42 -0
  105. package/dist/inbox/handler-registry.js +37 -0
  106. package/dist/inbox/index.d.ts +11 -0
  107. package/dist/inbox/index.js +10 -0
  108. package/dist/inbox/seen-set.d.ts +82 -0
  109. package/dist/inbox/seen-set.js +202 -0
  110. package/dist/inbox/subscription.d.ts +236 -0
  111. package/dist/inbox/subscription.js +644 -0
  112. package/dist/index.d.ts +10 -0
  113. package/dist/index.js +9 -0
  114. package/dist/invitations/competing-welcome.d.ts +223 -0
  115. package/dist/invitations/competing-welcome.js +128 -0
  116. package/dist/invitations/decline.d.ts +61 -0
  117. package/dist/invitations/decline.js +143 -0
  118. package/dist/invitations/expect-welcome.d.ts +66 -0
  119. package/dist/invitations/expect-welcome.js +138 -0
  120. package/dist/invitations/index.d.ts +16 -0
  121. package/dist/invitations/index.js +16 -0
  122. package/dist/invitations/invite.d.ts +303 -0
  123. package/dist/invitations/invite.js +966 -0
  124. package/dist/invitations/offers.d.ts +79 -0
  125. package/dist/invitations/offers.js +115 -0
  126. package/dist/invitations/on-proposal.d.ts +47 -0
  127. package/dist/invitations/on-proposal.js +40 -0
  128. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  129. package/dist/invitations/pending-proposal-policy.js +139 -0
  130. package/dist/invitations/proposal-deadline.d.ts +133 -0
  131. package/dist/invitations/proposal-deadline.js +164 -0
  132. package/dist/invitations/relay-planes.d.ts +43 -0
  133. package/dist/invitations/relay-planes.js +70 -0
  134. package/dist/invitations/welcome-processor.d.ts +253 -0
  135. package/dist/invitations/welcome-processor.js +1180 -0
  136. package/dist/key-packages/device-key.d.ts +131 -0
  137. package/dist/key-packages/device-key.js +272 -0
  138. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  139. package/dist/key-packages/device-rotation-records.js +173 -0
  140. package/dist/key-packages/group-refs.d.ts +40 -0
  141. package/dist/key-packages/group-refs.js +79 -0
  142. package/dist/key-packages/index.d.ts +18 -0
  143. package/dist/key-packages/index.js +18 -0
  144. package/dist/key-packages/key-package-ref.d.ts +16 -0
  145. package/dist/key-packages/key-package-ref.js +21 -0
  146. package/dist/key-packages/observation-stream.d.ts +4 -0
  147. package/dist/key-packages/observation-stream.js +120 -0
  148. package/dist/key-packages/offer-rumor.d.ts +26 -0
  149. package/dist/key-packages/offer-rumor.js +69 -0
  150. package/dist/key-packages/publisher.d.ts +174 -0
  151. package/dist/key-packages/publisher.js +1247 -0
  152. package/dist/key-packages/select-key-package.d.ts +24 -0
  153. package/dist/key-packages/select-key-package.js +90 -0
  154. package/dist/key-packages/slot-manager.d.ts +167 -0
  155. package/dist/key-packages/slot-manager.js +327 -0
  156. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  157. package/dist/key-packages/validate-key-package-event.js +49 -0
  158. package/dist/media/cache.d.ts +14 -0
  159. package/dist/media/cache.js +10 -0
  160. package/dist/media/index.d.ts +52 -0
  161. package/dist/media/index.js +71 -0
  162. package/dist/mls.d.ts +15 -0
  163. package/dist/mls.js +15 -0
  164. package/dist/shared/account-pubkey.d.ts +4 -0
  165. package/dist/shared/account-pubkey.js +10 -0
  166. package/dist/shared/errors.d.ts +21 -0
  167. package/dist/shared/errors.js +85 -0
  168. package/dist/shared/hex.d.ts +4 -0
  169. package/dist/shared/hex.js +13 -0
  170. package/dist/shared/index.d.ts +14 -0
  171. package/dist/shared/index.js +14 -0
  172. package/dist/shared/kinds.d.ts +8 -0
  173. package/dist/shared/kinds.js +28 -0
  174. package/dist/shared/publish-classification.d.ts +26 -0
  175. package/dist/shared/publish-classification.js +31 -0
  176. package/dist/storage/envelope.d.ts +39 -0
  177. package/dist/storage/envelope.js +201 -0
  178. package/dist/storage/index.d.ts +227 -0
  179. package/dist/storage/index.js +459 -0
  180. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  181. package/dist/storage/indexeddb/idb-types.js +1 -0
  182. package/dist/storage/indexeddb/index.d.ts +17 -0
  183. package/dist/storage/indexeddb/index.js +141 -0
  184. package/dist/storage/lease.d.ts +41 -0
  185. package/dist/storage/lease.js +117 -0
  186. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  187. package/dist/storage/memory/deterministic-signer.js +65 -0
  188. package/dist/storage/memory/index.d.ts +32 -0
  189. package/dist/storage/memory/index.js +87 -0
  190. package/dist/storage/memory/lock-manager.d.ts +8 -0
  191. package/dist/storage/memory/lock-manager.js +71 -0
  192. package/package.json +66 -3
@@ -0,0 +1,1034 @@
1
+ /**
2
+ * Persisted record codecs for the group runtime (S3): the `clientState`
3
+ * codec, the account-level group index, pending-intent records, the
4
+ * terminal ledger and the kind-445 ingest cursor. Pure `KeyValueView` codec
5
+ * helpers — no engine calls, no transport, no re-entrancy guard
6
+ * (`group-runtime.ts` / `pipeline.ts` / `ingest.ts` own those). Every helper
7
+ * accepts a `KeyValueView`, so it works identically against a store's own
8
+ * scope-level view or a transaction's `tx` view.
9
+ */
10
+ import { OWN_CHANGE_LOST_REASONS } from '../history/index.js';
11
+ import { deserializeClientState, GROUP_ADMIN_POLICY_COMPONENT_ID, GROUP_PROFILE_COMPONENT_ID, serializeClientState } from '@941design/marmot-engine/core';
12
+ import { decodeStoredWelcomes, encodeStoredWelcomes } from '../invitations/index.js';
13
+ import { MarmotError } from '../shared/index.js';
14
+ import { assertGroupProfile } from './group-profile.js';
15
+ import { isAccountPubkey, isHex64 } from '../shared/index.js';
16
+ import { CURSOR_KEY } from './transport-policy.js';
17
+ /** A fresh random pending-intent id (hex). Shared by every writer of `pendingIntents` — pipeline.ts's own
18
+ * intents and group-history.ts's atomic self-update re-enqueue (AC-RACE-1) alike. */
19
+ export function randomIntentId() {
20
+ const bytes = new Uint8Array(16);
21
+ globalThis.crypto.getRandomValues(bytes);
22
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
23
+ }
24
+ // ---------------------------------------------------------------------------
25
+ // clientState (GroupStore `clientState` artifact, key 'current')
26
+ // ---------------------------------------------------------------------------
27
+ const CLIENT_STATE_KEY = 'current';
28
+ /** Whether the group has a persisted `ClientState` (nothing is decoded: a presence check for listings). */
29
+ export async function hasGroupState(view) {
30
+ return (await view.get(CLIENT_STATE_KEY)) !== undefined;
31
+ }
32
+ /** Reads the group's persisted `ClientState`, or `undefined` when the group has never been created/joined locally. */
33
+ export async function readGroupState(view) {
34
+ const raw = await view.get(CLIENT_STATE_KEY);
35
+ if (raw === undefined)
36
+ return undefined;
37
+ if (!(raw instanceof Uint8Array)) {
38
+ throw new MarmotError('store-failed', 'clientState: stored value is not bytes', { details: { key: CLIENT_STATE_KEY, malformed: true } });
39
+ }
40
+ return deserializeClientState(raw);
41
+ }
42
+ /** Persists `state` as the group's current `ClientState`. */
43
+ export async function writeGroupState(view, state) {
44
+ await view.put(CLIENT_STATE_KEY, serializeClientState(state));
45
+ }
46
+ // ---------------------------------------------------------------------------
47
+ // Unfinished-restore marker (group extension `marmot.restorePending`, key 'current') — AC-MX-2
48
+ // ---------------------------------------------------------------------------
49
+ /**
50
+ * The group extension marking a `groups.restore` adoption whose self-update has not confirmed yet: written in the
51
+ * adoption transaction (with the snapshot's `clientState`), deleted in the confirmation transaction of an own
52
+ * self-update (pipeline.ts `confirmRecord`) — so a crash, or a dispose that could not wait for the group's queue,
53
+ * never leaves a half-restored group that a later client over the same stores would hold as if restored. A later
54
+ * client resumes such a group (group-runtime.ts `resumeRestore`: started by its startup scan and by every entry point
55
+ * that would read the group as held) — never discards it outright: the restore's self-update may already be on the
56
+ * relays, and only its record in these stores can confirm it.
57
+ */
58
+ export const RESTORE_PENDING_EXTENSION = 'marmot.restorePending';
59
+ const RESTORE_PENDING_KEY = 'current';
60
+ /** Marks the group as adopted by a restore whose self-update has not confirmed. */
61
+ export async function writeRestorePending(view, at) {
62
+ await view.put(RESTORE_PENDING_KEY, { v: 1, at });
63
+ }
64
+ /** Whether the group is marked as an unfinished restore (any stored value counts: the safe side is to resume). */
65
+ export async function readRestorePending(view) {
66
+ return (await view.get(RESTORE_PENDING_KEY)) !== undefined;
67
+ }
68
+ /** Clears the unfinished-restore mark (a no-op when absent). */
69
+ export async function clearRestorePending(view) {
70
+ await view.delete(RESTORE_PENDING_KEY);
71
+ }
72
+ // ---------------------------------------------------------------------------
73
+ // Restore adoptions in progress (AccountStore extension `marmot.restoring`, keyed by group id) — AC-MX-2
74
+ // ---------------------------------------------------------------------------
75
+ /**
76
+ * The account extension naming every `groups.restore` adoption that has not got its account group-index entry yet.
77
+ * The startup scan otherwise walks the group index only, and the adoption writes the group store (snapshot state,
78
+ * key material, the {@link RESTORE_PENDING_EXTENSION} mark) BEFORE that entry: a crash in between would leave a
79
+ * group store no later client ever finds. So the adoption runs as three transactions, each a separate one (never
80
+ * nested — the cross-scope lock order is group → account, and this order starts on the account):
81
+ * 1. account: this record (nothing of the group written yet);
82
+ * 2. group: the snapshot's state, rewind window, cursor and the unfinished-restore mark;
83
+ * 3. account: the group-index entry, and this record deleted — atomically.
84
+ * Every crash point leaves a state the scan finds and settles (group-runtime.ts `settleRestoringRecord`): after 1, a
85
+ * record without a mark (dropped); after 2, a marked group without an index entry (discarded — nothing was ever
86
+ * recorded for it — its group store wiped, then this record); after 3, an indexed marked group (resumed).
87
+ *
88
+ * A failed restore's take-back (group-runtime.ts `clearAdoptedGroup`) runs the reverse, with this record as its
89
+ * durable cleanup marker: 1. account: this record (re-)written; 2. group: the store cleared; 3. account: the
90
+ * group-index entry and this record deleted — atomically. After 1 the group is still marked (resumed); after 2 the
91
+ * record names an empty group store (no state, no mark) whose index entry the scan deletes with the record — never
92
+ * an index entry left naming a group nothing holds and no scan revisits.
93
+ */
94
+ export const RESTORING_EXTENSION = 'marmot.restoring';
95
+ /** Records that `groupId` is being adopted by a restore (step 1 above). */
96
+ export async function writeRestoringRecord(view, groupId, at) {
97
+ await view.put(groupId, { v: 1, at });
98
+ }
99
+ /** Deletes `groupId`'s restore record (a no-op when absent). */
100
+ export async function clearRestoringRecord(view, groupId) {
101
+ await view.delete(groupId);
102
+ }
103
+ /** Every group id with a restore record (any stored value counts: the safe side is to settle it). */
104
+ export async function listRestoringRecords(view) {
105
+ return view.keys();
106
+ }
107
+ // ---------------------------------------------------------------------------
108
+ // Post-load ratchet-skip marker (group extension `marmot.ratchetSkip`, key 'current') — AC-RATCH-1
109
+ // ---------------------------------------------------------------------------
110
+ /**
111
+ * The group extension holding the last post-load ratchet skip: written in the staging transaction of the skipped
112
+ * application message (next to the advanced `clientState`), marked `delivered` once a relay accepted an own
113
+ * application message at or after the skipped generation on the same epoch state. A load re-arms the skip unless
114
+ * the marker names the loaded epoch state, is undelivered, and the loaded ratchet already holds the skipped
115
+ * generation — so skips never pile up while nothing reaches a relay (every receiver's gap stays within one margin
116
+ * plus the undelivered messages), while a restore of a state without that marker (an older backup) still skips.
117
+ */
118
+ export const RATCHET_SKIP_EXTENSION = 'marmot.ratchetSkip';
119
+ const RATCHET_SKIP_KEY = 'current';
120
+ /** The stored marker; `undefined` when absent or unreadable (an unreadable marker re-arms the skip, the safe side for reuse). */
121
+ export async function readRatchetSkipMarker(view) {
122
+ const raw = await view.get(RATCHET_SKIP_KEY);
123
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
124
+ return undefined;
125
+ const r = raw;
126
+ if (typeof r.epoch !== 'bigint' || typeof r.tag !== 'string' || typeof r.generation !== 'number' || typeof r.delivered !== 'boolean')
127
+ return undefined;
128
+ return { epoch: r.epoch, tag: r.tag, generation: r.generation, delivered: r.delivered };
129
+ }
130
+ export async function writeRatchetSkipMarker(view, marker) {
131
+ await view.put(RATCHET_SKIP_KEY, { epoch: marker.epoch, tag: marker.tag, generation: marker.generation, delivered: marker.delivered });
132
+ }
133
+ /**
134
+ * Marks the stored marker delivered when `ordering` (an own application message a relay just accepted) was sent on
135
+ * the marker's epoch state at or after its skipped generation. A message whose generation could not be read
136
+ * (`-1`) or with no ordering key never marks it. Returns whether it marked it.
137
+ */
138
+ export async function markRatchetSkipDelivered(view, ordering) {
139
+ if (ordering === undefined)
140
+ return false;
141
+ const marker = await readRatchetSkipMarker(view);
142
+ if (marker === undefined || marker.delivered)
143
+ return false;
144
+ if (ordering.epoch !== marker.epoch || ordering.acceptedDigest !== marker.tag || ordering.generation < marker.generation)
145
+ return false;
146
+ await writeRatchetSkipMarker(view, { ...marker, delivered: true });
147
+ return true;
148
+ }
149
+ /**
150
+ * Whether a load of a state at (`epoch`, `tag`) whose own ratchet's next generation is `nextGeneration` re-arms the
151
+ * post-load skip, given the stored `marker`.
152
+ */
153
+ export function ratchetSkipArmed(marker, epoch, tag, nextGeneration) {
154
+ if (marker === undefined || marker.delivered)
155
+ return true;
156
+ // An undelivered skip of THIS epoch state the loaded ratchet already holds: skipping again would only widen the
157
+ // gap receivers must jump. Any other epoch state (an epoch change, a rewind) or an older state re-arms.
158
+ return !(marker.epoch === epoch && marker.tag === tag && nextGeneration > marker.generation);
159
+ }
160
+ /** Removes the group's persisted `ClientState` (undoes a `groups.create` that could not be indexed). */
161
+ export async function deleteGroupState(view) {
162
+ await view.delete(CLIENT_STATE_KEY);
163
+ }
164
+ // ---------------------------------------------------------------------------
165
+ // Account-level group index (AccountStore extension `marmot.groups`) — the
166
+ // account artifact set (AC-STORE-9) has no dedicated group-list artifact, so
167
+ // S3 uses an extension namespace for it (see spec Amendments / AC-STORE-9).
168
+ // ---------------------------------------------------------------------------
169
+ export const GROUP_INDEX_EXTENSION = 'marmot.groups';
170
+ function malformedIndex(groupId) {
171
+ return new MarmotError('store-failed', `group index: malformed entry for ${groupId}`, { details: { groupId, malformed: true } });
172
+ }
173
+ export async function readGroupIndexEntry(view, groupId) {
174
+ const raw = await view.get(groupId);
175
+ if (raw === undefined)
176
+ return undefined;
177
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || typeof raw.createdAt !== 'number') {
178
+ throw malformedIndex(groupId);
179
+ }
180
+ const adoptedBy = raw.adoptedBy;
181
+ return { createdAt: raw.createdAt, ...(typeof adoptedBy === 'string' ? { adoptedBy } : {}) };
182
+ }
183
+ export async function writeGroupIndexEntry(view, groupId, entry) {
184
+ await view.put(groupId, { createdAt: entry.createdAt, ...(entry.adoptedBy === undefined ? {} : { adoptedBy: entry.adoptedBy }) });
185
+ }
186
+ /** Every indexed group id. */
187
+ export async function listGroupIndex(view) {
188
+ return view.keys();
189
+ }
190
+ /**
191
+ * A commit re-drive record (S1): the durable record a withdrawal writes for a withdrawn own commit — a `commit` carrying
192
+ * `changes` (DD15; the decoder and the encoder enforce `changes` => `{ type: 'commit' }` + `reenqueuedFrom`). The
193
+ * self-update re-enqueue paths (AC-RACE-1) must neither pick it up nor count it among their siblings.
194
+ */
195
+ export function isCommitRedrive(record) {
196
+ return record.changes !== undefined;
197
+ }
198
+ function malformed(intentId, detail, cause) {
199
+ return new MarmotError('store-failed', `pendingIntents/${intentId}: malformed record (${detail})`, { details: { intentId, malformed: true }, ...(cause === undefined ? {} : { cause }) });
200
+ }
201
+ function decodeStorableIntent(intentId, raw) {
202
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
203
+ throw malformed(intentId, 'intent not an object');
204
+ const type = raw.type;
205
+ switch (type) {
206
+ case 'application': {
207
+ const rumor = raw.rumor;
208
+ if (rumor === undefined)
209
+ throw malformed(intentId, 'intent.rumor missing');
210
+ return { type: 'application', rumor: rumor };
211
+ }
212
+ case 'proposal': {
213
+ const proposal = raw.proposal;
214
+ if (proposal === undefined)
215
+ throw malformed(intentId, 'intent.proposal missing');
216
+ return { type: 'proposal', proposal: proposal };
217
+ }
218
+ case 'commit': {
219
+ const invite = raw.invite;
220
+ const removeLeafKeys = raw.removeLeafKeys;
221
+ if (removeLeafKeys !== undefined && (!Array.isArray(removeLeafKeys) || !removeLeafKeys.every((k) => typeof k === 'string'))) {
222
+ throw malformed(intentId, 'intent.removeLeafKeys invalid');
223
+ }
224
+ const admins = raw.admins;
225
+ if (admins !== undefined && (!Array.isArray(admins) || admins.length === 0 || !admins.every((k) => typeof k === 'string'))) {
226
+ throw malformed(intentId, 'intent.admins invalid');
227
+ }
228
+ const removeAccounts = raw.removeAccounts;
229
+ if (removeAccounts !== undefined && (!Array.isArray(removeAccounts) || removeAccounts.length === 0 || !removeAccounts.every(isAccountPubkey))) {
230
+ throw malformed(intentId, 'intent.removeAccounts invalid');
231
+ }
232
+ const removeAccountLeafKeys = raw.removeAccountLeafKeys;
233
+ if ((removeAccounts === undefined) !== (removeAccountLeafKeys === undefined) ||
234
+ (removeAccountLeafKeys !== undefined && (!Array.isArray(removeAccountLeafKeys) || removeAccountLeafKeys.length === 0 || !removeAccountLeafKeys.every(isHex64)))) {
235
+ throw malformed(intentId, 'intent.removeAccountLeafKeys invalid');
236
+ }
237
+ const origin = raw.origin;
238
+ if (origin !== undefined && origin !== 'approval')
239
+ throw malformed(intentId, 'intent.origin invalid');
240
+ const componentsRaw = raw.components;
241
+ const components = componentsRaw === undefined ? undefined : checkComponents(componentsRaw, (detail) => malformed(intentId, detail));
242
+ const profileRaw = raw.profile;
243
+ checkNoProfileClash(profileRaw !== undefined, components, (detail) => malformed(intentId, detail));
244
+ let profile;
245
+ if (profileRaw !== undefined) {
246
+ const { name, description } = (typeof profileRaw === 'object' && profileRaw !== null ? profileRaw : {});
247
+ if (typeof name !== 'string' || typeof description !== 'string')
248
+ throw malformed(intentId, 'intent.profile invalid');
249
+ // A record the pipeline wrote always passed `rename`'s validation; one outside the component's limits was altered at rest,
250
+ // and the encoder would throw when it is built — it is refused here instead, as a malformed intent.
251
+ try {
252
+ assertGroupProfile('intent.profile', name, description);
253
+ }
254
+ catch (cause) {
255
+ throw malformed(intentId, 'intent.profile outside the group-profile limits', cause);
256
+ }
257
+ profile = { name, description };
258
+ }
259
+ return {
260
+ type: 'commit',
261
+ ...(invite === undefined ? {} : { invite: decodeInviteIntent(intentId, invite) }),
262
+ ...(removeLeafKeys === undefined ? {} : { removeLeafKeys: removeLeafKeys }),
263
+ ...(admins === undefined ? {} : { admins: admins }),
264
+ ...(profile === undefined ? {} : { profile }),
265
+ ...(removeAccounts === undefined ? {} : { removeAccounts: removeAccounts, removeAccountLeafKeys: removeAccountLeafKeys }),
266
+ ...(origin === undefined ? {} : { origin }),
267
+ ...(components === undefined ? {} : { components }),
268
+ };
269
+ }
270
+ case 'self-update': {
271
+ const after = raw.after;
272
+ if (after !== undefined && typeof after !== 'string')
273
+ throw malformed(intentId, 'intent.after invalid');
274
+ const rekey = decodeRekey(intentId, raw.rekey);
275
+ return { type: 'self-update', ...(after === undefined ? {} : { after }), ...(rekey === undefined ? {} : { rekey }) };
276
+ }
277
+ default:
278
+ throw malformed(intentId, `unknown intent.type ${JSON.stringify(type)}`);
279
+ }
280
+ }
281
+ /** AC-REKEY-1: `{ target }` with a 64-char lower-case hex target and nothing else; any other shape is `malformed`. */
282
+ function decodeRekey(intentId, raw) {
283
+ if (raw === undefined)
284
+ return undefined;
285
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
286
+ throw malformed(intentId, 'intent.rekey invalid');
287
+ const keys = Object.keys(raw);
288
+ const target = raw.target;
289
+ if (keys.length !== 1 || keys[0] !== 'target' || typeof target !== 'string' || !isHex64(target))
290
+ throw malformed(intentId, 'intent.rekey invalid');
291
+ return { target };
292
+ }
293
+ /**
294
+ * The `components` rule, shared by the decoder and the writer: a non-empty array of `{ id, data }` (no other member),
295
+ * `id` an integer in the u16 range, `data` bytes or `null`, ids unique.
296
+ */
297
+ function checkComponents(raw, fail) {
298
+ if (!Array.isArray(raw) || raw.length === 0)
299
+ throw fail('intent.components invalid');
300
+ const out = raw.map((entry) => {
301
+ if (!isObject(entry))
302
+ throw fail('intent.components entry invalid');
303
+ onlyMembers(entry, ['id', 'data'], 'intent.components entry', fail);
304
+ const { id, data } = entry;
305
+ if (typeof id !== 'number' || !isComponentId(id) || !isBytesOrNull(data))
306
+ throw fail('intent.components entry invalid');
307
+ return { id, data };
308
+ });
309
+ if (new Set(out.map((c) => c.id)).size !== out.length)
310
+ throw fail('intent.components invalid');
311
+ // The admin list has its own typed field (`admins`, validated against the tree): a raw update of it would bypass that.
312
+ if (out.some((c) => c.id === GROUP_ADMIN_POLICY_COMPONENT_ID))
313
+ throw fail('intent.components names the admin policy (use intent.admins)');
314
+ return out;
315
+ }
316
+ /** `profile` and a `components` entry for the same component would be two AppDataUpdates of `0x8001` in one commit (AC-RENAME-9). */
317
+ function checkNoProfileClash(hasProfile, components, fail) {
318
+ if (hasProfile && components?.some((c) => c.id === GROUP_PROFILE_COMPONENT_ID) === true)
319
+ throw fail('intent.components names the group profile beside intent.profile');
320
+ }
321
+ function decodeInviteIntent(intentId, raw) {
322
+ const invitees = typeof raw === 'object' && raw !== null ? raw.invitees : undefined;
323
+ if (!Array.isArray(invitees) || invitees.length === 0)
324
+ throw malformed(intentId, 'intent.invite.invitees invalid');
325
+ return {
326
+ invitees: invitees.map((entry) => {
327
+ const { event, inviteeRef } = (typeof entry === 'object' && entry !== null ? entry : {});
328
+ if (typeof event !== 'object' || event === null || typeof inviteeRef !== 'string')
329
+ throw malformed(intentId, 'intent.invite invitee invalid');
330
+ return { event: event, inviteeRef };
331
+ }),
332
+ };
333
+ }
334
+ function encodeStorableIntent(intentId, intent) {
335
+ switch (intent.type) {
336
+ case 'application':
337
+ return { type: 'application', rumor: intent.rumor };
338
+ case 'proposal':
339
+ return { type: 'proposal', proposal: intent.proposal };
340
+ case 'commit': {
341
+ checkNoProfileClash(intent.profile !== undefined, intent.components, (detail) => malformed(intentId, detail));
342
+ return {
343
+ type: 'commit',
344
+ ...(intent.invite === undefined ? {} : { invite: { invitees: intent.invite.invitees.map((i) => ({ event: i.event, inviteeRef: i.inviteeRef })) } }),
345
+ ...(intent.removeLeafKeys === undefined ? {} : { removeLeafKeys: [...intent.removeLeafKeys] }),
346
+ ...(intent.admins === undefined ? {} : { admins: [...intent.admins] }),
347
+ ...(intent.profile === undefined ? {} : { profile: { name: intent.profile.name, description: intent.profile.description } }),
348
+ ...(intent.removeAccounts === undefined ? {} : { removeAccounts: [...intent.removeAccounts], removeAccountLeafKeys: [...(intent.removeAccountLeafKeys ?? [])] }),
349
+ ...(intent.origin === undefined ? {} : { origin: intent.origin }),
350
+ ...(intent.components === undefined ? {} : { components: checkComponents(intent.components, (detail) => malformed(intentId, detail)) }),
351
+ };
352
+ }
353
+ case 'self-update':
354
+ return {
355
+ type: 'self-update',
356
+ ...(intent.after === undefined ? {} : { after: intent.after }),
357
+ ...(intent.rekey === undefined ? {} : { rekey: { target: intent.rekey.target } }),
358
+ };
359
+ }
360
+ }
361
+ function decodePending(intentId, raw) {
362
+ if (raw === undefined)
363
+ return undefined;
364
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
365
+ throw malformed(intentId, 'pending not an object');
366
+ const r = raw;
367
+ const kind = r.kind;
368
+ if (kind !== 'proposal' && kind !== 'commit' && kind !== 'selfUpdate')
369
+ throw malformed(intentId, 'pending.kind invalid');
370
+ const newState = r.newState;
371
+ if (!(newState instanceof Uint8Array))
372
+ throw malformed(intentId, 'pending.newState missing');
373
+ const parentState = r.parentState;
374
+ if (parentState !== undefined && !(parentState instanceof Uint8Array))
375
+ throw malformed(intentId, 'pending.parentState invalid');
376
+ const commitMessage = r.commitMessage;
377
+ if (commitMessage !== undefined && !(commitMessage instanceof Uint8Array))
378
+ throw malformed(intentId, 'pending.commitMessage invalid');
379
+ const ownCommit = r.ownCommit;
380
+ if (ownCommit !== undefined && !(ownCommit instanceof Uint8Array))
381
+ throw malformed(intentId, 'pending.ownCommit invalid');
382
+ return {
383
+ kind,
384
+ newState,
385
+ ...(parentState === undefined ? {} : { parentState }),
386
+ ...(commitMessage === undefined ? {} : { commitMessage }),
387
+ ...(ownCommit === undefined ? {} : { ownCommit }),
388
+ };
389
+ }
390
+ function encodePending(pending) {
391
+ return {
392
+ kind: pending.kind,
393
+ newState: pending.newState,
394
+ ...(pending.parentState === undefined ? {} : { parentState: pending.parentState }),
395
+ ...(pending.commitMessage === undefined ? {} : { commitMessage: pending.commitMessage }),
396
+ ...(pending.ownCommit === undefined ? {} : { ownCommit: pending.ownCommit }),
397
+ };
398
+ }
399
+ export function decodePendingIntentRecord(intentId, raw) {
400
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
401
+ throw malformed(intentId, 'record not an object');
402
+ const r = raw;
403
+ if (r.v !== 1)
404
+ throw malformed(intentId, 'v mismatch');
405
+ if (typeof r.intentId !== 'string' || r.intentId !== intentId)
406
+ throw malformed(intentId, 'intentId mismatch');
407
+ if (typeof r.seq !== 'number')
408
+ throw malformed(intentId, 'seq missing');
409
+ const kind = r.kind;
410
+ if (kind !== 'application' && kind !== 'proposal' && kind !== 'commit' && kind !== 'self-update')
411
+ throw malformed(intentId, 'kind invalid');
412
+ const state = r.state;
413
+ if (state !== 'pending-publish' && state !== 'pending-confirm' && state !== 'awaiting-sync')
414
+ throw malformed(intentId, 'state invalid');
415
+ if (typeof r.parentEpoch !== 'bigint')
416
+ throw malformed(intentId, 'parentEpoch missing');
417
+ if (typeof r.attempts !== 'number')
418
+ throw malformed(intentId, 'attempts missing');
419
+ const pending = decodePending(intentId, r.pending);
420
+ const welcomes = r.welcomes === undefined ? undefined : decodeStoredWelcomes(`pendingIntents/${intentId}`, r.welcomes);
421
+ const ordering = decodeOrdering(r.ordering);
422
+ if (r.reenqueuedFrom !== undefined && typeof r.reenqueuedFrom !== 'string')
423
+ throw malformed(intentId, 'reenqueuedFrom not a string');
424
+ if (r.retryAt !== undefined && typeof r.retryAt !== 'number')
425
+ throw malformed(intentId, 'retryAt not a number');
426
+ const failPending = (detail) => malformed(intentId, detail);
427
+ const changes = r.changes === undefined ? undefined : decodeStoredOwnChanges(r.changes, 'changes', failPending, true);
428
+ assertChangesPair(changes, r.forkEpoch, failPending);
429
+ const intent = decodeStorableIntent(intentId, r.intent);
430
+ if (changes !== undefined)
431
+ assertRedriveShape(kind, intent, r.reenqueuedFrom, failPending);
432
+ return {
433
+ v: 1,
434
+ intentId,
435
+ seq: r.seq,
436
+ kind,
437
+ state,
438
+ parentEpoch: r.parentEpoch,
439
+ intent,
440
+ ...(r.envelope === undefined ? {} : { envelope: r.envelope }),
441
+ ...(pending === undefined ? {} : { pending }),
442
+ ...(welcomes === undefined ? {} : { welcomes }),
443
+ ...(ordering === undefined ? {} : { ordering }),
444
+ attempts: r.attempts,
445
+ ...(r.reenqueuedFrom === undefined ? {} : { reenqueuedFrom: r.reenqueuedFrom }),
446
+ ...(r.retryAt === undefined ? {} : { retryAt: r.retryAt }),
447
+ ...(changes === undefined ? {} : { changes }),
448
+ ...(r.forkEpoch === undefined ? {} : { forkEpoch: r.forkEpoch }),
449
+ };
450
+ }
451
+ function decodeOrdering(raw) {
452
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
453
+ return undefined;
454
+ const o = raw;
455
+ if (typeof o.account !== 'string' || typeof o.leafIndex !== 'number' || typeof o.epoch !== 'bigint' || typeof o.generation !== 'number' || typeof o.acceptedDigest !== 'string')
456
+ return undefined;
457
+ return Object.freeze({ account: o.account, leafIndex: o.leafIndex, epoch: o.epoch, generation: o.generation, acceptedDigest: o.acceptedDigest });
458
+ }
459
+ export function encodePendingIntentRecord(record) {
460
+ const failRecord = (detail) => malformed(record.intentId, detail);
461
+ assertChangesPair(record.changes, record.forkEpoch, failRecord);
462
+ if (record.changes !== undefined)
463
+ assertRedriveShape(record.kind, record.intent, record.reenqueuedFrom, failRecord);
464
+ return {
465
+ v: 1,
466
+ intentId: record.intentId,
467
+ seq: record.seq,
468
+ kind: record.kind,
469
+ state: record.state,
470
+ parentEpoch: record.parentEpoch,
471
+ intent: encodeStorableIntent(record.intentId, record.intent),
472
+ ...(record.envelope === undefined ? {} : { envelope: record.envelope }),
473
+ ...(record.pending === undefined ? {} : { pending: encodePending(record.pending) }),
474
+ ...(record.welcomes === undefined ? {} : { welcomes: encodeStoredWelcomes(record.welcomes) }),
475
+ ...(record.ordering === undefined
476
+ ? {}
477
+ : { ordering: { account: record.ordering.account, leafIndex: record.ordering.leafIndex, epoch: record.ordering.epoch, generation: record.ordering.generation, acceptedDigest: record.ordering.acceptedDigest } }),
478
+ attempts: record.attempts,
479
+ ...(record.reenqueuedFrom === undefined ? {} : { reenqueuedFrom: record.reenqueuedFrom }),
480
+ ...(record.retryAt === undefined ? {} : { retryAt: record.retryAt }),
481
+ ...(record.changes === undefined ? {} : { changes: encodeStoredOwnChanges(record.changes, true) }),
482
+ ...(record.forkEpoch === undefined ? {} : { forkEpoch: record.forkEpoch }),
483
+ };
484
+ }
485
+ export async function readPendingIntentRecord(view, intentId) {
486
+ const raw = await view.get(intentId);
487
+ if (raw === undefined)
488
+ return undefined;
489
+ return decodePendingIntentRecord(intentId, raw);
490
+ }
491
+ export async function writePendingIntentRecord(view, record) {
492
+ await view.put(record.intentId, encodePendingIntentRecord(record));
493
+ }
494
+ export async function deletePendingIntentRecord(view, intentId) {
495
+ await view.delete(intentId);
496
+ }
497
+ /** Every pending-intent record, ordered by `seq` (ascending — creation order). */
498
+ export async function listPendingIntentRecords(view) {
499
+ const ids = await view.keys();
500
+ const records = [];
501
+ for (const id of ids) {
502
+ const record = await readPendingIntentRecord(view, id);
503
+ if (record !== undefined)
504
+ records.push(record);
505
+ }
506
+ records.sort((a, b) => a.seq - b.seq);
507
+ return records;
508
+ }
509
+ /** `{ intentId, state, kind }` for every pending intent, ordered by `seq` (AC-PIPE-1). */
510
+ export async function listPendingIntentSummaries(view) {
511
+ const records = await listPendingIntentRecords(view);
512
+ return records.map((r) => ({ intentId: r.intentId, state: r.state, kind: r.kind }));
513
+ }
514
+ /** The next `seq` to assign: max existing `seq` + 1 (1 when the group has no pending intents yet). */
515
+ export async function nextSeq(view) {
516
+ const records = await listPendingIntentRecords(view);
517
+ let max = 0;
518
+ for (const r of records)
519
+ if (r.seq > max)
520
+ max = r.seq;
521
+ return max + 1;
522
+ }
523
+ function malformedQueued(queueId, detail) {
524
+ return new MarmotError('store-failed', `queuedRumors/${queueId}: malformed record (${detail})`, { details: { queueId, malformed: true } });
525
+ }
526
+ export function decodeQueuedRumorRecord(queueId, raw) {
527
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
528
+ throw malformedQueued(queueId, 'record not an object');
529
+ const r = raw;
530
+ if (r.v !== 1 || r.queueId !== queueId)
531
+ throw malformedQueued(queueId, 'header');
532
+ if (typeof r.seq !== 'number' || typeof r.queuedAt !== 'number')
533
+ throw malformedQueued(queueId, 'seq/queuedAt');
534
+ if (typeof r.rumor !== 'object' || r.rumor === null)
535
+ throw malformedQueued(queueId, 'rumor');
536
+ if (r.barrier !== undefined && typeof r.barrier !== 'bigint')
537
+ throw malformedQueued(queueId, 'barrier');
538
+ return {
539
+ v: 1,
540
+ queueId,
541
+ seq: r.seq,
542
+ rumor: r.rumor,
543
+ ...(r.barrier === undefined ? {} : { barrier: r.barrier }),
544
+ queuedAt: r.queuedAt,
545
+ };
546
+ }
547
+ export async function writeQueuedRumorRecord(view, record) {
548
+ await view.put(record.queueId, {
549
+ v: 1,
550
+ queueId: record.queueId,
551
+ seq: record.seq,
552
+ rumor: record.rumor,
553
+ ...(record.barrier === undefined ? {} : { barrier: record.barrier }),
554
+ queuedAt: record.queuedAt,
555
+ });
556
+ }
557
+ export async function readQueuedRumorRecord(view, queueId) {
558
+ const raw = await view.get(queueId);
559
+ return raw === undefined ? undefined : decodeQueuedRumorRecord(queueId, raw);
560
+ }
561
+ /** Every queued rumor, in queue order. */
562
+ export async function listQueuedRumorRecords(view) {
563
+ const records = [];
564
+ for (const id of await view.keys()) {
565
+ const record = await readQueuedRumorRecord(view, id);
566
+ if (record !== undefined)
567
+ records.push(record);
568
+ }
569
+ records.sort((a, b) => a.seq - b.seq);
570
+ return records;
571
+ }
572
+ function malformedLedger(eventId) {
573
+ return new MarmotError('store-failed', `terminalLedger/${eventId}: malformed entry`, { details: { eventId, malformed: true } });
574
+ }
575
+ /** `ownCommitRoot` needs `node` and excludes `selfUpdateIntentId` / `rekey` — enforced by the reader and the writer alike. */
576
+ const ownCommitRootInvalid = (e) => e.ownCommitRoot !== undefined && (e.node === undefined || e.selfUpdateIntentId !== undefined || e.rekey !== undefined);
577
+ export async function readTerminalLedgerEntry(view, eventId) {
578
+ const raw = await view.get(eventId);
579
+ if (raw === undefined)
580
+ return undefined;
581
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
582
+ throw malformedLedger(eventId);
583
+ const r = raw;
584
+ if (typeof r.disposition !== 'string' ||
585
+ typeof r.at !== 'number' ||
586
+ (r.createdAt !== undefined && typeof r.createdAt !== 'number') ||
587
+ (r.node !== undefined && typeof r.node !== 'string') ||
588
+ (r.selfUpdateIntentId !== undefined && typeof r.selfUpdateIntentId !== 'string') ||
589
+ (r.attempts !== undefined && typeof r.attempts !== 'number') ||
590
+ (r.rekey !== undefined && (typeof r.rekey !== 'string' || !isHex64(r.rekey))) ||
591
+ (r.ownCommitRoot !== undefined && typeof r.ownCommitRoot !== 'string')) {
592
+ throw malformedLedger(eventId);
593
+ }
594
+ if (ownCommitRootInvalid(r))
595
+ throw malformedLedger(eventId);
596
+ return {
597
+ disposition: r.disposition,
598
+ at: r.at,
599
+ ...(r.createdAt === undefined ? {} : { createdAt: r.createdAt }),
600
+ ...(r.node === undefined ? {} : { node: r.node }),
601
+ ...(r.selfUpdateIntentId === undefined ? {} : { selfUpdateIntentId: r.selfUpdateIntentId }),
602
+ ...(r.attempts === undefined ? {} : { attempts: r.attempts }),
603
+ ...(r.rekey === undefined ? {} : { rekey: r.rekey }),
604
+ ...(r.ownCommitRoot === undefined ? {} : { ownCommitRoot: r.ownCommitRoot }),
605
+ };
606
+ }
607
+ export async function writeTerminalLedgerEntry(view, eventId, entry) {
608
+ if (ownCommitRootInvalid(entry))
609
+ throw malformedLedger(eventId);
610
+ await view.put(eventId, {
611
+ disposition: entry.disposition,
612
+ at: entry.at,
613
+ ...(entry.createdAt === undefined ? {} : { createdAt: entry.createdAt }),
614
+ ...(entry.node === undefined ? {} : { node: entry.node }),
615
+ ...(entry.selfUpdateIntentId === undefined ? {} : { selfUpdateIntentId: entry.selfUpdateIntentId }),
616
+ ...(entry.attempts === undefined ? {} : { attempts: entry.attempts }),
617
+ ...(entry.rekey === undefined ? {} : { rekey: entry.rekey }),
618
+ ...(entry.ownCommitRoot === undefined ? {} : { ownCommitRoot: entry.ownCommitRoot }),
619
+ });
620
+ }
621
+ /**
622
+ * Retention: deletes every entry whose event `created_at` is below
623
+ * `belowCreatedAt`. The ingest cursor's `since` bounds what a relay can
624
+ * still redeliver, so an entry far below it no longer dedups anything the
625
+ * sync loop fetches; an older event fed to `ingest()` by hand falls back on
626
+ * the engine's own past-epoch / duplicate rules. Entries without a
627
+ * `createdAt` are kept, and so is every entry whose `node` is in `retained`
628
+ * (the stored rewind window's nodes, `retainedLedgerNodes`): a fork flip
629
+ * through that node still needs it for withdrawal detection and the
630
+ * self-update re-enqueue / cancel (ledger-retention-vs-rewind-horizon).
631
+ * Returns the number deleted.
632
+ */
633
+ export async function pruneTerminalLedger(view, belowCreatedAt, retained = new Set()) {
634
+ let pruned = 0;
635
+ for (const eventId of await view.keys()) {
636
+ const entry = await readTerminalLedgerEntry(view, eventId);
637
+ if (entry?.createdAt !== undefined && entry.createdAt < belowCreatedAt && (entry.node === undefined || !retained.has(entry.node))) {
638
+ await view.delete(eventId);
639
+ pruned += 1;
640
+ }
641
+ }
642
+ return pruned;
643
+ }
644
+ const isObject = (raw) => typeof raw === 'object' && raw !== null && !Array.isArray(raw) && !(raw instanceof Uint8Array);
645
+ /** A component id: an integer in the u16 range. */
646
+ const isComponentId = (v) => Number.isInteger(v) && v >= 0 && v <= 0xffff;
647
+ const isForkEpoch = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
648
+ const isBytesOrNull = (v) => v === null || v instanceof Uint8Array;
649
+ function onlyMembers(obj, allowed, where, fail) {
650
+ for (const k of Object.keys(obj))
651
+ if (obj[k] !== undefined && !allowed.includes(k))
652
+ throw fail(`${where}.${k} not allowed`);
653
+ }
654
+ export function decodeOwnChange(raw, at, fail) {
655
+ if (!isObject(raw))
656
+ throw fail(`${at} not an object`);
657
+ switch (raw.type) {
658
+ case 'member-removed':
659
+ onlyMembers(raw, ['type', 'account'], at, fail);
660
+ if (!isAccountPubkey(raw.account))
661
+ throw fail(`${at}.account invalid`);
662
+ return { type: 'member-removed', account: raw.account };
663
+ case 'member-added':
664
+ onlyMembers(raw, ['type', 'account', 'leafKey'], at, fail);
665
+ if (!isAccountPubkey(raw.account) || !isHex64(raw.leafKey))
666
+ throw fail(`${at} member-added invalid`);
667
+ return { type: 'member-added', account: raw.account, leafKey: raw.leafKey };
668
+ case 'admin':
669
+ onlyMembers(raw, ['type', 'account', 'admin'], at, fail);
670
+ if (!isAccountPubkey(raw.account) || typeof raw.admin !== 'boolean')
671
+ throw fail(`${at} admin invalid`);
672
+ return { type: 'admin', account: raw.account, admin: raw.admin };
673
+ case 'component':
674
+ onlyMembers(raw, ['type', 'componentId'], at, fail);
675
+ if (typeof raw.componentId !== 'number' || !isComponentId(raw.componentId))
676
+ throw fail(`${at}.componentId invalid`);
677
+ return { type: 'component', componentId: raw.componentId };
678
+ default:
679
+ throw fail(`${at}.type unknown`);
680
+ }
681
+ }
682
+ /**
683
+ * Strict decoder of one {@link StoredOwnChange}: a wrong type anywhere is a `store-failed` error built by `fail` (so
684
+ * the pending record and the marker each report under their own key). Shared by both records.
685
+ */
686
+ export function decodeStoredOwnChange(raw, at, fail, allowVerdict = true) {
687
+ if (!isObject(raw))
688
+ throw fail(`${at} not an object`);
689
+ const change = decodeOwnChange(raw.change, `${at}.change`, fail);
690
+ const forkRaw = raw.fork;
691
+ if (!isObject(forkRaw))
692
+ throw fail(`${at}.fork invalid`);
693
+ if (!allowVerdict && raw.verdict !== undefined)
694
+ throw fail(`${at}.verdict not allowed`);
695
+ if (raw.winnerHeldInvitee !== undefined && typeof raw.winnerHeldInvitee !== 'boolean')
696
+ throw fail(`${at}.winnerHeldInvitee invalid`);
697
+ if (raw.winnerRemovedTarget !== undefined && typeof raw.winnerRemovedTarget !== 'boolean')
698
+ throw fail(`${at}.winnerRemovedTarget invalid`);
699
+ // Per kind: exactly the members that belong to it (a member of another kind is refused, a required one must be present).
700
+ const members = (obj, allowed, where) => {
701
+ for (const k of Object.keys(obj))
702
+ if (obj[k] !== undefined && !allowed.includes(k))
703
+ throw fail(`${where}.${k} not allowed for ${change.type}`);
704
+ };
705
+ members(raw, change.type === 'component' ? ['change', 'data', 'fork', 'verdict'] : change.type === 'member-added' ? ['change', 'fork', 'winnerHeldInvitee', 'keyPackage', 'verdict'] : change.type === 'member-removed' ? ['change', 'fork', 'winnerRemovedTarget', 'verdict'] : ['change', 'fork', 'verdict'], at);
706
+ let data;
707
+ let keyPackage;
708
+ const fork = {};
709
+ switch (change.type) {
710
+ case 'component':
711
+ if (!isBytesOrNull(raw.data))
712
+ throw fail(`${at}.data invalid`);
713
+ if (!isBytesOrNull(forkRaw.component))
714
+ throw fail(`${at}.fork.component invalid`);
715
+ members(forkRaw, ['component'], `${at}.fork`);
716
+ data = raw.data;
717
+ fork.component = forkRaw.component;
718
+ break;
719
+ case 'admin':
720
+ if (typeof forkRaw.admin !== 'boolean')
721
+ throw fail(`${at}.fork.admin invalid`);
722
+ members(forkRaw, ['admin'], `${at}.fork`);
723
+ fork.admin = forkRaw.admin;
724
+ break;
725
+ case 'member-removed':
726
+ if (!Array.isArray(forkRaw.leafKeys) || !forkRaw.leafKeys.every(isHex64))
727
+ throw fail(`${at}.fork.leafKeys invalid`);
728
+ members(forkRaw, ['leafKeys'], `${at}.fork`);
729
+ fork.leafKeys = [...forkRaw.leafKeys];
730
+ break;
731
+ case 'member-added':
732
+ if (typeof forkRaw.held !== 'boolean')
733
+ throw fail(`${at}.fork.held invalid`);
734
+ members(forkRaw, ['held'], `${at}.fork`);
735
+ fork.held = forkRaw.held;
736
+ if (!isObject(raw.keyPackage))
737
+ throw fail(`${at}.keyPackage invalid`);
738
+ members(raw.keyPackage, ['event', 'inviteeRef'], `${at}.keyPackage`);
739
+ if (!isObject(raw.keyPackage.event) || typeof raw.keyPackage.inviteeRef !== 'string')
740
+ throw fail(`${at}.keyPackage invalid`);
741
+ keyPackage = { event: raw.keyPackage.event, inviteeRef: raw.keyPackage.inviteeRef };
742
+ break;
743
+ }
744
+ const verdict = raw.verdict;
745
+ if (verdict !== undefined && verdict !== 'reapplied' && !OWN_CHANGE_LOST_REASONS.includes(verdict))
746
+ throw fail(`${at}.verdict invalid`);
747
+ return {
748
+ change,
749
+ ...(data === undefined ? {} : { data }),
750
+ fork,
751
+ ...(raw.winnerHeldInvitee === undefined ? {} : { winnerHeldInvitee: raw.winnerHeldInvitee }),
752
+ ...(raw.winnerRemovedTarget === undefined ? {} : { winnerRemovedTarget: raw.winnerRemovedTarget }),
753
+ ...(keyPackage === undefined ? {} : { keyPackage }),
754
+ ...(verdict === undefined ? {} : { verdict: verdict }),
755
+ };
756
+ }
757
+ /** The `Storable` form of a {@link StoredOwnChange}; absent members stay absent (so a decode re-encodes identically). */
758
+ export function encodeStoredOwnChange(c, allowVerdict = true) {
759
+ const loose = c;
760
+ const raw = {
761
+ change: { ...loose.change },
762
+ ...(loose.data === undefined ? {} : { data: loose.data }),
763
+ fork: {
764
+ ...(loose.fork.component === undefined ? {} : { component: loose.fork.component }),
765
+ ...(loose.fork.admin === undefined ? {} : { admin: loose.fork.admin }),
766
+ ...(loose.fork.leafKeys === undefined ? {} : { leafKeys: [...loose.fork.leafKeys] }),
767
+ ...(loose.fork.held === undefined ? {} : { held: loose.fork.held }),
768
+ },
769
+ ...(loose.winnerHeldInvitee === undefined ? {} : { winnerHeldInvitee: loose.winnerHeldInvitee }),
770
+ ...(loose.winnerRemovedTarget === undefined ? {} : { winnerRemovedTarget: loose.winnerRemovedTarget }),
771
+ ...(loose.keyPackage === undefined ? {} : { keyPackage: { event: loose.keyPackage.event, inviteeRef: loose.keyPackage.inviteeRef } }),
772
+ ...(loose.verdict === undefined ? {} : { verdict: loose.verdict }),
773
+ };
774
+ // Defense in depth against a mis-shaped write that got past the type (a cast, untyped JS): the write-time check is the read-time rule.
775
+ decodeStoredOwnChange(raw, 'change', (detail) => new MarmotError('store-failed', `StoredOwnChange: refusing to write a malformed change (${detail})`, { details: { malformed: true } }), allowVerdict);
776
+ return raw;
777
+ }
778
+ function decodeStoredOwnChanges(raw, at, fail, allowVerdict) {
779
+ if (!Array.isArray(raw) || raw.length === 0)
780
+ throw fail(`${at} not a non-empty array`);
781
+ return raw.map((entry, i) => decodeStoredOwnChange(entry, `${at}[${String(i)}]`, fail, allowVerdict));
782
+ }
783
+ function encodeStoredOwnChanges(changes, allowVerdict) {
784
+ return changes.map((c) => encodeStoredOwnChange(c, allowVerdict));
785
+ }
786
+ /** `changes` and `forkEpoch` are written together (the removeAccounts / removeAccountLeafKeys convention); `changes` is never empty and `forkEpoch` a non-negative integer. */
787
+ function assertChangesPair(changes, forkEpoch, fail) {
788
+ if (forkEpoch !== undefined && !isForkEpoch(forkEpoch))
789
+ throw fail('forkEpoch not a non-negative integer');
790
+ if ((changes === undefined) !== (forkEpoch === undefined))
791
+ throw fail('changes and forkEpoch go together');
792
+ if (changes !== undefined && changes.length === 0)
793
+ throw fail('changes empty');
794
+ }
795
+ /**
796
+ * DD15: a record carrying `changes` is a re-drive record — a `commit` that re-enqueues a withdrawn own commit
797
+ * (`reenqueuedFrom` set) whose intent is exactly `{ type: 'commit' }`: no other member (invite, removals, admins,
798
+ * profile, origin, components).
799
+ */
800
+ function assertRedriveShape(kind, intent, reenqueuedFrom, fail) {
801
+ if (kind !== 'commit' || intent.type !== 'commit')
802
+ throw fail('changes only on a commit record');
803
+ if (reenqueuedFrom === undefined)
804
+ throw fail('changes without reenqueuedFrom');
805
+ if (Object.entries(intent).some(([k, v]) => k !== 'type' && v !== undefined))
806
+ throw fail('changes with an intent beyond { type: commit }');
807
+ }
808
+ /**
809
+ * The group extension holding one {@link OwnCommitMarker} per confirmed own commit, keyed by the commit's event id —
810
+ * the same key as its terminal-ledger entry (whose `ownCommitRoot` flags it). Written by the confirming transaction
811
+ * (S9); read when a rewind withdraws the commit.
812
+ */
813
+ export const OWN_COMMIT_EXTENSION = 'marmot.own-commit';
814
+ /** A declared set is non-empty: `removed` / `components` non-empty arrays (accounts, u16 ids, no duplicates), `admins` only as `true`. */
815
+ function checkDeclared(raw, fail) {
816
+ if (!isObject(raw))
817
+ throw fail('declared not an object');
818
+ onlyMembers(raw, ['removed', 'admins', 'components'], 'declared', fail);
819
+ const { removed, admins, components } = raw;
820
+ if (removed !== undefined && (!Array.isArray(removed) || removed.length === 0 || !removed.every(isAccountPubkey) || new Set(removed).size !== removed.length))
821
+ throw fail('declared.removed invalid');
822
+ if (admins !== undefined && admins !== true)
823
+ throw fail('declared.admins invalid');
824
+ if (components !== undefined && (!Array.isArray(components) || components.length === 0 || !components.every((id) => typeof id === 'number' && isComponentId(id)) || new Set(components).size !== components.length)) {
825
+ throw fail('declared.components invalid');
826
+ }
827
+ if (removed === undefined && admins === undefined && components === undefined)
828
+ throw fail('declared empty');
829
+ return {
830
+ ...(removed === undefined ? {} : { removed: [...removed] }),
831
+ ...(admins === undefined ? {} : { admins: true }),
832
+ ...(components === undefined ? {} : { components: [...components] }),
833
+ };
834
+ }
835
+ function malformedMarker(eventId, detail) {
836
+ return new MarmotError('store-failed', `${OWN_COMMIT_EXTENSION}/${eventId}: malformed record (${detail})`, { details: { eventId, malformed: true } });
837
+ }
838
+ export function decodeOwnCommitMarker(eventId, raw) {
839
+ const fail = (detail) => malformedMarker(eventId, detail);
840
+ if (!isObject(raw))
841
+ throw fail('record not an object');
842
+ if (raw.v !== 1)
843
+ throw fail('v mismatch');
844
+ if (typeof raw.root !== 'string')
845
+ throw fail('root missing');
846
+ if (typeof raw.node !== 'string')
847
+ throw fail('node missing');
848
+ if (typeof raw.attempts !== 'number')
849
+ throw fail('attempts missing');
850
+ let invitees;
851
+ if (raw.invitees !== undefined) {
852
+ if (!Array.isArray(raw.invitees) || raw.invitees.length === 0)
853
+ throw fail('invitees not a non-empty array');
854
+ invitees = raw.invitees.map((entry) => {
855
+ if (!isObject(entry) || !isObject(entry.event) || typeof entry.inviteeRef !== 'string' || !isHex64(entry.leafKey))
856
+ throw fail('invitee invalid');
857
+ return { event: entry.event, inviteeRef: entry.inviteeRef, leafKey: entry.leafKey };
858
+ });
859
+ }
860
+ const declared = raw.declared === undefined ? undefined : checkDeclared(raw.declared, fail);
861
+ const changes = raw.changes === undefined ? undefined : decodeStoredOwnChanges(raw.changes, 'changes', fail, false);
862
+ assertChangesPair(changes, raw.forkEpoch, fail);
863
+ return {
864
+ v: 1,
865
+ root: raw.root,
866
+ node: raw.node,
867
+ attempts: raw.attempts,
868
+ ...(invitees === undefined ? {} : { invitees }),
869
+ ...(declared === undefined ? {} : { declared }),
870
+ ...(changes === undefined ? {} : { changes }),
871
+ ...(raw.forkEpoch === undefined ? {} : { forkEpoch: raw.forkEpoch }),
872
+ };
873
+ }
874
+ export function encodeOwnCommitMarker(marker, eventId = '?') {
875
+ assertChangesPair(marker.changes, marker.forkEpoch, (detail) => malformedMarker(eventId, detail));
876
+ if (marker.invitees !== undefined && marker.invitees.length === 0)
877
+ throw malformedMarker(eventId, 'invitees empty');
878
+ for (const i of marker.invitees ?? [])
879
+ if (!isObject(i.event) || !isHex64(i.leafKey))
880
+ throw malformedMarker(eventId, 'invitee invalid');
881
+ const declared = marker.declared === undefined ? undefined : checkDeclared(marker.declared, (detail) => malformedMarker(eventId, detail));
882
+ return {
883
+ v: 1,
884
+ root: marker.root,
885
+ node: marker.node,
886
+ attempts: marker.attempts,
887
+ ...(marker.invitees === undefined ? {} : { invitees: marker.invitees.map((i) => ({ event: i.event, inviteeRef: i.inviteeRef, leafKey: i.leafKey })) }),
888
+ ...(declared === undefined ? {} : { declared }),
889
+ ...(marker.changes === undefined ? {} : { changes: encodeStoredOwnChanges(marker.changes, false) }),
890
+ ...(marker.forkEpoch === undefined ? {} : { forkEpoch: marker.forkEpoch }),
891
+ };
892
+ }
893
+ /** `view` is the group's `OWN_COMMIT_EXTENSION` namespace. */
894
+ export async function readOwnCommitMarker(view, eventId) {
895
+ const raw = await view.get(eventId);
896
+ if (raw === undefined)
897
+ return undefined;
898
+ return decodeOwnCommitMarker(eventId, raw);
899
+ }
900
+ export async function writeOwnCommitMarker(view, eventId, marker) {
901
+ await view.put(eventId, encodeOwnCommitMarker(marker, eventId));
902
+ }
903
+ /**
904
+ * DD9: the part of its root's publish budget a commit re-drive record holds that no marker does yet — its failed
905
+ * publishes and re-mints (`attempts`) and, while a relay-accepted publish awaits its confirm (`pending-confirm`), the
906
+ * one publish that confirm would have counted.
907
+ */
908
+ export function redriveSpendOf(record) {
909
+ return record.attempts + (record.state === 'pending-confirm' ? 1 : 0);
910
+ }
911
+ /** DD9: the highest spend any marker of `root` in `view` (the `OWN_COMMIT_EXTENSION` namespace) records; 0 when none. */
912
+ export async function rootMarkerSpend(view, root) {
913
+ let spend = 0;
914
+ for (const eventId of await view.keys()) {
915
+ const marker = await readOwnCommitMarker(view, eventId);
916
+ if (marker !== undefined && marker.root === root)
917
+ spend = Math.max(spend, marker.attempts);
918
+ }
919
+ return spend;
920
+ }
921
+ /**
922
+ * DD9: raises every marker of `root` in `view` — or only those of `eventIds` — to at least `spend` attempts (max-based,
923
+ * idempotent), so a later restore or withdrawal seeds its record from the marker instead of a fresh budget.
924
+ */
925
+ export async function raiseRootSpend(view, root, spend, eventIds) {
926
+ for (const eventId of eventIds ?? (await view.keys())) {
927
+ const marker = await readOwnCommitMarker(view, eventId);
928
+ if (marker !== undefined && marker.root === root && marker.attempts < spend)
929
+ await writeOwnCommitMarker(view, eventId, { ...marker, attempts: spend });
930
+ }
931
+ }
932
+ export async function deleteOwnCommitMarker(view, eventId) {
933
+ await view.delete(eventId);
934
+ }
935
+ /**
936
+ * Marker retention follows the node (DD6, AC-MARK-4): deletes every marker whose `node` is not in `retained` (the
937
+ * stored rewind window's nodes, `retainedLedgerNodes`) — whether or not its terminal-ledger entry still exists: a
938
+ * node that left the window can no longer be abandoned or restored by a fork flip, so its marker has nothing left to
939
+ * serve. `retained` is required so a caller cannot prune against an empty window by omission. Returns the number
940
+ * deleted. Called by the ingest ledger prune, in its transaction (S9).
941
+ */
942
+ export async function pruneOwnCommitMarkers(markers, retained) {
943
+ let pruned = 0;
944
+ for (const eventId of await markers.keys()) {
945
+ const marker = await readOwnCommitMarker(markers, eventId);
946
+ if (marker !== undefined && !retained.has(marker.node)) {
947
+ await markers.delete(eventId);
948
+ pruned += 1;
949
+ }
950
+ }
951
+ return pruned;
952
+ }
953
+ // ---------------------------------------------------------------------------
954
+ // Ingest cursor (GroupStore `ingestCursor` artifact, key {@link CURSOR_KEY})
955
+ // ---------------------------------------------------------------------------
956
+ function malformedCursor() {
957
+ return new MarmotError('store-failed', 'ingestCursor: malformed entry', { details: { key: CURSOR_KEY, malformed: true } });
958
+ }
959
+ function decodeHoldMap(raw) {
960
+ if (raw === undefined)
961
+ return undefined;
962
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
963
+ throw malformedCursor();
964
+ const map = {};
965
+ for (const [id, at] of Object.entries(raw)) {
966
+ if (typeof at !== 'number')
967
+ throw malformedCursor();
968
+ map[id] = at;
969
+ }
970
+ return map;
971
+ }
972
+ /**
973
+ * Reads the group's persisted kind-445 ingest cursor, or `undefined` when
974
+ * history has never been synced. `pins`, `busy` and `resume` are optional: a
975
+ * record written before those tiers existed decodes with every hold in the
976
+ * evictable tier, and without a resume window.
977
+ */
978
+ export async function readIngestCursor(view) {
979
+ const raw = await view.get(CURSOR_KEY);
980
+ if (raw === undefined)
981
+ return undefined;
982
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
983
+ throw malformedCursor();
984
+ const r = raw;
985
+ if (typeof r.since !== 'number' || (r.high !== undefined && typeof r.high !== 'number'))
986
+ throw malformedCursor();
987
+ const holds = decodeHoldMap(r.holds);
988
+ const pins = decodeHoldMap(r.pins);
989
+ const busy = decodeHoldMap(r.busy);
990
+ const resume = decodeResume(r.resume);
991
+ return {
992
+ since: r.since,
993
+ ...(r.high === undefined ? {} : { high: r.high }),
994
+ ...(holds === undefined ? {} : { holds }),
995
+ ...(pins === undefined ? {} : { pins }),
996
+ ...(busy === undefined ? {} : { busy }),
997
+ ...(resume === undefined ? {} : { resume }),
998
+ };
999
+ }
1000
+ function decodeResume(raw) {
1001
+ if (raw === undefined)
1002
+ return undefined;
1003
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
1004
+ throw malformedCursor();
1005
+ const { from, until, above } = raw;
1006
+ if (typeof from !== 'number' || (until !== undefined && typeof until !== 'number'))
1007
+ throw malformedCursor();
1008
+ if (above !== undefined && (!Array.isArray(above) || !above.every((top) => typeof top === 'number')))
1009
+ throw malformedCursor();
1010
+ return {
1011
+ from,
1012
+ ...(until === undefined ? {} : { until }),
1013
+ ...(above === undefined || above.length === 0 ? {} : { above: [...above] }),
1014
+ };
1015
+ }
1016
+ /** Persists `cursor` as the group's kind-445 ingest cursor. */
1017
+ export async function writeIngestCursor(view, cursor) {
1018
+ await view.put(CURSOR_KEY, {
1019
+ since: cursor.since,
1020
+ ...(cursor.high === undefined ? {} : { high: cursor.high }),
1021
+ ...(cursor.holds === undefined ? {} : { holds: { ...cursor.holds } }),
1022
+ ...(cursor.pins === undefined ? {} : { pins: { ...cursor.pins } }),
1023
+ ...(cursor.busy === undefined ? {} : { busy: { ...cursor.busy } }),
1024
+ ...(cursor.resume === undefined
1025
+ ? {}
1026
+ : {
1027
+ resume: {
1028
+ from: cursor.resume.from,
1029
+ ...(cursor.resume.until === undefined ? {} : { until: cursor.resume.until }),
1030
+ ...(cursor.resume.above === undefined || cursor.resume.above.length === 0 ? {} : { above: [...cursor.resume.above] }),
1031
+ },
1032
+ }),
1033
+ });
1034
+ }