@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
@@ -16,7 +16,7 @@
16
16
  * object is gone; the recorded one carries its message.
17
17
  */
18
18
  import { isLostPathSecretsError } from '@941design/marmot-engine/engine';
19
- import { MarmotError } from '../shared/index.js';
19
+ import { isMarmotError, MarmotError } from '../shared/index.js';
20
20
  /** Group extension namespace of the fence marker. */
21
21
  export const FENCE_EXTENSION = 'marmot.fence';
22
22
  const FENCE_KEY = 'current';
@@ -37,17 +37,56 @@ export function fencedError(groupId, operation, cause) {
37
37
  details: { groupId },
38
38
  });
39
39
  }
40
+ const FENCE_CAUSES = ['lost-path-secrets', 'invalid-stored-evidence', 'unknown'];
41
+ /**
42
+ * Stored fence evidence that cannot be trusted: a present but malformed fence marker, or a held-candidate record the
43
+ * engine refuses (client/opaque-candidates.ts `OpaqueRecordCorrupt` extends it). The group fails closed: it is
44
+ * fenced with cause `invalid-stored-evidence`.
45
+ */
46
+ export class InvalidStoredEvidenceError extends Error {
47
+ name = 'InvalidStoredEvidenceError';
48
+ }
40
49
  export async function writeFence(view, record) {
41
- await view.put(FENCE_KEY, { at: record.at, epoch: record.epoch, message: record.message });
50
+ await view.put(FENCE_KEY, { at: record.at, epoch: record.epoch, message: record.message, ...(record.cause === undefined ? {} : { cause: record.cause }) });
42
51
  }
