@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,50 @@
1
+ /**
2
+ * `invitations.outcome(id)` (epic marmot-invitation-outcomes S2; ADR-019 D9, D10; architecture SC-8, SC-9).
3
+ *
4
+ * The read classifies ONE instant of durable state:
5
+ *
6
+ * 1. the entry guard ({@link assertRecoveryReadAllowed}) refuses, synchronously and before anything is queued, a call
7
+ * made from a frame whose queue the read would wait on (a hook or a consumer group store call inside the
8
+ * adoption's own group transaction, an inbox handler on the inbox queue, any account-scope consumer surface) — it
9
+ * would deadlock, not read;
10
+ * 2. the read runs on the inbox's serial queue, where every adopting call runs (`accept`, a Welcome's dispatch,
11
+ * `completeStuckJoins`): it never observes the inside of an adoption call. It works with the inbox never started;
12
+ * 3. a read-only GROUP transaction on the record's group holds that group's store queue (no adoption, switch or
13
+ * teardown clear runs meanwhile) while it reads the adoption proofs and awaits a read-only ACCOUNT transaction
14
+ * that reads the record, the index entry and the group's stamps (group → account, the lock order). Both
15
+ * transactions are write-free and re-assert the lease when they settle (`no-lease` once it is lost).
16
+ *
17
+ * A record that names another group inside the account transaction than the routing read saw is read again once;
18
+ * a second move rejects `store-failed`.
19
+ */
20
+ import { type InvitationOutcome } from '../invitations/index.js';
21
+ import type { AccountStore, GroupStore } from '../storage/index.js';
22
+ import { type ConsumerSurface, type ReentrancyGuard } from './reentrancy-guard.js';
23
+ /** The inbox-queue consumer surfaces (any scope). */
24
+ export declare const RECOVERY_READ_INBOX_SURFACES: readonly ConsumerSurface[];
25
+ /**
26
+ * SC-9's entry guard, evaluated synchronously: throws `reentrant` (`details: { scope, operation, surface }`) when the
27
+ * calling code runs inside any live account-scope frame, inside a group-scope frame of one of
28
+ * {@link GROUP_CONSUMER_SURFACES} (when `groupSurfaces`: they run inside the group operation the read would queue
29
+ * behind), inside a group-scope `store` frame (when `groupStores`: a consumer group store servicing an adoption's group
30
+ * transaction runs inside the inbox task the read would queue behind), or inside an inbox handler or
31
+ * `onApplicationRumor` frame of any scope (when `inboxSurfaces`).
32
+ */
33
+ export declare function assertRecoveryReadAllowed(guard: ReentrancyGuard, operation: string, refusals: {
34
+ readonly groupSurfaces: boolean;
35
+ readonly inboxSurfaces: boolean;
36
+ readonly groupStores?: boolean;
37
+ }): void;
38
+ export interface InvitationOutcomeReaderDeps {
39
+ readonly guard: ReentrancyGuard;
40
+ /** The inbox's serial queue (`inbox.serialize`): usable before `inbox.start()`. */
41
+ serialize<T>(task: () => Promise<T>): Promise<T>;
42
+ readonly account: AccountStore;
43
+ /** The group's store (the same object for the same id: `WritableStores.groupFactory`). */
44
+ groupStore(groupId: string): GroupStore;
45
+ }
46
+ /**
47
+ * `invitations.outcome(id)`. The guard and the id check run synchronously: the returned promise is already rejected
48
+ * for a refused or invalid call, before anything was queued.
49
+ */
50
+ export declare function readInvitationOutcome(deps: InvitationOutcomeReaderDeps, id: unknown): Promise<InvitationOutcome>;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * `invitations.outcome(id)` (epic marmot-invitation-outcomes S2; ADR-019 D9, D10; architecture SC-8, SC-9).
3
+ *
4
+ * The read classifies ONE instant of durable state:
5
+ *
6
+ * 1. the entry guard ({@link assertRecoveryReadAllowed}) refuses, synchronously and before anything is queued, a call
7
+ * made from a frame whose queue the read would wait on (a hook or a consumer group store call inside the
8
+ * adoption's own group transaction, an inbox handler on the inbox queue, any account-scope consumer surface) — it
9
+ * would deadlock, not read;
10
+ * 2. the read runs on the inbox's serial queue, where every adopting call runs (`accept`, a Welcome's dispatch,
11
+ * `completeStuckJoins`): it never observes the inside of an adoption call. It works with the inbox never started;
12
+ * 3. a read-only GROUP transaction on the record's group holds that group's store queue (no adoption, switch or
13
+ * teardown clear runs meanwhile) while it reads the adoption proofs and awaits a read-only ACCOUNT transaction
14
+ * that reads the record, the index entry and the group's stamps (group → account, the lock order). Both
15
+ * transactions are write-free and re-assert the lease when they settle (`no-lease` once it is lost).
16
+ *
17
+ * A record that names another group inside the account transaction than the routing read saw is read again once;
18
+ * a second move rejects `store-failed`.
19
+ */
20
+ import { classifyInvitationOutcome, decodeInvitation, groupInvitationRecords, indexEntryView, outcomeReadsGroupStamps, stampsOf, } from '../invitations/index.js';
21
+ import { isMalformedRowError, isMarmotError, MarmotError } from '../shared/index.js';
22
+ import { readAdoptionProofs } from './adoption-proof.js';
23
+ import { GROUP_INDEX_EXTENSION } from './group-records.js';
24
+ import { ACCOUNT_SCOPE, GROUP_CONSUMER_SURFACES } from './reentrancy-guard.js';
25
+ /** The inbox-queue consumer surfaces (any scope). */
26
+ export const RECOVERY_READ_INBOX_SURFACES = ['inboxHandler', 'onApplicationRumor'];
27
+ function refuse(operation, scope, surface) {
28
+ return new MarmotError('reentrant', `${operation}: re-entrant call from inside ${surface} (scope ${JSON.stringify(scope)}); read it from an event listener instead`, {
29
+ details: { scope, operation, surface },
30
+ });
31
+ }
32
+ /**
33
+ * SC-9's entry guard, evaluated synchronously: throws `reentrant` (`details: { scope, operation, surface }`) when the
34
+ * calling code runs inside any live account-scope frame, inside a group-scope frame of one of
35
+ * {@link GROUP_CONSUMER_SURFACES} (when `groupSurfaces`: they run inside the group operation the read would queue
36
+ * behind), inside a group-scope `store` frame (when `groupStores`: a consumer group store servicing an adoption's group
37
+ * transaction runs inside the inbox task the read would queue behind), or inside an inbox handler or
38
+ * `onApplicationRumor` frame of any scope (when `inboxSurfaces`).
39
+ */
40
+ export function assertRecoveryReadAllowed(guard, operation, refusals) {
41
+ guard.assertNotReentrant(ACCOUNT_SCOPE, operation);
42
+ if (refusals.groupSurfaces) {
43
+ for (const surface of GROUP_CONSUMER_SURFACES) {
44
+ const frame = guard.withinGroupScope(surface);
45
+ if (frame !== undefined)
46
+ throw refuse(operation, frame.scope, surface);
47
+ }
48
+ }
49
+ if (refusals.groupStores === true) {
50
+ const frame = guard.withinGroupScope('store');
51
+ if (frame !== undefined)
52
+ throw refuse(operation, frame.scope, 'store');
53
+ }
54
+ if (refusals.inboxSurfaces) {
55
+ for (const surface of RECOVERY_READ_INBOX_SURFACES) {
56
+ const frame = guard.within(undefined, surface);
57
+ if (frame !== undefined)
58
+ throw refuse(operation, frame.scope, surface);
59
+ }
60
+ }
61
+ }
62
+ const OPERATION = 'invitations.outcome';
63
+ const RETRY = Symbol('retry');
64
+ /** The record's group as a store-level read sees it (routing only: the classification re-reads it in its transaction). */
65
+ function routingGroupOf(raw) {
66
+ const groupId = typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? raw.groupId : undefined;
67
+ return typeof groupId === 'string' && groupId.length > 0 ? groupId : undefined;
68
+ }
69
+ /**
70
+ * Reads the target record's stored value strictly (SC-7 row 12). An envelope that does not open is the same fact as a
71
+ * payload `decodeInvitation` refuses — the record is unreadable as data — so it rejects as that one documented error,
72
+ * `store-failed` with `details: { id, malformed: true }`. A version mismatch, a backend failure or a lost lease
73
+ * propagates unchanged.
74
+ */
75
+ async function readTargetRow(view, id) {
76
+ try {
77
+ return await view.get(id);
78
+ }
79
+ catch (error) {
80
+ if (isMarmotError(error, 'envelope-mismatch') && isMalformedRowError(error)) {
81
+ throw new MarmotError('store-failed', `pendingInvitations/${id}: malformed record (envelope)`, { cause: error, details: { id, malformed: true } });
82
+ }
83
+ throw error;
84
+ }
85
+ }
86
+ /**
87
+ * `invitations.outcome(id)`. The guard and the id check run synchronously: the returned promise is already rejected
88
+ * for a refused or invalid call, before anything was queued.
89
+ */
90
+ export function readInvitationOutcome(deps, id) {
91
+ try {
92
+ assertRecoveryReadAllowed(deps.guard, OPERATION, { groupSurfaces: true, inboxSurfaces: true, groupStores: true });
93
+ }
94
+ catch (error) {
95
+ return Promise.reject(error);
96
+ }
97
+ if (typeof id !== 'string' || id.length === 0) {
98
+ return Promise.reject(new MarmotError('invalid-options', `${OPERATION}: id must be a non-empty string`, { details: { reason: 'invalid-id' } }));
99
+ }
100
+ const { guard, account } = deps;
101
+ /** The account half: read-only, one instant; `RETRY` when the record names another group than `groupId`. */
102
+ const classifyIn = (groupId, proofs) => guard.call(ACCOUNT_SCOPE, 'store', () => account.transaction(async (atx) => {
103
+ const raw = await readTargetRow(atx.artifact('pendingInvitations'), id);
104
+ const record = raw === undefined ? undefined : decodeInvitation(id, raw);
105
+ if (record?.groupId !== groupId)
106
+ return RETRY;
107
+ if (groupId === undefined)
108
+ return classifyInvitationOutcome({ record, groupProofs: 'no-group', indexEntry: undefined, groupStamps: new Map() });
109
+ const indexEntry = indexEntryView(groupId, await atx.extension(GROUP_INDEX_EXTENSION).get(groupId));
110
+ // The sibling stamps need a scan of every account invitation, done only when the classification reads them
111
+ // (rule 3): a record its own stamp, an exact proof or its status decides is classified without the scan.
112
+ const known = { record, groupProofs: proofs, indexEntry };
113
+ const groupStamps = outcomeReadsGroupStamps(known) ? stampsOf(await groupInvitationRecords(atx, groupId)) : new Map();
114
+ return classifyInvitationOutcome({ ...known, groupStamps });
115
+ }));
116
+ return deps.serialize(async () => {
117
+ for (let attempt = 0; attempt < 2; attempt++) {
118
+ const routed = routingGroupOf(await guard.call(ACCOUNT_SCOPE, 'store', () => readTargetRow(account.artifact('pendingInvitations'), id)));
119
+ let result;
120
+ if (routed === undefined) {
121
+ result = await classifyIn(undefined, 'no-group');
122
+ }
123
+ else {
124
+ const store = deps.groupStore(routed);
125
+ result = await guard.call(routed, 'store', () => store.transaction(async (gtx) => {
126
+ const proofs = await readAdoptionProofs(gtx);
127
+ return classifyIn(routed, proofs);
128
+ }));
129
+ }
130
+ if (result !== RETRY)
131
+ return result;
132
+ }
133
+ throw new MarmotError('store-failed', `${OPERATION}: invitation record ${id} moved between groups while it was read`, { details: { id } });
134
+ });
135
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Lifecycle events (S7, AC-INBOX-6): `enrolmentApproved`, `deviceForgotten`
3
+ * and `groupCreated` — and, since epic marmot-device-key-rotation, `deviceKeyRotated`
4
+ * and `deviceKeyRotationSettled` — fire only AFTER the transaction(s) that made them true
5
+ * committed — never before, never for an operation whose commit failed.
6
+ *
7
+ * The discipline is structural: an operation hands its committing step to
8
+ * {@link LifecycleEvents.afterCommit}, which awaits it and emits with the
9
+ * payload built from its result. There is no other emit path for any
10
+ * `LifecycleEventPayloads` member inside the client (`groups.create` uses it since S7; same-account
11
+ * enrolment approval and `devices.forget` (S8) call it the same way).
12
+ *
13
+ * Payloads are frozen copies: a listener cannot mutate what the operation
14
+ * still holds (the `groups` arrays in particular). Listener errors never
15
+ * reach the operation (the client's `emit` swallows them).
16
+ */
17
+ import type { DeviceKeyRotationGroupOutcome } from '../key-packages/index.js';
18
+ export interface LifecycleEventPayloads {
19
+ /** A sibling device's enrolment was approved and committed (S8). */
20
+ enrolmentApproved: {
21
+ readonly account: string;
22
+ readonly leafIndex: number;
23
+ readonly leafKey: string;
24
+ readonly groups: readonly string[];
25
+ };
26
+ /** A device (leaf) was forgotten; `groups` still holding the leaf, if any (S8, AC-DEV-7). */
27
+ deviceForgotten: {
28
+ readonly leafKey: string;
29
+ readonly groups: readonly string[];
30
+ };
31
+ /** A group was created and persisted (its state and its account index entry). */
32
+ groupCreated: {
33
+ readonly groupId: string;
34
+ };
35
+ /**
36
+ * `devices.rotateKey()` committed its prepare transaction (epic marmot-device-key-rotation, S7, AC-ROT-8): `to` is now the
37
+ * device key, `from` the keys it replaces and `groups` the held groups whose own leaf the rotation re-keys. Fires once per
38
+ * rotation, never for one whose prepare failed, and — like `deviceForgotten` — at most once: a crash between the commit and
39
+ * the emit loses it, so a consumer must not depend on it for correctness.
40
+ */
41
+ deviceKeyRotated: {
42
+ readonly rotationId: string;
43
+ readonly from: readonly string[];
44
+ readonly to: string;
45
+ readonly groups: readonly string[];
46
+ };
47
+ /** Every group of a rotation reached a terminal outcome and the rotation was recorded settled (or given up); fires once per rotation. */
48
+ deviceKeyRotationSettled: {
49
+ readonly rotationId: string;
50
+ readonly perGroupOutcome: Readonly<Record<string, DeviceKeyRotationGroupOutcome>>;
51
+ };
52
+ }
53
+ export type LifecycleEventName = keyof LifecycleEventPayloads;
54
+ export interface LifecycleEvents {
55
+ /**
56
+ * Runs `commit` — the operation's committing step (its store
57
+ * transaction(s)) — and, once it resolved, emits `event` with
58
+ * `payload(result)`. A rejected `commit` emits nothing and rejects with
59
+ * its error. Resolves with `commit`'s result after the emit.
60
+ */
61
+ afterCommit<E extends LifecycleEventName, T>(event: E, commit: () => Promise<T>, payload: (result: T) => LifecycleEventPayloads[E]): Promise<T>;
62
+ }
63
+ export declare function createLifecycleEvents(emit: <E extends LifecycleEventName>(event: E, payload: LifecycleEventPayloads[E]) => void): LifecycleEvents;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Lifecycle events (S7, AC-INBOX-6): `enrolmentApproved`, `deviceForgotten`
3
+ * and `groupCreated` — and, since epic marmot-device-key-rotation, `deviceKeyRotated`
4
+ * and `deviceKeyRotationSettled` — fire only AFTER the transaction(s) that made them true
5
+ * committed — never before, never for an operation whose commit failed.
6
+ *
7
+ * The discipline is structural: an operation hands its committing step to
8
+ * {@link LifecycleEvents.afterCommit}, which awaits it and emits with the
9
+ * payload built from its result. There is no other emit path for any
10
+ * `LifecycleEventPayloads` member inside the client (`groups.create` uses it since S7; same-account
11
+ * enrolment approval and `devices.forget` (S8) call it the same way).
12
+ *
13
+ * Payloads are frozen copies: a listener cannot mutate what the operation
14
+ * still holds (the `groups` arrays in particular). Listener errors never
15
+ * reach the operation (the client's `emit` swallows them).
16
+ */
17
+ function frozenPayload(payload) {
18
+ const copy = { ...payload };
19
+ if (Array.isArray(copy.groups))
20
+ copy.groups = Object.freeze([...copy.groups]);
21
+ if (Array.isArray(copy.from))
22
+ copy.from = Object.freeze([...copy.from]);
23
+ if (typeof copy.perGroupOutcome === 'object' && copy.perGroupOutcome !== null)
24
+ copy.perGroupOutcome = Object.freeze({ ...copy.perGroupOutcome });
25
+ return Object.freeze(copy);
26
+ }
27
+ export function createLifecycleEvents(emit) {
28
+ return {
29
+ async afterCommit(event, commit, payload) {
30
+ const result = await commit();
31
+ emit(event, frozenPayload(payload(result)));
32
+ return result;
33
+ },
34
+ };
35
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Epic `marmot-branch-aware-own-leaf-fence` S8 (AC-PERS-1, AC-PERS-6, AC-PERS-11..13): the engine's held opaque
3
+ * candidates and its undecryptable set `U`, persisted.
4
+ *
5
+ * The engine (`MarmotGroupEngine.opaque`) holds every opaque candidate it judged `skipped` — a commit that
6
+ * authenticated at a node of the history tree but failed with the lost-path-secrets error — together with its
7
+ * ORIGINAL envelope, and decides it again on every convergence pass: a later pass may find that it could win, and
8
+ * then the group is fenced with that envelope. A `skipped` is therefore provisional, and only as durable as the
9
+ * record that holds it. The record is the group extension `marmot.opaque`, written in the SAME transaction as the
10
+ * batch that ledgers the provisional `skipped` (client/ingest.ts) — never before, never after — and handed back to
11
+ * every engine of the group on load, reload and rollback (client/group-runtime.ts), exactly as `marmot.removal` is.
12
+ *
13
+ * What is stored is the engine's record VERBATIM (`HeldOpaqueRecord<NostrEvent>`): the candidates (digest, parent
14
+ * tag, epoch, sender, error message, the full Nostr event the engine was handed) and `U`. The event comes back
15
+ * field for field because the `unreadable` the engine yields later carries it and the client fences and ledgers
16
+ * by it. `U` is persisted with the candidates: a rebuilt engine that lost it would undercount hidden edges and
17
+ * could skip a commit that should fence.
18
+ *
19
+ * Fail closed. The extension is read from a store, so its bytes are untrusted: a record of the wrong shape,
20
+ * with more than {@link MAX_HELD_OPAQUE_CANDIDATES} candidates, with a non-hex digest or a malformed event is
21
+ * CORRUPT. {@link readOpaque} throws {@link OpaqueRecordCorrupt} for it, and the caller (the group's load and
22
+ * reload) FENCES the group: reading it as "nothing held" would forget a candidate that may still be able to win
23
+ * (the unsafe direction), and handing it on would make the engine's constructor throw a `TypeError` and brick the
24
+ * load for good. A fenced group stays loadable, refuses to send and never processes input. An ABSENT extension is
25
+ * the empty record, not corruption.
26
+ *
27
+ * Size and write amplification (BACKLOG engine-undecryptable-set-unbounded; measured in
28
+ * `test/client/opaque-persistence.test.ts`, "record size and write amplification"):
29
+ * - The candidates are capped by the engine (16). An event is the Nostr envelope of one MLS commit: a few KiB.
30
+ * - `U` is bounded by the engine's cap (`MAX_UNDECRYPTABLE_IDS`, 1,024 ids: at most about 69 KB). One id is 64 hex
31
+ * characters, 67 bytes with its quotes and comma in the stored JSON. The id that would exceed the cap SATURATES
32
+ * `U`: the engine drops every id and the record carries one flag, `undecryptableSaturated` (about 30 bytes), which
33
+ * the engine reads as an unbounded count, so every opaque candidate fences (today's behaviour). That is the only
34
+ * safe direction: dropping an id and keeping a count would undercount hidden edges (a junk flood could then turn
35
+ * a fence into a skip). Saturation is sticky — a dropped id can no longer be told to have decrypted — and is
36
+ * persisted and restored like the ids it replaces. A record with ids and the flag is read as saturated.
37
+ * - The record is one value, so a change rewrites all of it: a batch that adds ids writes `|record|` bytes once,
38
+ * however many events it carried; `n` junk envelopes delivered in `n` separate batches write it `n` times
39
+ * (about `34 * n^2` bytes in total for ids alone, `n` at most the cap, then nothing). A batch that changed
40
+ * neither the candidates nor `U` writes nothing ({@link nextOpaque}). Sharding `U` per id would make growth
41
+ * O(delta); the cap makes it bounded instead.
42
+ */
43
+ import type { HeldOpaqueRecord } from '@941design/marmot-engine/engine';
44
+ import type { NostrEvent } from '@941design/nostr-events/event';
45
+ import type { KeyValueView } from '../storage/index.js';
46
+ import { InvalidStoredEvidenceError } from '../history/fencing.js';
47
+ /** Group extension holding the opaque record (one value). */
48
+ export declare const OPAQUE_EXTENSION = "marmot.opaque";
49
+ /** The engine's record, as the client persists it. */
50
+ export type OpaqueRecord = HeldOpaqueRecord<NostrEvent>;
51
+ /** What an absent extension reads as. */
52
+ export declare const EMPTY_OPAQUE: OpaqueRecord;
53
+ /** The stored `marmot.opaque` record is not a valid engine record: the group cannot be known safe (see the module comment). */
54
+ export declare class OpaqueRecordCorrupt extends InvalidStoredEvidenceError {
55
+ readonly reason: string;
56
+ readonly name = "OpaqueRecordCorrupt";
57
+ constructor(reason: string);
58
+ }
59
+ /** Whether `record` holds nothing (the engine exposes that as `undefined`). */
60
+ export declare function isEmptyOpaque(record: OpaqueRecord | undefined): boolean;
61
+ /**
62
+ * Validates a stored value as an engine record. Throws {@link OpaqueRecordCorrupt}; never returns a partial record.
63
+ * Exported for the tests that feed it malformed shapes.
64
+ */
65
+ export declare function parseOpaque(raw: unknown): OpaqueRecord;
66
+ /**
67
+ * The group's stored record; the empty record while the extension holds none. Throws {@link OpaqueRecordCorrupt}
68
+ * for a value that is not a valid record.
69
+ */
70
+ export declare function readOpaque(view: KeyValueView): Promise<OpaqueRecord>;
71
+ /** Writes (or replaces) the record inside the caller's transaction. */
72
+ export declare function writeOpaque(view: KeyValueView, record: OpaqueRecord): Promise<void>;
73
+ export declare function clearOpaque(view: KeyValueView): Promise<void>;
74
+ /** Whether two records hold the same candidates (field for field, the event by id and signature) and the same `U`. */
75
+ export declare function sameOpaque(a: OpaqueRecord | undefined, b: OpaqueRecord | undefined): boolean;
76
+ /**
77
+ * What to persist after the engine's record moved from `before` (the stored one, `undefined` = none) to `now`
78
+ * (`engine.opaque`): `undefined` = unchanged (nothing to write — the engine returns the same object while neither
79
+ * the held set nor `U` changed, and a rebuilt engine's equal record is recognised by content), `null` = it became
80
+ * empty (delete), else the new record. A change of `U` alone is a change.
81
+ */
82
+ export declare function nextOpaque(before: OpaqueRecord | undefined, now: OpaqueRecord | undefined): OpaqueRecord | null | undefined;
@@ -0,0 +1,170 @@
1
+ import { MAX_HELD_OPAQUE_CANDIDATES } from '@941design/marmot-engine/engine';
2
+ import { InvalidStoredEvidenceError } from '../history/fencing.js';
3
+ /** Group extension holding the opaque record (one value). */
4
+ export const OPAQUE_EXTENSION = 'marmot.opaque';
5
+ const KEY = 'opaque';
6
+ /** The longest `U` id accepted on read (event ids are 64 hex characters; the margin keeps any transport's id form). */
7
+ const MAX_ID_LENGTH = 128;
8
+ /** What an absent extension reads as. */
9
+ export const EMPTY_OPAQUE = Object.freeze({ candidates: Object.freeze([]), undecryptableIds: Object.freeze([]) });
10
+ /** The stored `marmot.opaque` record is not a valid engine record: the group cannot be known safe (see the module comment). */
11
+ export class OpaqueRecordCorrupt extends InvalidStoredEvidenceError {
12
+ reason;
13
+ name = 'OpaqueRecordCorrupt';
14
+ constructor(reason) {
15
+ super(`marmot.opaque is corrupt: ${reason}`);
16
+ this.reason = reason;
17
+ }
18
+ }
19
+ /** Whether `record` holds nothing (the engine exposes that as `undefined`). */
20
+ export function isEmptyOpaque(record) {
21
+ return record === undefined || (record.candidates.length === 0 && record.undecryptableIds.length === 0 && record.undecryptableSaturated !== true);
22
+ }
23
+ const isHex = (value, length) => typeof value === 'string' && /^(?:[0-9a-f]{2})+$/.test(value) && (length === undefined || value.length === length);
24
+ const isCount = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
25
+ function eventOf(raw) {
26
+ const corrupt = (what) => {
27
+ throw new OpaqueRecordCorrupt(`a candidate's event ${what}`);
28
+ };
29
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
30
+ return corrupt('is not an object');
31
+ const e = raw;
32
+ if (typeof e.id !== 'string' || e.id.length === 0 || e.id.length > MAX_ID_LENGTH)
33
+ return corrupt('has no id');
34
+ if (typeof e.pubkey !== 'string')
35
+ return corrupt('has no pubkey');
36
+ if (!isCount(e.kind))
37
+ return corrupt('has no kind');
38
+ if (!isCount(e.created_at))
39
+ return corrupt('has no created_at');
40
+ if (typeof e.content !== 'string')
41
+ return corrupt('has no content');
42
+ if (typeof e.sig !== 'string')
43
+ return corrupt('has no sig');
44
+ if (!Array.isArray(e.tags) || !e.tags.every((t) => Array.isArray(t) && t.every((x) => typeof x === 'string')))
45
+ return corrupt('has malformed tags');
46
+ return e;
47
+ }
48
+ function candidateOf(raw) {
49
+ const corrupt = (what) => {
50
+ throw new OpaqueRecordCorrupt(`a candidate ${what}`);
51
+ };
52
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
53
+ return corrupt('is not an object');
54
+ const c = raw;
55
+ if (!isHex(c.digest, 64))
56
+ return corrupt('digest is not 32-byte hex');
57
+ if (!isHex(c.parentTag))
58
+ return corrupt('parent tag is not hex');
59
+ if (!isCount(c.epoch))
60
+ return corrupt('epoch is not a non-negative integer');
61
+ if (c.sender !== undefined && !isCount(c.sender))
62
+ return corrupt('sender is not a non-negative integer');
63
+ if (typeof c.errorMessage !== 'string')
64
+ return corrupt('error message is not a string');
65
+ if (c.decided !== undefined && c.decided !== 'fenced')
66
+ return corrupt('decided mark is unknown');
67
+ const event = eventOf(c.event);
68
+ return {
69
+ digest: c.digest,
70
+ parentTag: c.parentTag,
71
+ epoch: c.epoch,
72
+ ...(c.sender === undefined ? {} : { sender: c.sender }),
73
+ errorMessage: c.errorMessage,
74
+ event,
75
+ ...(c.decided === undefined ? {} : { decided: 'fenced' }),
76
+ };
77
+ }
78
+ /**
79
+ * Validates a stored value as an engine record. Throws {@link OpaqueRecordCorrupt}; never returns a partial record.
80
+ * Exported for the tests that feed it malformed shapes.
81
+ */
82
+ export function parseOpaque(raw) {
83
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
84
+ throw new OpaqueRecordCorrupt('not a record');
85
+ const r = raw;
86
+ if (!Array.isArray(r.candidates))
87
+ throw new OpaqueRecordCorrupt('candidates is not a list');
88
+ if (!Array.isArray(r.undecryptableIds))
89
+ throw new OpaqueRecordCorrupt('undecryptableIds is not a list');
90
+ // Present only as `true`: a flag that is anything else is not read as "unsaturated" (the unsafe direction).
91
+ if (r.undecryptableSaturated !== undefined && r.undecryptableSaturated !== true)
92
+ throw new OpaqueRecordCorrupt('undecryptableSaturated is not true');
93
+ if (r.candidates.length > MAX_HELD_OPAQUE_CANDIDATES)
94
+ throw new OpaqueRecordCorrupt(`more than ${String(MAX_HELD_OPAQUE_CANDIDATES)} candidates (${String(r.candidates.length)})`);
95
+ const candidates = r.candidates.map(candidateOf);
96
+ if (new Set(candidates.map((c) => c.digest)).size !== candidates.length)
97
+ throw new OpaqueRecordCorrupt('two candidates share a digest');
98
+ const ids = [];
99
+ for (const id of r.undecryptableIds) {
100
+ if (typeof id !== 'string' || id.length === 0 || id.length > MAX_ID_LENGTH)
101
+ throw new OpaqueRecordCorrupt('an undecryptable id is not a short non-empty string');
102
+ ids.push(id);
103
+ }
104
+ return { candidates, undecryptableIds: ids, ...(r.undecryptableSaturated === true ? { undecryptableSaturated: true } : {}) };
105
+ }
106
+ /**
107
+ * The group's stored record; the empty record while the extension holds none. Throws {@link OpaqueRecordCorrupt}
108
+ * for a value that is not a valid record.
109
+ */
110
+ export async function readOpaque(view) {
111
+ const raw = await view.get(KEY);
112
+ if (raw === undefined)
113
+ return EMPTY_OPAQUE;
114
+ return parseOpaque(raw);
115
+ }
116
+ /** Writes (or replaces) the record inside the caller's transaction. */
117
+ export async function writeOpaque(view, record) {
118
+ await view.put(KEY, {
119
+ candidates: record.candidates.map((c) => ({
120
+ digest: c.digest,
121
+ parentTag: c.parentTag,
122
+ epoch: c.epoch,
123
+ ...(c.sender === undefined ? {} : { sender: c.sender }),
124
+ errorMessage: c.errorMessage,
125
+ event: c.event,
126
+ ...(c.decided === undefined ? {} : { decided: c.decided }),
127
+ })),
128
+ undecryptableIds: [...record.undecryptableIds],
129
+ ...(record.undecryptableSaturated === true ? { undecryptableSaturated: true } : {}),
130
+ });
131
+ }
132
+ export async function clearOpaque(view) {
133
+ await view.delete(KEY);
134
+ }
135
+ /** Whether two records hold the same candidates (field for field, the event by id and signature) and the same `U`. */
136
+ export function sameOpaque(a, b) {
137
+ if (a === b)
138
+ return true;
139
+ const x = a ?? EMPTY_OPAQUE;
140
+ const y = b ?? EMPTY_OPAQUE;
141
+ if (x.candidates.length !== y.candidates.length || x.undecryptableIds.length !== y.undecryptableIds.length)
142
+ return false;
143
+ if ((x.undecryptableSaturated === true) !== (y.undecryptableSaturated === true))
144
+ return false;
145
+ for (let i = 0; i < x.candidates.length; i++) {
146
+ const p = x.candidates[i];
147
+ const q = y.candidates[i];
148
+ if (p.digest !== q.digest || p.parentTag !== q.parentTag || p.epoch !== q.epoch || p.sender !== q.sender || p.errorMessage !== q.errorMessage || p.decided !== q.decided)
149
+ return false;
150
+ if (p.event !== q.event && (p.event.id !== q.event.id || p.event.sig !== q.event.sig))
151
+ return false;
152
+ }
153
+ for (let i = 0; i < x.undecryptableIds.length; i++)
154
+ if (x.undecryptableIds[i] !== y.undecryptableIds[i])
155
+ return false;
156
+ return true;
157
+ }
158
+ /**
159
+ * What to persist after the engine's record moved from `before` (the stored one, `undefined` = none) to `now`
160
+ * (`engine.opaque`): `undefined` = unchanged (nothing to write — the engine returns the same object while neither
161
+ * the held set nor `U` changed, and a rebuilt engine's equal record is recognised by content), `null` = it became
162
+ * empty (delete), else the new record. A change of `U` alone is a change.
163
+ */
164
+ export function nextOpaque(before, now) {
165
+ if (now === before)
166
+ return undefined;
167
+ if (isEmptyOpaque(now))
168
+ return isEmptyOpaque(before) ? undefined : null;
169
+ return sameOpaque(before, now) ? undefined : now;
170
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The terminal-notification outbox (epic marmot-rewound-own-commit-no-signal, S11; spec DD7 Delivery, DD11 Durability,
3
+ * AC-COMP-10). `own-change-reapplied` and `own-change-lost` are delivered AT LEAST ONCE: the terminal is written here in
4
+ * the SAME transaction that makes its fact durable (a record update or delete, a mint, a confirm, a restore), dispatched
5
+ * after that transaction commits, and removed in a follow-up transaction. A crash or a client dispose in between leaves
6
+ * the entry; the next load (or the next listener of the group) announces it again with an IDENTICAL payload.
7
+ * `own-change-withdrawn` stays at most once and has no entry here.
8
+ *
9
+ * Why an extension record and not a flag on the re-drive record: the paths that decide a terminal DELETE the re-drive
10
+ * record (no survivor, budget spent, publish refused, stranded, retired by a restore), so nothing durable would remain
11
+ * to carry the verdict. A separate namespace also keeps the verdict out of every reader of `pendingIntents`: it can never
12
+ * be driven, published, counted as an own commit pending, settled as stale, or matched by a restore or by
13
+ * `cancelRestoredReenqueues` (the same reason `proposalExpired`'s marker is an extension, not a flag on the proposal).
14
+ *
15
+ * Dedup key (what an application deduplicates by): `(groupId, intentId, change, type)`, plus `commitDigest` for a
16
+ * `reapplied` (a change reapplied by two different commits is two different facts). It is also the storage key
17
+ * (`groupId` is the store's own scope), so writing the same terminal twice is one entry, and growth is bounded by the
18
+ * number of distinct terminals not yet delivered. The only repeats an application may see are the identical redelivery
19
+ * after an injected crash or dispose, and a `reapplied` of the same change by the DD14 restore (a different commit, or
20
+ * the same one: then the same dedup key).
21
+ *
22
+ * Retention: the namespace is its own, so neither the terminal-ledger prune nor the marker prune touches it. Entries
23
+ * are removed only once delivered to at least one listener, or, for a row that does not decode, when the drain evicts it
24
+ * and reports it once as `groupStateFailed` (`store-failed`, `details.malformed`). As a last bound on a group nobody listens
25
+ * to, the OUTBOX_CAP most recent entries are kept (oldest evicted on write).
26
+ */
27
+ import { type OwnChangeLostNotification, type OwnChangeReappliedNotification } from '../history/index.js';
28
+ import { MarmotError } from '../shared/index.js';
29
+ import type { KeyValueView } from '../storage/index.js';
30
+ /** The group extension holding one entry per undelivered terminal, keyed by {@link terminalKey}. */
31
+ export declare const OWN_CHANGE_OUTBOX_EXTENSION = "marmot.own-change-outbox";
32
+ /** The most entries kept; the oldest is evicted when a write would exceed it (a group nobody listens to). */
33
+ export declare const OUTBOX_CAP = 512;
34
+ export type TerminalNotification = OwnChangeReappliedNotification | OwnChangeLostNotification;
35
+ /** One stored terminal with its delivery order (`seq`, ascending). */
36
+ export interface OutboxEntry {
37
+ readonly key: string;
38
+ readonly seq: number;
39
+ readonly notification: TerminalNotification;
40
+ }
41
+ export declare function isTerminalNotification(n: {
42
+ readonly type: string;
43
+ }): n is TerminalNotification;
44
+ /** The dedup key of a terminal: `(intentId, change, type)` plus `commitDigest` for a reapplied (`groupId` is the store's scope). */
45
+ export declare function terminalKey(n: TerminalNotification): string;
46
+ /** Every entry, in delivery order. `view` is the group's {@link OWN_CHANGE_OUTBOX_EXTENSION} namespace. */
47
+ export declare function readOutbox(view: KeyValueView): Promise<OutboxEntry[]>;
48
+ /**
49
+ * Like {@link readOutbox}, row by row: the rows that decode, in delivery order, and the ones that do not (a poisoned row, a future
50
+ * version) with their `store-failed` error, so one bad row neither blocks the good ones nor goes unnoticed.
51
+ */
52
+ export declare function readOutboxLenient(view: KeyValueView): Promise<{
53
+ readonly entries: OutboxEntry[];
54
+ readonly bad: {
55
+ readonly key: string;
56
+ readonly error: MarmotError;
57
+ }[];
58
+ }>;
59
+ /**
60
+ * Writes `notifications` (in order) into the outbox, in the caller's transaction. A terminal already stored under its
61
+ * dedup key is rewritten at the end of the order (same payload by construction for a repeat of the same fact).
62
+ * Evicts the oldest entries beyond {@link OUTBOX_CAP}.
63
+ */
64
+ export declare function enqueueTerminals(view: KeyValueView, notifications: readonly TerminalNotification[]): Promise<void>;
65
+ /** Removes the entries just delivered; one rewritten since (a different `seq`) is a newer fact and stays. */
66
+ export declare function dropDelivered(view: KeyValueView, delivered: readonly OutboxEntry[]): Promise<void>;