@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
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Group adoption proofs (epic marmot-invitation-outcomes S2; ADR-019 D6).
3
+ *
4
+ * Two group extensions record which invitation's Welcome put the group's state into this store:
5
+ *
6
+ * - `marmot.adoption` ({@link ADOPTION_PROOF_EXTENSION}): `invitationId` → `{ v: 1, via: 'join', tag, at }`, written
7
+ * in the SAME group transaction as the adopted state (`group-runtime.ts` `adoptJoinedGroupOp`). Adoption happens
8
+ * when that transaction commits and the adopting call does not retract it (its compensating clear);
9
+ * - `marmot.branchSwitch` ({@link SWITCH_PROOF_EXTENSION}): `invitationId` → `{ to }`, written in a competing
10
+ * Welcome's switch transaction (`rebaseOnQueue`).
11
+ *
12
+ * Only teardown (after stamping), the adoption's compensating clear and an account wipe remove them (the
13
+ * proof-retraction rule, enumerated by the S2 oracle's `RETRACTORS` test).
14
+ */
15
+ import { type AdoptionProof, type AdoptionProofs } from '../invitations/index.js';
16
+ import type { KeyValueView } from '../storage/index.js';
17
+ /** The group extension of join adoption proofs. */
18
+ export declare const ADOPTION_PROOF_EXTENSION = "marmot.adoption";
19
+ /** The group extension holding one row per invitation whose switch transaction committed: the durable proof it was written. */
20
+ export declare const SWITCH_PROOF_EXTENSION = "marmot.branchSwitch";
21
+ /** Anything with group extensions: a `GroupStore` or one of its transactions. */
22
+ export interface ExtensionScope {
23
+ extension(id: string): KeyValueView;
24
+ }
25
+ /** Writes invitation `invitationId`'s join adoption proof (inside the adoption's group transaction). */
26
+ export declare function writeAdoptionProof(scope: ExtensionScope, invitationId: string, proof: AdoptionProof): Promise<void>;
27
+ /**
28
+ * Invitation `invitationId`'s join adoption proof in the group, or `undefined`: none, or a malformed row — no evidence
29
+ * (the welcome processor's completion stamps only what a decodable proof names; the outcome reader rejects the row).
30
+ */
31
+ export declare function readAdoptionProofOf(scope: ExtensionScope, invitationId: string): Promise<AdoptionProof | undefined>;
32
+ /**
33
+ * Both proof maps of the group. A malformed row — its payload, or for either extension its envelope — rejects
34
+ * `store-failed` (`details.malformed`): the outcome reader never reads it as absent. `skipMalformed` (teardown's read before the clear): a malformed row is no evidence
35
+ * and is skipped, so it can never block the purge that deletes it.
36
+ */
37
+ export declare function readAdoptionProofs(scope: ExtensionScope, options?: {
38
+ readonly skipMalformed?: boolean;
39
+ }): Promise<AdoptionProofs>;
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Group adoption proofs (epic marmot-invitation-outcomes S2; ADR-019 D6).
3
+ *
4
+ * Two group extensions record which invitation's Welcome put the group's state into this store:
5
+ *
6
+ * - `marmot.adoption` ({@link ADOPTION_PROOF_EXTENSION}): `invitationId` → `{ v: 1, via: 'join', tag, at }`, written
7
+ * in the SAME group transaction as the adopted state (`group-runtime.ts` `adoptJoinedGroupOp`). Adoption happens
8
+ * when that transaction commits and the adopting call does not retract it (its compensating clear);
9
+ * - `marmot.branchSwitch` ({@link SWITCH_PROOF_EXTENSION}): `invitationId` → `{ to }`, written in a competing
10
+ * Welcome's switch transaction (`rebaseOnQueue`).
11
+ *
12
+ * Only teardown (after stamping), the adoption's compensating clear and an account wipe remove them (the
13
+ * proof-retraction rule, enumerated by the S2 oracle's `RETRACTORS` test).
14
+ */
15
+ import { isMalformedRowError } from '../invitations/index.js';
16
+ import { MarmotError } from '../shared/index.js';
17
+ /** The group extension of join adoption proofs. */
18
+ export const ADOPTION_PROOF_EXTENSION = 'marmot.adoption';
19
+ /** The group extension holding one row per invitation whose switch transaction committed: the durable proof it was written. */
20
+ export const SWITCH_PROOF_EXTENSION = 'marmot.branchSwitch';
21
+ function malformedProof(id, extension = ADOPTION_PROOF_EXTENSION, cause) {
22
+ return new MarmotError('store-failed', `${extension}/${id}: malformed adoption proof`, { details: { id, malformed: true }, ...(cause === undefined ? {} : { cause }) });
23
+ }
24
+ const MALFORMED = Symbol('malformed');
25
+ /**
26
+ * One proof row read raw: `undefined` when absent; `MALFORMED` when its envelope does not open (skipped when
27
+ * `skipMalformed`, else rejected `store-failed` `details.malformed` like a payload that does not decode). Every other
28
+ * error (the backend, the lease, a row of another build) propagates.
29
+ */
30
+ async function readProofRow(view, extension, key, skipMalformed) {
31
+ try {
32
+ return await view.get(key);
33
+ }
34
+ catch (error) {
35
+ if (!isMalformedRowError(error))
36
+ throw error;
37
+ if (skipMalformed)
38
+ return MALFORMED;
39
+ throw malformedProof(key, extension, error);
40
+ }
41
+ }
42
+ function decodeAdoptionProof(id, raw) {
43
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
44
+ throw malformedProof(id);
45
+ const r = raw;
46
+ if (r.v !== 1 || r.via !== 'join' || typeof r.tag !== 'string' || typeof r.at !== 'number')
47
+ throw malformedProof(id);
48
+ return { via: 'join', tag: r.tag, at: r.at };
49
+ }
50
+ /** Writes invitation `invitationId`'s join adoption proof (inside the adoption's group transaction). */
51
+ export async function writeAdoptionProof(scope, invitationId, proof) {
52
+ await scope.extension(ADOPTION_PROOF_EXTENSION).put(invitationId, { v: 1, via: proof.via, tag: proof.tag, at: proof.at });
53
+ }
54
+ /**
55
+ * Invitation `invitationId`'s join adoption proof in the group, or `undefined`: none, or a malformed row — no evidence
56
+ * (the welcome processor's completion stamps only what a decodable proof names; the outcome reader rejects the row).
57
+ */
58
+ export async function readAdoptionProofOf(scope, invitationId) {
59
+ // A row whose envelope (or payload) does not open is no evidence, as in the teardown scans: it must never strand a
60
+ // resumed join behind a throw.
61
+ const raw = await readProofRow(scope.extension(ADOPTION_PROOF_EXTENSION), ADOPTION_PROOF_EXTENSION, invitationId, true);
62
+ if (raw === undefined || raw === MALFORMED)
63
+ return undefined;
64
+ try {
65
+ return decodeAdoptionProof(invitationId, raw);
66
+ }
67
+ catch {
68
+ return undefined;
69
+ }
70
+ }
71
+ /**
72
+ * Both proof maps of the group. A malformed row — its payload, or for either extension its envelope — rejects
73
+ * `store-failed` (`details.malformed`): the outcome reader never reads it as absent. `skipMalformed` (teardown's read before the clear): a malformed row is no evidence
74
+ * and is skipped, so it can never block the purge that deletes it.
75
+ */
76
+ export async function readAdoptionProofs(scope, options = {}) {
77
+ const skipMalformed = options.skipMalformed === true;
78
+ const adoptionView = scope.extension(ADOPTION_PROOF_EXTENSION);
79
+ const adoption = new Map();
80
+ for (const key of await adoptionView.keys()) {
81
+ const raw = await readProofRow(adoptionView, ADOPTION_PROOF_EXTENSION, key, skipMalformed);
82
+ if (raw === undefined || raw === MALFORMED)
83
+ continue;
84
+ try {
85
+ adoption.set(key, decodeAdoptionProof(key, raw));
86
+ }
87
+ catch (error) {
88
+ if (!skipMalformed)
89
+ throw error;
90
+ }
91
+ }
92
+ const switchView = scope.extension(SWITCH_PROOF_EXTENSION);
93
+ const branchSwitch = new Set();
94
+ // A switch row's presence is the proof (its payload names the branch, `rebaseOnQueue`). A row whose envelope does
95
+ // not open is no evidence, as a malformed adoption row is.
96
+ for (const key of await switchView.keys()) {
97
+ const raw = await readProofRow(switchView, SWITCH_PROOF_EXTENSION, key, skipMalformed);
98
+ if (raw !== undefined && raw !== MALFORMED)
99
+ branchSwitch.add(key);
100
+ }
101
+ return { adoption, branchSwitch };
102
+ }
@@ -32,7 +32,7 @@ import { commitDigest } from '@941design/marmot-engine/core';
32
32
  import { tagOf } from '../history/index.js';
