@941design/marmot 0.2.0-alpha.0 → 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 (63) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/account/teardown.d.ts +66 -3
  3. package/dist/account/teardown.js +24 -2
  4. package/dist/client/admission-cleanup.d.ts +197 -0
  5. package/dist/client/admission-cleanup.js +635 -0
  6. package/dist/client/adoption-proof.d.ts +39 -0
  7. package/dist/client/adoption-proof.js +102 -0
  8. package/dist/client/before-publish-hooks.js +3 -1
  9. package/dist/client/commit-redrive.d.ts +28 -4
  10. package/dist/client/commit-redrive.js +54 -1
  11. package/dist/client/confirm-hooks.d.ts +6 -1
  12. package/dist/client/confirm-hooks.js +15 -0
  13. package/dist/client/create-client.d.ts +107 -3
  14. package/dist/client/create-client.js +114 -7
  15. package/dist/client/group-availability.d.ts +182 -0
  16. package/dist/client/group-availability.js +301 -0
  17. package/dist/client/group-history.d.ts +26 -0
  18. package/dist/client/group-history.js +77 -7
  19. package/dist/client/group-records.d.ts +39 -2
  20. package/dist/client/group-records.js +88 -5
  21. package/dist/client/group-runtime.d.ts +30 -3
  22. package/dist/client/group-runtime.js +131 -21
  23. package/dist/client/group-snapshot.d.ts +7 -1
  24. package/dist/client/group-snapshot.js +23 -2
  25. package/dist/client/index.d.ts +4 -1
  26. package/dist/client/ingest.js +47 -13
  27. package/dist/client/invitation-outcomes.d.ts +50 -0
  28. package/dist/client/invitation-outcomes.js +135 -0
  29. package/dist/client/opaque-candidates.d.ts +2 -1
  30. package/dist/client/opaque-candidates.js +2 -1
  31. package/dist/client/own-change-outbox.js +2 -0
  32. package/dist/client/pipeline.d.ts +30 -1
  33. package/dist/client/pipeline.js +142 -21
  34. package/dist/client/reentrancy-guard.d.ts +6 -0
  35. package/dist/client/reentrancy-guard.js +6 -0
  36. package/dist/history/admission-lineage.d.ts +186 -0
  37. package/dist/history/admission-lineage.js +589 -0
  38. package/dist/history/fencing.d.ts +41 -0
  39. package/dist/history/fencing.js +67 -7
  40. package/dist/history/index.d.ts +2 -1
  41. package/dist/history/index.js +2 -1
  42. package/dist/history/own-change.d.ts +13 -1
  43. package/dist/invitations/decline.d.ts +8 -2
  44. package/dist/invitations/decline.js +9 -3
  45. package/dist/invitations/delivery-evidence.d.ts +288 -0
  46. package/dist/invitations/delivery-evidence.js +766 -0
  47. package/dist/invitations/index.d.ts +4 -2
  48. package/dist/invitations/index.js +4 -2
  49. package/dist/invitations/invitation-outcome.d.ts +110 -0
  50. package/dist/invitations/invitation-outcome.js +210 -0
  51. package/dist/invitations/invite.d.ts +61 -6
  52. package/dist/invitations/invite.js +187 -51
  53. package/dist/invitations/welcome-processor.d.ts +20 -1
  54. package/dist/invitations/welcome-processor.js +81 -20
  55. package/dist/shared/errors.d.ts +7 -0
  56. package/dist/shared/errors.js +11 -0
  57. package/dist/shared/index.d.ts +1 -1
  58. package/dist/shared/index.js +1 -1
  59. package/dist/storage/index.d.ts +10 -0
  60. package/dist/storage/index.js +33 -1
  61. package/dist/storage/lease.d.ts +13 -0
  62. package/dist/storage/lease.js +51 -0
  63. package/package.json +2 -2
