@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
@@ -3,9 +3,9 @@ import { wrap as giftWrap } from '@941design/nostr-events/gift-wrap';
3
3
  import { ADDRESSABLE_KEY_PACKAGE_KIND, commitDigest, createWelcomeRumor, evaluateKeyPackageForGroup, getCredentialPubkey, getKeyPackage, getWelcomeKeyPackageRefs, } from '@941design/marmot-engine/core';
4
4
  import { defaultProposalTypes } from '@941design/marmot-engine/mls';
5
5
  import { computeKeyPackageRefHex, selectKeyPackage, validateKeyPackageEvent } from '../key-packages/index.js';
6
- import { classifyPublish, hexOfBytes, isHex64, isMarmotError, MarmotError, RUMOR_KINDS } from '../shared/index.js';
6
+ import { classifyPublish, hexOfBytes, isHex64, isMalformedRowError, isMarmotError, MarmotError, RUMOR_KINDS } from '../shared/index.js';
7
+ import { applyDecline, candidateIdOf, deliveriesOfSet, findDeclineCandidate, hasDeclineCandidate, missingLegacyDeliveriesTo, getOrMalformed, MALFORMED_ROW, matchCandidates, materializeLegacyEvidence, purgeGroupEvidence, readDeclineEvidence, recordDeliveryEvidence, scanDeclineCandidates, welcomeIdOfContent, writeDeclineEvidence, } from './delivery-evidence.js';
7
8
  import { resolveInboxRelays } from './relay-planes.js';
8
- import { welcomeIdOf } from './welcome-processor.js';
9
9
  function invalid(message, details) {
10
10
  return new MarmotError('invalid-options', `invite: ${message}`, { details });
11
11
  }
@@ -291,9 +291,11 @@ function prunable(record, nowMs, retentionMs) {
291
291
  }
292
292
  /**
293
293
  * Deletes `groupId`'s prunable records. Best-effort: a record that does not decode, or cannot be read at all, is
294
- * left as stored — retention never decides whether an operation of the group succeeds.
294
+ * left as stored — retention never decides whether an operation of the group succeeds. Every record read first gets
295
+ * its pre-upgrade delivery evidence backfilled (epic marmot-invitation-outcomes S3, idempotent): the evidence
296
+ * outlives the record, so a decline arriving after the prune still matches (spec DD2).
295
297
  */