33
33
  import { hexOf } from '../history/hex.js';
34
34
  import { MarmotError } from '../shared/index.js';
35
- import { cursorFloor } from './confirm-hooks.js';
35
+ import { cursorFloor, snapshotLineage } from './confirm-hooks.js';
36
36
  import { sealGroupSnapshot } from './group-snapshot.js';
37
37
  export function createBeforePublishRegistry(timeoutMs) {
38
38
  const hooks = [];
@@ -77,6 +77,7 @@ export async function runBeforePublish(site, run) {
77
77
  try {
78
78
  await site.transaction(async (tx) => {
79
79
  const since = await cursorFloor(tx);
80
+ const lineage = await snapshotLineage(tx);
80
81
  const snapshotOf = () => {
81
82
  if (!open) {
82
83
  throw new MarmotError('transaction-closed', 'BeforePublishContext.snapshot: read after the hook returned; read it inside the hook', {
@@ -91,6 +92,7 @@ export async function runBeforePublish(site, run) {
91
92
  window: run.window(),
92
93
  ...(run.createdAt === undefined ? {} : { createdAt: run.createdAt }),
93
94
  ...(since === undefined ? {} : { since }),
95
+ ...(lineage.length === 0 ? {} : { lineage }),
94
96
  pending: { digest, parentTag },
95
97
  });
96
98
  return sealed;
@@ -1,6 +1,6 @@
1
- import type { ClientState } from '@941design/marmot-engine/mls';
2
- import { type OwnChange, type OwnChangeLostReason, type RetainedWindow } from '../history/index.js';
3
- import type { StorableIntent, StoredOwnChange } from './group-records.js';
1
+ import { type ClientState } from '@941design/marmot-engine/mls';
2
+ import { type AdmissionDerivation, type OwnChange, type OwnChangeLostReason, type RetainedWindow } from '../history/index.js';
3
+ import type { AdmissionTarget, StorableIntent, StoredOwnChange } from './group-records.js';
4
4
  /** The facts the checks read: the tip the commit will be built on and the window the lineage evidence lives in. */
5
5
  export interface RedriveFacts {
6
6
  /** The engine's tip state: the tree the commit is built on. */
@@ -18,11 +18,35 @@ export interface RedriveFacts {
18
18
  * ladder only reads it. Required: a caller that cannot say must not look as if every KeyPackage is valid.
19
19
  */
20
20
  readonly invalidKeyPackages: ReadonlySet<string>;
21
+ /**
22
+ * Epic marmot-invitation-outcomes S5 (SC-5 I15): what the selected path proves about a cleanup target's admission at the build
23
+ * state (its stored lineage derived over the window). Decided by the drive, which owns the store; absent (or `undefined` for a
24
+ * target) proves nothing, so an `admission-removed` change is then lost `concurrent-change` (fail closed).
25
+ */
26
+ readonly admissionOf?: (target: AdmissionTarget) => AdmissionDerivation | undefined;
21
27
  }
22
28
  /** What the surviving changes of one kind add to the intent the commit is built from (never stored: DD15). */
23
29
  export type RedriveContribution = Partial<Pick<Extract<StorableIntent, {
24
30
  type: 'commit';
25
- }>, 'removeAccounts' | 'removeAccountLeafKeys' | 'admins' | 'components' | 'invite'>>;
31
+ }>, 'removeAccounts' | 'removeAccountLeafKeys' | 'admins' | 'components' | 'invite' | 'removeAdmission'>>;
32
+ /**
33
+ * Epic marmot-invitation-outcomes S5 (SC-11 D8, I14): why a scoped cleanup of the leaf at `leafIndex` cannot be built on `state`
34
+ * now, or `undefined`. A staged Remove or SelfRemove of that leaf would be carried by reference (a by-reference end is never
35
+ * attributed, I14) and a second Remove of it is invalid; a staged Add may refill the vacated position in the same commit (a
36
+ * `replaced` end, never attributed). Either way the consumer commits the staged proposals first and retries. Pure.
37
+ */
38
+ export declare function stagedCleanupConflict(state: ClientState, leafIndex: number): 'staged-removal-of-target' | 'staged-add-conflict' | undefined;
39
+ /**
40
+ * Epic marmot-invitation-outcomes S5 (SC-5 I15): why `target` may not be removed by a commit built on `state` (the actual parent),
41
+ * given what the selected path proves about its admission there (`admission`), or `undefined` when the proven original admission
42
+ * occupies the target position under the derived key and nothing staged interferes. Pure; shared by the build recheck and the re-drive
43
+ * check. `already-applied`: the admission ended or its Add is off the path; `concurrent-change`: nothing proves it (a gap), the leaf
44
+ * changed under it, the position is the committer's own, or a staged proposal conflicts.
45
+ */
46
+ export declare function cleanupTargetRefusal(target: AdmissionTarget, admission: AdmissionDerivation | undefined, state: ClientState): {
47
+ readonly lost: OwnChangeLostReason;
48
+ readonly reason: string;
49
+ } | undefined;
26
50
  /** The part of the ladder that is specific to one kind of change. */
27
51
  export interface RedriveChangeKind<C extends StoredOwnChange> {
28
52
  /** The reason `change` is lost at `facts`, or `undefined` when it still applies. Decided from the change's fork-point values and the current state. */
@@ -16,11 +16,51 @@
16
16
  * another (the admin list) also gives {@link RedriveChangeKind.checkSet}, which runs over the survivors of the per-change check.
17
17
  */
18
18
  import { GROUP_ADMIN_POLICY_COMPONENT_ID } from '@941design/marmot-engine/core';
19
+ import { defaultProposalTypes, selfRemoveProposalType } from '@941design/marmot-engine/mls';
19
20
  import { validateAdminList } from '../account/index.js';
20
- import { adminsOf, commitViewOf, holdsLeafKey, sameBytes, winnerHeldLeaf, winnerRemovedAccount } from '../history/index.js';
21
+ import { adminsOf, commitViewOf, holdsLeafKey, leafKeyAt, sameBytes, winnerHeldLeaf, winnerRemovedAccount } from '../history/index.js';
21
22
  import { stagesComponentUpdate } from './component-update.js';
22
23
  import { stagedAddLeafKeys } from '../invitations/index.js';
23
24
  import { holdsLeafOfAny } from './group-remove-member.js';
25
+ /**
26
+ * Epic marmot-invitation-outcomes S5 (SC-11 D8, I14): why a scoped cleanup of the leaf at `leafIndex` cannot be built on `state`
27
+ * now, or `undefined`. A staged Remove or SelfRemove of that leaf would be carried by reference (a by-reference end is never
28
+ * attributed, I14) and a second Remove of it is invalid; a staged Add may refill the vacated position in the same commit (a
29
+ * `replaced` end, never attributed). Either way the consumer commits the staged proposals first and retries. Pure.
30
+ */
31
+ export function stagedCleanupConflict(state, leafIndex) {
32
+ let add = false;
33
+ for (const { proposal, senderLeafIndex } of Object.values(state.unappliedProposals)) {
34
+ if (proposal.proposalType === defaultProposalTypes.remove && 'remove' in proposal && Number(proposal.remove.removed) === leafIndex)
35
+ return 'staged-removal-of-target';
36
+ if (proposal.proposalType === selfRemoveProposalType && senderLeafIndex !== undefined && Number(senderLeafIndex) === leafIndex)
37
+ return 'staged-removal-of-target';
38
+ if (proposal.proposalType === defaultProposalTypes.add)
39
+ add = true;
40
+ }
41
+ return add ? 'staged-add-conflict' : undefined;
42
+ }
43
+ /**
44
+ * Epic marmot-invitation-outcomes S5 (SC-5 I15): why `target` may not be removed by a commit built on `state` (the actual parent),
45
+ * given what the selected path proves about its admission there (`admission`), or `undefined` when the proven original admission
46
+ * occupies the target position under the derived key and nothing staged interferes. Pure; shared by the build recheck and the re-drive
47
+ * check. `already-applied`: the admission ended or its Add is off the path; `concurrent-change`: nothing proves it (a gap), the leaf
48
+ * changed under it, the position is the committer's own, or a staged proposal conflicts.
49
+ */
50
+ export function cleanupTargetRefusal(target, admission, state) {
51
+ const occupancy = admission?.occupancy;
52
+ if (occupancy === undefined || occupancy.kind === 'gap')
53
+ return { lost: 'concurrent-change', reason: 'admission-unproven' };
54
+ if (occupancy.kind === 'ended' || occupancy.kind === 'add-off-path')
55
+ return { lost: 'already-applied', reason: 'admission-ended' };
56
+ const leafIndex = target.anchor.leafIndex;
57
+ if (leafKeyAt(state, leafIndex) !== occupancy.leafKey)
58
+ return { lost: 'concurrent-change', reason: 'admission-changed' };
59
+ if (Number(state.privatePath.leafIndex) === leafIndex)
60
+ return { lost: 'concurrent-change', reason: 'self' };
61
+ const conflict = stagedCleanupConflict(state, leafIndex);
62
+ return conflict === undefined ? undefined : { lost: 'concurrent-change', reason: conflict };
63
+ }
24
64
  /**
25
65
  * Member removal (DD4 as amended, DD5, DD12). Already applied: the account holds no leaf. Reversed: the winning branch above
26
66
  * the fork point REMOVED the account (captured at withdrawal as `winnerRemovedTarget`, extended with the current window's canonical
@@ -166,12 +206,25 @@ const memberAdded = {
166
206
  },
167
207
  contribute: (survivors) => ({ invite: { invitees: survivors.map((s) => ({ event: s.keyPackage.event, inviteeRef: s.keyPackage.inviteeRef })) } }),
168
208
  };
209
+ /**
210
+ * A scoped cleanup (epic marmot-invitation-outcomes S5, SC-6 I16/I17). The change names the target ADMISSION, never the account: the
211
+ * re-drive removes that one leaf position again, inline, and only while the proven original admission still occupies it on the actual
212
+ * parent ({@link cleanupTargetRefusal} over the drive's lineage derivation). Already applied: the admission ended (whoever removed it)
213
+ * or its Add left the path. Concurrent change: a lineage gap, a changed leaf, or a staged proposal in the way. Never re-driven as an
214
+ * account-wide removal (`removeAccounts`).
215
+ */
216
+ const admissionRemoved = {
217
+ check: ({ target }, { state, admissionOf }) => cleanupTargetRefusal(target, admissionOf?.(target), state)?.lost,
218
+ // One cleanup per record (the intent is exclusive): the first survivor's target is the commit's.
219
+ contribute: (survivors) => ({ removeAdmission: survivors[0].target }),
220
+ };
169
221
  /** The handlers by change type: every kind has one, so a change is never lost for want of a handler. */
170
222
  export const REDRIVE_CHANGE_KINDS = {
171
223
  'member-removed': memberRemoved,
172
224
  'member-added': memberAdded,
173
225
  admin: adminFlipped,
174
226
  component: componentChanged,
227
+ 'admission-removed': admissionRemoved,
175
228
  };
176
229
  function handlerOf(change) {
177
230
  return REDRIVE_CHANGE_KINDS[change.change.type];
@@ -12,7 +12,7 @@
12
12
  * whatever they had become. Read after that, it throws `transaction-closed`, like a settled transaction's views.
13
13
  */
14
14
  import type { ClientState } from '@941design/marmot-engine/mls';
15
- import type { AppliedNotification } from '../history/index.js';
15
+ import { type AdmissionLineageRecord, type AppliedNotification } from '../history/index.js';
16
16
  import type { RetainedWindow } from '../history/index.js';
17
17
  import type { GroupStoreTx } from '../storage/index.js';
18
18
  import type { ConfirmHook, ConfirmKind } from './create-client.js';
@@ -46,5 +46,10 @@ export interface ConfirmHookRun {
46
46
  }
47
47
  /** The ingest cursor's floor as the transaction sees it; a missing or unreadable cursor is simply not carried. */
48
48
  export declare function cursorFloor(tx: GroupStoreTx): Promise<number | undefined>;
49
+ /**
50
+ * The group's admission lineage as the transaction sees it — what a sealed snapshot carries (epic
51
+ * marmot-invitation-outcomes S4). Unreadable lineage is simply not carried: the restore then reads a gap (fail closed).
52
+ */
53
+ export declare function snapshotLineage(tx: GroupStoreTx): Promise<readonly AdmissionLineageRecord[]>;
49
54
  /** Runs every registered hook, in order, each in the group's `onConfirm` re-entrancy frame. A throw propagates. */
50
55
  export declare function runConfirmHooks(site: ConfirmHookSite, run: ConfirmHookRun): Promise<void>;
@@ -1,3 +1,4 @@
1
+ import { ADMISSION_LINEAGE_EXTENSION, readLineageRecords } from '../history/index.js';
1
2
  import { MarmotError } from '../shared/index.js';
2
3
  import { readIngestCursor } from './group-records.js';
3
4
  import { sealGroupSnapshot } from './group-snapshot.js';
@@ -10,12 +11,25 @@ export async function cursorFloor(tx) {
10
11
  return undefined;
11
12
  }
12
13
  }
14
+ /**
15
+ * The group's admission lineage as the transaction sees it — what a sealed snapshot carries (epic
16
+ * marmot-invitation-outcomes S4). Unreadable lineage is simply not carried: the restore then reads a gap (fail closed).
17
+ */
18
+ export async function snapshotLineage(tx) {
19
+ try {
20
+ return await readLineageRecords(tx.extension(ADMISSION_LINEAGE_EXTENSION));
21
+ }
22
+ catch {
23
+ return [];
24
+ }
25
+ }
13
26
  /** Runs every registered hook, in order, each in the group's `onConfirm` re-entrancy frame. A throw propagates. */
14
27
  export async function runConfirmHooks(site, run) {
15
28
  const hooks = [...site.hooks];
16
29
  if (hooks.length === 0)
17
30
  return;
18
31
  const since = await cursorFloor(run.tx);
32
+ const lineage = await snapshotLineage(run.tx);
19
33
  let open = true;
20
34
  let sealed;
21
35
  const snapshotOf = () => {
@@ -33,6 +47,7 @@ export async function runConfirmHooks(site, run) {
33
47
  window,
34
48
  ...(run.createdAt === undefined ? {} : { createdAt: run.createdAt }),
35
49
  ...(since === undefined ? {} : { since }),
50
+ ...(lineage.length === 0 ? {} : { lineage }),
36
51
  });
37
52
  return sealed;
38
53
  };
@@ -20,16 +20,18 @@ import type { AppliedNotification, GroupNotification, HistoryBackend, LeafEquivo
20
20
  import type { EncryptedMedia, EncryptMediaOptions, MediaCache } from '../media/index.js';
21
21
  import { type DeviceForgetOutcome, type DeviceInfo, type DeviceKeyRotationOutcome, type DeviceLineage, type DeviceMaintenanceKind, type EnrolmentApprovalOutcome, type EnrolmentPrompt, type EnrolmentRequestHandle, type EnrolmentRequestOptions } from '../account/index.js';
22
22
  import { type InboxDisposition, type InboxRumorHandler } from '../inbox/index.js';
23
- import { type KeyPackageOffer, type MaintenanceKind, type PendingInvitation, type ProposalCallback, type WelcomeOutcome } from '../invitations/index.js';
23
+ import { type KeyPackageOffer, type MaintenanceKind, type InvitationOutcome, type CleanupReference, type DeclineCandidate, type DeclineCandidatePage, type PendingInvitation, type ProposalCallback, type WelcomeOutcome } from '../invitations/index.js';
24
24
  import { MarmotError } from '../shared/index.js';
25
25
  import type { AccountStore, GroupStore, GroupStoreTx } from '../storage/index.js';
26
26
  import { type BeforeCreateGroupGates, type CreateGroupGate } from './before-create-group.js';
27
27
  import { type BeforePublishHook, type BeforePublishRegistry, type BeforePublishSkipped } from './before-publish-hooks.js';
28
28
  import { type GroupRegistry, type GroupRuntime } from './group-runtime.js';
29
+ import type { AvailabilityObservation } from './group-availability.js';
29
30
  import type { GroupSnapshot } from './group-snapshot.js';
30
31
  import { type InboxRumorDelivery } from './inbox-send.js';
31
32
  import { type LifecycleEventPayloads, type LifecycleEvents } from './lifecycle-events.js';
32
33
  import { type EngineSeamsOverride } from './client-config.js';
34
+ import { type CleanupDispositionReport } from './admission-cleanup.js';
33
35
  /** Consumer-supplied check run on every relay event before it is trusted (ADR-008). */
34
36
  export type EventVerifier = (event: NostrEvent) => boolean | Promise<boolean>;
35
37
  /**
@@ -348,12 +350,32 @@ export interface MarmotClientEvents {
348
350
  * invitee account, naming that Welcome's id (SHA-256 of the MLS Welcome) and group. Fires once per delivery,
349
351
  * after it went `declined` durably (terminal: no further automatic or `retryWelcome` publish); a redelivered or
350
352
  * repeated decline does not fire it again, nor does a decline from any other account. The rumor itself still
351
- * reaches `onApplicationRumor` unchanged.
353
+ * reaches `onApplicationRumor` unchanged. `candidateId` (epic marmot-invitation-outcomes S3) is the delivery's
354
+ * stable candidate identity, the one `declineCandidate` and `invitations.declineCandidates()` carry. A decline
355
+ * whose `keyPackageRef` selects one delivery declines only that one; delivery status `declined` confers no cleanup
356
+ * authority — only the candidate's disposition does.
352
357
  */
353
358
  welcomeDeclined: {
354
359
  readonly groupId: string;
355
360
  readonly inviteeRef: string;
361
+ readonly candidateId: string;
356
362
  };
363
+ /**
364
+ * Epic marmot-invitation-outcomes S3 (SC-13): the decline evidence of one locally issued delivery changed — a new
365
+ * candidate (`ambiguous` or `actionable`), a late match after the delivery's record left retention, or a
366
+ * refinement (a selector naming it after an ambiguous decline: `actionable`, `qualified`, a higher `rev`, the same
367
+ * `cleanupRef`). Fires after the evidence was written durably, at most once per `(candidateId, rev)`; a crash in
368
+ * between loses it — `invitations.declineCandidates()` recovers every candidate. Subscribe before scanning and
369
+ * deduplicate by `(candidateId, rev)`.
370
+ */
371
+ declineCandidate: DeclineCandidate;
372
+ /**
373
+ * Epic marmot-invitation-outcomes S5 (SC-12): the cleanup disposition of a candidate this session submitted, confirmed or saw
374
+ * withdrawn changed — `pending` once `removeAdmission` recorded it, `removed-revisable` once its own inline Remove confirmed,
375
+ * `removed-settled`, or back to `eligible` / `absent` when a rewind or a lost re-drive undid it. Best effort, after the change is
376
+ * durable: a crash, a restart or a listener added late can miss one — `invitations.cleanupDisposition(ref)` recovers the latest.
377
+ */
378
+ cleanupDisposition: CleanupDispositionReport;
357
379
  /**
358
380
  * What the inbox did with one inbound kind-1059 wrap (S6): `joined`,
359
381
  * `already-member`, `pending` (an unexpected Welcome, see
@@ -541,6 +563,7 @@ export interface LeafInfo {
541
563
  readonly leafKey: string;
542
564
  }
543
565
  export type { EncryptedMedia, EncryptMediaOptions, MediaCache } from '../media/index.js';
566
+ export type { AvailabilityEndReason, AvailabilityObservation, FenceCause, GroupAvailability } from './group-availability.js';
544
567
  export interface MarmotGroup {
545
568
  readonly id: string;
546
569
  readonly nostrGroupId: string;
@@ -579,9 +602,29 @@ export interface MarmotGroup {
579
602
  * or joined, or that already synced. Until then `send()` records `awaiting-sync` intents and `invite`,
580
603
  * `setAdmins`, `rename`, `removeMember`, `departAsAdmin`, `leave` and `devices.forget` are refused `commit-pending` (reason
581
604
  * `awaiting-sync`). Never settles while no sync can complete (offline). Rejects `fenced` when the group is or
582
- * becomes fenced (AC-HIST-4), `disposed` / `not-a-member` when the client is disposed / the group abandoned.
605
+ * becomes fenced (AC-HIST-4), `disposed` / `not-a-member` when the client is disposed / the group abandoned, and
606
+ * `no-lease` when the stores lost their lease before the group's first catch-up (at once once the loss is known,
607
+ * else when a background retry meets it; epic marmot-invitation-outcomes S1).
583
608
  */
584
609
  synced(): Promise<void>;
610
+ /**
611
+ * Epic marmot-invitation-outcomes (S1, SC-10): observes the group's availability — the fence, the sync state and the
612
+ * membership as independent facts, and whether an own write may be attempted now. The current snapshot is delivered
613
+ * synchronously, before this returns, then every change in the order it happened, each with a strictly increasing
614
+ * `seq`. A fence is an ordinary observation: the subscription stays open (no fence is ever lifted in place, so within
615
+ * a client session no `clear` follows `fenced` — not even after a failed fence-marker write and the reload that
616
+ * follows). Exactly one `ended` closes it, with `final.writable` `false` (a fenced group stays fenced in it): reason
617
+ * `torn-down` (leave, abandon, destroy, or another teardown purge), `restore-undone` (a failed restore taken back),
618
+ * `disposed` (the client), `no-lease` (the account store's lease was released, closed or lost — immediately when the
619
+ * store implements `AccountStore.onLeaseEnded`). After that, a subscription gets the one `ended` at once and nothing
620
+ * more; this method itself never throws for a fenced, torn-down or disposed group. Exempt from the fenced refusal.
621
+ * Change notifications run outside every library frame (a listener may start group operations, which queue); what
622
+ * is delivered before this returns runs in the caller's own frame — subscribed from inside a library callback (an
623
+ * `onConfirm` hook, a store, …), a same-group operation the listener starts there is rejected `reentrant`, as one
624
+ * the callback started itself would be. A throwing listener is ignored. Returns the unsubscribe function (idempotent): no callback follows it. `invalid-options` when `listener`
625
+ * is not a function.
626
+ */
627
+ observeAvailability(listener: (observation: AvailabilityObservation) => void): () => void;
585
628
  ingest(events: readonly NostrEvent[]): Promise<readonly IngestDisposition[]>;
586
629
  /**
587
630
  * The durable outbound intents, read directly — NOT serialised behind the group's operation queue: an intent can
@@ -671,6 +714,30 @@ export interface MarmotGroup {
671
714
  * `stranded`, `attempts-exhausted`). `leaf-removal-withdrawn` is unchanged. A record that outlives a concurrent remove-and-re-add of the same device by another admin removes the account again.
672
715
  */
673
716
  removeMember(account: string): Promise<void>;
717
+ /**
718
+ * Epic marmot-invitation-outcomes S5 (SC-11): removes exactly the ONE admission a declined delivery made — the leaf position the
719
+ * candidate's proven original Add put in this group — by `ref`, the candidate's cleanup reference. A reference confers no
720
+ * authority: every call re-derives the disposition from durable evidence and lineage.
721
+ *
722
+ * Resolves with a {@link CleanupDispositionReport}: `pending` (with the root `intentId`) when the cleanup was durably accepted —
723
+ * or was already in flight: a repeated, concurrent or lost-reply submit coalesces with it, with no resume, transport call or write
724
+ * — and otherwise the current disposition when it is not `eligible` (`removed-revisable`, `removed-settled`, `absent`,
725
+ * `insufficient-evidence`; nothing is recorded). An accepted cleanup is built, published and confirmed in the background; its
726
+ * commit re-checks the target on the actual parent and is dropped (never removing a replacement) when it no longer holds.
727
+ *
728
+ * Refusals enqueue nothing: `fenced`, `not-a-member` (`disbanded`), `invalid-options` (`details.reason`
729
+ * `malformed-reference`, `foreign-reference` — another account than the signer's or another group —, `unknown-reference`,
730
+ * `self` — the committer's own leaf; another device of the own account is a valid target —, `not-admin`), `confirm-blocked`,
731
+ * `commit-pending` (another own commit pending, or `awaiting-sync`: retryable), `send-rejected` with `details.retryable` for a
732
+ * staged proposal in the way (`staged-add-conflict`, `staged-removal-of-target`, `staged-admin-policy-update` — the last leaf of an
733
+ * admin account gets the account removal's admin coupling). After an uncertain failure, read
734
+ * `invitations.cleanupDisposition(ref)` before resubmitting.
735
+ *
736
+ * Fork loss: a withdrawn cleanup reads `pending` until its library re-drive ends; the application hears `own-change-withdrawn`
737
+ * `{ admission-removed }` (never `member-removed`), then `own-change-reapplied` or `own-change-lost` with the existing reasons. It is
738
+ * never re-driven as an account-wide removal.
739
+ */
740
+ removeAdmission(ref: CleanupReference): Promise<CleanupDispositionReport>;
674
741
  departAsAdmin(): Promise<void>;
675
742
  leave(): Promise<void>;
676
743
  abandon(): Promise<void>;
@@ -795,6 +862,43 @@ export interface MarmotClient {
795
862
  }): Promise<void>;
796
863
  /** S8: KeyPackage offers received for groups this client holds (optionally one group's), oldest first; admit one with `group.invite([offer.keyPackageEvent])`. */
797
864
  offers(groupId?: string): Promise<readonly KeyPackageOffer[]>;
865
+ /**
866
+ * Epic marmot-invitation-outcomes S2: whether THIS invitation (a Welcome id) caused this device to join its group,
867
+ * read from durable evidence at one instant (ADR-019 D7, D9) — authoritative where `accept(id)` is not (an
868
+ * `accept` may return the held group's handle for a Welcome that was kept out). Runs on the inbox queue (behind the
869
+ * current inbox task) and works before `inbox.start()`. Rejects `reentrant` synchronously from inside an `onConfirm`
870
+ * / `onBeforePublish` / `verifier` / `onProposal` hook, an inbox handler, `onApplicationRumor` or any account-scope
871
+ * consumer surface — read it from an event listener (e.g. `groupJoined`) instead.
872
+ */
873
+ outcome(id: string): Promise<InvitationOutcome>;
874
+ /**
875
+ * Epic marmot-invitation-outcomes S3 (SC-13): one page of the locally issued deliveries their invitee's account
876
+ * declined, recovered offline from this account store alone (no group is opened). Read-only: no publication, no
877
+ * intent, no pruning, no store write. Pages are ordered and bounded (`limit` clamped to `[1, 256]`, default 256);
878
+ * pass the previous page's `next` as `after` until `complete`. Each candidate appears at most once across the
879
+ * pages of one walk; one recorded meanwhile surfaces through the `declineCandidate` event — register it first.
880
+ * Rejects `reentrant` synchronously from inside an account-scope consumer surface (a store, signer or verifier
881
+ * call); allowed from group hooks, inbox handlers and event listeners.
882
+ */
883
+ declineCandidates(options?: {
884
+ readonly after?: string;
885
+ readonly limit?: number;
886
+ }): Promise<DeclineCandidatePage>;
887
+ /**
888
+ * Epic marmot-invitation-outcomes S4 (SC-12): what this store's durable evidence proves about the admission a
889
+ * declined delivery made, by the candidate's cleanup reference — `eligible` (the proven original admission is
890
+ * present), `absent` (`add-off-path`: its Add is not on the selected path; `occupancy-ended`: the admission
891
+ * ended), or `insufficient-evidence` (`unresolved-selector`, `ambiguous-legacy`, `no-anchor`, `lineage-gap`).
892
+ * Read-only and offline: no group runtime, no publication, no intent, no store write; recompute it after branch
893
+ * changes. On a fenced group it still answers, with the last disposition the store proved (`lastKnown: true`).
894
+ * Rejects `invalid-options` (`details.reason`: `malformed-reference`, `foreign-reference` — another account than
895
+ * the signer's —, `unknown-reference`) with no effect. Rejects `reentrant` synchronously from inside an
896
+ * `onConfirm` / `onBeforePublish` / `verifier` / `onProposal` hook, a consumer group-store call or any
897
+ * account-scope consumer surface other than an inbox handler; allowed from inbox handlers and event listeners.
898
+ * Since S5 it also reads `pending` (a cleanup durably accepted, or a library re-drive of a withdrawn one, under the
899
+ * root `intentId`) and `removed-revisable` / `removed-settled` (the cleanup's own confirmed inline Remove, `commitDigest`).
900
+ */
901
+ cleanupDisposition(ref: CleanupReference): Promise<CleanupDispositionReport>;
798
902
  };
799
903
  readonly inbox: {
800
904
  start(): Promise<void>;