@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,214 @@
1
+ import { classifyPublish, MarmotError } from '../shared/index.js';
2
+ // Gate-remediation R2: `classifyPublish`/`PublishOutcome` now live in
3
+ // `shared/publish-classification.ts` (key-packages/ needs the same
4
+ // classification and cannot import client/) — re-exported here UNCHANGED so
5
+ // this module's own callers (pipeline.ts) and its tests need no changes.
6
+ export { classifyPublish };
7
+ /** Kind of Marmot group events (MIP-03). */
8
+ export const GROUP_EVENT_KIND = 445;
9
+ /**
10
+ * The group's relay plane for kind 445: the group state's relays (routing
11
+ * component), or `fallback` (the client's `relays.defaults`) when the group
12
+ * names none. Order preserved, raw strings, duplicates dropped by exact match.
13
+ */
14
+ export function groupRelayPlane(groupRelays, fallback) {
15
+ const source = groupRelays.length > 0 ? groupRelays : fallback;
16
+ const seen = new Set();
17
+ const plane = [];
18
+ for (const relay of source) {
19
+ if (seen.has(relay))
20
+ continue;
21
+ seen.add(relay);
22
+ plane.push(relay);
23
+ }
24
+ return plane;
25
+ }
26
+ /** The kind-445 filter for one group, `since` the cursor when given. */
27
+ export function groupEventFilter(nostrGroupId, since) {
28
+ const filter = { kinds: [GROUP_EVENT_KIND], '#h': [nostrGroupId] };
29
+ if (since !== undefined)
30
+ filter.since = since;
31
+ return filter;
32
+ }
33
+ export function createHistorySilenceTracker(threshold) {
34
+ if (!Number.isInteger(threshold) || threshold <= 0) {
35
+ throw new MarmotError('invalid-options', `createHistorySilenceTracker: threshold must be a positive integer, got ${JSON.stringify(threshold)}`);
36
+ }
37
+ // Consecutive-silence count per relay, and the excluded set (insertion order preserved for `excluded()`).
38
+ const counters = new Map();
39
+ const excludedOrder = [];
40
+ const excludedSet = new Set();
41
+ return {
42
+ record(requested, result) {
43
+ const newlySilent = [];
44
+ const silentSet = new Set(result.silentRelays);
45
+ for (const relay of requested) {
46
+ if (result.timedOut && silentSet.has(relay)) {
47
+ const count = (counters.get(relay) ?? 0) + 1;
48
+ counters.set(relay, count);
49
+ if (count >= threshold && !excludedSet.has(relay)) {
50
+ excludedSet.add(relay);
51
+ excludedOrder.push(relay);
52
+ newlySilent.push(relay);
53
+ }
54
+ }
55
+ else {
56
+ counters.set(relay, 0);
57
+ }
58
+ }
59
+ return { newlySilent };
60
+ },
61
+ historyRelays(plane) {
62
+ const filtered = plane.filter((relay) => !excludedSet.has(relay));
63
+ return filtered.length > 0 ? filtered : [...plane];
64
+ },
65
+ excluded() {
66
+ return [...excludedOrder];
67
+ },
68
+ exclude(relay) {
69
+ if (excludedSet.has(relay))
70
+ return false;
71
+ excludedSet.add(relay);
72
+ excludedOrder.push(relay);
73
+ return true;
74
+ },
75
+ };
76
+ }
77
+ export const CURSOR_KEY = 'kind445';
78
+ /** Tolerated future skew of an event's `created_at` against the client clock (seconds). */
79
+ export const CURSOR_FUTURE_SKEW_S = 300;
80
+ /** `since` sits this far below the cursor's floor so late-stamped events are redelivered; the ledger dedups them (seconds). */
81
+ export const CURSOR_REDELIVERY_MARGIN_S = 300;
82
+ /** Ledger entries whose event `created_at` lies this far below the cursor's `since` are pruned (seconds). */
83
+ export const LEDGER_RETENTION_S = 7 * 86_400;
84
+ /** An undecryptable hold older than this is given up, so junk cannot pin the cursor forever (seconds). Pins are exempt. */
85
+ export const HOLD_MAX_AGE_S = 7 * 86_400;
86
+ /** At most this many undecryptable holds are kept (eviction policy: see {@link IngestCursor}), bounding the cursor record. Pins are exempt. */
87
+ export const MAX_HOLDS = 1000;
88
+ /** At most this many `group-busy` holds are kept (eviction policy: see {@link IngestCursor}), bounding the record during a long blocked confirmation. */
89
+ export const MAX_BUSY_PINS = 1000;
90
+ const byId = (a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
91
+ /**
92
+ * The cursor after one sync batch (see {@link IngestCursor}); `current`
93
+ * itself when nothing moved it. `high` never decreases except through the
94
+ * future-skew clamp; `since` may move backwards when a new hold predates it.
95
+ * A cursor without `high` (nothing authenticated has advanced it yet) keeps
96
+ * its `since` until something does.
97
+ */
98
+ export function nextCursor(current, update, nowSeconds) {
99
+ const ceiling = nowSeconds + CURSOR_FUTURE_SKEW_S;
100
+ let high = current?.high === undefined ? undefined : Math.min(current.high, ceiling);
101
+ for (const createdAt of update.advanced) {
102
+ const clamped = Math.min(createdAt, ceiling);
103
+ high = high === undefined ? clamped : Math.max(high, clamped);
104
+ }
105
+ const holds = new Map(Object.entries(current?.holds ?? {}));
106
+ const pins = new Map(Object.entries(current?.pins ?? {}));
107
+ const busy = new Map(Object.entries(current?.busy ?? {}));
108
+ for (const id of update.released) {
109
+ holds.delete(id);
110
+ pins.delete(id);
111
+ busy.delete(id);
112
+ }
113
+ // The batch's classification of an event replaces any earlier tier it sat in.
114
+ for (const [id, createdAt] of update.held) {
115
+ if (update.released.has(id))
116
+ continue;
117
+ pins.delete(id);
118
+ busy.delete(id);
119
+ if (createdAt <= ceiling)
120
+ holds.set(id, createdAt);
121
+ }
122
+ for (const [id, createdAt] of update.pinned) {
123
+ if (update.released.has(id))
124
+ continue;
125
+ holds.delete(id);
126
+ busy.delete(id);
127
+ if (createdAt <= ceiling)
128
+ pins.set(id, createdAt);
129
+ }
130
+ // `group-busy` says nothing new about an event already classified: it keeps its tier.
131
+ for (const [id, createdAt] of update.busy ?? []) {
132
+ if (update.released.has(id) || pins.has(id) || holds.has(id))
133
+ continue;
134
+ if (createdAt <= ceiling)
135
+ busy.set(id, createdAt);
136
+ }
137
+ for (const [id, createdAt] of holds)
138
+ if (createdAt < nowSeconds - HOLD_MAX_AGE_S)
139
+ holds.delete(id);
140
+ // The capped tiers' eviction policy (see IngestCursor): the oldest are kept.
141
+ const oldestFirst = (a, b) => a[1] - b[1] || byId(a, b);
142
+ const keptHolds = [...holds].sort(oldestFirst).slice(0, MAX_HOLDS);
143
+ const keptBusy = [...busy].sort(oldestFirst).slice(0, MAX_BUSY_PINS);
144
+ const keptPins = [...pins];
145
+ const resume = update.resume === undefined ? current?.resume : (update.resume ?? undefined);
146
+ let floor = high;
147
+ for (const [, createdAt] of [...keptHolds, ...keptPins, ...keptBusy])
148
+ floor = floor === undefined ? createdAt : Math.min(floor, createdAt);
149
+ // An unwalked window keeps `since` at or below its `from`.
150
+ if (resume !== undefined)
151
+ floor = Math.min(floor ?? Infinity, resume.from + CURSOR_REDELIVERY_MARGIN_S);
152
+ if (floor === undefined) {
153
+ // Nothing authenticated yet and no hold left: keep `since` where it was.
154
+ return current === undefined || (current.holds === undefined && current.pins === undefined && current.busy === undefined && current.resume === undefined)
155
+ ? current
156
+ : { since: current.since };
157
+ }
158
+ const next = {
159
+ since: Math.max(0, floor - CURSOR_REDELIVERY_MARGIN_S),
160
+ ...(high === undefined ? {} : { high }),
161
+ ...(keptHolds.length === 0 ? {} : { holds: Object.fromEntries(keptHolds.sort(byId)) }),
162
+ ...(keptPins.length === 0 ? {} : { pins: Object.fromEntries(keptPins.sort(byId)) }),
163
+ ...(keptBusy.length === 0 ? {} : { busy: Object.fromEntries(keptBusy.sort(byId)) }),
164
+ ...(resume === undefined ? {} : { resume: copyResume(resume) }),
165
+ };
166
+ return current !== undefined && sameCursor(current, next) ? current : next;
167
+ }
168
+ /**
169
+ * Pins and busy entries of `cursor` that a history pass should have
170
+ * returned but did not — so no relay can still redeliver them, and the
171
+ * entry would otherwise hold the floor forever. An entry is released only
172
+ * when the pass was complete (not `timedOut`, pagination finished — a
173
+ * truncated response proves nothing about what it cut off), covered the
174
+ * entry's `created_at` (within `[since, until]`, each edge open when absent,
175
+ * and not on a gap second a relay may have truncated), and
176
+ * asked the whole relay plane (a relay excluded as silent may still hold
177
+ * it). Anything else releases nothing.
178
+ */
179
+ export function absentPins(cursor, coverage, returnedIds) {
180
+ const absent = new Set();
181
+ if (!coverage.complete || !coverage.wholePlane)
182
+ return absent;
183
+ const { since, until } = coverage;
184
+ const gaps = new Set(coverage.gaps);
185
+ for (const tier of [cursor?.pins, cursor?.busy]) {
186
+ for (const [id, createdAt] of Object.entries(tier ?? {})) {
187
+ if ((since === undefined || createdAt >= since) && (until === undefined || createdAt <= until) && !gaps.has(createdAt) && !returnedIds.has(id))
188
+ absent.add(id);
189
+ }
190
+ }
191
+ return absent;
192
+ }
193
+ function copyResume(resume) {
194
+ return {
195
+ from: resume.from,
196
+ ...(resume.until === undefined ? {} : { until: resume.until }),
197
+ ...(resume.above === undefined || resume.above.length === 0 ? {} : { above: [...resume.above] }),
198
+ };
199
+ }
200
+ function sameHoldMap(a, b) {
201
+ const ah = Object.entries(a ?? {});
202
+ const bh = b ?? {};
203
+ return ah.length === Object.keys(bh).length && ah.every(([id, at]) => bh[id] === at);
204
+ }
205
+ function sameCursor(a, b) {
206
+ return (a.since === b.since &&
207
+ a.high === b.high &&
208
+ a.resume?.from === b.resume?.from &&
209
+ a.resume?.until === b.resume?.until &&
210
+ (a.resume?.above ?? []).join() === (b.resume?.above ?? []).join() &&
211
+ sameHoldMap(a.holds, b.holds) &&
212
+ sameHoldMap(a.pins, b.pins) &&
213
+ sameHoldMap(a.busy, b.busy));
214
+ }
@@ -0,0 +1,186 @@
1
+ import { type ClientState } from '@941design/marmot-engine/mls';
2
+ import type { KeyValueView, Storable } from '../storage/index.js';
3
+ import { type RetainedWindow, type WindowNode } from './retained-window.js';
4
+ /** Group extension holding one {@link AdmissionLineageRecord} per anchor, keyed `<addDigest>:<leafIndex>`. */
5
+ export declare const ADMISSION_LINEAGE_EXTENSION = "marmot.admission-lineage";
6
+ /** Where one Add put its leaf (structurally the invitations module's `AddAnchor`, SC-1 I3). */
7
+ export interface LineageAnchor {
8
+ /** Hex SHA-256 of the Add commit's MLS wire bytes. */
9
+ readonly addDigest: string;
10
+ /** Hex confirmation tag of the state the Add produced (its node in the rewind window). */
11
+ readonly addTag: string;
12
+ readonly commitEventId: string;
13
+ /** Leaf position in `addTag`'s state. */
14
+ readonly leafIndex: number;
15
+ /** Hex signature key of the added leaf. */
16
+ readonly leafKey: string;
17
+ }
18
+ /** Why an admission's occupancy cannot be proven. */
19
+ export type LineageGapReason = 'unprovable-root' | 'undecodable-commit' | 'restore' | 'switch';
20
+ /** How the occupancy that ended an admission ended. */
21
+ export type LineageEndedBy = 'inline-remove' | 'replaced' | 'by-reference';
22
+ /** The occupancy of one admission at one node of the selected path. */
23
+ export type LineageOccupancy = {
24
+ readonly kind: 'occupying';
25
+ readonly leafKey: string;
26
+ } | {
27
+ readonly kind: 'ended';
28
+ readonly digest: string;
29
+ readonly by: LineageEndedBy;
30
+ readonly committerOwn: boolean;
31
+ } | {
32
+ readonly kind: 'add-off-path';
33
+ } | {
34
+ readonly kind: 'gap';
35
+ readonly reason: LineageGapReason;
36
+ };
37
+ /** Where a checkpoint's occupancy came from: authenticated transitions of this store, or an imported snapshot. */
38
+ export type LineageProvenance = 'transition' | 'snapshot';
39
+ export interface LineageCheckpoint {
40
+ readonly at: {
41
+ readonly tag: string;
42
+ readonly epoch: number;
43
+ };
44
+ readonly occupancy: LineageOccupancy;
45
+ readonly provenance: LineageProvenance;
46
+ }
47
+ /** SC-4: one admission's durable lineage (group extension `marmot.admission-lineage`). */
48
+ export interface AdmissionLineageRecord {
49
+ readonly v: 1;
50
+ readonly anchor: LineageAnchor;
51
+ /** The decline candidates (deliveries) this Add admitted — each delivery of the Add with this anchor. */
52
+ readonly candidateIds: readonly string[];
53
+ /**
54
+ * The occupancy at a node of the selected path. Seeded at the Add node itself (occupying, `transition`); moved only
55
+ * to a new window root, inside `recordTransition`'s transaction. Absent: the Add node is the only evidence.
56
+ */
57
+ readonly checkpoint?: LineageCheckpoint;
58
+ }
59
+ /** The record key of `anchor`. */
60
+ export declare function lineageKey(anchor: Pick<LineageAnchor, 'addDigest' | 'leafIndex'>): string;
61
+ /** The record an own Add confirmation seeds: the Add node (at `addEpoch`) is its checkpoint, occupying. */
62
+ export declare function seedLineage(anchor: LineageAnchor, candidateIds: readonly string[], addEpoch: number): AdmissionLineageRecord;
63
+ /**
64
+ * `stored` with `seed`'s candidates merged in, or `seed` when nothing is stored. A stored record keeps its checkpoint
65
+ * (idempotent: a re-run confirmation never moves an advanced checkpoint back to the Add). `undefined` when `stored`
66
+ * already holds every candidate (nothing to write).
67
+ */
68
+ export declare function mergeSeed(stored: AdmissionLineageRecord | undefined, seed: AdmissionLineageRecord): AdmissionLineageRecord | undefined;
69
+ /** One link of the selected path: the commit from `parent` to `child`, as the window holds it. */
70
+ export interface LineageLink {
71
+ /** The child node (its `commit`, `digest`). */
72
+ readonly node: WindowNode;
73
+ /** The parent's state (the commit was built from it: its staged proposals, its own leaf). */
74
+ parentState(): ClientState | undefined;
75
+ /** The child's state (the commit's result). */
76
+ childState(): ClientState | undefined;
77
+ }
78
+ /** Hex signature key of the leaf at `leafIndex` of `state`, or `undefined` when the leaf is blank (or out of range). */
79
+ export declare function leafKeyAt(state: ClientState, leafIndex: number): string | undefined;
80
+ /**
81
+ * I10: the occupancy after one commit of the selected path. Only an `occupying` admission moves; every other
82
+ * occupancy is final for the walk. The commit must be a framed PublicMessage commit whose digest matches its stored
83
+ * one, every proposal reference must resolve against the parent's staged proposals, and both states must be at hand
84
+ * — otherwise `gap` (`undecodable-commit`). A Remove of the position (inline, by reference, or the leaf's own
85
+ * `self_remove`) ends it: `by-reference` when any such Remove came by reference, `replaced` when the same commit put
86
+ * a leaf back at the position, else `inline-remove`; `committerOwn` when this device committed it. Otherwise the leaf
87
+ * must still be there, and a changed signature key needs an Update by the leaf or the leaf's own commit (a path
88
+ * succession) — a leaf that changes or vanishes any other way is a `gap`. Never throws.
89
+ */
90
+ export declare function admissionStep(occupancy: LineageOccupancy, link: LineageLink, leafIndex: number): LineageOccupancy;
91
+ /** What the selected path of a window proves about one admission. */
92
+ export interface AdmissionDerivation {
93
+ readonly occupancy: LineageOccupancy;
94
+ /** `snapshot` when the proof starts at a checkpoint an imported snapshot supplied (never settled until re-proven). */
95
+ readonly provenance: LineageProvenance;
96
+ /** The node the derivation reached (the window's tip, or `upTo`). */
97
+ readonly at: {
98
+ readonly tag: string;
99
+ readonly epoch: number;
100
+ };
101
+ /**
102
+ * For an `ended` occupancy whose ending commit is still on the derived path: how many commits follow it there.
103
+ * Absent when the end was carried by a checkpoint (its commit already left the window).
104
+ */
105
+ readonly endedDepth?: number;
106
+ }
107
+ /** A cache of the window's deserialized states (the tip is `tipState`), shared by every derivation over that window. */
108
+ export type StateResolver = (node: WindowNode) => ClientState | undefined;
109
+ export declare function stateResolver(window: RetainedWindow, tipState: ClientState | undefined): StateResolver;
110
+ /**
111
+ * The occupancy of `record`'s admission at the tip of `window`'s selected path (`tipState` is the tip's state, the
112
+ * stored `clientState`), or at the path node `upTo`. The proof starts at the Add node when it is on the path, else at
113
+ * the checkpoint when its node is on the path (same epoch), and walks every later commit with {@link admissionStep}.
114
+ *
115
+ * - The Add node is in the window but off the path, or the record only holds its seed (the Add node itself) and the
116
+ * path covers the Add's epoch with another node or ends below it: `add-off-path` (the Add may return to the path).
117
+ * - Neither the Add nor the checkpoint is on the path otherwise: `gap` (`unprovable-root`) — fail closed (I12).
118
+ * - The start state must hold the admission's leaf at its position under the recorded key, and a derivation ending
119
+ * `occupying` must find that leaf on the end state; otherwise `gap`.
120
+ * - A proof that starts at an `occupying` checkpoint of `snapshot` provenance is re-checked against the window as a
121
+ * restore validates it (`snapshotCheckpointHolds`); one the window refutes is a `gap` (`restore`).
122
+ */
123
+ export declare function deriveAdmission(record: Pick<AdmissionLineageRecord, 'anchor' | 'checkpoint'>, window: RetainedWindow, tipState: ClientState | undefined, upTo?: string): AdmissionDerivation;
124
+ /**
125
+ * One window holding every node of `windows`, tip `tipTag`. A node several windows hold keeps the version with a
126
+ * parent link (a window's root is stored without one) and with a snapshot when one has it.
127
+ */
128
+ export declare function mergeWindows(tipTag: string, windows: readonly RetainedWindow[]): RetainedWindow;
129
+ /** The root of `window`'s selected path. */
130
+ export declare function windowRootOf(window: RetainedWindow): WindowNode | undefined;
131
+ /**
132
+ * I11: `record` with its checkpoint moved to the root of `after` (the window a transition persists, whose tip state is
133
+ * `afterTip`), or `undefined` when it needs no move. A move is needed only when `after` alone no longer proves what
134
+ * the record proved — neither its Add nor its checkpoint is left on `after`'s path, and `after`'s root is not already
135
+ * the checkpoint. The occupancy at the new root is derived over every node the transition saw (`before`, the window
136
+ * it diffed against, and `after`), starting where the record's proof starts. What cannot be bridged becomes a `gap`
137
+ * checkpoint at the new root: `switch` when the new path shares no node with `before` (a branch switch), else
138
+ * `unprovable-root`. A checkpoint derived from a snapshot-supplied checkpoint keeps `snapshot` provenance.
139
+ */
140
+ export declare function advanceLineage(record: AdmissionLineageRecord, windows: {
141
+ readonly before: RetainedWindow;
142
+ readonly diff?: RetainedWindow;
143
+ readonly after: RetainedWindow;
144
+ }, afterTip: ClientState | undefined): AdmissionLineageRecord | undefined;
145
+ /**
146
+ * The lineage a restore adopts from a snapshot's `records`, validated against the snapshot's own selected path
147
+ * (`window`, tip state `tipState`). A record whose Add is on that path is kept (the window proves it). A record whose
148
+ * checkpoint names a node of that path at its epoch is kept with `snapshot` provenance when the window cannot refute
149
+ * it — for an `occupying` checkpoint: the Add is nowhere in the window, and the position's occupant is carried from
150
+ * the window's root to that node, without a Remove or an unprovable link, under the claimed key
151
+ * ({@link snapshotCheckpointHolds}). Every other record gets a `gap` (`restore`) checkpoint at the window's root:
152
+ * insufficient evidence until a transition re-proves it from the Add. A record of a duplicate key keeps its first
153
+ * occurrence.
154
+ */
155
+ export declare function validateRestoredLineage(records: readonly AdmissionLineageRecord[], window: RetainedWindow, tipState: ClientState): AdmissionLineageRecord[];
156
+ /** Decodes one stored (or snapshot-carried) record strictly: anything else throws a malformed-row error. */
157
+ export declare function decodeLineageRecord(where: string, raw: unknown): AdmissionLineageRecord;
158
+ export declare function encodeLineageRecord(record: AdmissionLineageRecord): Storable;
159
+ /**
160
+ * Every decodable record of the extension view. A row that does not open or decode is skipped — no record is no
161
+ * evidence, so the admission it described reads as a gap (fail closed); any other read error propagates.
162
+ */
163
+ export declare function readLineageRecords(view: KeyValueView): Promise<AdmissionLineageRecord[]>;
164
+ /** The record at `key`, `undefined` when absent or malformed (envelope or payload); other read errors propagate. */
165
+ export declare function readLineageRecord(view: KeyValueView, key: string): Promise<AdmissionLineageRecord | undefined>;
166
+ export declare function writeLineageRecord(view: KeyValueView, record: AdmissionLineageRecord): Promise<void>;
167
+ /**
168
+ * Seeds the lineage of the anchors an own Add commit confirmed (in the confirmation's group transaction):
169
+ * `anchors` maps each anchor to the candidates it admitted; `addEpoch` is the epoch of the Add's state.
170
+ * Idempotent: a re-run confirmation only merges candidates into a stored record and never moves its checkpoint.
171
+ */
172
+ export declare function seedLineageRecords(view: KeyValueView, anchors: ReadonlyMap<string, {
173
+ readonly anchor: LineageAnchor;
174
+ readonly candidateIds: readonly string[];
175
+ }>, addEpoch: number): Promise<void>;
176
+ /**
177
+ * I11, the shell: moves every stored record's checkpoint the transition needs moved ({@link advanceLineage}), in the
178
+ * transition's own transaction. Records that need no move are not rewritten.
179
+ */
180
+ export declare function advanceLineageRecords(view: KeyValueView, windows: {
181
+ readonly before: RetainedWindow;
182
+ readonly diff?: RetainedWindow;
183
+ readonly after: RetainedWindow;
184
+ }, afterTip: ClientState | undefined): Promise<void>;
185
+ /** Replaces the extension's records with `records` (a restore's adoption, inside its transaction). */
186
+ export declare function replaceLineageRecords(view: KeyValueView, records: readonly AdmissionLineageRecord[]): Promise<void>;