296
- async function pruneGroup(view, keys, groupId, nowMs, retentionMs) {
298
+ async function pruneGroup(tx, view, keys, groupId, nowMs, retentionMs) {
297
299
  for (const key of keysOfGroup(keys, groupId)) {
298
300
  let record;
299
301
  try {
@@ -302,7 +304,10 @@ async function pruneGroup(view, keys, groupId, nowMs, retentionMs) {
302
304
  catch {
303
305
  continue;
304
306
  }
305
- if (record !== undefined && prunable(record, nowMs, retentionMs))
307
+ if (record === undefined)
308
+ continue;
309
+ await materializeLegacyEvidence(tx, record);
310
+ if (prunable(record, nowMs, retentionMs))
306
311
  await view.delete(key);
307
312
  }
308
313
  }
@@ -393,6 +398,9 @@ function encodeInviteRecord(record) {
393
398
  * raw `groupId` field.
394
399
  */
395
400
  export async function purgeGroupInvites(tx, groupId) {
401
+ // Epic marmot-invitation-outcomes S3: the group's delivery and decline evidence ends with it (group purge ends
402
+ // inviter matching for the group).
403
+ await purgeGroupEvidence(tx, groupId);
396
404
  const view = tx.artifact(INVITES);
397
405
  for (const key of await view.keys()) {
398
406
  const parts = parseInviteKey(key);
@@ -416,8 +424,8 @@ async function readInvite(view, key) {
416
424
  * operation fails transiently and is retried rather than concluding the record is not there.
417
425
  */
418
426
  async function readDecodable(view, key) {
419
- const raw = await view.get(key);
420
- if (raw === undefined)
427
+ const raw = await getOrMalformed(view, key);
428
+ if (raw === undefined || raw === MALFORMED_ROW)
421
429
  return undefined;
422
430
  try {
423
431
  return decodeInviteRecord(key, raw);
@@ -426,7 +434,13 @@ async function readDecodable(view, key) {
426
434
  return undefined;
427
435
  }
428
436
  }
429
- /** The content of a DECLINE rumor (`decline.ts` `buildDeclineRumor`): `{ v: 1, welcome, groupId }`; `undefined` otherwise. */
437
+ /**
438
+ * The content of a DECLINE rumor (`decline.ts` `buildDeclineRumor`): `{ v: 1, welcome, groupId, keyPackageRef? }`;
439
+ * `undefined` otherwise. Other extra fields are ignored. The optional `keyPackageRef` (epic marmot-invitation-outcomes
440
+ * S3, spec DD3) selects one delivery: a non-empty string is a selector (valid only if it names a delivery of that
441
+ * Welcome to the author — decided by the matching), anything else present under that name is an invalid selector,
442
+ * which authorizes nothing and is never read as an unqualified decline.
443
+ */
430
444
  function parseDeclineContent(content) {
431
445
  let parsed;
432
446
  try {
@@ -439,7 +453,70 @@ function parseDeclineContent(content) {
439
453
  return undefined;
440
454
  if (parsed.welcome.length === 0 || parsed.groupId.length === 0)
441
455
  return undefined;
442
- return { welcomeId: parsed.welcome, groupId: parsed.groupId };
456
+ const ref = parsed.keyPackageRef;
457
+ const selector = !('keyPackageRef' in parsed) ? { kind: 'unqualified' } : typeof ref === 'string' && ref.length > 0 ? { kind: 'qualified', inviteeRef: ref } : { kind: 'invalid' };
458
+ return { welcomeId: parsed.welcome, groupId: parsed.groupId, selector };
459
+ }
460
+ /**
461
+ * Every decodable `invites` record of the store, read-only (epic marmot-invitation-outcomes S3: the input of the
462
+ * virtual backfill of {@link scanDeclineCandidates}). A record still under its pre-AC-HYG-2 key `<inviteId>` is read
463
+ * where it is (the scan never re-keys) unless its current key exists too. A record that does not decode is skipped;
464
+ * a failed read propagates.
465
+ */
466
+ async function legacyInviteViews(tx) {
467
+ const view = tx.artifact(INVITES);
468
+ const keys = await view.keys();
469
+ const present = new Set(keys);
470
+ const out = [];
471
+ for (const key of keys) {
472
+ const raw = await getOrMalformed(view, key);
473
+ if (raw === undefined || raw === MALFORMED_ROW)
474
+ continue;
475
+ let current = key;
476
+ if (parseInviteKey(key) === undefined) {
477
+ if (!isObject(raw) || typeof raw.groupId !== 'string' || raw.groupId.length === 0 || raw.inviteId !== key)
478
+ continue;
479
+ current = inviteKey(raw.groupId, key);
480
+ if (present.has(current))
481
+ continue;
482
+ }
483
+ try {
484
+ out.push(decodeInviteRecord(current, raw));
485
+ }
486
+ catch (error) {
487
+ if (!isMalformedRowError(error))
488
+ throw error;
489
+ }
490
+ }
491
+ return out;
492
+ }
493
+ /**
494
+ * `invitations.declineCandidates` (epic marmot-invitation-outcomes S3, SC-13): one page of the account's decline
495
+ * candidates, read in the caller's (read-only) account transaction. Writes nothing.
496
+ */
497
+ export async function declineCandidatePage(tx, opts) {
498
+ return scanDeclineCandidates(tx, { ...opts, legacy: await legacyInviteViews(tx) });
499
+ }
500
+ /**
501
+ * `invitations.cleanupDisposition` (epic marmot-invitation-outcomes S4, SC-3 I9, I9a): the delivery and candidate named
502
+ * by a cleanup reference, read in the caller's (read-only) account transaction — the candidate exactly as the scan
503
+ * returns it — plus the identity of the delivery's invite commit while its `invites` record is retained (what lazy
504
+ * legacy anchor resolution needs). `undefined` when the store holds no such delivery. Writes nothing.
505
+ */
506
+ export async function cleanupCandidateOf(tx, opts) {
507
+ const legacy = (await legacyInviteViews(tx)).filter((r) => r.groupId === opts.groupId);
508
+ const found = await findDeclineCandidate(tx, { ...opts, legacy });
509
+ if (found === undefined)
510
+ return undefined;
511
+ const record = legacy.find((r) => r.inviteId === found.delivery.inviteId);
512
+ return record === undefined ? found : { ...found, invite: { commitEventId: record.commitEventId, ...(record.commitTag === undefined ? {} : { commitTag: record.commitTag }) } };
513
+ }
514
+ /**
515
+ * Whether {@link cleanupCandidateOf} would name a candidate for that identity — the routing read of
516
+ * `invitations.cleanupDisposition`, which resolves no candidate set. Writes nothing.
517
+ */
518
+ export async function cleanupCandidateExists(tx, opts) {
519
+ return hasDeclineCandidate(tx, { ...opts, legacy: (await legacyInviteViews(tx)).filter((r) => r.groupId === opts.groupId) });
443
520
  }
444
521
  export function toWelcomeOutcome(delivery, cause) {
445
522
  const status = delivery.status === 'pending' ? 'retryable' : delivery.status;
@@ -511,7 +588,7 @@ export function createInvitationsService(deps) {
511
588
  .transaction(async (tx) => {
512
589
  const view = tx.artifact(INVITES);
513
590
  let listed = migrating ? await migrateLegacyKeys(view) : undefined;
514
- return fn(view, async () => (listed ??= await view.keys()));
591
+ return fn(view, async () => (listed ??= await view.keys()), tx);
515
592
  })
516
593
  .then((result) => {
517
594
  if (migrating)
@@ -526,7 +603,7 @@ export function createInvitationsService(deps) {
526
603
  */
527
604
  async function pruneBestEffort(groupId) {
528
605
  try {
529
- await invitesTx(async (view, keys) => pruneGroup(view, await keys(), groupId, deps.clock.now(), deps.inviteRetentionMs));
606
+ await invitesTx(async (view, keys, tx) => pruneGroup(tx, view, await keys(), groupId, deps.clock.now(), deps.inviteRetentionMs));
530
607
  }
531
608
  catch {
532
609
  // dropped: retried at the group's next load, handoff, retry or decline
@@ -716,11 +793,27 @@ export function createInvitationsService(deps) {
716
793
  });
717
794
  }
718
795
  return {
719
- async recordCommitted({ inviteId, groupId, commitEventId, commitTag, welcomes }) {
720
- await invitesTx(async (view) => {
796
+ async recordCommitted({ inviteId, groupId, commitEventId, commitTag, welcomes, anchors }) {
797
+ await invitesTx(async (view, _keys, tx) => {
721
798
  const key = inviteKey(groupId, inviteId);
722
- if ((await view.get(key)) !== undefined)
799
+ // A row that does not open is present but unusable: left as stored, never overwritten.
800
+ const existing = await getOrMalformed(view, key);
801
+ if (existing === MALFORMED_ROW)
723
802
  return;
803
+ if (existing !== undefined) {
804
+ // A repeated hand-off keeps the record's progress; one written before delivery evidence existed gets its
805
+ // backfill (idempotent: rows already there are kept, anchors are immutable).
806
+ let decoded;
807
+ try {
808
+ decoded = decodeInviteRecord(key, existing);
809
+ }
810
+ catch {
811
+ decoded = undefined;
812
+ }
813
+ if (decoded !== undefined)
814
+ await materializeLegacyEvidence(tx, decoded);
815
+ return;
816
+ }
724
817
  const now = deps.clock.now();
725
818
  const record = {
726
819
  v: 1,
@@ -732,6 +825,26 @@ export function createInvitationsService(deps) {
732
825
  invitees: welcomes.map((w) => ({ ...w, status: 'pending', attempts: 0 })),
733
826
  };
734
827
  await view.put(key, encodeInviteRecord(record));
828
+ // Epic marmot-invitation-outcomes S3 (SC-1 I2, SC-2): the payload-free evidence of every delivery, with its
829
+ // Add anchor, in the same transaction as the record — it outlives the record's retention.
830
+ for (const welcome of welcomes) {
831
+ const welcomeId = welcomeIdOfContent(welcome.rumor.content);
832
+ if (welcomeId === undefined)
833
+ continue; // names no Welcome: no decline can ever match it
834
+ const anchor = anchors?.get(welcome.inviteeRef);
835
+ await recordDeliveryEvidence(tx, {
836
+ v: 1,
837
+ candidateId: candidateIdOf(groupId, inviteId, welcome.inviteeRef),
838
+ groupId,
839
+ inviteId,
840
+ inviteeRef: welcome.inviteeRef,
841
+ recipient: welcome.pubkey,
842
+ welcomeId,
843
+ issuedAt: now,
844
+ ...(anchor === undefined ? {} : { anchor }),
845
+ origin: 'issued',
846
+ });
847
+ }
735
848
  });
736
849
  await pruneBestEffort(groupId);
737
850
  },
@@ -899,62 +1012,85 @@ export function createInvitationsService(deps) {
899
1012
  if (content === undefined)
900
1013
  return;
901
1014
  const author = rumor.pubkey;
902
- // Retention first, as for retryWelcome (AC-HYG-2): a delivery past it is no longer matched — a late decline
1015
+ const { groupId, welcomeId, selector } = content;
1016
+ // Retention first, as for retryWelcome (AC-HYG-2): a delivery row past it is no longer flipped — a late decline
903
1017
  // neither reports it nor renews its retention — and every decline of the group, matched or not, runs the pass.
904
- await pruneBestEffort(content.groupId);
905
- // 1. The candidate deliveries: the content's group's records, invitees authored by the seal's author.
906
- const candidates = await invitesTx(async (view, keys) => {
1018
+ // The pass backfills the group's pre-upgrade evidence before it deletes anything.
1019
+ await pruneBestEffort(groupId);
1020
+ // A present but invalid selector authorizes nothing (spec DD3): no status change, no evidence, no event.
1021
+ if (selector.kind === 'invalid')
1022
+ return;
1023
+ /** The candidate set: stored evidence plus the backfill of records not materialized yet (read-only here). */
1024
+ const candidateSet = async (tx, records) => {
1025
+ const set = new Map((await deliveriesOfSet(tx, groupId, welcomeId, author)).map((d) => [d.candidateId, d]));
1026
+ for (const record of records) {
1027
+ for (const d of await missingLegacyDeliveriesTo(tx, record, author)) {
1028
+ if (d.welcomeId === welcomeId && !set.has(d.candidateId))
1029
+ set.set(d.candidateId, d);
1030
+ }
1031
+ }
1032
+ return [...set.values()];
1033
+ };
1034
+ const groupRecords = async (view, keys) => {
907
1035
  const out = [];
908
- for (const key of keysOfGroup(await keys(), content.groupId)) {
909
- // A record that does not decode cannot be matched (and is left as stored).
1036
+ for (const key of keysOfGroup(await keys(), groupId)) {
1037
+ // A record that does not decode cannot be matched (and is left as stored); a failed read propagates.
910
1038
  const record = await readDecodable(view, key);
911
- for (const invitee of record?.invitees ?? [])
912
- if (invitee.pubkey === author && invitee.status !== 'declined')
913
- out.push({ key, welcome: invitee.rumor.content });
1039
+ if (record !== undefined)
1040
+ out.push({ key, record });
914
1041
  }
915
1042
  return out;
1043
+ };
1044
+ // 1. Is there anything to match? (Read-only: an unknown author, Welcome or group writes nothing.)
1045
+ const matchable = await invitesTx(async (view, keys, tx) => {
1046
+ const set = await candidateSet(tx, (await groupRecords(view, keys)).map((r) => r.record));
1047
+ return selector.kind === 'unqualified' ? set.length > 0 : set.some((d) => d.inviteeRef === selector.inviteeRef);
916
1048
  });
917
- if (candidates.length === 0)
918
- return;
919
- // 2. The Welcome identities, hashed outside any transaction.
920
- const matching = new Set();
921
- for (const welcome of new Set(candidates.map((c) => c.welcome))) {
922
- let id;
923
- try {
924
- id = await welcomeIdOf({ ...rumor, kind: RUMOR_KINDS.WELCOME, content: welcome });
925
- }
926
- catch {
927
- id = undefined; // not base64: names no Welcome
928
- }
929
- if (id === content.welcomeId)
930
- matching.add(welcome);
931
- }
932
- if (matching.size === 0)
1049
+ if (!matchable)
933
1050
  return;
1051
+ const account = deps.account ?? (await deps.signer.getPublicKey());
934
1052
  assertLive();
935
- // 3. One transaction: every matching delivery still not declined goes `declined` (re-read: a concurrent decline counts once).
1053
+ // 2. One transaction: re-read (a concurrent decline counts once), backfill, then the row flips and the evidence.
936
1054
  const now = deps.clock.now();
937
- const declined = await invitesTx(async (view) => {
938
- const changed = [];
939
- for (const key of new Set(candidates.map((c) => c.key))) {
940
- const record = await readDecodable(view, key);
941
- if (record === undefined)
942
- continue;
1055
+ const outcome = await invitesTx(async (view, keys, tx) => {
1056
+ const records = await groupRecords(view, keys);
1057
+ for (const { record } of records)
1058
+ await materializeLegacyEvidence(tx, record);
1059
+ const set = await candidateSet(tx, []);
1060
+ const current = await readDeclineEvidence(tx, groupId, welcomeId, author);
1061
+ const next = applyDecline(current, set, selector, now);
1062
+ if (selector.kind === 'qualified' && !set.some((d) => d.inviteeRef === selector.inviteeRef))
1063
+ return undefined;
1064
+ const members = new Set(set.filter((d) => selector.kind === 'unqualified' || d.inviteeRef === selector.inviteeRef).map((d) => d.candidateId));
1065
+ const flipped = [];
1066
+ for (const { key, record } of records) {
943
1067
  let touched = false;
944
1068
  const invitees = record.invitees.map((invitee) => {
945
- if (invitee.pubkey !== author || invitee.status === 'declined' || !matching.has(invitee.rumor.content))
1069
+ if (invitee.status === 'declined')
1070
+ return invitee;
1071
+ const candidateId = candidateIdOf(record.groupId, record.inviteId, invitee.inviteeRef);
1072
+ if (!members.has(candidateId))
946
1073
  return invitee;
947
1074
  touched = true;
948
- changed.push({ groupId: record.groupId, inviteeRef: invitee.inviteeRef });
1075
+ flipped.push({ groupId: record.groupId, inviteeRef: invitee.inviteeRef, candidateId });
949
1076
  return { ...withoutReason(invitee), status: 'declined', settledAt: now };
950
1077
  });
951
1078
  if (touched)
952
1079
  await view.put(key, encodeInviteRecord({ ...record, invitees }));
953
1080
  }
954
- return changed;
1081
+ if (next !== undefined)
1082
+ await writeDeclineEvidence(tx, groupId, welcomeId, author, next);
1083
+ const keyed = (evidence) => (evidence === undefined ? [] : [{ groupId, welcomeId, author, evidence }]);
1084
+ const before = new Map(matchCandidates(account, set, keyed(current)).map((c) => [c.candidateId, c.rev]));
1085
+ const changed = next === undefined ? [] : matchCandidates(account, set, keyed(next)).filter((c) => before.get(c.candidateId) !== c.rev);
1086
+ return { flipped, changed };
955
1087
  });
956
- for (const d of declined)
957
- deps.onDeclined?.(d);
1088
+ if (outcome === undefined)
1089
+ return;
1090
+ for (const { candidateId, ...declined } of outcome.flipped)
1091
+ deps.onDeclined?.(declined, { candidateId });
1092
+ for (const candidate of outcome.changed)
1093
+ deps.onCandidate?.(candidate);
958
1094
  },
959
1095
  dispose() {
960
1096
  disposed = true;
@@ -62,6 +62,7 @@ import type { AccountStoreTx, KeyValueView, Storable } from '../storage/index.js
62
62
  import { type CompetingWelcomePorts } from './competing-welcome.js';
63
63
  import { type DeclineDeliveryDeps, type DeclineState } from './decline.js';
64
64
  import { type ManifestRecord } from './expect-welcome.js';
65
+ import type { AdoptionProof, AdoptionStamp } from './invitation-outcome.js';
65
66
  /** The MLS Welcome of a Welcome rumor, decoded from its base64 content (no tag is required). Throws on anything else. */
66
67
  export declare function decodeWelcomeRumor(rumor: Rumor): Welcome;
67
68
  /** The Welcome identity: hex SHA-256 of the serialized MLS Welcome (the rumor content, base64-decoded). */
@@ -126,9 +127,16 @@ export interface InvitationRecord {
126
127
  readonly from: string;
127
128
  readonly to: string;
128
129
  };
130
+ /**
131
+ * Epic marmot-invitation-outcomes S2 (ADR-019 D6–D8): the durable stamp that THIS invitation's Welcome caused the
132
+ * adoption of its group — written when the adoption completes, and by teardown before the group store and the
133
+ * index entry go. A record that carries it is never turned into a negative outcome (rejected, declined, abandoned).
134
+ * Additive optional field of the v:1 record (absent on every record written before it).
135
+ */
136
+ readonly adoption?: AdoptionStamp;
129
137
  }
130
138
  export declare function decodeInvitation(id: string, raw: unknown): InvitationRecord;
131
- /** A pending (unexpected) invitation as `client.invitations.pending()` lists it. */
139
+ export declare function encodeInvitation(record: InvitationRecord): Storable;
132
140
  /**
133
141
  * S9 teardown: the consumed KeyPackageRefs of the invitations that named
134
142
  * `groupId` (their retained keys are purged with the group); deletes the
@@ -136,6 +144,11 @@ export declare function decodeInvitation(id: string, raw: unknown): InvitationRe
136
144
  * terminal (`rejected`, reason `abandoned`, pinned key and Welcome dropped). Decided invitations (joined, declined,
137
145
  * rejected) are kept: they are what makes a redelivered Welcome of the
138
146
  * abandoned group a no-op rather than a re-join (at-most-once join).
147
+ *
148
+ * Epic marmot-invitation-outcomes S2: a record teardown stamped (`adoption`, written by `stampAdoptions` before this
149
+ * runs) caused the adoption — whatever its status, it becomes `joined` with its stamp (pinned key, Welcome and open
150
+ * markers dropped), never `rejected/abandoned` nor deleted: its outcome reads `joined` after the purge, and a
151
+ * redelivered Welcome answers `already-member`.
139
152
  */
140
153
  export declare function purgeGroupInvitations(tx: {
141
154
  artifact(name: 'pendingInvitations'): KeyValueView;
@@ -179,6 +192,12 @@ export interface WelcomeServiceDeps extends DeclineDeliveryDeps {
179
192
  */
180
193
  /** Rejects `not-a-member` for a group this client tore down whose state the Welcome would bring back (S9). */
181
194
  adoptJoinedGroup(groupId: string, state: ClientState, joinedAtMs: number, joinEvidence?: JoinEvidenceOfWelcome, invitationId?: string, welcomeCreatedAtMs?: number): Promise<'joined' | 'already-member'>;
195
+ /**
196
+ * Epic marmot-invitation-outcomes S2: invitation `invitationId`'s join adoption proof in the group's store, or
197
+ * `undefined` (none, or malformed). A resumed join whose adoption answered `already-member` is stamped only when
198
+ * the held group's proof names it: its own adoption committed in an earlier attempt, not another invitation's.
199
+ */
200
+ adoptionProofOf(groupId: string, invitationId: string): Promise<AdoptionProof | undefined>;
182
201
  /** Whether this client already holds the group. */
183
202
  hasGroup(groupId: string): Promise<boolean>;
184
203
  /**
@@ -7,6 +7,7 @@ import { epochOf, judgeCompetingWelcome, otherLeafSignatureKeysOf, terminalClass
7
7
  import { welcomeCommitTagOf } from './invite.js';
8
8
  import { attemptDeclineDelivery, buildDeclineRumor, decodeDecline, decodeRumor, encodeDecline, encodeRumor } from './decline.js';
9
9
  import { matchManifest, readManifest, recordManifest, validateManifest, writeManifest } from './expect-welcome.js';
10
+ import { isMalformedRowError } from '../shared/index.js';
10
11
  // ---------------------------------------------------------------------------
11
12
  // Welcome decoding and identity
12
13
  // ---------------------------------------------------------------------------
@@ -45,6 +46,15 @@ function optionalString(id, record, field) {
45
46
  throw malformed(id, field);
46
47
  return value;
47
48
  }
49
+ function decodeAdoption(id, raw) {
50
+ const r = raw;
51
+ if (typeof r !== 'object' || r === null || Array.isArray(r))
52
+ throw malformed(id, 'adoption');
53
+ if ((r.via !== 'join' && r.via !== 'switch') || (r.source !== 'group-proof' && r.source !== 'legacy-index') || typeof r.at !== 'number' || !Number.isFinite(r.at)) {
54
+ throw malformed(id, 'adoption');
55
+ }
56
+ return { via: r.via, source: r.source, at: r.at };
57
+ }
48
58
  export function decodeInvitation(id, raw) {
49
59
  if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
50
60
  throw malformed(id, 'not an object');
@@ -97,9 +107,10 @@ export function decodeInvitation(id, raw) {
97
107
  ...(reason === undefined ? {} : { reason }),
98
108
  ...(r.decline === undefined ? {} : { decline: decodeDecline(where, r.decline) }),
99
109
  ...(switching === undefined ? {} : { switching }),
110
+ ...(r.adoption === undefined ? {} : { adoption: decodeAdoption(id, r.adoption) }),
100
111
  };
101
112
  }
102
- function encodeInvitation(record) {
113
+ export function encodeInvitation(record) {
103
114
  return {
104
115
  v: 1,
105
116
  id: record.id,
@@ -117,6 +128,7 @@ function encodeInvitation(record) {
117
128
  ...(record.reason === undefined ? {} : { reason: record.reason }),
118
129
  ...(record.decline === undefined ? {} : { decline: encodeDecline(record.decline) }),
119
130
  ...(record.switching === undefined ? {} : { switching: { from: record.switching.from, to: record.switching.to } }),
131
+ ...(record.adoption === undefined ? {} : { adoption: { via: record.adoption.via, source: record.adoption.source, at: record.adoption.at } }),
120
132
  };
121
133
  }
122
134
  async function readInvitation(view, id) {
@@ -126,7 +138,16 @@ async function readInvitation(view, id) {
126
138
  async function writeInvitation(view, record) {
127
139
  await view.put(record.id, encodeInvitation(record));
128
140
  }
129
- /** A pending (unexpected) invitation as `client.invitations.pending()` lists it. */
141
+ /** Whether a stored adoption stamp decodes: only a readable stamp is evidence to preserve a record as `joined` at purge. */
142
+ function hasDecodableAdoption(id, raw) {
143
+ try {
144
+ decodeAdoption(id, raw);
145
+ return true;
146
+ }
147
+ catch {
148
+ return false;
149
+ }
150
+ }
130
151
  /**
131
152
  * S9 teardown: the consumed KeyPackageRefs of the invitations that named
132
153
  * `groupId` (their retained keys are purged with the group); deletes the
@@ -134,16 +155,36 @@ async function writeInvitation(view, record) {
134
155
  * terminal (`rejected`, reason `abandoned`, pinned key and Welcome dropped). Decided invitations (joined, declined,
135
156
  * rejected) are kept: they are what makes a redelivered Welcome of the
136
157
  * abandoned group a no-op rather than a re-join (at-most-once join).
158
+ *
159
+ * Epic marmot-invitation-outcomes S2: a record teardown stamped (`adoption`, written by `stampAdoptions` before this
160
+ * runs) caused the adoption — whatever its status, it becomes `joined` with its stamp (pinned key, Welcome and open
161
+ * markers dropped), never `rejected/abandoned` nor deleted: its outcome reads `joined` after the purge, and a
162
+ * redelivered Welcome answers `already-member`.
137
163
  */
138
164
  export async function purgeGroupInvitations(tx, groupId) {
139
165
  const view = tx.artifact(INVITATIONS);
140
166
  const refs = [];
141
167
  for (const key of await view.keys()) {
142
- const raw = (await view.get(key));
168
+ let raw;
169
+ try {
170
+ raw = (await view.get(key));
171
+ }
172
+ catch (error) {
173
+ // A row whose envelope does not open names no group this purge could act on: it never aborts an unrelated
174
+ // group's teardown. A version mismatch or a backend failure still propagates.
175
+ if (isMalformedRowError(error))
176
+ continue;
177
+ throw error;
178
+ }
143
179
  if (typeof raw !== 'object' || raw === null || raw.groupId !== groupId)
144
180
  continue;
145
181
  if (typeof raw.keyPackageRef === 'string')
146
182
  refs.push(raw.keyPackageRef);
183
+ if (raw.adoption !== undefined && hasDecodableAdoption(key, raw.adoption) && (raw.status === 'pending' || raw.status === 'competing' || raw.status === 'joining')) {
184
+ const { rumor: _rumor, pinned: _pinned, deferred: _deferred, switching: _switching, joinFailed: _joinFailed, reason: _reason, ...rest } = raw;
185
+ await view.put(key, { ...rest, status: 'joined' });
186
+ continue;
187
+ }
147
188
  // A `competing` record (a second Welcome waiting for the group's gate) goes with the group it was to switch.
148
189
  if (raw.status === 'pending' || raw.status === 'competing')
149
190
  await view.delete(key);
@@ -336,7 +377,8 @@ export function createWelcomeService(deps) {
336
377
  await deps.transaction(async (tx) => {
337
378
  const view = tx.artifact(INVITATIONS);
338
379
  const current = await readInvitation(view, id);
339
- if (current !== undefined && current.status !== 'joined') {
380
+ // A stamped record caused an adoption: never turned negative (S2, negative writers skip stamps).
381
+ if (current !== undefined && current.status !== 'joined' && current.adoption === undefined) {
340
382
  const { rumor: _rumor, pinned: _pinned, deferred: _deferred, ...rest } = current;
341
383
  await writeInvitation(view, { ...rest, status: 'rejected', reason: 'abandoned' });
342
384
  }
@@ -344,6 +386,11 @@ export function createWelcomeService(deps) {
344
386
  });
345
387
  return 'abandoned';
346
388
  }
389
+ // S2 (architecture SC-7): this call's adoption is proven when it wrote the group, or — a join resumed after its
390
+ // group transaction committed in an earlier attempt — when the held group's proof names this invitation. An
391
+ // `already-member` that another invitation's Welcome caused proves nothing for this one. Read before the account
392
+ // transaction (group → account, never an account transaction awaiting a group scope).
393
+ const proof = adopted === 'already-member' && prior === 'joining' ? await deps.adoptionProofOf(candidate.groupId, id) : undefined;
347
394
  const joined = await deps.transaction(async (tx) => {
348
395
  const view = tx.artifact(INVITATIONS);
349
396
  const current = await readInvitation(view, id);
@@ -355,6 +402,11 @@ export function createWelcomeService(deps) {
355
402
  await ctx?.markSeen(tx);
356
403
  if (current?.status === 'joined')
357
404
  return false;
405
+ const caused = adopted === 'joined' || prior === 'joining';
406
+ // S2 (architecture SC-7): the joined record of the adopting invitation carries its stamp (an existing one is
407
+ // kept), timed like teardown's A1 stamp: the proof's `at` — the arrival `adoptJoinedGroup` wrote it with.
408
+ const stampAt = adopted === 'joined' ? receivedAt : proof?.at;
409
+ const adoption = current?.adoption ?? (stampAt === undefined ? undefined : { via: 'join', source: 'group-proof', at: stampAt });
358
410
  await writeInvitation(view, {
359
411
  v: 1,
360
412
  id,
@@ -366,8 +418,9 @@ export function createWelcomeService(deps) {
366
418
  // Rotated on arrival already (a pending invitation): not again.
367
419
  rotation: current?.rotation === 'done' || current?.rotation === 'failed' ? current.rotation : 'pending',
368
420
  ...(current?.failures === undefined ? {} : { failures: current.failures }),
421
+ ...(adoption === undefined ? {} : { adoption }),
369
422
  });
370
- return adopted === 'joined' || prior === 'joining';
423
+ return caused;
371
424
  });
372
425
  if (joined)
373
426
  deps.onJoined({ groupId: candidate.groupId, invitationId: id });
@@ -535,6 +588,8 @@ export function createWelcomeService(deps) {
535
588
  await writeManifest(tx, { ...manifest, status: 'expired' });
536
589
  }
537
590
  if (current?.status !== 'joined') {
591
+ // S2: a confirmed switch (no reason) is this Welcome's adoption via its branch switch; an existing stamp is kept.
592
+ const adoption = current?.adoption ?? (reason === undefined ? { via: 'switch', source: 'group-proof', at: deps.clock.now() } : undefined);
538
593
  await writeInvitation(view, {
539
594
  v: 1,
540
595
  id,
@@ -546,6 +601,7 @@ export function createWelcomeService(deps) {
546
601
  ...(reason === undefined ? {} : { reason }),
547
602
  rotation: current?.rotation === 'done' || current?.rotation === 'failed' ? current.rotation : 'pending',
548
603
  ...(current?.failures === undefined ? {} : { failures: current.failures }),
604
+ ...(adoption === undefined ? {} : { adoption }),
549
605
  });
550
606
  }
551
607
  await ctx?.markSeen(tx);
@@ -640,7 +696,7 @@ export function createWelcomeService(deps) {
640
696
  await deps.transaction(async (tx) => {
641
697
  const view = tx.artifact(INVITATIONS);
642
698
  const current = await readInvitation(view, id);
643
- if (current?.status === 'competing') {
699
+ if (current?.status === 'competing' && current.adoption === undefined) {
644
700
  const { rumor: _rumor, pinned: _pinned, switching: _switching, deferred: _deferred, ...rest } = current;
645
701
  await writeInvitation(view, { ...rest, status: 'rejected', reason: 'abandoned' });
646
702
  }
@@ -666,11 +722,14 @@ export function createWelcomeService(deps) {
666
722
  * Design Decisions 2, 3, 5, 7, 8, 13, 14: settles a valid Welcome for a group this client holds. In order:
667
723
  *
668
724
  * 1. a `competing` record with a `switching` marker is completed first (the rebase is idempotent over a crash);
669
- * 2. a `competing` record whose matching manifest's deadline passed expires;
670
- * 3. the held branch is read from the stored group; C below its tip epoch, or the very branch it is on, is
725
+ * a marker whose switch never wrote its state expires past the matching manifest's deadline only while the
726
+ * gate is open;
727
+ * 2. the held branch is read from the stored group; C below its tip epoch, or the very branch it is on, is
671
728
  * terminal without the gate;
672
- * 4. a closed gate holds C as a durable `competing` record; an open one decides — `keep` is terminal,
673
- * `undecidable` is held, `switch` writes the intent and runs the rebase.
729
+ * 3. a closed gate holds C as a durable `competing` record — never expired, whatever the clock says (AC-JOIN-7:
730
+ * the library decides nothing for the application while the gate is closed);
731
+ * 4. an open gate decides — `keep` is terminal, `switch` writes the intent and runs the rebase, `undecidable`
732
+ * is held until the matching manifest's deadline passed, then expires (AC-FWJ-16).
674
733
  *
675
734
  * `legacy`: the decision does not apply and the caller keeps the plain join path (an interrupted join
676
735
  * of this very Welcome; a group with nothing stored to compare). Never throws for a rebase failure.
@@ -697,8 +756,9 @@ export function createWelcomeService(deps) {
697
756
  await settleTerminal(id, candidate, receivedAt, 'same-lineage', ctx);
698
757
  return { kind: 'kept' };
699
758
  }
700
- // A switch that never wrote its state is still a held Welcome: the manifest's deadline applies to it.
701
- if (written === 'absent' && (await manifestExpired(candidate, record))) {
759
+ // A switch that never wrote its state is still a held Welcome: the manifest's deadline applies to it, but only
760
+ // under an open gate (AC-JOIN-7: a closed gate holds the Welcome unresolved, whatever the clock says).
761
+ if (written === 'absent' && (await ports.competingGate(candidate.groupId)).open && (await manifestExpired(candidate, record))) {
702
762
  await settleTerminal(id, candidate, receivedAt, 'expired', ctx);
703
763
  return { kind: 'kept' };
704
764
  }
@@ -720,10 +780,6 @@ export function createWelcomeService(deps) {
720
780
  if (own === undefined || (own.joinEpoch === competing.epoch && own.joinTag === competing.tag) || own.adoptedBy === id)
721
781
  return { kind: 'legacy' };
722
782
  }
723
- if (record?.status === 'competing' && (await manifestExpired(candidate, record))) {
724
- await settleTerminal(id, candidate, receivedAt, 'expired', ctx);
725
- return { kind: 'kept' };
726
- }
727
783
  const held = await ports.heldBranch(candidate.groupId);
728
784
  if (held === undefined)
729
785
  return record?.status === 'competing' ? { kind: 'open' } : { kind: 'legacy' };
@@ -746,6 +802,11 @@ export function createWelcomeService(deps) {
746
802
  return { kind: 'kept' };
747
803
  }
748
804
  if (verdict.decision === 'undecidable') {
805
+ // Only a Welcome the open gate could not decide is bounded by the matching manifest's deadline (AC-FWJ-16).
806
+ if (record?.status === 'competing' && (await manifestExpired(candidate, record))) {
807
+ await settleTerminal(id, candidate, receivedAt, 'expired', ctx);
808
+ return { kind: 'kept' };
809
+ }
749
810
  await holdCompeting(id, candidate, rumor, receivedAt, undefined, ctx);
750
811
  return { kind: 'open' };
751
812
  }
@@ -777,7 +838,7 @@ export function createWelcomeService(deps) {
777
838
  await deps.transaction(async (tx) => {
778
839
  const view = tx.artifact(INVITATIONS);
779
840
  const current = await readInvitation(view, id);
780
- if (current?.status !== 'competing')
841
+ if (current?.status !== 'competing' || current.adoption !== undefined)
781
842
  return;
782
843
  const { rumor: _rumor, pinned: _pinned, switching: _switching, ...rest } = current;
783
844
  await writeInvitation(view, { ...rest, status: 'rejected', reason: evaluation.reason });
@@ -937,7 +998,7 @@ export function createWelcomeService(deps) {
937
998
  await deps.transaction(async (tx) => {
938
999
  const view = tx.artifact(INVITATIONS);
939
1000
  const current = await readInvitation(view, record.id);
940
- if (current?.status !== 'pending' && current?.status !== 'joining')
1001
+ if ((current?.status !== 'pending' && current?.status !== 'joining') || current.adoption !== undefined)
941
1002
  return;
942
1003
  const { rumor: _rumor, pinned: _pinned, deferred: _deferred, ...rest } = current;
943
1004
  await writeInvitation(view, { ...rest, status: 'rejected', reason: evaluation.reason });
@@ -1051,14 +1112,14 @@ export function createWelcomeService(deps) {
1051
1112
  const declined = await deps.transaction(async (tx) => {
1052
1113
  const view = tx.artifact(INVITATIONS);
1053
1114
  const current = await readInvitation(view, id);
1054
- if (current?.status !== 'pending')
1115
+ if (current?.status !== 'pending' || current.adoption !== undefined)
1055
1116
  return false;
1056
1117
  // The pinned key goes with the rumor: nothing can join this invitation any more.
1057
1118
  const { rumor: _rumor, pinned: _pinned, deferred: _deferred, ...rest } = current;
1058
1119
  const decline = author === undefined || current.sponsorAccount === undefined
1059
1120
  ? undefined
1060
1121
  : {
1061
- rumor: buildDeclineRumor({ author, welcomeId: id, groupId: current.groupId ?? '', nowSeconds: Math.floor(deps.clock.now() / 1000) }),
1122
+ rumor: buildDeclineRumor({ author, welcomeId: id, groupId: current.groupId ?? '', nowSeconds: Math.floor(deps.clock.now() / 1000), ...(current.keyPackageRef === undefined ? {} : { keyPackageRef: current.keyPackageRef }) }),
1062
1123
  recipient: current.sponsorAccount,
1063
1124
  status: 'pending',
1064
1125
  attempts: 0,