@@ -187,6 +187,40 @@ export async function writeGroupIndexEntry(view, groupId, entry) {
187
187
  export async function listGroupIndex(view) {
188
188
  return view.keys();
189
189
  }
190
+ const isHexString = (v) => typeof v === 'string' && v.length > 0 && v.length % 2 === 0 && /^[0-9a-f]+$/.test(v);
191
+ /** Strict decoder of an {@link AdmissionTarget}: exactly its members, each well-formed; `fail` builds the error. */
192
+ export function decodeAdmissionTarget(raw, at, fail) {
193
+ if (!isObject(raw))
194
+ throw fail(`${at} not an object`);
195
+ onlyMembers(raw, ['candidateId', 'anchor', 'acceptedAtTag', 'account'], at, fail);
196
+ const { candidateId, anchor, acceptedAtTag, account } = raw;
197
+ if (!isHex64(candidateId))
198
+ throw fail(`${at}.candidateId invalid`);
199
+ if (!isHexString(acceptedAtTag))
200
+ throw fail(`${at}.acceptedAtTag invalid`);
201
+ if (!isAccountPubkey(account))
202
+ throw fail(`${at}.account invalid`);
203
+ if (!isObject(anchor))
204
+ throw fail(`${at}.anchor invalid`);
205
+ onlyMembers(anchor, ['addDigest', 'addTag', 'commitEventId', 'leafIndex', 'leafKey'], `${at}.anchor`, fail);
206
+ const { addDigest, addTag, commitEventId, leafIndex, leafKey } = anchor;
207
+ if (!isHex64(addDigest) || !isHexString(addTag) || typeof commitEventId !== 'string' || commitEventId.length === 0 || typeof leafIndex !== 'number' || !Number.isSafeInteger(leafIndex) || leafIndex < 0 || !isHexString(leafKey)) {
208
+ throw fail(`${at}.anchor invalid`);
209
+ }
210
+ return { candidateId, anchor: { addDigest, addTag, commitEventId, leafIndex, leafKey }, acceptedAtTag, account };
211
+ }
212
+ /** The `Storable` form of an {@link AdmissionTarget} (re-checked: a mis-shaped write is refused like a mis-shaped read). */
213
+ export function encodeAdmissionTarget(target, fail) {
214
+ const { anchor } = target;
215
+ const raw = {
216
+ candidateId: target.candidateId,
217
+ anchor: { addDigest: anchor.addDigest, addTag: anchor.addTag, commitEventId: anchor.commitEventId, leafIndex: anchor.leafIndex, leafKey: anchor.leafKey },
218
+ acceptedAtTag: target.acceptedAtTag,
219
+ account: target.account,
220
+ };
221
+ decodeAdmissionTarget(raw, 'removeAdmission', fail);
222
+ return raw;
223
+ }
190
224
  /**
191
225
  * A commit re-drive record (S1): the durable record a withdrawal writes for a withdrawn own commit — a `commit` carrying
192
226
  * `changes` (DD15; the decoder and the encoder enforce `changes` => `{ type: 'commit' }` + `reenqueuedFrom`). The
@@ -241,6 +275,11 @@ function decodeStorableIntent(intentId, raw) {
241
275
  const components = componentsRaw === undefined ? undefined : checkComponents(componentsRaw, (detail) => malformed(intentId, detail));
242
276
  const profileRaw = raw.profile;
243
277
  checkNoProfileClash(profileRaw !== undefined, components, (detail) => malformed(intentId, detail));
278
+ const removeAdmissionRaw = raw.removeAdmission;
279
+ const removeAdmission = removeAdmissionRaw === undefined ? undefined : decodeAdmissionTarget(removeAdmissionRaw, 'intent.removeAdmission', (detail) => malformed(intentId, detail));
280
+ // S5 (SC-5): a scoped cleanup is exclusive with every other member of a commit intent.
281
+ if (removeAdmission !== undefined && Object.entries(raw).some(([k, v]) => k !== 'type' && k !== 'removeAdmission' && v !== undefined))
282
+ throw malformed(intentId, 'intent.removeAdmission beside another member');
244
283
  let profile;
245
284
  if (profileRaw !== undefined) {
246
285
  const { name, description } = (typeof profileRaw === 'object' && profileRaw !== null ? profileRaw : {});
@@ -265,6 +304,7 @@ function decodeStorableIntent(intentId, raw) {
265
304
  ...(removeAccounts === undefined ? {} : { removeAccounts: removeAccounts, removeAccountLeafKeys: removeAccountLeafKeys }),
266
305
  ...(origin === undefined ? {} : { origin }),
267
306
  ...(components === undefined ? {} : { components }),
307
+ ...(removeAdmission === undefined ? {} : { removeAdmission }),
268
308
  };
269
309
  }
270
310
  case 'self-update': {
@@ -339,6 +379,8 @@ function encodeStorableIntent(intentId, intent) {
339
379
  return { type: 'proposal', proposal: intent.proposal };
340
380
  case 'commit': {
341
381
  checkNoProfileClash(intent.profile !== undefined, intent.components, (detail) => malformed(intentId, detail));
382
+ if (intent.removeAdmission !== undefined && Object.entries(intent).some(([k, v]) => k !== 'type' && k !== 'removeAdmission' && v !== undefined))
383
+ throw malformed(intentId, 'intent.removeAdmission beside another member');
342
384
  return {
343
385
  type: 'commit',
344
386
  ...(intent.invite === undefined ? {} : { invite: { invitees: intent.invite.invitees.map((i) => ({ event: i.event, inviteeRef: i.inviteeRef })) } }),
@@ -348,6 +390,7 @@ function encodeStorableIntent(intentId, intent) {
348
390
  ...(intent.removeAccounts === undefined ? {} : { removeAccounts: [...intent.removeAccounts], removeAccountLeafKeys: [...(intent.removeAccountLeafKeys ?? [])] }),
349
391
  ...(intent.origin === undefined ? {} : { origin: intent.origin }),
350
392
  ...(intent.components === undefined ? {} : { components: checkComponents(intent.components, (detail) => malformed(intentId, detail)) }),
393
+ ...(intent.removeAdmission === undefined ? {} : { removeAdmission: encodeAdmissionTarget(intent.removeAdmission, (detail) => malformed(intentId, detail)) }),
351
394
  };
352
395
  }
353
396
  case 'self-update':
@@ -675,6 +718,11 @@ export function decodeOwnChange(raw, at, fail) {
675
718
  if (typeof raw.componentId !== 'number' || !isComponentId(raw.componentId))
676
719
  throw fail(`${at}.componentId invalid`);
677
720
  return { type: 'component', componentId: raw.componentId };
721
+ case 'admission-removed':
722
+ onlyMembers(raw, ['type', 'account', 'leafKey', 'candidateId'], at, fail);
723
+ if (!isAccountPubkey(raw.account) || !isHexString(raw.leafKey) || !isHex64(raw.candidateId))
724
+ throw fail(`${at} admission-removed invalid`);
725
+ return { type: 'admission-removed', account: raw.account, leafKey: raw.leafKey, candidateId: raw.candidateId };
678
726
  default:
679
727
  throw fail(`${at}.type unknown`);
680
728
  }
@@ -702,9 +750,18 @@ export function decodeStoredOwnChange(raw, at, fail, allowVerdict = true) {
702
750
  if (obj[k] !== undefined && !allowed.includes(k))
703
751
  throw fail(`${where}.${k} not allowed for ${change.type}`);
704
752
  };
705
- members(raw, change.type === 'component' ? ['change', 'data', 'fork', 'verdict'] : change.type === 'member-added' ? ['change', 'fork', 'winnerHeldInvitee', 'keyPackage', 'verdict'] : change.type === 'member-removed' ? ['change', 'fork', 'winnerRemovedTarget', 'verdict'] : ['change', 'fork', 'verdict'], at);
753
+ members(raw, change.type === 'component'
754
+ ? ['change', 'data', 'fork', 'verdict']
755
+ : change.type === 'member-added'
756
+ ? ['change', 'fork', 'winnerHeldInvitee', 'keyPackage', 'verdict']
757
+ : change.type === 'member-removed'
758
+ ? ['change', 'fork', 'winnerRemovedTarget', 'verdict']
759
+ : change.type === 'admission-removed'
760
+ ? ['change', 'fork', 'target', 'verdict']
761
+ : ['change', 'fork', 'verdict'], at);
706
762
  let data;
707
763
  let keyPackage;
764
+ let target;
708
765
  const fork = {};
709
766
  switch (change.type) {
710
767
  case 'component':
@@ -740,6 +797,13 @@ export function decodeStoredOwnChange(raw, at, fail, allowVerdict = true) {
740
797
  throw fail(`${at}.keyPackage invalid`);
741
798
  keyPackage = { event: raw.keyPackage.event, inviteeRef: raw.keyPackage.inviteeRef };
742
799
  break;
800
+ case 'admission-removed':
801
+ members(forkRaw, [], `${at}.fork`);
802
+ target = decodeAdmissionTarget(raw.target, `${at}.target`, fail);
803
+ // The change names exactly its target (I16): the same candidate, account and leaf.
804
+ if (target.candidateId !== change.candidateId || target.account !== change.account || target.anchor.leafKey !== change.leafKey)
805
+ throw fail(`${at}.target does not match the change`);
806
+ break;
743
807
  }
744
808
  const verdict = raw.verdict;
745
809
  if (verdict !== undefined && verdict !== 'reapplied' && !OWN_CHANGE_LOST_REASONS.includes(verdict))
@@ -751,6 +815,7 @@ export function decodeStoredOwnChange(raw, at, fail, allowVerdict = true) {
751
815
  ...(raw.winnerHeldInvitee === undefined ? {} : { winnerHeldInvitee: raw.winnerHeldInvitee }),
752
816
  ...(raw.winnerRemovedTarget === undefined ? {} : { winnerRemovedTarget: raw.winnerRemovedTarget }),
753
817
  ...(keyPackage === undefined ? {} : { keyPackage }),
818
+ ...(target === undefined ? {} : { target }),
754
819
  ...(verdict === undefined ? {} : { verdict: verdict }),
755
820
  };
756
821
  }
@@ -769,6 +834,7 @@ export function encodeStoredOwnChange(c, allowVerdict = true) {
769
834
  ...(loose.winnerHeldInvitee === undefined ? {} : { winnerHeldInvitee: loose.winnerHeldInvitee }),
770
835
  ...(loose.winnerRemovedTarget === undefined ? {} : { winnerRemovedTarget: loose.winnerRemovedTarget }),
771
836
  ...(loose.keyPackage === undefined ? {} : { keyPackage: { event: loose.keyPackage.event, inviteeRef: loose.keyPackage.inviteeRef } }),
837
+ ...(loose.target === undefined ? {} : { target: encodeAdmissionTarget(loose.target, (detail) => new MarmotError('store-failed', `StoredOwnChange: refusing to write a malformed change (${detail})`, { details: { malformed: true } })) }),
772
838
  ...(loose.verdict === undefined ? {} : { verdict: loose.verdict }),
773
839
  };
774
840
  // Defense in depth against a mis-shaped write that got past the type (a cast, untyped JS): the write-time check is the read-time rule.
@@ -811,12 +877,20 @@ function assertRedriveShape(kind, intent, reenqueuedFrom, fail) {
811
877
  * (S9); read when a rewind withdraws the commit.
812
878
  */
813
879
  export const OWN_COMMIT_EXTENSION = 'marmot.own-commit';
814
- /** A declared set is non-empty: `removed` / `components` non-empty arrays (accounts, u16 ids, no duplicates), `admins` only as `true`. */
880
+ /** A declared set is non-empty: `removed` / `components` / `admissions` non-empty arrays (accounts, u16 ids, targets; no duplicates), `admins` only as `true`. */
815
881
  function checkDeclared(raw, fail) {
816
882
  if (!isObject(raw))
817
883
  throw fail('declared not an object');
818
- onlyMembers(raw, ['removed', 'admins', 'components'], 'declared', fail);
884
+ onlyMembers(raw, ['removed', 'admins', 'components', 'admissions'], 'declared', fail);
819
885
  const { removed, admins, components } = raw;
886
+ let admissions;
887
+ if (raw.admissions !== undefined) {
888
+ if (!Array.isArray(raw.admissions) || raw.admissions.length === 0)
889
+ throw fail('declared.admissions invalid');
890
+ admissions = raw.admissions.map((t, i) => decodeAdmissionTarget(t, `declared.admissions[${String(i)}]`, fail));
891
+ if (new Set(admissions.map((t) => t.candidateId)).size !== admissions.length)
892
+ throw fail('declared.admissions invalid');
893
+ }
820
894
  if (removed !== undefined && (!Array.isArray(removed) || removed.length === 0 || !removed.every(isAccountPubkey) || new Set(removed).size !== removed.length))
821
895
  throw fail('declared.removed invalid');
822
896
  if (admins !== undefined && admins !== true)
@@ -824,12 +898,13 @@ function checkDeclared(raw, fail) {
824
898
  if (components !== undefined && (!Array.isArray(components) || components.length === 0 || !components.every((id) => typeof id === 'number' && isComponentId(id)) || new Set(components).size !== components.length)) {
825
899
  throw fail('declared.components invalid');
826
900
  }
827
- if (removed === undefined && admins === undefined && components === undefined)
901
+ if (removed === undefined && admins === undefined && components === undefined && admissions === undefined)
828
902
  throw fail('declared empty');
829
903
  return {
830
904
  ...(removed === undefined ? {} : { removed: [...removed] }),
831
905
  ...(admins === undefined ? {} : { admins: true }),
832
906
  ...(components === undefined ? {} : { components: [...components] }),
907
+ ...(admissions === undefined ? {} : { admissions }),
833
908
  };
834
909
  }
835
910
  function malformedMarker(eventId, detail) {
@@ -878,7 +953,15 @@ export function encodeOwnCommitMarker(marker, eventId = '?') {
878
953
  for (const i of marker.invitees ?? [])
879
954
  if (!isObject(i.event) || !isHex64(i.leafKey))
880
955
  throw malformedMarker(eventId, 'invitee invalid');
881
- const declared = marker.declared === undefined ? undefined : checkDeclared(marker.declared, (detail) => malformedMarker(eventId, detail));
956
+ const checked = marker.declared === undefined ? undefined : checkDeclared(marker.declared, (detail) => malformedMarker(eventId, detail));
957
+ const declared = checked === undefined
958
+ ? undefined
959
+ : {
960
+ ...(checked.removed === undefined ? {} : { removed: [...checked.removed] }),
961
+ ...(checked.admins === undefined ? {} : { admins: true }),
962
+ ...(checked.components === undefined ? {} : { components: [...checked.components] }),
963
+ ...(checked.admissions === undefined ? {} : { admissions: checked.admissions.map((t) => encodeAdmissionTarget(t, (detail) => malformedMarker(eventId, detail))) }),
964
+ };
882
965
  return {
883
966
  v: 1,
884
967
  root: marker.root,
@@ -15,11 +15,12 @@ import type { Unsubscribable } from '@941design/nostr-events/transport/contract'
15
15
  import { MarmotGroupEngine, type ActiveAdminLeaverPredicate } from '@941design/marmot-engine/engine';
16
16
  import { type ClientState } from '@941design/marmot-engine/mls';
17
17
  import { type DeviceGroupPort, type TeardownGroupPort, type TeardownService } from '../account/index.js';
18
- import { type CompetingWelcomePorts, type InvitationsService } from '../invitations/index.js';
18
+ import { type AdoptionProof, type CompetingWelcomePorts, type InvitationsService } from '../invitations/index.js';
19
19
  import { MarmotError } from '../shared/index.js';
20
20
  import type { GroupStore } from '../storage/index.js';
21
21
  import { type GroupNotification, type JoinEvidence, type RetainedWindow } from '../history/index.js';
22
22
  import { type HeldRemoval } from './group-removal.js';
23
+ import { type RuntimeAvailability } from './group-availability.js';
23
24
  import { type OpaqueRecord } from './opaque-candidates.js';
24
25
  import type { ClientContext, ConfirmHook, GroupIntent, LeafInfo, MarmotGroup, MarmotClient } from './create-client.js';
25
26
  import { type DisbandRecord } from './group-disband.js';
@@ -29,7 +30,7 @@ import { type SelfRemoveElection } from './pipeline.js';
29
30
  import { type HistorySilenceTracker } from './transport-policy.js';
30
31
  /** Every leaf of `account` in `state`: its leaf index and signature key (hex). */
31
32
  export declare function leafInfosOf(state: ClientState, account: string): LeafInfo[];
32
- export interface GroupRuntime {
33
+ export interface GroupRuntime extends RuntimeAvailability {
33
34
  readonly groupId: string;
34
35
  readonly groupStore: GroupStore;
35
36
  engine: MarmotGroupEngine<NostrEvent>;
@@ -292,7 +293,9 @@ export interface GroupRuntime {
292
293
  disbanded: DisbandRecord | undefined;
293
294
  /**
294
295
  * S10 (AC-HIST-4): set once the group is fenced — the `cause` every further operation's `fenced` carries.
295
- * Assigning it (ingest.ts, group-history.ts `fenceGroup`) fires {@link terminalWatchers}.
296
+ * Assigning it (ingest.ts, group-history.ts `fenceGroup`) fires {@link terminalWatchers}, records the fence in the
297
+ * client's session fences and publishes the group's availability (client/group-availability.ts: an observation,
298
+ * never a termination of the availability subscriptions).
296
299
  */
297
300
  fence: Error | undefined;
298
301
  /** S10: `onNotification` listeners, in registration order. */
@@ -347,6 +350,17 @@ export interface GroupRegistry {
347
350
  * GroupInfo, written on the root of the join-time window; absent for an untagged Welcome.
348
351
  */
349
352
  adoptJoinedGroup(groupId: string, state: ClientState, joinedAtMs: number, joinEvidence?: JoinEvidence, invitationId?: string, welcomeCreatedAtMs?: number): Promise<'joined' | 'already-member'>;
353
+ /**
354
+ * Epic marmot-invitation-outcomes S2: invitation `invitationId`'s join adoption proof in `groupId`'s store
355
+ * (`marmot.adoption`), or `undefined` (none, or malformed). How a resumed join whose adoption answered
356
+ * `already-member` tells its own earlier adoption from another invitation's.
357
+ */
358
+ adoptionProofOf(groupId: string, invitationId: string): Promise<AdoptionProof | undefined>;
359
+ /**
360
+ * Epic marmot-invitation-outcomes S4 (AC-REMOVE-15): whether a fence of `groupId` was raised in this client session —
361
+ * a live runtime's fence, or one whose marker write failed. The disposition read reports `lastKnown` for it.
362
+ */
363
+ sessionFenced(groupId: string): boolean;
350
364
  /**
351
365
  * The ports of the competing-Welcome decision (epic marmot-welcome-race-joiner): the group's gate, its held
352
366
  * branch, the rebase onto a competing Welcome's state and the switch report.
@@ -382,6 +396,19 @@ export interface GroupRegistry {
382
396
  * access to a group still checks its mark). A scan whose index read failed is redone by the next call. Never throws.
383
397
  */
384
398
  resumeUnfinishedRestores(): void;
399
+ /**
400
+ * Epic marmot-invitation-outcomes (SC-10 A-4, A-5): the client's account lease ended — every runtime's availability
401
+ * subscriptions end `no-lease`, and every later subscription gets one immediate `ended`. Synchronous; schedules no
402
+ * group work and touches no store. Never throws.
403
+ */
404
+ endAvailabilityForLease(): void;
405
+ /**
406
+ * Phase one of `client.dispose()`, run before any consumer teardown code (a store unsubscriber): records the
407
+ * client-wide `disposed` end (unless the lease ended first) and every live runtime's `ended`, delivering nothing. A
408
+ * subscribe from inside that teardown gets the one stored `ended`, never a snapshot of a disposed client's group.
409
+ * {@link dispose} delivers the recorded ends. Idempotent; never throws.
410
+ */
411
+ beginDispose(): void;
385
412
  /** Tears every runtime down, each step isolated; returns the errors of the steps that threw (never throws itself). */
386
413
  dispose(): unknown[];
387
414
  }
@@ -5,11 +5,14 @@ import { accountLeafIndexes, activeAdmins, enforceStateProofs, isActiveAdmin, is
5
5
  import { ownLeafOf } from './rekey.js';
6
6
  import { DEFAULT_CIPHERSUITE_NAME, deviceProofSigner, ensureDeviceSigningKey, readDeviceSigningKey, withDeviceSignatureKey } from '../key-packages/index.js';
7
7
  import { carriesBranch, judgeCompetingWelcome, toWelcomeOutcome } from '../invitations/index.js';
8
- import { MarmotError, isMarmotError } from '../shared/index.js';
9
- import { canonicalPath, successionsInWindow, EQUIVOCATION_EXTENSION, FENCE_EXTENSION, fencedError, heldBranchScore, readEquivocationNotifications, readFence, readWindow, recordedFencingError, restoreHistory, REWIND_HORIZON, tagOf, tipOnlyWindow, windowFor, writeWindow, } from '../history/index.js';
8
+ import { hexOfBytes, MarmotError, isMarmotError } from '../shared/index.js';
9
+ import { ADMISSION_LINEAGE_EXTENSION, canonicalPath, replaceLineageRecords, successionsInWindow, validateRestoredLineage, EQUIVOCATION_EXTENSION, FENCE_EXTENSION, fencedError, heldBranchScore, InvalidStoredEvidenceError, loadFenceMarker, readEquivocationNotifications, readWindow, recordedFencingError, restoreHistory, REWIND_HORIZON, tagOf, tipOnlyWindow, windowFor, writeWindow, } from '../history/index.js';
10
10
  import { belongsTo, clearRemoval, readRemoval, REMOVAL_EXTENSION, settlesAt } from './group-removal.js';
11
+ import { beginDisposeAvailability, closeAvailability, createClientAvailability, beginLeaseEndAvailability, observeAvailability, publishAvailability, } from './group-availability.js';
12
+ import { readAdoptionProofOf, readAdoptionProofs, SWITCH_PROOF_EXTENSION, writeAdoptionProof } from './adoption-proof.js';
13
+ import { removeAdmissionIntent } from './admission-cleanup.js';
11
14
  import { clearOpaque, isEmptyOpaque, OPAQUE_EXTENSION, OpaqueRecordCorrupt, readOpaque } from './opaque-candidates.js';
12
- import { assertNotInHistoryBackend, awaitHistoryCallSettled, boundedHistoryCall, issueMutation, clearSettlementRecheck, decryptMediaOp, deliverTransition, reconcileInvitesWithWindow, encryptMediaOp, planTransition, recordTransition, scheduleHistoryDrain, WITHDRAWN_DISPOSITION, stopHistoryDrain, historyOf, readSettlementRecheckRecord, SETTLEMENT_RECHECK_EXTENSION, subscribeNotifications } from './group-history.js';
15
+ import { assertNotInHistoryBackend, awaitHistoryCallSettled, boundedHistoryCall, issueMutation, clearSettlementRecheck, decryptMediaOp, deliverTransition, reconcileInvitesWithWindow, encryptMediaOp, planTransition, recordTransition, scheduleHistoryDrain, WITHDRAWN_DISPOSITION, stopHistoryDrain, historyOf, readSettlementRecheckRecord, SETTLEMENT_RECHECK_EXTENSION, subscribeNotifications, rejectSyncWaiters, syncedLeaseLostError, accountLeaseEndedError } from './group-history.js';
13
16
  import { clearRestoringRecord, GROUP_INDEX_EXTENSION, deletePendingIntentRecord, hasGroupState, listGroupIndex, listRestoringRecords, listPendingIntentRecords, listPendingIntentSummaries, listQueuedRumorRecords, RATCHET_SKIP_EXTENSION, ratchetSkipArmed, readGroupIndexEntry, readGroupState, readIngestCursor, readRatchetSkipMarker, readRestorePending, RESTORE_PENDING_EXTENSION, RESTORING_EXTENSION, writeGroupIndexEntry, writeGroupState, writeIngestCursor, writeRestorePending, writeTerminalLedgerEntry, writeRestoringRecord, } from './group-records.js';
14
17
  import { DISBAND_EXTENSION, disbandedError, groupDisbandedOf, readDisband } from './group-disband.js';
15
18
  import { drainConvergence, ingestEvents, requestHistoryResync, scheduleRemovalSettle, restartSyncOnRoutingChange, startGroupSync, stopGroupSync, treeFedPass } from './ingest.js';
@@ -18,8 +21,6 @@ import { ACCOUNT_SCOPE } from './reentrancy-guard.js';
18
21
  import { advanceQueue, backoffMs, inviteIntent, proposeSelfRemoveIntent, removeLeafIntent, electionAtRest, removeMemberIntent, renameIntent, rekeyIntent, resumePendingInBackground, scheduleAwaitingFenceCleanup, scheduleDeferredReenqueueRetry, scheduleProposalDeadlineCheck, scheduleRekeyFollowUp, scheduleSelfRemoveCommit, notifySettled, ownMessage, scheduleWithdrawnRedrives, sendIntent, setAdminsIntent, } from './pipeline.js';
19
22
  import { createHistorySilenceTracker, CURSOR_FUTURE_SKEW_S, CURSOR_REDELIVERY_MARGIN_S } from './transport-policy.js';
20
23
  import { runConfirmHooks } from './confirm-hooks.js';
21
- /** The group extension holding one row per invitation whose switch transaction committed: the durable proof it was written. */
22
- const SWITCH_PROOF_EXTENSION = 'marmot.branchSwitch';
23
24
  /** An error thrown by an `onConfirm` hook itself (as opposed to the store or the guard around it). */
24
25
  class HookRefusal extends Error {
25
26
  error;
@@ -177,6 +178,10 @@ async function loadOpaque(guard, groupId, groupStore) {
177
178
  }
178
179
  export function createGroupRegistry(ctx, guard, invitations, teardown) {
179
180
  const runtimes = new Map();
181
+ /** Epic marmot-invitation-outcomes S1: this client session's fences and lease-end flag (client/group-availability.ts). */
182
+ const availabilityClient = createClientAvailability(() => runtimes.values());
183
+ /** The recorded-but-undelivered `ended/'disposed'` deliveries ({@link GroupRegistry.beginDispose}, then `dispose`). */
184
+ const disposeAvailabilityDeliveries = [];
180
185
  // Stryker disable next-line all: test seam (InternalClientOptions.exposeRuntimesForTest)
181
186
  ctx.exposeRuntimesForTest?.((groupId) => runtimes.get(groupId));
182
187
  const loading = new Map();
@@ -557,6 +562,10 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
557
562
  assertLive();
558
563
  return rt.run('ingest', (rtc) => ingestEvents(rtc, events));
559
564
  },
565
+ observeAvailability(listener) {
566
+ // Exempt from the fenced refusal, and answers after teardown, dispose or lease end with the one `ended` (A-6).
567
+ return observeAvailability(rt, listener);
568
+ },
560
569
  async synced() {
561
570
  assertLive();
562
571
  if (rt.fence !== undefined)
@@ -565,6 +574,12 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
565
574
  throw disbandedError(rt.groupId, 'synced', rt.disbanded);
566
575
  if (rt.sendGateOpen)
567
576
  return;
577
+ // The lease is gone for this client (observed on this group, or client-wide through the store's lease-end
578
+ // signal, also for a runtime built afterwards): the gate never opens, so the wait fails at once.
579
+ if (rt.leaseLost !== undefined)
580
+ throw syncedLeaseLostError(rt, rt.leaseLost);
581
+ if (rt.availabilityClient.leaseEnded)
582
+ throw syncedLeaseLostError(rt, accountLeaseEndedError());
568
583
  // ADR-013: awaited from inside a consumer surface of this group (a verifier, onProposal, a store call of the
569
584
  // very ingest that would open the gate), the wait could never end — rejected `reentrant` instead.
570
585
  guard.assertNotReentrant(rt.groupId, 'synced');
@@ -630,6 +645,11 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
630
645
  assertLive();
631
646
  await rt.run('removeMember', (rtc) => removeMemberIntent(rtc, account));
632
647
  },
648
+ // Epic marmot-invitation-outcomes S5 (SC-11): the cleanup ladder runs as one group operation.
649
+ async removeAdmission(ref) {
650
+ assertLive();
651
+ return rt.run('removeAdmission', (rtc) => removeAdmissionIntent(rtc, ref));
652
+ },
633
653
  departAsAdmin() {
634
654
  return teardownOp('departAsAdmin', (t) => t.depart(rt.groupId));
635
655
  },
@@ -669,6 +689,16 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
669
689
  function makeRuntime(groupId, groupStore, engine, joinedAtMs, persisted = {}) {
670
690
  let exposed = engine.state;
671
691
  let fence = persisted.fence;
692
+ // Epic marmot-invitation-outcomes S1: the availability facts below publish through their accessors (SC-10).
693
+ let caughtUp = false;
694
+ // AC-PIPE-15: closed only for state read back from the store (see GroupRuntime.sendGateOpen).
695
+ let sendGateOpen = persisted.loaded !== true;
696
+ let disbanded = persisted.disbanded;
697
+ // A-7: a new adoption (a join, a restore) starts the group over; a fence a load starts with is the session's.
698
+ if (fence !== undefined)
699
+ availabilityClient.sessionFences.record(groupId, fence);
700
+ else if (persisted.adoption === true)
701
+ availabilityClient.sessionFences.clear(groupId);
672
702
  const rt = {
673
703
  groupId,
674
704
  groupStore,
@@ -679,8 +709,10 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
679
709
  set exposedState(state) {
680
710
  const changed = state !== exposed;
681
711
  exposed = state;
682
- if (changed)
712
+ if (changed) {
683
713
  notifyState(groupId);
714
+ publishAvailability(rt);
715
+ }
684
716
  },
685
717
  joinedAtMs,
686
718
  resyncNeeded: false,
@@ -707,8 +739,11 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
707
739
  set fence(cause) {
708
740
  const was = fence;
709
741
  fence = cause;
710
- if (was === undefined && cause !== undefined)
742
+ if (was === undefined && cause !== undefined) {
743
+ availabilityClient.sessionFences.record(groupId, cause);
711
744
  endRuntime(rt, { reason: 'fenced', cause });
745
+ }
746
+ publishAvailability(rt);
712
747
  },
713
748
  removal: persisted.removal,
714
749
  async removalSettled(actor) {
@@ -725,7 +760,18 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
725
760
  opaque: persisted.opaque,
726
761
  pendingCommit: persisted.pendingCommit,
727
762
  pendingLeaf: persisted.pendingLeaf,
728
- disbanded: persisted.disbanded,
763
+ get disbanded() {
764
+ return disbanded;
765
+ },
766
+ set disbanded(record) {
767
+ disbanded = record;
768
+ publishAvailability(rt);
769
+ },
770
+ availabilityListeners: new Set(),
771
+ availabilitySeq: 0,
772
+ availabilityLast: undefined,
773
+ availabilityEnded: undefined,
774
+ availabilityClient,
729
775
  notificationListeners: new Set(),
730
776
  announceRewind: () => announceRewind(groupId),
731
777
  announceRotation: () => announceRotation(groupId),
@@ -739,10 +785,21 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
739
785
  walkStartedAt: undefined,
740
786
  catchUpSince: undefined,
741
787
  syncStarted: false,
742
- caughtUp: false,
788
+ get caughtUp() {
789
+ return caughtUp;
790
+ },
791
+ set caughtUp(value) {
792
+ caughtUp = value;
793
+ publishAvailability(rt);
794
+ },
743
795
  connectivityGeneration: 0,
744
- // AC-PIPE-15: closed only for state read back from the store (see GroupRuntime.sendGateOpen).
745
- sendGateOpen: persisted.loaded !== true,
796
+ get sendGateOpen() {
797
+ return sendGateOpen;
798
+ },
799
+ set sendGateOpen(value) {
800
+ sendGateOpen = value;
801
+ publishAvailability(rt);
802
+ },
746
803
  // AC-RATCH-1: armed for the same loaded state unless its stored skip is still undelivered (see GroupRuntime.ratchetSkipPending).
747
804
  ratchetSkipPending: persisted.loaded === true && persisted.ratchetSkipArmed !== false,
748
805
  syncWaiters: new Set(),
@@ -870,6 +927,8 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
870
927
  },
871
928
  };
872
929
  rt.handle = buildHandle(rt);
930
+ // The runtime's first availability snapshot (seq 1): what a subscriber's initial observation carries until a change.
931
+ publishAvailability(rt);
873
932
  runtimes.set(groupId, rt);
874
933
  // AC-FWJ-31: an own intent settling clears "own commit pending"; the first sync's end (the send gate opening)
875
934
  // clears "syncing". Both ask whether a `competing` Welcome waits for the group.
@@ -1064,6 +1123,10 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
1064
1123
  // Epic marmot-leaf-backup-pre-publish S2: what an earlier state of this group parked or marked belongs to that state.
1065
1124
  await clearPendingLeaf(tx.extension(PENDING_LEAF_EXTENSION));
1066
1125
  await clearPendingCommit(tx.extension(PENDING_COMMIT_EXTENSION));
1126
+ // Epic marmot-invitation-outcomes S2 (ADR-019 D6): the adopting invitation's proof, with the state it adopted.
1127
+ // Adoption happens when this transaction commits and the compensating clear below does not retract it.
1128
+ if (invitationId !== undefined)
1129
+ await writeAdoptionProof(tx, invitationId, { via: 'join', tag: hexOfBytes(clientState.confirmationTag), at: joinedAtMs });
1067
1130
  // AC-MX-1: only an adoption that writes the group runs the hooks (never `already-member`); a throw
1068
1131
  // stores nothing — the join stays `joining` and a later inbox pass completes it.
1069
1132
  await runConfirmHooks({ groupId, guard, hooks: confirmHooks }, { intentId: groupId, kind: 'join', epoch: clientState.groupContext.epoch, tx, persisted: () => ({ state: clientState, window }), notifications: [], createdAt: joinedAtMs });
@@ -1092,7 +1155,7 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
1092
1155
  engine.dispose();
1093
1156
  throw new MarmotError('disposed', 'invitations: client was disposed while joining the group');
1094
1157
  }
1095
- rt = makeRuntime(groupId, groupStore, engine, joinedAtMs, { window });
1158
+ rt = makeRuntime(groupId, groupStore, engine, joinedAtMs, { window, adoption: true });
1096
1159
  }
1097
1160
  }
1098
1161
  catch (error) {
@@ -1252,7 +1315,8 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
1252
1315
  const indexEntry = await guard.call(groupId, 'store', () => guard.call(ACCOUNT_SCOPE, 'store', () => readGroupIndexEntry(ctx.stores.account.extension(GROUP_INDEX_EXTENSION), groupId)));
1253
1316
  // S10: the rewind window and the fence marker, read with the state they describe.
1254
1317
  const stored = await guard.call(groupId, 'store', () => readWindow(groupStore.artifact('rewindTree')));
1255
- const fence = await guard.call(groupId, 'store', () => readFence(groupStore.extension(FENCE_EXTENSION)));
1318
+ // Epic marmot-invitation-outcomes S1 (A-7, AC-FENCE-4): a malformed present marker fails closed.
1319
+ const marker = await guard.call(groupId, 'store', () => loadFenceMarker(groupStore.extension(FENCE_EXTENSION)));
1256
1320
  const disbanded = await guard.call(groupId, 'store', () => readDisband(groupStore.extension(DISBAND_EXTENSION)));
1257
1321
  // S20: a stored tombstone keeps its revisable removal (the retained tip and history are the removal's parent).
1258
1322
  const storedRemoval = await guard.call(groupId, 'store', () => readRemoval(groupStore.extension(REMOVAL_EXTENSION)));
@@ -1272,13 +1336,21 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
1272
1336
  engine.dispose();
1273
1337
  throw new MarmotError('disposed', 'groups.get: client was disposed while loading the group');
1274
1338
  }
1339
+ // A-7: a fence this session already raised for the group (its marker write may have failed), else the marker, else
1340
+ // a malformed present marker, else a corrupt held-candidate record.
1341
+ const fenceOnLoad = availabilityClient.sessionFences.get(groupId) ??
1342
+ (marker.kind === 'valid'
1343
+ ? recordedFencingError(marker.record)
1344
+ : marker.kind === 'malformed'
1345
+ ? new InvalidStoredEvidenceError(`group ${groupId}: the stored fence marker (${FENCE_EXTENSION}) is malformed`)
1346
+ : corrupt);
1275
1347
  return makeRuntime(groupId, groupStore, engine, indexEntry?.createdAt, {
1276
1348
  loaded: true,
1277
1349
  ratchetSkipArmed: ratchetSkipArmed(skipMarker, state.groupContext.epoch, tagOf(state), nextOwnApplicationGeneration(state)),
1278
1350
  window: windowFor(stored, state),
1279
1351
  ...(removal === undefined ? {} : { removal }),
1280
1352
  ...(corrupt !== undefined || opaque.record === undefined ? {} : { opaque: opaque.record }),
1281
- ...(fence !== undefined ? { fence: recordedFencingError(fence) } : corrupt === undefined ? {} : { fence: corrupt }),
1353
+ ...(fenceOnLoad === undefined ? {} : { fence: fenceOnLoad }),
1282
1354
  ...(disbanded === undefined ? {} : { disbanded }),
1283
1355
  ...pendingRestore,
1284
1356
  });
@@ -1463,6 +1535,9 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
1463
1535
  await writeRestorePending(tx.extension(RESTORE_PENDING_EXTENSION), ctx.clock.now());
1464
1536
  await writeGroupState(tx.artifact('clientState'), content.state);
1465
1537
  await writeWindow(tx.artifact('rewindTree'), window);
1538
+ // Epic marmot-invitation-outcomes S4 (SC-4): the snapshot's admission lineage, kept only where its own window
1539
+ // proves it; every other record restores as a gap (`restore`) — never settled until a transition re-proves it.
1540
+ await replaceLineageRecords(tx.extension(ADMISSION_LINEAGE_EXTENSION), validateRestoredLineage(content.lineage ?? [], window, content.state));
1466
1541
  // The restored engine is built with no opaque record (nothing was handed to the snapshot's state yet); a
1467
1542
  // `marmot.opaque` left by an earlier state of this group belongs to that state, so it goes in this transaction:
1468
1543
  // a reload must not rehydrate candidates that describe another history.
@@ -1502,7 +1577,7 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
1502
1577
  throw new MarmotError('disposed', 'groups.restore: client was disposed while restoring the group');
1503
1578
  }
1504
1579
  // A load, not a join: the snapshot may be older than what the relays hold (AC-PIPE-15, AC-RATCH-1).
1505
- rt = makeRuntime(groupId, groupStore, engine, createdAt, { loaded: true, window, ...(pendingMarker === undefined ? {} : { pendingCommit: pendingMarker }) });
1580
+ rt = makeRuntime(groupId, groupStore, engine, createdAt, { loaded: true, adoption: true, window, ...(pendingMarker === undefined ? {} : { pendingCommit: pendingMarker }) });
1506
1581
  entry.runtime = rt;
1507
1582
  const runtime = rt;
1508
1583
  runtime.terminalWatchers.add((ending) => end(restoreEndError(groupId, ending)));
@@ -1855,7 +1930,7 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
1855
1930
  await rt
1856
1931
  .runLast(() => {
1857
1932
  if (!rt.disposed)
1858
- retireRuntime(rt, 'could not be restored');
1933
+ retireRuntime(rt, 'could not be restored', 'restore-undone');
1859
1934
  })
1860
1935
  .catch(() => undefined);
1861
1936
  if (runtimes.get(groupId) === rt)
@@ -2083,9 +2158,10 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
2083
2158
  /**
2084
2159
  * Retires a group's runtime for good — inside its last operation (an abandoned group's purge, a failed restore
2085
2160
  * taken back): no sync, no timers, no engine; its handle and operations answer `not-a-member`; waiting queued
2086
- * sends and `synced()` callers learn `not-a-member` ("group X {@link what} before …"); its terminal watchers fire.
2161
+ * sends and `synced()` callers learn `not-a-member` ("group X {@link what} before …"); its terminal watchers fire;
2162
+ * its availability subscriptions end with `ended` (client/group-availability.ts) — after the last observation.
2087
2163
  */
2088
- function retireRuntime(rt, what) {
2164
+ function retireRuntime(rt, what, ended) {
2089
2165
  rt.abandoned = true;
2090
2166
  rt.disposed = true;
2091
2167
  for (const handle of rt.pipelineTimers)
@@ -2099,6 +2175,7 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
2099
2175
  waiter.reject(new MarmotError('not-a-member', `synced: group ${rt.groupId} ${what} before its first sync`, { details: { groupId: rt.groupId } }));
2100
2176
  rt.syncWaiters.clear();
2101
2177
  endRuntime(rt, { reason: 'retired' });
2178
+ closeAvailability(rt, ended);
2102
2179
  try {
2103
2180
  stopGroupSync(rt);
2104
2181
  }
@@ -2183,15 +2260,19 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
2183
2260
  }
2184
2261
  }
2185
2262
  const epoch = (await guard.call(groupId, 'store', () => readGroupState(store.artifact('clientState'))))?.groupContext.epoch;
2186
- if (epoch !== undefined)
2187
- await guard.call(ACCOUNT_SCOPE, 'store', () => beforeClear(epoch));
2263
+ if (epoch !== undefined) {
2264
+ // Epic marmot-invitation-outcomes S2 (A1): the adoption proofs the clear deletes, read in the same serialized
2265
+ // step, so teardown stamps every invitation they make `joined` before they go.
2266
+ const proofs = await guard.call(groupId, 'store', () => readAdoptionProofs(store, { skipMalformed: true }));
2267
+ await guard.call(ACCOUNT_SCOPE, 'store', () => beforeClear(epoch, proofs));
2268
+ }
2188
2269
  await guard.call(groupId, 'store', () => store.clear());
2189
2270
  };
2190
2271
  if (rt !== undefined && !rt.abandoned && !rt.disposed) {
2191
2272
  // Last operation on the group's queue: every operation queued before it finishes first, none after it runs.
2192
2273
  await rt.run('abandon', async (rtc) => {
2193
2274
  await deleteAll(rtc.groupStore, rtc);
2194
- retireRuntime(rtc, 'was left or abandoned');
2275
+ retireRuntime(rtc, 'was left or abandoned', 'torn-down');
2195
2276
  });
2196
2277
  }
2197
2278
  else {
@@ -2201,6 +2282,8 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
2201
2282
  if (rt !== undefined && runtimes.get(groupId) === rt)
2202
2283
  runtimes.delete(groupId);
2203
2284
  openedStores.delete(groupId);
2285
+ // A-7: the purged group's session fence goes with it (a later join or restore starts the group over).
2286
+ availabilityClient.sessionFences.clear(groupId);
2204
2287
  notifyState(groupId);
2205
2288
  }
2206
2289
  // ---------------------------------------------------------------------------
@@ -2573,6 +2656,8 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
2573
2656
  restore: restoreGroupOp,
2574
2657
  },
2575
2658
  adoptJoinedGroup: adoptJoinedGroupOp,
2659
+ adoptionProofOf: (groupId, invitationId) => guard.call(groupId, 'store', () => readAdoptionProofOf(groupStoreOf(groupId), invitationId)),
2660
+ sessionFenced: (groupId) => availabilityClient.sessionFences.get(groupId) !== undefined || runtimes.get(groupId)?.fence !== undefined,
2576
2661
  competing: competingPorts,
2577
2662
  onGateMayHaveCleared(listener) {
2578
2663
  gateClearedListener = listener;
@@ -2649,10 +2734,33 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
2649
2734
  });
2650
2735
  });
2651
2736
  },
2737
+ endAvailabilityForLease() {
2738
+ // The store's lease-end signal (A-5): in memory only — no group work, store access or transport call. Every
2739
+ // pending `synced()` wait fails `no-lease` now (the send gate never opens without the lease); a later one fails
2740
+ // at once through the client-wide flag. The waits fail before any availability listener runs: one reacting to its
2741
+ // `ended/'no-lease'` (a `dispose()`) must not turn the lease loss that came first into `disposed`.
2742
+ const deliverAvailabilityEnds = beginLeaseEndAvailability(availabilityClient, runtimes.values());
2743
+ const cause = accountLeaseEndedError();
2744
+ for (const rt of [...runtimes.values()])
2745
+ rejectSyncWaiters(rt, () => syncedLeaseLostError(rt, cause));
2746
+ deliverAvailabilityEnds();
2747
+ },
2748
+ beginDispose() {
2749
+ try {
2750
+ disposeAvailabilityDeliveries.push(beginDisposeAvailability(availabilityClient, runtimes.values()));
2751
+ }
2752
+ catch {
2753
+ // dispose() records whatever this missed
2754
+ }
2755
+ },
2652
2756
  dispose() {
2653
2757
  // Every runtime is torn down even when a step throws (a transport
2654
2758
  // unsubscribe, an engine dispose): the errors are returned, not thrown.
2655
2759
  const errors = [];
2760
+ // Every runtime's `ended/'disposed'` is recorded before any is delivered (and delivered only once all are torn
2761
+ // down): a listener of one group's `ended` never finds another group of this disposed client still open.
2762
+ // A runtime registered after `beginDispose` is marked here (the ones it marked are not marked twice).
2763
+ disposeAvailabilityDeliveries.push(beginDisposeAvailability(availabilityClient, runtimes.values()));
2656
2764
  for (const rt of runtimes.values()) {
2657
2765
  rt.disposed = true;
2658
2766
  for (const handle of rt.pipelineTimers) {
@@ -2695,6 +2803,8 @@ export function createGroupRegistry(ctx, guard, invitations, teardown) {
2695
2803
  rewindListeners.clear();
2696
2804
  restoredListeners.clear();
2697
2805
  rotationListeners.clear();
2806
+ for (const deliver of disposeAvailabilityDeliveries.splice(0))
2807
+ deliver();
2698
2808
  return errors;
2699
2809
  },
2700
2810
  };
@@ -1,5 +1,5 @@
1
1
  import { type CiphersuiteImpl, type ClientConfig, type ClientState } from '@941design/marmot-engine/mls';
2
- import { type RestoredHistory, type RetainedWindow } from '../history/index.js';
2
+ import { type AdmissionLineageRecord, type RestoredHistory, type RetainedWindow } from '../history/index.js';
3
3
  import { type CodecVersions } from '../storage/index.js';
4
4
  declare const GROUP_SNAPSHOT_BRAND: unique symbol;
5
5
  /**
@@ -59,6 +59,12 @@ export interface GroupSnapshotContent {
59
59
  * parent node carries its serialized state, so a restore that finds the commit unpublished can land at the parent.
60
60
  */
61
61
  readonly pending?: PendingMarker;
62
+ /**
63
+ * Epic marmot-invitation-outcomes S4 (SC-4): the group's admission lineage when the snapshot was taken (additive on
64
+ * v1: a snapshot without it opens as before). Opened as well-formed records only; `groups.restore` keeps a record
65
+ * only where the snapshot's own window proves it (`validateRestoredLineage`), every other one restores as a gap.
66
+ */
67
+ readonly lineage?: readonly AdmissionLineageRecord[];
62
68
  }
63
69
  /**
64
70
  * Seals `content` as a {@link GroupSnapshot} stamped with `versions` (default: this build). Throws