43
- export async function readFence(view) {
44
- const raw = await view.get(FENCE_KEY);
52
+ /**
53
+ * The fence marker as a load must judge it (fail closed): `absent` when no marker is stored, `valid` for a
54
+ * well-formed one (its `cause` kept when it is a known cause), `malformed` for anything else that is present —
55
+ * including a stored payload that does not decode. A malformed marker is never read as no fence. Any other read failure (an incompatible store, a failing backend) is thrown.
56
+ */
57
+ export async function loadFenceMarker(view) {
58
+ let raw;
59
+ try {
60
+ raw = await view.get(FENCE_KEY);
61
+ }
62
+ catch (error) {
63
+ if (isMarmotError(error, 'envelope-mismatch') && error.details?.reason === 'malformed')
64
+ return { kind: 'malformed' };
65
+ throw error;
66
+ }
67
+ if (raw === undefined)
68
+ return { kind: 'absent' };
45
69
  if (typeof raw !== 'object' || raw === null || Array.isArray(raw) || raw instanceof Uint8Array)
46
- return undefined;
70
+ return { kind: 'malformed' };
47
71
  const r = raw;
48
72
  if (typeof r.at !== 'number' || typeof r.epoch !== 'string' || typeof r.message !== 'string')
73
+ return { kind: 'malformed' };
74
+ if (r.cause !== undefined && !FENCE_CAUSES.includes(r.cause))
75
+ return { kind: 'malformed' };
76
+ const cause = r.cause;
77
+ return { kind: 'valid', record: { at: r.at, epoch: r.epoch, message: r.message, ...(cause === undefined ? {} : { cause }) } };
78
+ }
79
+ /**
80
+ * Compatibility/test reader: the legacy fields (`at`, `epoch`, `message` — no `cause`) of a {@link loadFenceMarker |
81
+ * valid} marker, else `undefined`. `undefined` does not mean "no marker": a malformed one also reads `undefined` here,
82
+ * while a load fails closed on it. Code that decides whether a group is fenced uses {@link loadFenceMarker}.
83
+ */
84
+ export async function readFence(view) {
85
+ const marker = await loadFenceMarker(view);
86
+ if (marker.kind !== 'valid')
49
87
  return undefined;
50
- return { at: r.at, epoch: r.epoch, message: r.message };
88
+ const { at, epoch, message } = marker.record;
89
+ return { at, epoch, message };
51
90
  }
52
91
  /**
53
92
  * The cause a reloaded fence carries: the ts-mls `InternalError` object does
@@ -55,7 +94,28 @@ export async function readFence(view) {
55
94
  * with the recorded message (not an `instanceof InternalError`).
56
95
  */
57
96
  export function recordedFencingError(record) {
58
- const error = new Error(record.message);
97
+ const error = new RecordedFencingError(record.message, record.cause ?? 'unknown');
59
98
  error.name = 'InternalError';
60
99
  return error;
61
100
  }
101
+ /** A reloaded fence's cause object: carries the marker's recorded {@link FenceCause} (`unknown` for a legacy marker). */
102
+ class RecordedFencingError extends Error {
103
+ fenceCause;
104
+ constructor(message, fenceCause) {
105
+ super(message);
106
+ this.fenceCause = fenceCause;
107
+ }
108
+ }
109
+ /**
110
+ * The coarse cause of the fence `error` stands for: a reloaded marker's recorded cause, `invalid-stored-evidence` for
111
+ * {@link InvalidStoredEvidenceError}, `lost-path-secrets` for the ts-mls replay failure, else `unknown`.
112
+ */
113
+ export function fenceCauseOf(error) {
114
+ if (error instanceof RecordedFencingError)
115
+ return error.fenceCause;
116
+ if (error instanceof InvalidStoredEvidenceError)
117
+ return 'invalid-stored-evidence';
118
+ if (isFencingError(error))
119
+ return 'lost-path-secrets';
120
+ return 'unknown';
121
+ }
@@ -69,5 +69,6 @@ export { orderingKeyOf, senderGeneration, messageEpoch } from './ordering-key.js
69
69
  export { EQUIVOCATION_EXTENSION, equivocationKey, equivocationNotification, equivocationRecordOf, isRecordableEquivocation, readEquivocations, readEquivocationNotifications, writeEquivocation, type EquivocationRecord, } from './equivocation.js';
70
70
  export { adminsOf, commitViewOf, holdsLeafKey, sameBytes, diffCommitViews, ownCommitChanges, OWN_CHANGE_LOST_REASONS, type CommitView, type OwnChange, type OwnChangeLostNotification, type OwnChangeLostReason, type OwnChangeReappliedNotification, type OwnChangeWithdrawnNotification, type OwnCommitChange, } from './own-change.js';
71
71
  export { breakdownWithdrawnCommit, forkPointNode, intersectDeclared, winnerHeldLeaf, winnerRemovedAccount, type BreakdownUnreadable, type DeclaredChanges, type ForkedChange, type WithdrawalBreakdown, } from './own-change-fork.js';
72
- export { FENCE_EXTENSION, fencedError, fencingErrorIn, isFencingError, readFence, recordedFencingError, writeFence, type FenceRecord } from './fencing.js';
72
+ export { ADMISSION_LINEAGE_EXTENSION, admissionStep, advanceLineage, advanceLineageRecords, decodeLineageRecord, deriveAdmission, encodeLineageRecord, leafKeyAt, lineageKey, mergeSeed, mergeWindows, readLineageRecord, readLineageRecords, replaceLineageRecords, seedLineage, seedLineageRecords, stateResolver, validateRestoredLineage, windowRootOf, writeLineageRecord, type AdmissionDerivation, type AdmissionLineageRecord, type LineageAnchor, type LineageCheckpoint, type LineageEndedBy, type LineageGapReason, type LineageLink, type LineageOccupancy, type LineageProvenance, type StateResolver, } from './admission-lineage.js';
73
+ export { FENCE_EXTENSION, fenceCauseOf, fencedError, fencingErrorIn, InvalidStoredEvidenceError, isFencingError, loadFenceMarker, readFence, recordedFencingError, writeFence, type FenceCause, type FenceMarker, type FenceRecord } from './fencing.js';
73
74
  export { canonicalPath, captureWindow, commitOf, extendWindow, heldBranchScore, withForkNode, linkRestorable, readWindow, restoreHistory, restrictWindow, rewoundToParent, REWIND_HORIZON, sameNode, sameWindow, senderOfNode, senderOfStored, tagOf, tipOnlyWindow, windowFor, wireOf, writeWindow, type HeldBranchScore, type JoinEvidence, type RestoredHistory, type RetainedWindow, type WindowNode, } from './retained-window.js';
@@ -27,5 +27,6 @@ export { orderingKeyOf, senderGeneration, messageEpoch } from './ordering-key.js
27
27
  export { EQUIVOCATION_EXTENSION, equivocationKey, equivocationNotification, equivocationRecordOf, isRecordableEquivocation, readEquivocations, readEquivocationNotifications, writeEquivocation, } from './equivocation.js';
28
28
  export { adminsOf, commitViewOf, holdsLeafKey, sameBytes, diffCommitViews, ownCommitChanges, OWN_CHANGE_LOST_REASONS, } from './own-change.js';
29
29
  export { breakdownWithdrawnCommit, forkPointNode, intersectDeclared, winnerHeldLeaf, winnerRemovedAccount, } from './own-change-fork.js';
30
- export { FENCE_EXTENSION, fencedError, fencingErrorIn, isFencingError, readFence, recordedFencingError, writeFence } from './fencing.js';
30
+ export { ADMISSION_LINEAGE_EXTENSION, admissionStep, advanceLineage, advanceLineageRecords, decodeLineageRecord, deriveAdmission, encodeLineageRecord, leafKeyAt, lineageKey, mergeSeed, mergeWindows, readLineageRecord, readLineageRecords, replaceLineageRecords, seedLineage, seedLineageRecords, stateResolver, validateRestoredLineage, windowRootOf, writeLineageRecord, } from './admission-lineage.js';
31
+ export { FENCE_EXTENSION, fenceCauseOf, fencedError, fencingErrorIn, InvalidStoredEvidenceError, isFencingError, loadFenceMarker, readFence, recordedFencingError, writeFence } from './fencing.js';
31
32
  export { canonicalPath, captureWindow, commitOf, extendWindow, heldBranchScore, withForkNode, linkRestorable, readWindow, restoreHistory, restrictWindow, rewoundToParent, REWIND_HORIZON, sameNode, sameWindow, senderOfNode, senderOfStored, tagOf, tipOnlyWindow, windowFor, wireOf, writeWindow, } from './retained-window.js';
@@ -22,6 +22,18 @@ export type OwnChange =
22
22
  | {
23
23
  readonly type: 'component';
24
24
  readonly componentId: number;
25
+ }
26
+ /**
27
+ * Epic marmot-invitation-outcomes (SC-6): a scoped cleanup (`MarmotGroup.removeAdmission`) removed the ONE admission of decline
28
+ * candidate `candidateId` — the leaf of `account` its Add put in the group, `leafKey` being that leaf's signature key (hex) as the
29
+ * Add admitted it. Declared from the cleanup's intent, never derived from a state diff: a cleanup commit never reports
30
+ * `member-removed`, even when the removed leaf was the account's last, and is never re-driven as an account-wide removal.
31
+ */
32
+ | {
33
+ readonly type: 'admission-removed';
34
+ readonly account: string;
35
+ readonly leafKey: string;
36
+ readonly candidateId: string;
25
37
  };
26
38
  /** Why a change was dropped instead of re-applied (`own-change-lost`). Closed set. */
27
39
  export type OwnChangeLostReason = 'concurrent-change' | 'reversed' | 'already-applied' | 'not-admin' | 'stranded' | 'invalid-keypackage' | 'attempts-exhausted';
@@ -32,7 +44,7 @@ export declare const OWN_CHANGE_LOST_REASONS: readonly OwnChangeLostReason[];
32
44
  */
33
45
  export type OwnCommitChange = {
34
46
  readonly change: Exclude<OwnChange, {
35
- readonly type: 'component';
47
+ readonly type: 'component' | 'admission-removed';
36
48
  }>;
37
49
  } | {
38
50
  readonly change: Extract<OwnChange, {
@@ -3,7 +3,7 @@
3
3
  * decline rumor to the sponsor (ADR-008 — there is no protocol decline) and
4
4
  * its durable delivery.
5
5
  *
6
- * The rumor (kind `RUMOR_KINDS.DECLINE`, content `{ v: 1, welcome, groupId }`,
6
+ * The rumor (kind `RUMOR_KINDS.DECLINE`, content `{ v: 1, welcome, groupId, keyPackageRef? }`,
7
7
  * no tags — the group id stays inside the gift wrap) is stored with the
8
8
  * invitation's `declined` record before anything is signed. A delivery
9
9
  * attempt is intent -> publish -> confirm, like S5's Welcome delivery:
@@ -35,12 +35,18 @@ export interface DeclineState {
35
35
  readonly attempts: number;
36
36
  readonly reason?: string;
37
37
  }
38
- /** The decline rumor for invitation `welcomeId` of `groupId`, authored by `author`. */
38
+ /**
39
+ * The decline rumor for invitation `welcomeId` of `groupId`, authored by `author`. `keyPackageRef` (epic
40
+ * marmot-invitation-outcomes S3, spec DD3) is the KeyPackageRef the Welcome was consumed with: an optional extra field
41
+ * of the same v1 content that selects this device's delivery at an upgraded inviter; a reader that predates it
42
+ * ignores it. Omitted, the content is exactly `{ v: 1, welcome, groupId }` (an unqualified decline).
43
+ */
39
44
  export declare function buildDeclineRumor(opts: {
40
45
  readonly author: string;
41
46
  readonly welcomeId: string;
42
47
  readonly groupId: string;
43
48
  readonly nowSeconds: number;
49
+ readonly keyPackageRef?: string;
44
50
  }): Rumor;
45
51
  export declare function encodeRumor(rumor: Rumor): Storable;
46
52
  /** Decodes a stored rumor; `kind` pins the only kind the record may hold. */
@@ -3,7 +3,7 @@
3
3
  * decline rumor to the sponsor (ADR-008 — there is no protocol decline) and
4
4
  * its durable delivery.
5
5
  *
6
- * The rumor (kind `RUMOR_KINDS.DECLINE`, content `{ v: 1, welcome, groupId }`,
6
+ * The rumor (kind `RUMOR_KINDS.DECLINE`, content `{ v: 1, welcome, groupId, keyPackageRef? }`,
7
7
  * no tags — the group id stays inside the gift wrap) is stored with the
8
8
  * invitation's `declined` record before anything is signed. A delivery
9
9
  * attempt is intent -> publish -> confirm, like S5's Welcome delivery:
@@ -23,9 +23,15 @@ import { getEventHash } from '@941design/nostr-events/event';
23
23
  import { wrap as giftWrap } from '@941design/nostr-events/gift-wrap';
24
24
  import { classifyPublish, MarmotError, RUMOR_KINDS } from '../shared/index.js';
25
25
  import { resolveInboxRelays } from './relay-planes.js';
26
- /** The decline rumor for invitation `welcomeId` of `groupId`, authored by `author`. */
26
+ /**
27
+ * The decline rumor for invitation `welcomeId` of `groupId`, authored by `author`. `keyPackageRef` (epic
28
+ * marmot-invitation-outcomes S3, spec DD3) is the KeyPackageRef the Welcome was consumed with: an optional extra field
29
+ * of the same v1 content that selects this device's delivery at an upgraded inviter; a reader that predates it
30
+ * ignores it. Omitted, the content is exactly `{ v: 1, welcome, groupId }` (an unqualified decline).
31
+ */
27
32
  export function buildDeclineRumor(opts) {
28
- const draft = { kind: RUMOR_KINDS.DECLINE, pubkey: opts.author, created_at: opts.nowSeconds, tags: [], content: JSON.stringify({ v: 1, welcome: opts.welcomeId, groupId: opts.groupId }) };
33
+ const body = { v: 1, welcome: opts.welcomeId, groupId: opts.groupId, ...(opts.keyPackageRef === undefined ? {} : { keyPackageRef: opts.keyPackageRef }) };
34
+ const draft = { kind: RUMOR_KINDS.DECLINE, pubkey: opts.author, created_at: opts.nowSeconds, tags: [], content: JSON.stringify(body) };
29
35
  return { ...draft, id: getEventHash(draft) };
30
36
  }
31
37
  // ---------------------------------------------------------------------------
@@ -0,0 +1,288 @@
1
+ import { type ClientState, type KeyPackage } from '@941design/marmot-engine/mls';
2
+ import type { AccountStoreTx, KeyValueView, Storable } from '../storage/index.js';
3
+ export declare const DELIVERY_EVIDENCE_EXTENSION = "marmot.delivery-evidence";
4
+ export declare const DECLINE_EVIDENCE_EXTENSION = "marmot.decline-evidence";
5
+ /** Upper bound of one `declineCandidates` page (SC-13); a larger `limit` is clamped to it. */
6
+ export declare const DECLINE_SCAN_PAGE_MAX = 256;
7
+ /** SC-1: where the Add of one delivery put its leaf, fixed at confirmation. Immutable once written. */
8
+ export interface AddAnchor {
9
+ /** Hex SHA-256 of the Add commit's MLS wire bytes. */
10
+ readonly addDigest: string;
11
+ /** Hex confirmation tag of the state the Add produced (`InviteRecord.commitTag`). */
12
+ readonly addTag: string;
13
+ readonly commitEventId: string;
14
+ /** Leaf position in `addTag`'s state. */
15
+ readonly leafIndex: number;
16
+ /** Hex signature key of the added leaf (from the invitee's KeyPackage). */
17
+ readonly leafKey: string;
18
+ }
19
+ /** SC-2: one locally issued delivery, payload-free (no Welcome rumor, no wrap). */
20
+ export interface DeliveryEvidence {
21
+ readonly v: 1;
22
+ readonly candidateId: string;
23
+ readonly groupId: string;
24
+ /** The pending-intent id of the invite commit (the `invites` record id). */
25
+ readonly inviteId: string;
26
+ /** The invitee's KeyPackageRef. */
27
+ readonly inviteeRef: string;
28
+ /** The invitee's account. */
29
+ readonly recipient: string;
30
+ /** SHA-256 (hex) of the MLS Welcome bytes. */
31
+ readonly welcomeId: string;
32
+ /** Client clock (ms) of the hand-off (or of the backfilled record's hand-off). */
33
+ readonly issuedAt: number;
34
+ /** Absent for legacy or unanchorable deliveries. */
35
+ readonly anchor?: AddAnchor;
36
+ readonly origin: 'issued' | 'legacy-backfill';
37
+ }
38
+ /** SC-2: the authenticated declines of one Welcome by one account. */
39
+ export interface DeclineEvidence {
40
+ readonly v: 1;
41
+ /** Client clock (ms) of the first authenticated unqualified decline. */
42
+ readonly unqualifiedAt?: number;
43
+ /** Valid selectors only, in arrival order, each KeyPackageRef at most once. */
44
+ readonly qualified: readonly {
45
+ readonly inviteeRef: string;
46
+ readonly at: number;
47
+ }[];
48
+ /** Backfilled from a `declined` row written before this release. */
49
+ readonly legacy?: true;
50
+ /** `+1` on every change of this row. */
51
+ readonly rev: number;
52
+ }
53
+ declare const CLEANUP_REF_BRAND: unique symbol;
54
+ /**
55
+ * SC-3: the scoped reference of one candidate, `mcr1.<account>.<groupId>.<candidateId>`. Opaque to consumers.
56
+ * Identity only — it confers no authority; whatever reads it recomputes authority from durable evidence.
57
+ */
58
+ export type CleanupReference = string & {
59
+ readonly [CLEANUP_REF_BRAND]: 'CleanupReference';
60
+ };
61
+ /** One locally issued delivery its invitee's account declined (public; SC-2). */
62
+ export interface DeclineCandidate {
63
+ /** Stable across Welcome retransmission and restarts: SHA-256 of `groupId|inviteId|inviteeRef`. */
64
+ readonly candidateId: string;
65
+ readonly groupId: string;
66
+ /** The declining (invitee) account. */
67
+ readonly recipient: string;
68
+ /** The delivery's KeyPackageRef (`WelcomeOutcome.inviteeRef`). */
69
+ readonly inviteeRef: string;
70
+ /** The Welcome id (SHA-256 of the MLS Welcome). */
71
+ readonly welcomeId: string;
72
+ /**
73
+ * `actionable`: the unique authenticated, selector-consistent match. `ambiguous`: the account declined a Welcome
74
+ * that went to several of its KeyPackages without saying which; never resolved by elimination. Actionability is
75
+ * monotone and makes no claim about current group membership.
76
+ */
77
+ readonly status: 'actionable' | 'ambiguous';
78
+ /** The strongest evidence for this delivery: a selector naming it, an unqualified decline, or a pre-upgrade record. */
79
+ readonly basis: 'unqualified' | 'qualified' | 'legacy';
80
+ /** Grows with every new piece of evidence for this delivery: equal `rev` = the same observation (a duplicate). */
81
+ readonly rev: number;
82
+ /** Present for every candidate, whatever its status. */
83
+ readonly cleanupRef: CleanupReference;
84
+ }
85
+ /** One page of {@link scanDeclineCandidates} (SC-13). */
86
+ export interface DeclineCandidatePage {
87
+ readonly candidates: readonly DeclineCandidate[];
88
+ /** Cursor of the next page (pass as `after`); absent on the last page. */
89
+ readonly next?: string;
90
+ /** `true` on the last page. */
91
+ readonly complete: boolean;
92
+ }
93
+ /** SC-2 I4: hex SHA-256 over `groupId|inviteId|inviteeRef`. A re-drive has a new `inviteId`, hence a new candidate. */
94
+ export declare function candidateIdOf(groupId: string, inviteId: string, inviteeRef: string): string;
95
+ /**
96
+ * The Welcome id of a Welcome rumor's content (base64 MLS Welcome) — the same value as `welcomeIdOf`
97
+ * (`welcome-processor.ts`), computed synchronously. `undefined` for content that is not base64: it names no Welcome.
98
+ */
99
+ export declare function welcomeIdOfContent(content: string): string | undefined;
100
+ /** SC-3: the reference of `candidateId` of `groupId` in `account`'s store. */
101
+ export declare function encodeCleanupReference(account: string, groupId: string, candidateId: string): CleanupReference;
102
+ /**
103
+ * SC-3 I9: format check only — `undefined` for anything that is not `mcr1.<64 hex>.<groupId>.<64 hex>` (a group id
104
+ * holds no `.`). Whether the account, group and candidate are this store's is the reader's question.
105
+ */
106
+ export declare function decodeCleanupReference(raw: unknown): {
107
+ readonly account: string;
108
+ readonly groupId: string;
109
+ readonly candidateId: string;
110
+ } | undefined;
111
+ /**
112
+ * SC-1 I1: the {@link AddAnchor} of each delivery of one confirmed own commit, by KeyPackageRef. Computed only from
113
+ * the confirmed `parentState` → `newState` pair plus the KeyPackages the commit added (the intent's invitee
114
+ * KeyPackages and the Adds staged in the parent). A delivery gets an anchor only when exactly one leaf of `newState`
115
+ * carries its KeyPackage's signature key, that key is on no leaf of `parentState`, and the leaf came from a
116
+ * KeyPackage; otherwise it gets none. Never throws (an undecodable KeyPackage anchors nothing).
117
+ */
118
+ export declare function addAnchorsOf(input: {
119
+ readonly parentState: ClientState;
120
+ readonly newState: ClientState;
121
+ readonly addDigest: string;
122
+ readonly addTag: string;
123
+ readonly commitEventId: string;
124
+ readonly keyPackages: readonly KeyPackage[];
125
+ }): Promise<Map<string, AddAnchor>>;
126
+ /** Decodes the delivery evidence stored under `key` (`<groupId>/<candidateId>`); its fields must name the same group and candidate. */
127
+ export declare function decodeDeliveryEvidence(key: string, raw: unknown): DeliveryEvidence;
128
+ export declare function encodeDeliveryEvidence(evidence: DeliveryEvidence): Storable;
129
+ export declare function decodeDeclineEvidence(key: string, raw: unknown): DeclineEvidence;
130
+ export declare function encodeDeclineEvidence(evidence: DeclineEvidence): Storable;
131
+ export declare function deliveryKey(groupId: string, candidateId: string): string;
132
+ export declare function declineKey(groupId: string, welcomeId: string, author: string): string;
133
+ /** One decline evidence row with the identity its key carries. */
134
+ export interface KeyedDeclineEvidence {
135
+ readonly groupId: string;
136
+ readonly welcomeId: string;
137
+ readonly author: string;
138
+ readonly evidence: DeclineEvidence;
139
+ }
140
+ /**
141
+ * Every candidate the evidence holds (SC-2 I5, I6). The candidate set of a decline row is every delivery of its group
142
+ * to its author (recipient) with its Welcome id, pruned or not, declined or not. A delivery is a candidate when that
143
+ * row holds any decline for it: its own valid selector (`qualified`), or an unqualified or legacy decline of the
144
+ * whole set. It is `actionable` when a selector names it, or when an unqualified or legacy decline covers a set
145
+ * whose deliveries all name the same KeyPackage (exactly one recipient device); otherwise `ambiguous` — never decided
146
+ * by elimination. `rev` counts the kinds of evidence present for the delivery (legacy, unqualified, own selector):
147
+ * it only grows as evidence is added, and an equal `rev` means the same status and basis. The result is ordered by
148
+ * `<groupId>/<candidateId>`.
149
+ */
150
+ export declare function matchCandidates(account: string, deliveries: readonly DeliveryEvidence[], declines: readonly KeyedDeclineEvidence[]): DeclineCandidate[];
151
+ /** What an authenticated decline asks for (its parsed DECLINE content). */
152
+ export type DeclineSelector = {
153
+ readonly kind: 'unqualified';
154
+ } | {
155
+ readonly kind: 'qualified';
156
+ readonly inviteeRef: string;
157
+ } | {
158
+ readonly kind: 'invalid';
159
+ };
160
+ /**
161
+ * Spec DD3 applied to one decline row: the evidence after an authenticated decline of a Welcome whose candidate set
162
+ * (the deliveries of that Welcome to the author) is `set`. `undefined` when the decline changes nothing — an empty
163
+ * set (no delivery of that Welcome went to that account), a present but invalid or non-matching selector (SC-2 I7:
164
+ * never downgraded to an unqualified decline), or a duplicate.
165
+ */
166
+ export declare function applyDecline(current: DeclineEvidence | undefined, set: readonly DeliveryEvidence[], selector: DeclineSelector, at: number): DeclineEvidence | undefined;
167
+ /** The parts of one `invites` record backfill reads (`InviteRecord`, structurally). */
168
+ export interface LegacyInviteView {
169
+ readonly groupId: string;
170
+ readonly inviteId: string;
171
+ readonly committedAt: number;
172
+ readonly invitees: readonly {
173
+ readonly inviteeRef: string;
174
+ readonly pubkey: string;
175
+ readonly status: string;
176
+ readonly rumor: {
177
+ readonly content: string;
178
+ };
179
+ }[];
180
+ }
181
+ /**
182
+ * The evidence a retained `invites` record proves: one `legacy-backfill` {@link DeliveryEvidence} (no anchor) per
183
+ * delivery whose Welcome content names a Welcome, and a legacy decline for each Welcome and account with a `declined`
184
+ * delivery (the pre-upgrade code declined every delivery of the Welcome to that account at once). Pure.
185
+ */
186
+ export declare function evidenceFromLegacyInvite(record: LegacyInviteView): {
187
+ readonly deliveries: DeliveryEvidence[];
188
+ readonly legacyDeclines: Array<{
189
+ readonly groupId: string;
190
+ readonly welcomeId: string;
191
+ readonly author: string;
192
+ }>;
193
+ };
194
+ /**
195
+ * The backfill deliveries of `record` to `recipient` whose evidence row is absent — read-only, what
196
+ * {@link materializeLegacyEvidence} would write for that recipient (a key repeated inside the record counts once).
197
+ * Deliveries to other accounts are skipped unread, and a Welcome is decoded and hashed only for a missing delivery: a
198
+ * decline's candidate set costs no Welcome hash once the group's evidence is materialized.
199
+ */
200
+ export declare function missingLegacyDeliveriesTo(tx: AccountStoreTx, record: LegacyInviteView, recipient: string): Promise<DeliveryEvidence[]>;
201
+ /**
202
+ * Materializes `record`'s backfill in the caller's (write) transaction: idempotent — a second run finds every row
203
+ * and writes nothing. Called on write paths before anything prunes or flips the record.
204
+ */
205
+ export declare function materializeLegacyEvidence(tx: AccountStoreTx, record: LegacyInviteView): Promise<void>;
206
+ /**
207
+ * The stored deliveries of `groupId` with Welcome `welcomeId` to `recipient` — the candidate set of a decline. A
208
+ * row that does not decode is skipped (a malformed row never blocks matching the others); a failed read propagates.
209
+ */
210
+ export declare function deliveriesOfSet(tx: AccountStoreTx, groupId: string, welcomeId: string, recipient: string): Promise<DeliveryEvidence[]>;
211
+ /**
212
+ * The decline evidence row of `(groupId, welcomeId, author)`. A row that does not decode reads absent (the next
213
+ * write replaces it): a damaged secondary row must not block recording a decline; a failed read propagates.
214
+ */
215
+ export declare function readDeclineEvidence(tx: AccountStoreTx, groupId: string, welcomeId: string, author: string): Promise<DeclineEvidence | undefined>;
216
+ export declare function writeDeclineEvidence(tx: AccountStoreTx, groupId: string, welcomeId: string, author: string, evidence: DeclineEvidence): Promise<void>;
217
+ /**
218
+ * Writes `evidence` unless a row already exists for its candidate (the hand-off is idempotent: the first row wins,
219
+ * anchors are immutable). A row that does not open is present: it is left as stored, never overwritten.
220
+ */
221
+ export declare function recordDeliveryEvidence(tx: AccountStoreTx, evidence: DeliveryEvidence): Promise<void>;
222
+ /** Group purge: deletes every evidence row of `groupId` (group purge ends inviter matching for the group). */
223
+ export declare function purgeGroupEvidence(tx: AccountStoreTx, groupId: string): Promise<void>;
224
+ /** Marks a stored row whose envelope or payload does not open ({@link isMalformedRowError}). */
225
+ export declare const MALFORMED_ROW: unique symbol;
226
+ /**
227
+ * The stored value at `key`, `undefined` when absent, or {@link MALFORMED_ROW} when the row is present but does not
228
+ * open. Any other read error (storage, backend, version, lease) propagates.
229
+ */
230
+ export declare function getOrMalformed(view: KeyValueView, key: string): Promise<unknown>;
231
+ /**
232
+ * SC-13: one page of the account's decline candidates, in `<groupId>/<candidateId>` order after the cursor `after`,
233
+ * at most `limit` long. READ-ONLY: it never writes, prunes, publishes or opens a group — a retained pre-upgrade
234
+ * record's backfill is synthesized here, not written. Malformed evidence rows and undecodable records are skipped; a
235
+ * failed read propagates. Keyset pagination: each candidate is returned at most once across pages; one created
236
+ * meanwhile below the cursor surfaces through the live `declineCandidate` event registered before the scan.
237
+ *
238
+ * Cost: the ordered delivery keys skip everything up to the cursor without a read; from there the walk reads one
239
+ * delivery row and its set's decline row per key until the page is full and one more candidate proves `next`. A
240
+ * delivery whose own selector does not name it but whose set an unqualified or legacy decline covers needs its set's
241
+ * KeyPackages (`ambiguous` vs `actionable`): delivery keys do not carry the Welcome or the recipient, so that reads
242
+ * the delivery rows of its group once per page, indexed by set, and matches each such set once per page.
243
+ */
244
+ export declare function scanDeclineCandidates(tx: AccountStoreTx, opts: {
245
+ readonly account: string;
246
+ readonly after?: string;
247
+ readonly limit: number;
248
+ readonly legacy: readonly LegacyInviteView[];
249
+ }): Promise<DeclineCandidatePage>;
250
+ /**
251
+ * Epic marmot-invitation-outcomes S4: one delivery and its candidate by identity, read-only — the candidate exactly as
252
+ * {@link scanDeclineCandidates} returns it (the same virtual backfill of `groupId`'s retained records in `legacy`, the
253
+ * same set matching). `undefined` when no delivery (stored and decodable, or synthesized) has that identity; a delivery
254
+ * without decline evidence comes back without a candidate. A malformed row is no delivery; a failed read propagates.
255
+ *
256
+ * Cost: the group's delivery keys, the delivery row and its set's decline row. Only a delivery a covering (unqualified
257
+ * or legacy) decline holds without its own selector reads the rest of its group's delivery rows — its set's
258
+ * KeyPackages decide `actionable` vs `ambiguous`; a selector decides on its own, as in the scan.
259
+ */
260
+ export declare function findDeclineCandidate(tx: AccountStoreTx, opts: {
261
+ readonly account: string;
262
+ readonly groupId: string;
263
+ readonly candidateId: string;
264
+ readonly legacy: readonly LegacyInviteView[];
265
+ }): Promise<{
266
+ readonly delivery: DeliveryEvidence;
267
+ readonly candidate?: DeclineCandidate;
268
+ } | undefined>;
269
+ /**
270
+ * Whether {@link findDeclineCandidate} would return a candidate, without resolving it: a delivery holds a candidate
271
+ * exactly when its set's decline row selects it or covers its set (the delivery is a member of its own set). Reads the
272
+ * group's delivery keys, the delivery row and its set's decline row — never the rest of the set.
273
+ */
274
+ export declare function hasDeclineCandidate(tx: AccountStoreTx, opts: {
275
+ readonly groupId: string;
276
+ readonly candidateId: string;
277
+ readonly legacy: readonly LegacyInviteView[];
278
+ }): Promise<boolean>;
279
+ /**
280
+ * SC-13: the validated paging options of `invitations.declineCandidates(options?)` — `after` a cursor string (a
281
+ * previous page's `next`), `limit` a finite number clamped to `[1, DECLINE_SCAN_PAGE_MAX]` (default: the maximum).
282
+ * Throws `invalid-options` for anything else.
283
+ */
284
+ export declare function declineScanOptions(options: unknown): {
285
+ readonly after?: string;
286
+ readonly limit: number;
287
+ };
288
+ export {};