@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,182 @@
1
+ /**
2
+ * Group availability (epic marmot-invitation-outcomes S1, SC-10 A-1..A-8): one race-free observation per group of
3
+ * three independent facts — the fence, the sync state and the membership — plus whether the group is writable now.
4
+ *
5
+ * Availability subscriptions are their own set on the runtime ({@link GroupRuntime.availabilityListeners}). They are
6
+ * never terminal watchers: a fence is an ordinary observation that leaves the subscription open, and `endRuntime`
7
+ * never closes them. Exactly one `ended` closes a subscription, and only for the lifecycle exits
8
+ * ({@link AvailabilityEndReason}): a teardown purge, a failed restore taken back, client dispose, or the account
9
+ * lease ending (released, closed, or lost to a successor).
10
+ *
11
+ * Every change of a fact goes through one choke point on the runtime (the accessors of `fence`, `exposedState`,
12
+ * `caughtUp`, `sendGateOpen` and `disbanded`, group-runtime.ts `makeRuntime`), which calls
13
+ * {@link publishAvailability}; an observation is delivered only when the snapshot actually changed, so listeners see
14
+ * changes in the order they happened, each with a strictly increasing `seq` per runtime.
15
+ *
16
+ * Fence observation is monotonic within a client session: the fence setter records every fence in the client's
17
+ * {@link SessionFences}, and a runtime the client builds again for the group (group-runtime.ts `readLoadedRuntime`)
18
+ * starts fenced from it even when the durable marker could not be written. Nothing here awaits, schedules work or
19
+ * touches a store: {@link closeAvailability} and {@link closeAllAvailability} are synchronous, which is what lets the
20
+ * lease-end close run inside the store's release barrier.
21
+ */
22
+ import { type FenceCause } from '../history/fencing.js';
23
+ import type { GroupRuntime } from './group-runtime.js';
24
+ export type { FenceCause };
25
+ /** The three independent facts of a group, and whether an own write may be attempted now. */
26
+ export interface GroupAvailability {
27
+ /** `fenced` once this device's state for the group can no longer be trusted (no in-place lift). */
28
+ readonly fence: {
29
+ readonly state: 'clear';
30
+ } | {
31
+ readonly state: 'fenced';
32
+ readonly cause: FenceCause;
33
+ };
34
+ /**
35
+ * `synced` once a complete history pass ran since the last connectivity gap (`caughtUp`) and, for a group loaded
36
+ * from the store, the send gate opened (it opens on the first such pass after the load, AC-PIPE-15).
37
+ */
38
+ readonly sync: 'syncing' | 'synced';
39
+ /** `membership-lost`: the local leaf was removed (revisable or settled); `disbanded`: a peer disband was selected. */
40
+ readonly membership: 'member' | 'membership-lost' | 'disbanded';
41
+ /** `clear && synced && member && lease live`. A clear fence alone never promises it. */
42
+ readonly writable: boolean;
43
+ }
44
+ /** Why an availability subscription ended. */
45
+ export type AvailabilityEndReason = 'torn-down' | 'restore-undone' | 'disposed' | 'no-lease';
46
+ /** What an availability listener receives: changes, then at most one `ended` (whose `final.writable` is `false`). */
47
+ export type AvailabilityObservation = {
48
+ readonly type: 'availability';
49
+ readonly seq: number;
50
+ readonly availability: GroupAvailability;
51
+ } | {
52
+ readonly type: 'ended';
53
+ readonly seq: number;
54
+ readonly reason: AvailabilityEndReason;
55
+ readonly final: GroupAvailability;
56
+ };
57
+ export type AvailabilityListener = (observation: AvailabilityObservation) => void;
58
+ type EndedObservation = Extract<AvailabilityObservation, {
59
+ type: 'ended';
60
+ }>;
61
+ /**
62
+ * Fences raised in this client session, by group: a runtime built again for the group starts fenced from here, so a
63
+ * fence whose marker write failed never reads clear again in the same session (A-7). Cleared by a teardown purge and
64
+ * by a new adoption of the group (a join or a restore), which start the group over.
65
+ */
66
+ export declare class SessionFences {
67
+ #private;
68
+ /** Records `groupId`'s first fence of the session (a later one never replaces it). */
69
+ record(groupId: string, fence: Error): void;
70
+ get(groupId: string): Error | undefined;
71
+ causeOf(groupId: string): FenceCause | undefined;
72
+ clear(groupId: string): void;
73
+ }
74
+ /** The per-client part: the session's fences and whether the client's account lease ended (A-5, A-6). */
75
+ export interface ClientAvailability {
76
+ readonly sessionFences: SessionFences;
77
+ leaseEnded: boolean;
78
+ /**
79
+ * The client-wide end that came first (`no-lease` or `disposed`), recorded before any runtime's `ended` is
80
+ * delivered: a subscription made afterwards — even from inside a listener of that very close — ends with it.
81
+ */
82
+ ended: Extract<AvailabilityEndReason, 'no-lease' | 'disposed'> | undefined;
83
+ /** The client's live runtimes (the registry's): what a lease end observed on one group closes. */
84
+ readonly runtimes: () => Iterable<GroupRuntime>;
85
+ }
86
+ export declare function createClientAvailability(runtimes?: () => Iterable<GroupRuntime>): ClientAvailability;
87
+ /** The per-runtime state (GroupRuntime fields). */
88
+ export interface RuntimeAvailability {
89
+ readonly availabilityListeners: Set<AvailabilitySubscription>;
90
+ /** The `seq` of the last observation produced (the current snapshot's, or the `ended`'s); 0 before the first. */
91
+ availabilitySeq: number;
92
+ /** The snapshot last published (what a new subscriber's initial observation carries). */
93
+ availabilityLast: GroupAvailability | undefined;
94
+ /** Set once the subscriptions ended: every later subscriber gets exactly this `ended`, and nothing more. */
95
+ availabilityEnded: EndedObservation | undefined;
96
+ readonly availabilityClient: ClientAvailability;
97
+ }
98
+ /** The inputs {@link availabilityFrom} decides on — read off a runtime by {@link availabilityOf}. */
99
+ export interface AvailabilityFacts {
100
+ readonly fence: Error | undefined;
101
+ readonly caughtUp: boolean;
102
+ readonly sendGateOpen: boolean;
103
+ readonly removedFromGroup: boolean;
104
+ readonly disbanded: boolean;
105
+ readonly leaseLive: boolean;
106
+ }
107
+ /** Pure: the availability the facts describe. */
108
+ export declare function availabilityFrom(facts: AvailabilityFacts): GroupAvailability;
109
+ /** The runtime's current facts. */
110
+ export declare function factsOf(rt: GroupRuntime): AvailabilityFacts;
111
+ /** The runtime's current availability (pure over {@link factsOf}). */
112
+ export declare function availabilityOf(rt: GroupRuntime): GroupAvailability;
113
+ /**
114
+ * One live subscription: its own FIFO of observations not yet delivered. Every observation is enqueued to every live
115
+ * subscription before any of them is drained, and a subscription's drain is non-reentrant (a publish or close raised
116
+ * from inside its listener only enqueues; the outer drain delivers it next). So each listener receives every change in
117
+ * `seq` order, then at most one `ended`, and nothing after it — whatever the listeners do from inside their callbacks.
118
+ */
119
+ export interface AvailabilitySubscription {
120
+ readonly listener: AvailabilityListener;
121
+ readonly queue: AvailabilityObservation[];
122
+ draining: boolean;
123
+ /** The `ended` was enqueued: nothing more is ever enqueued. */
124
+ endQueued: boolean;
125
+ /** Unsubscribed: the queue is discarded and nothing more is delivered. */
126
+ unsubscribed: boolean;
127
+ }
128
+ /**
129
+ * Re-reads the runtime's facts and, when the snapshot changed, delivers it to every live listener with the next
130
+ * `seq`. A no-op once the subscriptions ended. Synchronous; never throws.
131
+ */
132
+ export declare function publishAvailability(rt: GroupRuntime): void;
133
+ /**
134
+ * Subscribes `listener` to the group's availability (`MarmotGroup.observeAvailability`): the current snapshot is
135
+ * delivered synchronously, before this returns, then every change. After the subscriptions ended — or once the
136
+ * client's account lease ended — the listener gets the one `ended` and nothing more. The returned function
137
+ * unsubscribes (idempotent); no callback reaches the listener after it. What is delivered before this returns runs in
138
+ * the caller's re-entrancy frame (see {@link deliver}); every later change runs detached.
139
+ */
140
+ export declare function observeAvailability(rt: GroupRuntime, listener: AvailabilityListener): () => void;
141
+ /**
142
+ * Ends the runtime's availability subscriptions (A-3): exactly one `ended` with `reason` to every listener, whose
143
+ * `final` is the current snapshot made not writable (a fenced group stays fenced in it). Idempotent: a later call is a
144
+ * no-op. Synchronous: awaits, schedules and stores nothing.
145
+ */
146
+ export declare function closeAvailability(rt: GroupRuntime, reason: AvailabilityEndReason): void;
147
+ /**
148
+ * Ends every runtime's subscriptions in two phases: every runtime's `ended` is recorded (each isolated) before the
149
+ * returned function delivers any of them. So no listener of one runtime's `ended` can observe another runtime of the
150
+ * same close still open — a subscribe to it gets the stored `ended`, and a second close (a dispose raised from a
151
+ * `no-lease` listener) finds it already ended with the first reason.
152
+ */
153
+ export declare function markAllAvailabilityEnded(runtimes: Iterable<GroupRuntime>, reason: AvailabilityEndReason): () => void;
154
+ /** {@link closeAvailability} for every runtime: all recorded first, then all delivered (see {@link markAllAvailabilityEnded}). */
155
+ export declare function closeAllAvailability(runtimes: Iterable<GroupRuntime>, reason: AvailabilityEndReason): void;
156
+ /**
157
+ * The client is being disposed: records the client-wide `disposed` end (unless the lease ended first) and every
158
+ * runtime's `ended/'disposed'` without delivering any; the returned function delivers them. Run the delivery once the
159
+ * runtimes are torn down, so a listener never sees a disposed client's group as still open.
160
+ */
161
+ export declare function beginDisposeAvailability(client: ClientAvailability, runtimes: Iterable<GroupRuntime>): () => void;
162
+ /**
163
+ * Phase one of the client's account lease end (A-5): records the client-wide lease end (every later subscription of
164
+ * this client gets one immediate `ended/'no-lease'`) and every runtime's `ended/'no-lease'`, delivering nothing; the
165
+ * returned function delivers them. The caller settles its own lease-end consequences (the pending `synced()` waits)
166
+ * between the two, so a listener reacting to its `ended` (a `dispose()`) never pre-empts them. Synchronous; schedules
167
+ * no group work, timer, store access or transport call.
168
+ */
169
+ export declare function beginLeaseEndAvailability(client: ClientAvailability, runtimes: Iterable<GroupRuntime>): () => void;
170
+ /**
171
+ * The client's account lease ended (A-5): every runtime's subscriptions end `no-lease`, and every later subscription
172
+ * of this client gets one immediate `ended/'no-lease'`. Every runtime is marked ended before any listener runs.
173
+ * Synchronous; schedules no group work, timer, store access or transport call.
174
+ */
175
+ export declare function endAvailabilityForLease(client: ClientAvailability, runtimes: Iterable<GroupRuntime>): void;
176
+ /**
177
+ * A lost lease observed lazily on `rt` (a background retry meeting `no-lease`): the account lease is the client's, so
178
+ * this is phase one of the client-wide lease end of {@link beginLeaseEndAvailability} — the fallback for a store
179
+ * without `onLeaseEnded`. `rt` is closed too even when the registry does not hold it (yet). The returned function
180
+ * delivers the `ended` observations.
181
+ */
182
+ export declare function beginLostLeaseAvailability(rt: GroupRuntime): () => void;
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Group availability (epic marmot-invitation-outcomes S1, SC-10 A-1..A-8): one race-free observation per group of
3
+ * three independent facts — the fence, the sync state and the membership — plus whether the group is writable now.
4
+ *
5
+ * Availability subscriptions are their own set on the runtime ({@link GroupRuntime.availabilityListeners}). They are
6
+ * never terminal watchers: a fence is an ordinary observation that leaves the subscription open, and `endRuntime`
7
+ * never closes them. Exactly one `ended` closes a subscription, and only for the lifecycle exits
8
+ * ({@link AvailabilityEndReason}): a teardown purge, a failed restore taken back, client dispose, or the account
9
+ * lease ending (released, closed, or lost to a successor).
10
+ *
11
+ * Every change of a fact goes through one choke point on the runtime (the accessors of `fence`, `exposedState`,
12
+ * `caughtUp`, `sendGateOpen` and `disbanded`, group-runtime.ts `makeRuntime`), which calls
13
+ * {@link publishAvailability}; an observation is delivered only when the snapshot actually changed, so listeners see
14
+ * changes in the order they happened, each with a strictly increasing `seq` per runtime.
15
+ *
16
+ * Fence observation is monotonic within a client session: the fence setter records every fence in the client's
17
+ * {@link SessionFences}, and a runtime the client builds again for the group (group-runtime.ts `readLoadedRuntime`)
18
+ * starts fenced from it even when the durable marker could not be written. Nothing here awaits, schedules work or
19
+ * touches a store: {@link closeAvailability} and {@link closeAllAvailability} are synchronous, which is what lets the
20
+ * lease-end close run inside the store's release barrier.
21
+ */
22
+ import { fenceCauseOf } from '../history/fencing.js';
23
+ import { MarmotError } from '../shared/index.js';
24
+ /**
25
+ * Fences raised in this client session, by group: a runtime built again for the group starts fenced from here, so a
26
+ * fence whose marker write failed never reads clear again in the same session (A-7). Cleared by a teardown purge and
27
+ * by a new adoption of the group (a join or a restore), which start the group over.
28
+ */
29
+ export class SessionFences {
30
+ #fences = new Map();
31
+ /** Records `groupId`'s first fence of the session (a later one never replaces it). */
32
+ record(groupId, fence) {
33
+ if (!this.#fences.has(groupId))
34
+ this.#fences.set(groupId, fence);
35
+ }
36
+ get(groupId) {
37
+ return this.#fences.get(groupId);
38
+ }
39
+ causeOf(groupId) {
40
+ const fence = this.#fences.get(groupId);
41
+ return fence === undefined ? undefined : fenceCauseOf(fence);
42
+ }
43
+ clear(groupId) {
44
+ this.#fences.delete(groupId);
45
+ }
46
+ }
47
+ export function createClientAvailability(runtimes = () => []) {
48
+ return { sessionFences: new SessionFences(), leaseEnded: false, ended: undefined, runtimes };
49
+ }
50
+ const CLEAR = Object.freeze({ state: 'clear' });
51
+ /** Pure: the availability the facts describe. */
52
+ export function availabilityFrom(facts) {
53
+ const fence = facts.fence === undefined ? CLEAR : Object.freeze({ state: 'fenced', cause: fenceCauseOf(facts.fence) });
54
+ // The send gate opens right after the first catch-up of a loaded group: one change, observed once.
55
+ const sync = facts.caughtUp && facts.sendGateOpen ? 'synced' : 'syncing';
56
+ const membership = facts.disbanded ? 'disbanded' : facts.removedFromGroup ? 'membership-lost' : 'member';
57
+ const writable = fence.state === 'clear' && sync === 'synced' && membership === 'member' && facts.leaseLive;
58
+ return Object.freeze({ fence, sync, membership, writable });
59
+ }
60
+ /** The runtime's current facts. */
61
+ export function factsOf(rt) {
62
+ return {
63
+ fence: rt.fence,
64
+ caughtUp: rt.caughtUp,
65
+ sendGateOpen: rt.sendGateOpen,
66
+ removedFromGroup: rt.exposedState.groupActiveState.kind === 'removedFromGroup',
67
+ disbanded: rt.disbanded !== undefined,
68
+ leaseLive: rt.leaseLost === undefined && !rt.availabilityClient.leaseEnded,
69
+ };
70
+ }
71
+ /** The runtime's current availability (pure over {@link factsOf}). */
72
+ export function availabilityOf(rt) {
73
+ return availabilityFrom(factsOf(rt));
74
+ }
75
+ function sameAvailability(a, b) {
76
+ if (a.sync !== b.sync || a.membership !== b.membership || a.writable !== b.writable || a.fence.state !== b.fence.state)
77
+ return false;
78
+ return a.fence.state === 'clear' || b.fence.state === 'clear' || a.fence.cause === b.fence.cause;
79
+ }
80
+ /**
81
+ * Hands `observation` to `listener`. Never throws. Two contexts:
82
+ * - `'detached'` (a change the group's own work published): outside every re-entrancy frame of the operation that
83
+ * produced it — nothing waits on the listener, so an operation it starts simply queues.
84
+ * - `'caller'` (a delivery made synchronously inside `observeAvailability`, on the subscribing caller's stack): in
85
+ * the caller's own frame, so a subscription made from inside a consumer surface (an `onConfirm` hook, a store, …)
86
+ * gets the same `reentrant` rejection for a same-group operation its listener starts as the surface itself would —
87
+ * instead of an operation queued behind the one awaiting that surface.
88
+ */
89
+ function deliver(rt, listener, observation, context) {
90
+ const run = () => {
91
+ try {
92
+ // The listener type returns `void`, so an `async` listener type-checks: its rejection is swallowed here without
93
+ // awaiting it (delivery stays synchronous), so it never surfaces as an unhandled rejection.
94
+ const returned = listener(observation);
95
+ if (typeof returned?.then === 'function') {
96
+ returned.then(undefined, () => undefined);
97
+ }
98
+ }
99
+ catch {
100
+ // A throwing listener never breaks the operation that changed the group, nor the other listeners.
101
+ }
102
+ };
103
+ if (context === 'caller')
104
+ run();
105
+ else
106
+ rt.guard.detached(run);
107
+ }
108
+ function enqueue(sub, observation) {
109
+ if (sub.endQueued || sub.unsubscribed)
110
+ return;
111
+ sub.queue.push(observation);
112
+ if (observation.type === 'ended')
113
+ sub.endQueued = true;
114
+ }
115
+ function drain(rt, sub, context = 'detached') {
116
+ if (sub.draining)
117
+ return;
118
+ sub.draining = true;
119
+ try {
120
+ while (!sub.unsubscribed) {
121
+ const next = sub.queue.shift();
122
+ if (next === undefined)
123
+ break;
124
+ deliver(rt, sub.listener, next, context);
125
+ }
126
+ if (sub.unsubscribed)
127
+ sub.queue.length = 0;
128
+ }
129
+ finally {
130
+ sub.draining = false;
131
+ }
132
+ }
133
+ /** Enqueues `observation` for every subscription live now, then drains each (a drain already running continues it). */
134
+ function broadcast(rt, subs, observation) {
135
+ for (const sub of subs)
136
+ enqueue(sub, observation);
137
+ for (const sub of subs)
138
+ drain(rt, sub);
139
+ }
140
+ /**
141
+ * Re-reads the runtime's facts and, when the snapshot changed, delivers it to every live listener with the next
142
+ * `seq`. A no-op once the subscriptions ended. Synchronous; never throws.
143
+ */
144
+ export function publishAvailability(rt) {
145
+ if (rt.availabilityEnded !== undefined)
146
+ return;
147
+ const next = availabilityOf(rt);
148
+ const last = rt.availabilityLast;
149
+ if (last !== undefined && sameAvailability(last, next))
150
+ return;
151
+ rt.availabilityLast = next;
152
+ rt.availabilitySeq += 1;
153
+ if (last === undefined)
154
+ return;
155
+ const observation = Object.freeze({ type: 'availability', seq: rt.availabilitySeq, availability: next });
156
+ broadcast(rt, [...rt.availabilityListeners], observation);
157
+ }
158
+ /**
159
+ * Subscribes `listener` to the group's availability (`MarmotGroup.observeAvailability`): the current snapshot is
160
+ * delivered synchronously, before this returns, then every change. After the subscriptions ended — or once the
161
+ * client's account lease ended — the listener gets the one `ended` and nothing more. The returned function
162
+ * unsubscribes (idempotent); no callback reaches the listener after it. What is delivered before this returns runs in
163
+ * the caller's re-entrancy frame (see {@link deliver}); every later change runs detached.
164
+ */
165
+ export function observeAvailability(rt, listener) {
166
+ if (typeof listener !== 'function')
167
+ throw new MarmotError('invalid-options', 'MarmotGroup.observeAvailability: listener must be a function');
168
+ const client = rt.availabilityClient;
169
+ const clientEnd = client.ended ?? (client.leaseEnded ? 'no-lease' : undefined);
170
+ if (rt.availabilityEnded === undefined && clientEnd !== undefined)
171
+ closeAvailability(rt, clientEnd);
172
+ const ended = rt.availabilityEnded;
173
+ if (ended !== undefined) {
174
+ deliver(rt, listener, ended, 'caller');
175
+ return () => undefined;
176
+ }
177
+ // Bring the snapshot up to date first (an existing listener sees a pending change before this one's initial).
178
+ publishAvailability(rt);
179
+ const sub = { listener, queue: [], draining: false, endQueued: false, unsubscribed: false };
180
+ // The initial observation is the subscription's first entry, and the subscription joins the set in the same step:
181
+ // every later change or `ended` queues behind it (AC-FENCE-2 — a change its own callback raises is never delivered
182
+ // nested inside it; it follows it), with no gap and no duplicate.
183
+ enqueue(sub, Object.freeze({ type: 'availability', seq: rt.availabilitySeq, availability: rt.availabilityLast ?? availabilityOf(rt) }));
184
+ rt.availabilityListeners.add(sub);
185
+ // Drained on the caller's stack and in the caller's frame: the initial snapshot, then any change its own callback
186
+ // raised (still synchronously inside this call). Later changes drain detached, from whatever published them.
187
+ drain(rt, sub, 'caller');
188
+ return () => {
189
+ sub.unsubscribed = true;
190
+ sub.queue.length = 0;
191
+ rt.availabilityListeners.delete(sub);
192
+ };
193
+ }
194
+ /**
195
+ * Phase one of a close: records the runtime's `ended` (every later subscriber gets exactly it), clears its listener set
196
+ * and enqueues the `ended` to every subscription it held — delivering nothing. `undefined` when it had already ended.
197
+ */
198
+ function markEnded(rt, reason) {
199
+ if (rt.availabilityEnded !== undefined)
200
+ return undefined;
201
+ const final = Object.freeze({ ...availabilityOf(rt), writable: false });
202
+ rt.availabilitySeq += 1;
203
+ const ended = Object.freeze({ type: 'ended', seq: rt.availabilitySeq, reason, final });
204
+ rt.availabilityEnded = ended;
205
+ const subs = [...rt.availabilityListeners];
206
+ rt.availabilityListeners.clear();
207
+ for (const sub of subs)
208
+ enqueue(sub, ended);
209
+ return { rt, subs };
210
+ }
211
+ /** Phase two: delivers what {@link markEnded} enqueued (a drain already running continues it). Never throws. */
212
+ function drainEnded(pending) {
213
+ for (const { rt, subs } of pending) {
214
+ for (const sub of subs) {
215
+ try {
216
+ drain(rt, sub);
217
+ }
218
+ catch {
219
+ // One runtime never keeps the others' listeners from their `ended`.
220
+ }
221
+ }
222
+ }
223
+ }
224
+ /**
225
+ * Ends the runtime's availability subscriptions (A-3): exactly one `ended` with `reason` to every listener, whose
226
+ * `final` is the current snapshot made not writable (a fenced group stays fenced in it). Idempotent: a later call is a
227
+ * no-op. Synchronous: awaits, schedules and stores nothing.
228
+ */
229
+ export function closeAvailability(rt, reason) {
230
+ const pending = markEnded(rt, reason);
231
+ if (pending !== undefined)
232
+ drainEnded([pending]);
233
+ }
234
+ /**
235
+ * Ends every runtime's subscriptions in two phases: every runtime's `ended` is recorded (each isolated) before the
236
+ * returned function delivers any of them. So no listener of one runtime's `ended` can observe another runtime of the
237
+ * same close still open — a subscribe to it gets the stored `ended`, and a second close (a dispose raised from a
238
+ * `no-lease` listener) finds it already ended with the first reason.
239
+ */
240
+ export function markAllAvailabilityEnded(runtimes, reason) {
241
+ const pending = [];
242
+ for (const rt of runtimes) {
243
+ try {
244
+ const marked = markEnded(rt, reason);
245
+ if (marked !== undefined)
246
+ pending.push(marked);
247
+ }
248
+ catch {
249
+ // One runtime never keeps the others open.
250
+ }
251
+ }
252
+ let drained = false;
253
+ return () => {
254
+ if (drained)
255
+ return;
256
+ drained = true;
257
+ drainEnded(pending);
258
+ };
259
+ }
260
+ /** {@link closeAvailability} for every runtime: all recorded first, then all delivered (see {@link markAllAvailabilityEnded}). */
261
+ export function closeAllAvailability(runtimes, reason) {
262
+ markAllAvailabilityEnded(runtimes, reason)();
263
+ }
264
+ /**
265
+ * The client is being disposed: records the client-wide `disposed` end (unless the lease ended first) and every
266
+ * runtime's `ended/'disposed'` without delivering any; the returned function delivers them. Run the delivery once the
267
+ * runtimes are torn down, so a listener never sees a disposed client's group as still open.
268
+ */
269
+ export function beginDisposeAvailability(client, runtimes) {
270
+ client.ended ??= 'disposed';
271
+ return markAllAvailabilityEnded(runtimes, 'disposed');
272
+ }
273
+ /**
274
+ * Phase one of the client's account lease end (A-5): records the client-wide lease end (every later subscription of
275
+ * this client gets one immediate `ended/'no-lease'`) and every runtime's `ended/'no-lease'`, delivering nothing; the
276
+ * returned function delivers them. The caller settles its own lease-end consequences (the pending `synced()` waits)
277
+ * between the two, so a listener reacting to its `ended` (a `dispose()`) never pre-empts them. Synchronous; schedules
278
+ * no group work, timer, store access or transport call.
279
+ */
280
+ export function beginLeaseEndAvailability(client, runtimes) {
281
+ client.leaseEnded = true;
282
+ client.ended ??= 'no-lease';
283
+ return markAllAvailabilityEnded(runtimes, 'no-lease');
284
+ }
285
+ /**
286
+ * The client's account lease ended (A-5): every runtime's subscriptions end `no-lease`, and every later subscription
287
+ * of this client gets one immediate `ended/'no-lease'`. Every runtime is marked ended before any listener runs.
288
+ * Synchronous; schedules no group work, timer, store access or transport call.
289
+ */
290
+ export function endAvailabilityForLease(client, runtimes) {
291
+ beginLeaseEndAvailability(client, runtimes)();
292
+ }
293
+ /**
294
+ * A lost lease observed lazily on `rt` (a background retry meeting `no-lease`): the account lease is the client's, so
295
+ * this is phase one of the client-wide lease end of {@link beginLeaseEndAvailability} — the fallback for a store
296
+ * without `onLeaseEnded`. `rt` is closed too even when the registry does not hold it (yet). The returned function
297
+ * delivers the `ended` observations.
298
+ */
299
+ export function beginLostLeaseAvailability(rt) {
300
+ return beginLeaseEndAvailability(rt.availabilityClient, [rt, ...rt.availabilityClient.runtimes()]);
301
+ }
@@ -0,0 +1,28 @@
1
+ import { MarmotError } from '../shared/index.js';
2
+ import type { KeyValueView } from '../storage/index.js';
3
+ import type { GroupDisbanded } from './create-client.js';
4
+ import type { GroupDisbandedNotification } from '../history/index.js';
5
+ import type { GroupRuntime } from './group-runtime.js';
6
+ /** Group extension namespace of the disband marker. */
7
+ export declare const DISBAND_EXTENSION = "marmot.disband";
8
+ /** The persisted marker; `epoch` is a decimal string (a bigint epoch does not survive the store's JSON). */
9
+ export interface DisbandRecord {
10
+ readonly at: number;
11
+ readonly epoch: string;
12
+ readonly nodeTag: string;
13
+ readonly commitDigest: string;
14
+ readonly actor: string;
15
+ }
16
+ export declare function writeDisband(view: KeyValueView, record: DisbandRecord): Promise<void>;
17
+ export declare function readDisband(view: KeyValueView): Promise<DisbandRecord | undefined>;
18
+ /** `MarmotGroup.disbanded` of a marker. */
19
+ export declare function groupDisbandedOf(record: DisbandRecord): GroupDisbanded;
20
+ export declare function disbandedError(groupId: string, operation: string, record: DisbandRecord): MarmotError;
21
+ /** Refuses an own operation on a disbanded group. */
22
+ export declare function assertNotDisbanded(rt: GroupRuntime, operation: string): void;
23
+ /**
24
+ * After a convergence drive: when it selected a disband (engine lifecycle `Disbanded` with its evidence), persists
25
+ * the marker, sets `rt.disbanded`, rejects waiting `synced()` calls and returns the notification to announce.
26
+ * `undefined` when nothing was selected, or the group already carries a marker.
27
+ */
28
+ export declare function recordSelectedDisband(rt: GroupRuntime): Promise<GroupDisbandedNotification | undefined>;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * A peer's terminal disband, once selected (BACKLOG `marmot-disband-settled-store-divergence`).
3
+ *
4
+ * The engine holds an admitted disband commit as a terminal candidate and selects it in its scheduled settlement
5
+ * (`driveConvergence`); its lifecycle is then `Disbanded`. marmot passes the engine no lifecycle store and never
6
+ * persists the selected state (no proof gate judged it), so without this marker only the in-memory engine knew: a
7
+ * reload rebuilt the group from the pre-disband state and the client kept treating it as live. The marker is the
8
+ * group's durable tombstone (group extension {@link DISBAND_EXTENSION}): written once, read on every load, and from
9
+ * then on the group does not sync, rejects input and refuses own operations (`not-a-member`, reason `disbanded`).
10
+ * The stored MLS state stays the disband's parent — nothing ungated is persisted.
11
+ */
12
+ import { groupLifecycleStates } from '@941design/marmot-engine/core';
13
+ import { hexOf } from '../history/hex.js';
14
+ import { MarmotError } from '../shared/index.js';
15
+ /** Group extension namespace of the disband marker. */
16
+ export const DISBAND_EXTENSION = 'marmot.disband';
17
+ const DISBAND_KEY = 'selected';
18
+ const HEX64 = /^[0-9a-f]{64}$/;
19
+ export async function writeDisband(view, record) {
20
+ await view.put(DISBAND_KEY, { at: record.at, epoch: record.epoch, nodeTag: record.nodeTag, commitDigest: record.commitDigest, actor: record.actor });
21
+ }
22
+ export async function readDisband(view) {
23
+ const raw = await view.get(DISBAND_KEY);
24
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
25
+ return undefined;
26
+ const r = raw;
27
+ if (typeof r.at !== 'number' || typeof r.epoch !== 'string' || !/^\d+$/.test(r.epoch) || typeof r.nodeTag !== 'string' || typeof r.commitDigest !== 'string' || typeof r.actor !== 'string')
28
+ return undefined;
29
+ return { at: r.at, epoch: r.epoch, nodeTag: r.nodeTag, commitDigest: r.commitDigest, actor: r.actor };
30
+ }
31
+ /** `MarmotGroup.disbanded` of a marker. */
32
+ export function groupDisbandedOf(record) {
33
+ return Object.freeze({ actor: record.actor, epoch: BigInt(record.epoch), nodeTag: record.nodeTag, commitDigest: record.commitDigest, at: record.at });
34
+ }
35
+ export function disbandedError(groupId, operation, record) {
36
+ return new MarmotError('not-a-member', `${operation}: group ${groupId} was disbanded by ${record.actor}`, { details: { groupId, reason: 'disbanded' } });
37
+ }
38
+ /** Refuses an own operation on a disbanded group. */
39
+ export function assertNotDisbanded(rt, operation) {
40
+ if (rt.disbanded !== undefined)
41
+ throw disbandedError(rt.groupId, operation, rt.disbanded);
42
+ }
43
+ /**
44
+ * After a convergence drive: when it selected a disband (engine lifecycle `Disbanded` with its evidence), persists
45
+ * the marker, sets `rt.disbanded`, rejects waiting `synced()` calls and returns the notification to announce.
46
+ * `undefined` when nothing was selected, or the group already carries a marker.
47
+ */
48
+ export async function recordSelectedDisband(rt) {
49
+ if (rt.disbanded !== undefined || rt.engine.lifecycle !== groupLifecycleStates.disbanded)
50
+ return undefined;
51
+ const evidence = rt.engine.selectedDisbandEvidence;
52
+ if (evidence === undefined)
53
+ return undefined;
54
+ const commitDigest = hexOf(evidence.commitDigest);
55
+ if (!HEX64.test(commitDigest))
56
+ return undefined;
57
+ const record = { at: rt.ctx.clock.now(), epoch: String(evidence.sourceEpoch), nodeTag: evidence.parentTag, commitDigest, actor: evidence.actorPubkey };
58
+ await rt.guard.call(rt.groupId, 'store', () => rt.groupStore.transaction((tx) => writeDisband(tx.extension(DISBAND_EXTENSION), record)));
59
+ rt.disbanded = record;
60
+ for (const waiter of rt.syncWaiters)
61
+ waiter.reject(disbandedError(rt.groupId, 'synced', record));
62
+ rt.syncWaiters.clear();
63
+ return { type: 'group-disbanded', actor: record.actor, epoch: BigInt(record.epoch), nodeTag: record.nodeTag, commitDigest };
64
+ }