@serfab/cadre-core 1.19.0 → 1.20.0

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 (131) hide show
  1. package/dist/cadre-node.d.ts +118 -16
  2. package/dist/cadre-node.js +210 -31
  3. package/dist/cadre-node.js.map +1 -1
  4. package/dist/control-database.d.ts +2 -1
  5. package/dist/control-database.js +128 -126
  6. package/dist/control-database.js.map +1 -1
  7. package/dist/control-protocol-guard.js +3 -2
  8. package/dist/control-protocol-guard.js.map +1 -1
  9. package/dist/control-read-retry.d.ts +19 -16
  10. package/dist/control-read-retry.js +22 -54
  11. package/dist/control-read-retry.js.map +1 -1
  12. package/dist/control-retry.d.ts +50 -6
  13. package/dist/control-retry.js +53 -6
  14. package/dist/control-retry.js.map +1 -1
  15. package/dist/control-stream.js +2 -1
  16. package/dist/control-stream.js.map +1 -1
  17. package/dist/control-write-retry.d.ts +24 -16
  18. package/dist/control-write-retry.js +58 -30
  19. package/dist/control-write-retry.js.map +1 -1
  20. package/dist/describe-thrown.d.ts +12 -0
  21. package/dist/describe-thrown.js +59 -0
  22. package/dist/describe-thrown.js.map +1 -0
  23. package/dist/edge-node/config.d.ts +8 -2
  24. package/dist/edge-node/config.js +5 -1
  25. package/dist/edge-node/config.js.map +1 -1
  26. package/dist/edge-node/dissolve.d.ts +1 -1
  27. package/dist/edge-node/dissolve.js +1 -1
  28. package/dist/edge-node/dissolve.js.map +1 -1
  29. package/dist/edge-node/edge-join.js +4 -1
  30. package/dist/edge-node/edge-join.js.map +1 -1
  31. package/dist/edge-node/edge-node.d.ts +10 -0
  32. package/dist/edge-node/edge-node.js +54 -9
  33. package/dist/edge-node/edge-node.js.map +1 -1
  34. package/dist/edge-node/options.d.ts +11 -2
  35. package/dist/edge-node/options.js +11 -4
  36. package/dist/edge-node/options.js.map +1 -1
  37. package/dist/edge-node/platform.d.ts +15 -3
  38. package/dist/edge-node/strand-move.d.ts +0 -2
  39. package/dist/edge-node/strand-move.js +1 -4
  40. package/dist/edge-node/strand-move.js.map +1 -1
  41. package/dist/edge-node/strands.js +5 -3
  42. package/dist/edge-node/strands.js.map +1 -1
  43. package/dist/enrollment.js +2 -1
  44. package/dist/enrollment.js.map +1 -1
  45. package/dist/index.d.ts +6 -2
  46. package/dist/index.js +9 -1
  47. package/dist/index.js.map +1 -1
  48. package/dist/member-redemption.js +3 -9
  49. package/dist/member-redemption.js.map +1 -1
  50. package/dist/node-local-snapshot.js +2 -1
  51. package/dist/node-local-snapshot.js.map +1 -1
  52. package/dist/peer-dial.js +3 -2
  53. package/dist/peer-dial.js.map +1 -1
  54. package/dist/pending-join-runner.d.ts +29 -2
  55. package/dist/pending-join-runner.js +60 -20
  56. package/dist/pending-join-runner.js.map +1 -1
  57. package/dist/push-notifier-apns.js +8 -7
  58. package/dist/push-notifier-apns.js.map +1 -1
  59. package/dist/push-notifier-fcm.js +6 -5
  60. package/dist/push-notifier-fcm.js.map +1 -1
  61. package/dist/push-notifier-shared.d.ts +0 -2
  62. package/dist/push-notifier-shared.js +4 -4
  63. package/dist/push-notifier-shared.js.map +1 -1
  64. package/dist/relay-reservation.js +4 -3
  65. package/dist/relay-reservation.js.map +1 -1
  66. package/dist/strand-addr-protocol.js +2 -1
  67. package/dist/strand-addr-protocol.js.map +1 -1
  68. package/dist/strand-app-schema-report.d.ts +53 -0
  69. package/dist/strand-app-schema-report.js +77 -0
  70. package/dist/strand-app-schema-report.js.map +1 -0
  71. package/dist/strand-database.d.ts +60 -0
  72. package/dist/strand-database.js +93 -0
  73. package/dist/strand-database.js.map +1 -1
  74. package/dist/strand-first-sync-gate.js +4 -3
  75. package/dist/strand-first-sync-gate.js.map +1 -1
  76. package/dist/strand-formation-protocol.js +4 -3
  77. package/dist/strand-formation-protocol.js.map +1 -1
  78. package/dist/strand-instance-manager.d.ts +73 -2
  79. package/dist/strand-instance-manager.js +112 -9
  80. package/dist/strand-instance-manager.js.map +1 -1
  81. package/dist/strand-membership-reconciler.d.ts +13 -1
  82. package/dist/strand-membership-reconciler.js +25 -16
  83. package/dist/strand-membership-reconciler.js.map +1 -1
  84. package/dist/strand-membership-writer.d.ts +16 -2
  85. package/dist/strand-membership-writer.js +54 -8
  86. package/dist/strand-membership-writer.js.map +1 -1
  87. package/dist/strand-move.js +4 -6
  88. package/dist/strand-move.js.map +1 -1
  89. package/dist/strand-offline.d.ts +102 -0
  90. package/dist/strand-offline.js +97 -0
  91. package/dist/strand-offline.js.map +1 -0
  92. package/dist/types.d.ts +37 -0
  93. package/dist/types.js.map +1 -1
  94. package/package.json +8 -8
  95. package/src/cadre-node.ts +230 -31
  96. package/src/control-database.ts +5594 -5592
  97. package/src/control-protocol-guard.ts +3 -2
  98. package/src/control-read-retry.ts +22 -58
  99. package/src/control-retry.ts +54 -6
  100. package/src/control-stream.ts +2 -1
  101. package/src/control-write-retry.ts +58 -30
  102. package/src/describe-thrown.ts +60 -0
  103. package/src/edge-node/config.ts +11 -2
  104. package/src/edge-node/dissolve.ts +2 -1
  105. package/src/edge-node/edge-join.ts +2 -1
  106. package/src/edge-node/edge-node.ts +57 -7
  107. package/src/edge-node/options.ts +20 -4
  108. package/src/edge-node/platform.ts +15 -3
  109. package/src/edge-node/strand-move.ts +1 -5
  110. package/src/edge-node/strands.ts +74 -72
  111. package/src/enrollment.ts +2 -1
  112. package/src/index.ts +27 -1
  113. package/src/member-redemption.ts +3 -9
  114. package/src/node-local-snapshot.ts +2 -1
  115. package/src/peer-dial.ts +605 -604
  116. package/src/pending-join-runner.ts +68 -22
  117. package/src/push-notifier-apns.ts +8 -7
  118. package/src/push-notifier-fcm.ts +6 -5
  119. package/src/push-notifier-shared.ts +5 -5
  120. package/src/relay-reservation.ts +1212 -1211
  121. package/src/strand-addr-protocol.ts +2 -1
  122. package/src/strand-app-schema-report.ts +115 -0
  123. package/src/strand-database.ts +123 -1
  124. package/src/strand-first-sync-gate.ts +600 -599
  125. package/src/strand-formation-protocol.ts +4 -3
  126. package/src/strand-instance-manager.ts +137 -10
  127. package/src/strand-membership-reconciler.ts +942 -928
  128. package/src/strand-membership-writer.ts +61 -14
  129. package/src/strand-move.ts +594 -597
  130. package/src/strand-offline.ts +178 -0
  131. package/src/types.ts +36 -0
@@ -1,597 +1,594 @@
1
- /**
2
- * Moving a party's strands into another party of the same owner.
3
- *
4
- * A party's participation in a strand is control-database state: its `Strand` row (a strand
5
- * it founded) or `JoinedStrand` row (one it joined), carrying the strand's shared read secret,
6
- * and its `StrandPartyKey` row, the membership identity whose public half seats the party's
7
- * `Member` / `Manager` rows in the strand database. Nothing in the strand database names a
8
- * party, so a strand follows those rows: re-seated in another party under the same member key,
9
- * on the same peer, the strand's other members see the same member on the same peer and
10
- * nothing on the strand side changes.
11
- *
12
- * The case this serves is a phone app that founded a one-node cadre of its own (party B) and
13
- * then joins the user's main cadre (party A) by switching its one node across
14
- * (docs/architecture.md → "An app joins an existing cadre" → "Moving the app's strands"). Two
15
- * nodes never run at once, so the move has two ends: {@link exportStrandBundle} reads everything
16
- * B's node knows about its strands while it still runs, the embedder carries the bundle across
17
- * the switch as data, and {@link adoptStrandBundle} seats it on A's node once the app's key is
18
- * an owner there. Nothing is deleted in B; dissolving it is the embedder's later step, once
19
- * {@link unheldBundleContent} finds nothing of B's export that A's {@link readStrandHoldings} lacks.
20
- *
21
- * Built over `CadreNode`'s public surface, so `cadre-node.ts` does not grow by the feature.
22
- */
23
- import debug from 'debug';
24
- import type { PersistedNetworkState } from '@optimystic/db-p2p';
25
- import type { CadreNode } from './cadre-node.js';
26
- import type { OwnerSign } from './owner-signer.js';
27
- import {
28
- isPendingJoinConflict,
29
- isStrandIdConflict,
30
- pendingJoinId,
31
- type ControlDatabase,
32
- type JoinRequestFields
33
- } from './control-database.js';
34
- import { joinedStrandRow } from './joined-strand-store.js';
35
- import type { PendingJoin, StrandRow } from './types.js';
36
-
37
- const log = debug('sereus:cadre:strand-move');
38
-
39
- /**
40
- * Everything one party knows about its strands, as read from a running node of that party.
41
- * Carries secrets: every read secret, every party key and every bearer invitation. JSON-safe,
42
- * so an embedder can keep it in its secure store across a node switch.
43
- */
44
- export interface StrandBundle {
45
- v: 1;
46
- /** The exporting party. */
47
- partyId: string;
48
- /** Epoch ms. */
49
- exportedAt: number;
50
- strands: StrandBundleEntry[];
51
- /** Every row `queryPendingJoins` returned, outcome included. */
52
- pendingJoins: PendingJoin[];
53
- /** The invitations still redeemable at export. */
54
- formationInvites: FormationInviteEntry[];
55
- }
56
-
57
- export interface StrandBundleEntry {
58
- /** A `Strand` row, or a `JoinedStrand` row / machine-local unpublished join. */
59
- kind: 'own' | 'joined';
60
- row: Pick<StrandRow, 'Id' | 'Type' | 'MemberPrivateKey'>;
61
- /** `StrandPartyKey.PrivateKey` when the party holds one. */
62
- partyKey: string | null;
63
- /** The strand's saved routing table, opaque here; absent when the node held none. */
64
- networkState?: PersistedNetworkState;
65
- /** The addresses the strand's formation carried, in memory on the exporting node. */
66
- carriedAddrs: string[];
67
- }
68
-
69
- export interface FormationInviteEntry {
70
- token: string;
71
- sAppId: string;
72
- expiresAtMs: number | null;
73
- /** `TotalUses` minus the usage recorded so far; null is unlimited. */
74
- usesLeft: number | null;
75
- validationUrl: string | null;
76
- /** A bound invitation's host strand. */
77
- strandId: string | null;
78
- }
79
-
80
- /** One item an adoption could not seat this time; retrying the same bundle will. */
81
- export interface StrandMoveFailure {
82
- kind: 'strand' | 'invitation' | 'pending-join';
83
- /** The strand id, the join request id, or the id a join request for the invitation would carry (never the bearer token). */
84
- id: string;
85
- reason: string;
86
- }
87
-
88
- export interface StrandMoveReport {
89
- fromPartyId: string;
90
- /** Strand ids now seated in this party, those already there included. */
91
- moved: string[];
92
- /** Permanent: retrying will not help. */
93
- refused: Array<{ strandId: string; reason: string }>;
94
- /** Transient: adopt the same bundle again. */
95
- failed: StrandMoveFailure[];
96
- invitationsMoved: number;
97
- invitationsDropped: number;
98
- pendingJoinsMoved: number;
99
- }
100
-
101
- /** {@link adoptStrandBundle} refused before any write: the running node's owner key is not an owner of its party. */
102
- export class StrandMoveNotOwnerError extends Error {
103
- constructor(readonly partyId: string) {
104
- super(`Cannot adopt strands into party ${partyId}: this node's owner key is not one of its owners, and every re-seated row is owner-signed`);
105
- this.name = 'StrandMoveNotOwnerError';
106
- }
107
- }
108
-
109
- /** {@link adoptStrandBundle} refused before any write: the bundle was exported from the party the node runs. */
110
- export class StrandMoveSamePartyError extends Error {
111
- constructor(readonly partyId: string) {
112
- super(`Cannot adopt strands into party ${partyId}: the bundle was exported from that same party`);
113
- this.name = 'StrandMoveSamePartyError';
114
- }
115
- }
116
-
117
- /**
118
- * Read, from a running node, everything its party knows about its strands: the party's own
119
- * strands, the strands it joined (party-wide rows and this machine's unpublished records), each
120
- * with its party key, saved routing table and carried addresses; every pending join with its
121
- * outcome; and every invitation still redeemable.
122
- *
123
- * @throws when the node is not started.
124
- */
125
- export async function exportStrandBundle(node: CadreNode): Promise<StrandBundle> {
126
- const database = requireControlDatabase(node, 'export a strand bundle');
127
- const now = Date.now();
128
- const bundle: StrandBundle = {
129
- v: 1,
130
- partyId: node.partyId,
131
- exportedAt: now,
132
- strands: await exportStrands(node, database),
133
- pendingJoins: await database.queryPendingJoins(),
134
- formationInvites: await exportFormationInvites(database, now)
135
- };
136
- log('export(%s): %d strand(s), %d pending join(s), %d invitation(s)',
137
- node.partyId, bundle.strands.length, bundle.pendingJoins.length, bundle.formationInvites.length);
138
- return bundle;
139
- }
140
-
141
- /** One entry per strand id, the party's own first: an id in both `Strand` and `JoinedStrand` exports once, as `own`. */
142
- async function exportStrands(node: CadreNode, database: ControlDatabase): Promise<StrandBundleEntry[]> {
143
- const entries = new Map<string, StrandBundleEntry>();
144
- for (const row of await database.queryStrands()) {
145
- entries.set(row.Id, await exportStrand(node, database, 'own', row));
146
- }
147
- // Publication needs a control connection, so a one-node party's joins are machine-local
148
- // records until it holds one (a relay's or a foreign party's node counts) and `JoinedStrand`
149
- // rows after. Both are read.
150
- const unpublished = (await node.listUnpublishedJoinedStrands()).map(joinedStrandRow);
151
- for (const row of [...await database.queryJoinedStrands(), ...unpublished]) {
152
- if (!entries.has(row.Id)) {
153
- entries.set(row.Id, await exportStrand(node, database, 'joined', row));
154
- }
155
- }
156
- return [...entries.values()];
157
- }
158
-
159
- async function exportStrand(
160
- node: CadreNode,
161
- database: ControlDatabase,
162
- kind: StrandBundleEntry['kind'],
163
- row: StrandRow
164
- ): Promise<StrandBundleEntry> {
165
- const networkState = node.getStrandNetworkStateStore()?.load(row.Id);
166
- return {
167
- kind,
168
- row: { Id: row.Id, Type: row.Type, MemberPrivateKey: row.MemberPrivateKey },
169
- partyKey: await database.queryStrandPartyKey(row.Id),
170
- ...(networkState !== undefined && { networkState }),
171
- carriedAddrs: node.getCarriedStrandAddrs(row.Id)
172
- };
173
- }
174
-
175
- /**
176
- * The invitations still redeemable at export: unexpired, with uses left after the usage
177
- * recorded so far. `FormationUsage` rows are append-only history and stay behind, so the
178
- * adopting party's count restarts at zero against the reduced cap. A spent or expired
179
- * invitation is left out: there is nothing to keep.
180
- */
181
- async function exportFormationInvites(database: ControlDatabase, now: number): Promise<FormationInviteEntry[]> {
182
- const entries: FormationInviteEntry[] = [];
183
- for (const row of await database.queryFormationInvites()) {
184
- if (isExpired(row.expiresAtMs, now)) {
185
- continue;
186
- }
187
- const usesLeft = row.totalUses === null ? null : row.totalUses - await database.countFormationUsage(row.token);
188
- if (usesLeft !== null && usesLeft <= 0) {
189
- continue;
190
- }
191
- entries.push({
192
- token: row.token,
193
- sAppId: row.sAppId,
194
- expiresAtMs: row.expiresAtMs,
195
- usesLeft,
196
- validationUrl: row.validationUrl,
197
- strandId: row.strandId
198
- });
199
- }
200
- return entries;
201
- }
202
-
203
- /**
204
- * Seat `bundle` in the running node's party, every row owner-signed through the node's owner
205
- * signer (`CadreNode.getOwnerSigner`, wired here by `wireOwnKeyIfOwner` when it is not yet),
206
- * in one approval for the whole bundle. Refuses up front, with a typed error and no write, when
207
- * that signer's key is not an owner of the party ({@link StrandMoveNotOwnerError}) or the
208
- * bundle came from this very party ({@link StrandMoveSamePartyError}).
209
- *
210
- * Strands first, then the invitations, then the pending joins. Every write is idempotent (a row
211
- * already present with the same content is skipped and counted as moved), so the same bundle
212
- * can be adopted again after a crash or a transient write failure and finishes what is left.
213
- * One strand's failure does not stop the others: it is reported under `failed` for the retry.
214
- * One transaction over the whole bundle was weighed and declined: the per-row writers already
215
- * carry the stamp, signature and retry policy, and the resumable bundle covers a crash between
216
- * rows.
217
- *
218
- * @throws when the node is not started, beside the two typed refusals.
219
- */
220
- export async function adoptStrandBundle(node: CadreNode, bundle: StrandBundle): Promise<StrandMoveReport> {
221
- const database = requireControlDatabase(node, 'adopt a strand bundle');
222
- if (bundle.partyId === node.partyId) {
223
- throw new StrandMoveSamePartyError(node.partyId);
224
- }
225
- const owner = (await node.wireOwnKeyIfOwner()) ? node.getOwnerSigner() : null;
226
- if (owner === null) {
227
- throw new StrandMoveNotOwnerError(node.partyId);
228
- }
229
- const action = `Move ${bundle.strands.length} strand(s) from the cadre ${bundle.partyId} into this one`;
230
- return await owner.approve({ partyId: node.partyId, action }, (sign) =>
231
- adoptUnderApproval(node, database, bundle, { ownerKey: owner.publicKey, sign }));
232
- }
233
-
234
- /** An open owner approval: the key every row is written under, and the approval's `sign`. */
235
- interface OwnerApproval {
236
- ownerKey: string;
237
- sign: OwnerSign;
238
- }
239
-
240
- /** {@link adoptStrandBundle}'s writes, every one signed inside the one approval `approval`. */
241
- async function adoptUnderApproval(
242
- node: CadreNode,
243
- database: ControlDatabase,
244
- bundle: StrandBundle,
245
- approval: OwnerApproval
246
- ): Promise<StrandMoveReport> {
247
- const report: StrandMoveReport = {
248
- fromPartyId: bundle.partyId,
249
- moved: [],
250
- refused: [],
251
- failed: [],
252
- invitationsMoved: 0,
253
- invitationsDropped: 0,
254
- pendingJoinsMoved: 0
255
- };
256
- for (const entry of bundle.strands) {
257
- await adoptStrand(node, database, approval, entry, report);
258
- }
259
- const settled = settledStrands(report);
260
- const now = Date.now();
261
- for (const invite of bundle.formationInvites) {
262
- await adoptFormationInvite(node, database, approval.sign, invite, settled, report, now);
263
- }
264
- for (const join of bundle.pendingJoins) {
265
- await adoptPendingJoin(database, approval, join, report);
266
- }
267
- log('adopt(%s ← %s): %d moved, %d refused, %d failed; %d invitation(s) moved, %d dropped; %d pending join(s)',
268
- node.partyId, bundle.partyId, report.moved.length, report.refused.length, report.failed.length,
269
- report.invitationsMoved, report.invitationsDropped, report.pendingJoinsMoved);
270
- return report;
271
- }
272
-
273
- /** The strands an adoption has decided on, by outcome, for the invitations bound to them. */
274
- interface SettledStrands {
275
- moved: Set<string>;
276
- failed: Set<string>;
277
- }
278
-
279
- function settledStrands(report: StrandMoveReport): SettledStrands {
280
- return {
281
- moved: new Set(report.moved),
282
- failed: new Set(report.failed.filter((entry) => entry.kind === 'strand').map((entry) => entry.id))
283
- };
284
- }
285
-
286
- /**
287
- * Seat one strand, in the order the adopting node's strand watcher demands. The watcher runs
288
- * on every change to `Strand` and `JoinedStrand` and launches, or offers, a new row at once; a
289
- * closed strand's founder launch resolves the party key and, finding none, mints a fresh one,
290
- * which would found the strand a second time under a stranger's identity. So the party key is
291
- * seated before the row, and the strand's peers (its saved routing table and carried addresses)
292
- * before both, so the launch's cohort seed has somewhere to dial. Every step is
293
- * insert-if-absent.
294
- */
295
- async function adoptStrand(
296
- node: CadreNode,
297
- database: ControlDatabase,
298
- approval: OwnerApproval,
299
- entry: StrandBundleEntry,
300
- report: StrandMoveReport
301
- ): Promise<void> {
302
- const strandId = entry.row.Id;
303
- try {
304
- const live = await readLiveStrand(database, strandId);
305
- const refusal = strandRefusal(entry, live);
306
- if (refusal !== null) {
307
- log('adopt: strand %s refused: %s', strandId, refusal);
308
- report.refused.push({ strandId, reason: refusal });
309
- return;
310
- }
311
- await seatStrandPeers(node, entry);
312
- if (entry.partyKey !== null) {
313
- await node.ensureStrandPartyKey(strandId, entry.partyKey, approval.sign);
314
- }
315
- if (entry.kind === 'own') {
316
- // NOTE: with the party key seated first, a closed strand's founding transaction is refused
317
- // on `StrandPartyKey.Id` and written again without a key: a local refusal, no extra commit.
318
- // If moves of many closed strands get slow, let publishStrand take a known party key.
319
- await node.publishStrand(strandId, entry.row.Type, entry.row.MemberPrivateKey ?? undefined, approval.sign);
320
- } else {
321
- await seatJoinedStrand(database, approval, entry.row, live.joined);
322
- }
323
- report.moved.push(strandId);
324
- } catch (error) {
325
- log('adopt: strand %s (%s) not seated this time; adopt the same bundle again: %o', strandId, entry.kind, error);
326
- report.failed.push({ kind: 'strand', id: strandId, reason: errorText(error) });
327
- }
328
- }
329
-
330
- /** What the adopting party already holds for a strand id. */
331
- interface LiveStrand {
332
- partyKey: string | null;
333
- own: StrandRow | null;
334
- joined: StrandRow | null;
335
- }
336
-
337
- async function readLiveStrand(database: ControlDatabase, strandId: string): Promise<LiveStrand> {
338
- return {
339
- partyKey: await database.queryStrandPartyKey(strandId),
340
- own: await database.queryStrand(strandId),
341
- joined: await database.queryJoinedStrand(strandId)
342
- };
343
- }
344
-
345
- /**
346
- * Why `entry` can never be seated here, or null. A strand this party already participates in
347
- * under its own identity keeps that membership: its `StrandPartyKey` is the key its `Member`
348
- * row was seated under, and the bundle's key is another party's seat. A row for the id of the
349
- * other kind (the party founded what the bundle joined, or joined what the bundle founded), or
350
- * of the same kind with different content, is the same refusal. Decided from a read before any
351
- * write, so a retry reports the refusal again instead of failing on a write; the writes
352
- * re-check (`ensureStrandPartyKey` and `publishStrand` throw on a mismatch), so a row landing
353
- * between the read and the write fails the strand this time and is refused on the retry.
354
- */
355
- function strandRefusal(entry: StrandBundleEntry, live: LiveStrand): string | null {
356
- const strandId = entry.row.Id;
357
- if (live.partyKey !== null && live.partyKey !== entry.partyKey) {
358
- return `this party already holds its own membership identity for strand ${strandId} and keeps that membership`;
359
- }
360
- if (entry.kind === 'own' && live.joined !== null) {
361
- return `this party already participates in strand ${strandId} as a strand it joined and keeps that membership`;
362
- }
363
- if (entry.kind === 'joined' && live.own !== null) {
364
- return `this party already holds strand ${strandId} as its own and keeps that membership`;
365
- }
366
- const same = entry.kind === 'own' ? live.own : live.joined;
367
- if (same !== null && !sameStrandContent(same, entry.row)) {
368
- return `this party already holds strand ${strandId} as ${entry.kind === 'own' ? 'its own' : 'a join'} with different content`;
369
- }
370
- return null;
371
- }
372
-
373
- /**
374
- * The strand's saved routing table and carried addresses, when this node holds none for it: a
375
- * launch here since an earlier attempt may have saved fresher state than the bundle carries.
376
- */
377
- async function seatStrandPeers(node: CadreNode, entry: StrandBundleEntry): Promise<void> {
378
- const strandId = entry.row.Id;
379
- const store = node.getStrandNetworkStateStore();
380
- if (entry.networkState !== undefined && store !== null && store.load(strandId) === undefined) {
381
- await store.save(strandId, entry.networkState);
382
- }
383
- if (entry.carriedAddrs.length > 0 && node.getCarriedStrandAddrs(strandId).length === 0) {
384
- await node.recordCarriedStrandAddrs(strandId, entry.carriedAddrs);
385
- }
386
- }
387
-
388
- /**
389
- * `insertJoinedStrand`, read as done when the identical row is already there: `existing` from
390
- * the refusal read (a retry), or one landing between that read and the insert (a sibling's
391
- * publish; `strandRefusal` has already compared the content of the first, and the second is
392
- * compared here).
393
- */
394
- async function seatJoinedStrand(
395
- database: ControlDatabase,
396
- approval: OwnerApproval,
397
- row: StrandBundleEntry['row'],
398
- existing: StrandRow | null
399
- ): Promise<void> {
400
- if (existing !== null) {
401
- return;
402
- }
403
- try {
404
- await database.insertJoinedStrand(row, approval.ownerKey, approval.sign);
405
- } catch (error) {
406
- if (!isStrandIdConflict(error, 'JoinedStrand')) {
407
- throw error;
408
- }
409
- const landed = await database.queryJoinedStrand(row.Id);
410
- if (landed === null || !sameStrandContent(landed, row)) {
411
- throw error;
412
- }
413
- log('adopt: joined strand %s landed concurrently with identical content; adopted', row.Id);
414
- }
415
- }
416
-
417
- /**
418
- * Copy one invitation the exporting party handed out. Its envelope names the app's machine,
419
- * whose peer id and relay address do not change with the party, so the row here is what keeps
420
- * an envelope already handed out redeemable. Dropped and counted: an invitation with a
421
- * `ValidationUrl` (its sign-offs verify against a `ValidationKey` row, and which keys may
422
- * validate here is this party's owners' decision) and one bound to a strand not seated here,
423
- * whether refused above or no longer held by the exporting party (`unpublishStrand` leaves a
424
- * bound row behind): the formation recorder would refuse every redemption as a missing host.
425
- * Dropped silently: one that expired since the export. One bound to a strand that failed this
426
- * time is left for the retry that seats the strand.
427
- */
428
- async function adoptFormationInvite(
429
- node: CadreNode,
430
- database: ControlDatabase,
431
- sign: OwnerSign,
432
- invite: FormationInviteEntry,
433
- settled: SettledStrands,
434
- report: StrandMoveReport,
435
- now: number
436
- ): Promise<void> {
437
- if (invite.strandId !== null && settled.failed.has(invite.strandId)) {
438
- return;
439
- }
440
- const hostMissing = invite.strandId !== null && !settled.moved.has(invite.strandId);
441
- if (invite.validationUrl !== null || hostMissing) {
442
- report.invitationsDropped += 1;
443
- return;
444
- }
445
- if (isExpired(invite.expiresAtMs, now)) {
446
- return;
447
- }
448
- try {
449
- if (await database.queryFormationInvite(invite.token) === null) {
450
- await node.publishFormationInvite(invite.token, invite.sAppId, {
451
- expiresAtMs: invite.expiresAtMs ?? undefined,
452
- totalUses: invite.usesLeft ?? undefined,
453
- strandId: invite.strandId ?? undefined
454
- }, sign);
455
- }
456
- report.invitationsMoved += 1;
457
- } catch (error) {
458
- log('adopt: invitation for sApp %s not seated this time; adopt the same bundle again: %o', invite.sAppId, error);
459
- report.failed.push({ kind: 'invitation', id: pendingJoinId(invite.token), reason: errorText(error) });
460
- }
461
- }
462
-
463
- /**
464
- * Re-seat one join the exporting party asked for, with its outcome, under a fresh request
465
- * stamp. A `joined` outcome's membership invitation matters: for a closed strand it is the seat
466
- * the party's membership reconciler has not redeemed yet, and this node's retry loop re-stages
467
- * it from the moved row at its next read. A `failed` outcome is history for the user to
468
- * dismiss; the seven-day removal cleans it up.
469
- *
470
- * A request this party already holds for the invitation is read as done, whether an earlier
471
- * adoption seated it or the user asked for the same invitation from here. Its outcome is written
472
- * only when the live request is still pending and is this bundle's own (every request column
473
- * equal), which closes the crash window between the request insert and its outcome insert
474
- * without touching a request this party made on its own. A `joined` outcome whose strand was
475
- * refused above moves too: its invitation is staged like any other, and the reconciler, finding
476
- * the party's member row already seated, burns it unspent or drops it dead.
477
- *
478
- * NOTE: if party-private app tables land in the control database
479
- * (tickets/blocked/decide-party-private-labels-and-app-state.md), they must move with the
480
- * strands, and this is the site: one more per-row idempotent write beside the join.
481
- */
482
- async function adoptPendingJoin(
483
- database: ControlDatabase,
484
- approval: OwnerApproval,
485
- join: PendingJoin,
486
- report: StrandMoveReport
487
- ): Promise<void> {
488
- const { StampId: _stampId, outcome, ...request } = join;
489
- try {
490
- const live = await seatJoinRequest(database, approval, request);
491
- if (live !== null && outcome !== null && live.outcome === null) {
492
- await database.recordJoinOutcome(live, outcome, approval.ownerKey, approval.sign);
493
- }
494
- report.pendingJoinsMoved += 1;
495
- } catch (error) {
496
- log('adopt: pending join %s not seated this time; adopt the same bundle again: %o', join.Id, error);
497
- report.failed.push({ kind: 'pending-join', id: join.Id, reason: errorText(error) });
498
- }
499
- }
500
-
501
- /**
502
- * The live request for `request` after its insert: the row just written, the identical row
503
- * already there, or null when the party holds a different request for the invitation (its
504
- * own ask, left alone) or a dismissed one whose retired stamp is still held until the reap
505
- * pass (the party chose not to have it).
506
- */
507
- async function seatJoinRequest(database: ControlDatabase, approval: OwnerApproval, request: JoinRequestFields): Promise<PendingJoin | null> {
508
- try {
509
- return await database.insertJoinRequest(request, approval.ownerKey, approval.sign);
510
- } catch (error) {
511
- if (!isPendingJoinConflict(error)) {
512
- throw error;
513
- }
514
- const existing = await database.queryPendingJoin(request.Id);
515
- return existing !== null && sameRequest(existing, request) ? existing : null;
516
- }
517
- }
518
-
519
- function sameRequest(live: PendingJoin, request: JoinRequestFields): boolean {
520
- return live.Invitation === request.Invitation
521
- && live.Disclosure === request.Disclosure
522
- && live.RequestedAt === request.RequestedAt
523
- && live.ExpiresAt === request.ExpiresAt;
524
- }
525
-
526
- /** What a party already holds of strands and joins, read from its running node. */
527
- export interface StrandHoldings {
528
- strandIds: ReadonlySet<string>;
529
- pendingJoinIds: ReadonlySet<string>;
530
- }
531
-
532
- /**
533
- * Every strand id the node's party holds, of either kind (`Strand`, `JoinedStrand` and this
534
- * machine's unpublished joins), and every pending join id it holds, whatever the outcome.
535
- *
536
- * @throws when the node is not started.
537
- */
538
- export async function readStrandHoldings(node: CadreNode): Promise<StrandHoldings> {
539
- const database = requireControlDatabase(node, 'read its strand holdings');
540
- const strands = [
541
- ...await database.queryStrands(),
542
- ...await database.queryJoinedStrands(),
543
- ...await node.listUnpublishedJoinedStrands()
544
- ];
545
- return {
546
- strandIds: new Set(strands.map((row) => row.Id)),
547
- pendingJoinIds: new Set((await database.queryPendingJoins()).map((join) => join.Id))
548
- };
549
- }
550
-
551
- /**
552
- * What of `bundle` a party with `holdings` lacks, so the exporting party can be dissolved only
553
- * when this is empty. A strand counts as held under any kind: one the adoption refused is in
554
- * the holdings (that is why it was refused), so its data stays reachable and only the
555
- * exporting party's seat in it is lost. A pending join counts only while open at `nowMs`: a
556
- * `joined` one's strand is covered by the strand check, a `failed` one is history, and an
557
- * expired one can never be attempted. Formation invitations are not compared: the exporting
558
- * node never runs again once dissolved, so one the adoption dropped was unredeemable from then.
559
- */
560
- export function unheldBundleContent(bundle: StrandBundle, holdings: StrandHoldings, nowMs: number): {
561
- strandIds: string[];
562
- pendingJoinIds: string[];
563
- } {
564
- return {
565
- strandIds: bundle.strands.map((entry) => entry.row.Id).filter((strandId) => !holdings.strandIds.has(strandId)),
566
- pendingJoinIds: bundle.pendingJoins
567
- .filter((join) => isOpenJoin(join, nowMs) && !holdings.pendingJoinIds.has(join.Id))
568
- .map((join) => join.Id)
569
- };
570
- }
571
-
572
- /** No outcome yet, and before `ExpiresAt`: the pending-join runner attempts nothing at or after it. */
573
- function isOpenJoin(join: PendingJoin, nowMs: number): boolean {
574
- return join.outcome === null && nowMs < join.ExpiresAt;
575
- }
576
-
577
- /** Content only: `Type` and the read secret. The founder columns are provenance, and a moved strand's change. */
578
- function sameStrandContent(live: StrandRow, desired: StrandBundleEntry['row']): boolean {
579
- return live.Type === desired.Type && (live.MemberPrivateKey ?? null) === (desired.MemberPrivateKey ?? null);
580
- }
581
-
582
- /** The comparison `hasOutstandingFormationInvite` makes, so an invitation the responder would refuse is never copied. */
583
- function isExpired(expiresAtMs: number | null, now: number): boolean {
584
- return expiresAtMs !== null && expiresAtMs <= now;
585
- }
586
-
587
- function requireControlDatabase(node: CadreNode, action: string): ControlDatabase {
588
- const database = node.getControlDatabase();
589
- if (database === null) {
590
- throw new Error(`CadreNode must be started before it can ${action}`);
591
- }
592
- return database;
593
- }
594
-
595
- function errorText(error: unknown): string {
596
- return error instanceof Error ? error.message : String(error);
597
- }
1
+ /**
2
+ * Moving a party's strands into another party of the same owner.
3
+ *
4
+ * A party's participation in a strand is control-database state: its `Strand` row (a strand
5
+ * it founded) or `JoinedStrand` row (one it joined), carrying the strand's shared read secret,
6
+ * and its `StrandPartyKey` row, the membership identity whose public half seats the party's
7
+ * `Member` / `Manager` rows in the strand database. Nothing in the strand database names a
8
+ * party, so a strand follows those rows: re-seated in another party under the same member key,
9
+ * on the same peer, the strand's other members see the same member on the same peer and
10
+ * nothing on the strand side changes.
11
+ *
12
+ * The case this serves is a phone app that founded a one-node cadre of its own (party B) and
13
+ * then joins the user's main cadre (party A) by switching its one node across
14
+ * (docs/architecture.md → "An app joins an existing cadre" → "Moving the app's strands"). Two
15
+ * nodes never run at once, so the move has two ends: {@link exportStrandBundle} reads everything
16
+ * B's node knows about its strands while it still runs, the embedder carries the bundle across
17
+ * the switch as data, and {@link adoptStrandBundle} seats it on A's node once the app's key is
18
+ * an owner there. Nothing is deleted in B; dissolving it is the embedder's later step, once
19
+ * {@link unheldBundleContent} finds nothing of B's export that A's {@link readStrandHoldings} lacks.
20
+ *
21
+ * Built over `CadreNode`'s public surface, so `cadre-node.ts` does not grow by the feature.
22
+ */
23
+ import debug from 'debug';
24
+ import type { PersistedNetworkState } from '@optimystic/db-p2p';
25
+ import type { CadreNode } from './cadre-node.js';
26
+ import type { OwnerSign } from './owner-signer.js';
27
+ import {
28
+ isPendingJoinConflict,
29
+ isStrandIdConflict,
30
+ pendingJoinId,
31
+ type ControlDatabase,
32
+ type JoinRequestFields
33
+ } from './control-database.js';
34
+ import { joinedStrandRow } from './joined-strand-store.js';
35
+ import type { PendingJoin, StrandRow } from './types.js';
36
+ import { describeThrown } from './describe-thrown.js';
37
+
38
+ const log = debug('sereus:cadre:strand-move');
39
+
40
+ /**
41
+ * Everything one party knows about its strands, as read from a running node of that party.
42
+ * Carries secrets: every read secret, every party key and every bearer invitation. JSON-safe,
43
+ * so an embedder can keep it in its secure store across a node switch.
44
+ */
45
+ export interface StrandBundle {
46
+ v: 1;
47
+ /** The exporting party. */
48
+ partyId: string;
49
+ /** Epoch ms. */
50
+ exportedAt: number;
51
+ strands: StrandBundleEntry[];
52
+ /** Every row `queryPendingJoins` returned, outcome included. */
53
+ pendingJoins: PendingJoin[];
54
+ /** The invitations still redeemable at export. */
55
+ formationInvites: FormationInviteEntry[];
56
+ }
57
+
58
+ export interface StrandBundleEntry {
59
+ /** A `Strand` row, or a `JoinedStrand` row / machine-local unpublished join. */
60
+ kind: 'own' | 'joined';
61
+ row: Pick<StrandRow, 'Id' | 'Type' | 'MemberPrivateKey'>;
62
+ /** `StrandPartyKey.PrivateKey` when the party holds one. */
63
+ partyKey: string | null;
64
+ /** The strand's saved routing table, opaque here; absent when the node held none. */
65
+ networkState?: PersistedNetworkState;
66
+ /** The addresses the strand's formation carried, in memory on the exporting node. */
67
+ carriedAddrs: string[];
68
+ }
69
+
70
+ export interface FormationInviteEntry {
71
+ token: string;
72
+ sAppId: string;
73
+ expiresAtMs: number | null;
74
+ /** `TotalUses` minus the usage recorded so far; null is unlimited. */
75
+ usesLeft: number | null;
76
+ validationUrl: string | null;
77
+ /** A bound invitation's host strand. */
78
+ strandId: string | null;
79
+ }
80
+
81
+ /** One item an adoption could not seat this time; retrying the same bundle will. */
82
+ export interface StrandMoveFailure {
83
+ kind: 'strand' | 'invitation' | 'pending-join';
84
+ /** The strand id, the join request id, or the id a join request for the invitation would carry (never the bearer token). */
85
+ id: string;
86
+ reason: string;
87
+ }
88
+
89
+ export interface StrandMoveReport {
90
+ fromPartyId: string;
91
+ /** Strand ids now seated in this party, those already there included. */
92
+ moved: string[];
93
+ /** Permanent: retrying will not help. */
94
+ refused: Array<{ strandId: string; reason: string }>;
95
+ /** Transient: adopt the same bundle again. */
96
+ failed: StrandMoveFailure[];
97
+ invitationsMoved: number;
98
+ invitationsDropped: number;
99
+ pendingJoinsMoved: number;
100
+ }
101
+
102
+ /** {@link adoptStrandBundle} refused before any write: the running node's owner key is not an owner of its party. */
103
+ export class StrandMoveNotOwnerError extends Error {
104
+ constructor(readonly partyId: string) {
105
+ super(`Cannot adopt strands into party ${partyId}: this node's owner key is not one of its owners, and every re-seated row is owner-signed`);
106
+ this.name = 'StrandMoveNotOwnerError';
107
+ }
108
+ }
109
+
110
+ /** {@link adoptStrandBundle} refused before any write: the bundle was exported from the party the node runs. */
111
+ export class StrandMoveSamePartyError extends Error {
112
+ constructor(readonly partyId: string) {
113
+ super(`Cannot adopt strands into party ${partyId}: the bundle was exported from that same party`);
114
+ this.name = 'StrandMoveSamePartyError';
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Read, from a running node, everything its party knows about its strands: the party's own
120
+ * strands, the strands it joined (party-wide rows and this machine's unpublished records), each
121
+ * with its party key, saved routing table and carried addresses; every pending join with its
122
+ * outcome; and every invitation still redeemable.
123
+ *
124
+ * @throws when the node is not started.
125
+ */
126
+ export async function exportStrandBundle(node: CadreNode): Promise<StrandBundle> {
127
+ const database = requireControlDatabase(node, 'export a strand bundle');
128
+ const now = Date.now();
129
+ const bundle: StrandBundle = {
130
+ v: 1,
131
+ partyId: node.partyId,
132
+ exportedAt: now,
133
+ strands: await exportStrands(node, database),
134
+ pendingJoins: await database.queryPendingJoins(),
135
+ formationInvites: await exportFormationInvites(database, now)
136
+ };
137
+ log('export(%s): %d strand(s), %d pending join(s), %d invitation(s)',
138
+ node.partyId, bundle.strands.length, bundle.pendingJoins.length, bundle.formationInvites.length);
139
+ return bundle;
140
+ }
141
+
142
+ /** One entry per strand id, the party's own first: an id in both `Strand` and `JoinedStrand` exports once, as `own`. */
143
+ async function exportStrands(node: CadreNode, database: ControlDatabase): Promise<StrandBundleEntry[]> {
144
+ const entries = new Map<string, StrandBundleEntry>();
145
+ for (const row of await database.queryStrands()) {
146
+ entries.set(row.Id, await exportStrand(node, database, 'own', row));
147
+ }
148
+ // Publication needs a control connection, so a one-node party's joins are machine-local
149
+ // records until it holds one (a relay's or a foreign party's node counts) and `JoinedStrand`
150
+ // rows after. Both are read.
151
+ const unpublished = (await node.listUnpublishedJoinedStrands()).map(joinedStrandRow);
152
+ for (const row of [...await database.queryJoinedStrands(), ...unpublished]) {
153
+ if (!entries.has(row.Id)) {
154
+ entries.set(row.Id, await exportStrand(node, database, 'joined', row));
155
+ }
156
+ }
157
+ return [...entries.values()];
158
+ }
159
+
160
+ async function exportStrand(
161
+ node: CadreNode,
162
+ database: ControlDatabase,
163
+ kind: StrandBundleEntry['kind'],
164
+ row: StrandRow
165
+ ): Promise<StrandBundleEntry> {
166
+ const networkState = node.getStrandNetworkStateStore()?.load(row.Id);
167
+ return {
168
+ kind,
169
+ row: { Id: row.Id, Type: row.Type, MemberPrivateKey: row.MemberPrivateKey },
170
+ partyKey: await database.queryStrandPartyKey(row.Id),
171
+ ...(networkState !== undefined && { networkState }),
172
+ carriedAddrs: node.getCarriedStrandAddrs(row.Id)
173
+ };
174
+ }
175
+
176
+ /**
177
+ * The invitations still redeemable at export: unexpired, with uses left after the usage
178
+ * recorded so far. `FormationUsage` rows are append-only history and stay behind, so the
179
+ * adopting party's count restarts at zero against the reduced cap. A spent or expired
180
+ * invitation is left out: there is nothing to keep.
181
+ */
182
+ async function exportFormationInvites(database: ControlDatabase, now: number): Promise<FormationInviteEntry[]> {
183
+ const entries: FormationInviteEntry[] = [];
184
+ for (const row of await database.queryFormationInvites()) {
185
+ if (isExpired(row.expiresAtMs, now)) {
186
+ continue;
187
+ }
188
+ const usesLeft = row.totalUses === null ? null : row.totalUses - await database.countFormationUsage(row.token);
189
+ if (usesLeft !== null && usesLeft <= 0) {
190
+ continue;
191
+ }
192
+ entries.push({
193
+ token: row.token,
194
+ sAppId: row.sAppId,
195
+ expiresAtMs: row.expiresAtMs,
196
+ usesLeft,
197
+ validationUrl: row.validationUrl,
198
+ strandId: row.strandId
199
+ });
200
+ }
201
+ return entries;
202
+ }
203
+
204
+ /**
205
+ * Seat `bundle` in the running node's party, every row owner-signed through the node's owner
206
+ * signer (`CadreNode.getOwnerSigner`, wired here by `wireOwnKeyIfOwner` when it is not yet),
207
+ * in one approval for the whole bundle. Refuses up front, with a typed error and no write, when
208
+ * that signer's key is not an owner of the party ({@link StrandMoveNotOwnerError}) or the
209
+ * bundle came from this very party ({@link StrandMoveSamePartyError}).
210
+ *
211
+ * Strands first, then the invitations, then the pending joins. Every write is idempotent (a row
212
+ * already present with the same content is skipped and counted as moved), so the same bundle
213
+ * can be adopted again after a crash or a transient write failure and finishes what is left.
214
+ * One strand's failure does not stop the others: it is reported under `failed` for the retry.
215
+ * One transaction over the whole bundle was weighed and declined: the per-row writers already
216
+ * carry the stamp, signature and retry policy, and the resumable bundle covers a crash between
217
+ * rows.
218
+ *
219
+ * @throws when the node is not started, beside the two typed refusals.
220
+ */
221
+ export async function adoptStrandBundle(node: CadreNode, bundle: StrandBundle): Promise<StrandMoveReport> {
222
+ const database = requireControlDatabase(node, 'adopt a strand bundle');
223
+ if (bundle.partyId === node.partyId) {
224
+ throw new StrandMoveSamePartyError(node.partyId);
225
+ }
226
+ const owner = (await node.wireOwnKeyIfOwner()) ? node.getOwnerSigner() : null;
227
+ if (owner === null) {
228
+ throw new StrandMoveNotOwnerError(node.partyId);
229
+ }
230
+ const action = `Move ${bundle.strands.length} strand(s) from the cadre ${bundle.partyId} into this one`;
231
+ return await owner.approve({ partyId: node.partyId, action }, (sign) =>
232
+ adoptUnderApproval(node, database, bundle, { ownerKey: owner.publicKey, sign }));
233
+ }
234
+
235
+ /** An open owner approval: the key every row is written under, and the approval's `sign`. */
236
+ interface OwnerApproval {
237
+ ownerKey: string;
238
+ sign: OwnerSign;
239
+ }
240
+
241
+ /** {@link adoptStrandBundle}'s writes, every one signed inside the one approval `approval`. */
242
+ async function adoptUnderApproval(
243
+ node: CadreNode,
244
+ database: ControlDatabase,
245
+ bundle: StrandBundle,
246
+ approval: OwnerApproval
247
+ ): Promise<StrandMoveReport> {
248
+ const report: StrandMoveReport = {
249
+ fromPartyId: bundle.partyId,
250
+ moved: [],
251
+ refused: [],
252
+ failed: [],
253
+ invitationsMoved: 0,
254
+ invitationsDropped: 0,
255
+ pendingJoinsMoved: 0
256
+ };
257
+ for (const entry of bundle.strands) {
258
+ await adoptStrand(node, database, approval, entry, report);
259
+ }
260
+ const settled = settledStrands(report);
261
+ const now = Date.now();
262
+ for (const invite of bundle.formationInvites) {
263
+ await adoptFormationInvite(node, database, approval.sign, invite, settled, report, now);
264
+ }
265
+ for (const join of bundle.pendingJoins) {
266
+ await adoptPendingJoin(database, approval, join, report);
267
+ }
268
+ log('adopt(%s ← %s): %d moved, %d refused, %d failed; %d invitation(s) moved, %d dropped; %d pending join(s)',
269
+ node.partyId, bundle.partyId, report.moved.length, report.refused.length, report.failed.length,
270
+ report.invitationsMoved, report.invitationsDropped, report.pendingJoinsMoved);
271
+ return report;
272
+ }
273
+
274
+ /** The strands an adoption has decided on, by outcome, for the invitations bound to them. */
275
+ interface SettledStrands {
276
+ moved: Set<string>;
277
+ failed: Set<string>;
278
+ }
279
+
280
+ function settledStrands(report: StrandMoveReport): SettledStrands {
281
+ return {
282
+ moved: new Set(report.moved),
283
+ failed: new Set(report.failed.filter((entry) => entry.kind === 'strand').map((entry) => entry.id))
284
+ };
285
+ }
286
+
287
+ /**
288
+ * Seat one strand, in the order the adopting node's strand watcher demands. The watcher runs
289
+ * on every change to `Strand` and `JoinedStrand` and launches, or offers, a new row at once; a
290
+ * closed strand's founder launch resolves the party key and, finding none, mints a fresh one,
291
+ * which would found the strand a second time under a stranger's identity. So the party key is
292
+ * seated before the row, and the strand's peers (its saved routing table and carried addresses)
293
+ * before both, so the launch's cohort seed has somewhere to dial. Every step is
294
+ * insert-if-absent.
295
+ */
296
+ async function adoptStrand(
297
+ node: CadreNode,
298
+ database: ControlDatabase,
299
+ approval: OwnerApproval,
300
+ entry: StrandBundleEntry,
301
+ report: StrandMoveReport
302
+ ): Promise<void> {
303
+ const strandId = entry.row.Id;
304
+ try {
305
+ const live = await readLiveStrand(database, strandId);
306
+ const refusal = strandRefusal(entry, live);
307
+ if (refusal !== null) {
308
+ log('adopt: strand %s refused: %s', strandId, refusal);
309
+ report.refused.push({ strandId, reason: refusal });
310
+ return;
311
+ }
312
+ await seatStrandPeers(node, entry);
313
+ if (entry.partyKey !== null) {
314
+ await node.ensureStrandPartyKey(strandId, entry.partyKey, approval.sign);
315
+ }
316
+ if (entry.kind === 'own') {
317
+ // NOTE: with the party key seated first, a closed strand's founding transaction is refused
318
+ // on `StrandPartyKey.Id` and written again without a key: a local refusal, no extra commit.
319
+ // If moves of many closed strands get slow, let publishStrand take a known party key.
320
+ await node.publishStrand(strandId, entry.row.Type, entry.row.MemberPrivateKey ?? undefined, approval.sign);
321
+ } else {
322
+ await seatJoinedStrand(database, approval, entry.row, live.joined);
323
+ }
324
+ report.moved.push(strandId);
325
+ } catch (error) {
326
+ log('adopt: strand %s (%s) not seated this time; adopt the same bundle again: %o', strandId, entry.kind, error);
327
+ report.failed.push({ kind: 'strand', id: strandId, reason: describeThrown(error) });
328
+ }
329
+ }
330
+
331
+ /** What the adopting party already holds for a strand id. */
332
+ interface LiveStrand {
333
+ partyKey: string | null;
334
+ own: StrandRow | null;
335
+ joined: StrandRow | null;
336
+ }
337
+
338
+ async function readLiveStrand(database: ControlDatabase, strandId: string): Promise<LiveStrand> {
339
+ return {
340
+ partyKey: await database.queryStrandPartyKey(strandId),
341
+ own: await database.queryStrand(strandId),
342
+ joined: await database.queryJoinedStrand(strandId)
343
+ };
344
+ }
345
+
346
+ /**
347
+ * Why `entry` can never be seated here, or null. A strand this party already participates in
348
+ * under its own identity keeps that membership: its `StrandPartyKey` is the key its `Member`
349
+ * row was seated under, and the bundle's key is another party's seat. A row for the id of the
350
+ * other kind (the party founded what the bundle joined, or joined what the bundle founded), or
351
+ * of the same kind with different content, is the same refusal. Decided from a read before any
352
+ * write, so a retry reports the refusal again instead of failing on a write; the writes
353
+ * re-check (`ensureStrandPartyKey` and `publishStrand` throw on a mismatch), so a row landing
354
+ * between the read and the write fails the strand this time and is refused on the retry.
355
+ */
356
+ function strandRefusal(entry: StrandBundleEntry, live: LiveStrand): string | null {
357
+ const strandId = entry.row.Id;
358
+ if (live.partyKey !== null && live.partyKey !== entry.partyKey) {
359
+ return `this party already holds its own membership identity for strand ${strandId} and keeps that membership`;
360
+ }
361
+ if (entry.kind === 'own' && live.joined !== null) {
362
+ return `this party already participates in strand ${strandId} as a strand it joined and keeps that membership`;
363
+ }
364
+ if (entry.kind === 'joined' && live.own !== null) {
365
+ return `this party already holds strand ${strandId} as its own and keeps that membership`;
366
+ }
367
+ const same = entry.kind === 'own' ? live.own : live.joined;
368
+ if (same !== null && !sameStrandContent(same, entry.row)) {
369
+ return `this party already holds strand ${strandId} as ${entry.kind === 'own' ? 'its own' : 'a join'} with different content`;
370
+ }
371
+ return null;
372
+ }
373
+
374
+ /**
375
+ * The strand's saved routing table and carried addresses, when this node holds none for it: a
376
+ * launch here since an earlier attempt may have saved fresher state than the bundle carries.
377
+ */
378
+ async function seatStrandPeers(node: CadreNode, entry: StrandBundleEntry): Promise<void> {
379
+ const strandId = entry.row.Id;
380
+ const store = node.getStrandNetworkStateStore();
381
+ if (entry.networkState !== undefined && store !== null && store.load(strandId) === undefined) {
382
+ await store.save(strandId, entry.networkState);
383
+ }
384
+ if (entry.carriedAddrs.length > 0 && node.getCarriedStrandAddrs(strandId).length === 0) {
385
+ await node.recordCarriedStrandAddrs(strandId, entry.carriedAddrs);
386
+ }
387
+ }
388
+
389
+ /**
390
+ * `insertJoinedStrand`, read as done when the identical row is already there: `existing` from
391
+ * the refusal read (a retry), or one landing between that read and the insert (a sibling's
392
+ * publish; `strandRefusal` has already compared the content of the first, and the second is
393
+ * compared here).
394
+ */
395
+ async function seatJoinedStrand(
396
+ database: ControlDatabase,
397
+ approval: OwnerApproval,
398
+ row: StrandBundleEntry['row'],
399
+ existing: StrandRow | null
400
+ ): Promise<void> {
401
+ if (existing !== null) {
402
+ return;
403
+ }
404
+ try {
405
+ await database.insertJoinedStrand(row, approval.ownerKey, approval.sign);
406
+ } catch (error) {
407
+ if (!isStrandIdConflict(error, 'JoinedStrand')) {
408
+ throw error;
409
+ }
410
+ const landed = await database.queryJoinedStrand(row.Id);
411
+ if (landed === null || !sameStrandContent(landed, row)) {
412
+ throw error;
413
+ }
414
+ log('adopt: joined strand %s landed concurrently with identical content; adopted', row.Id);
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Copy one invitation the exporting party handed out. Its envelope names the app's machine,
420
+ * whose peer id and relay address do not change with the party, so the row here is what keeps
421
+ * an envelope already handed out redeemable. Dropped and counted: an invitation with a
422
+ * `ValidationUrl` (its sign-offs verify against a `ValidationKey` row, and which keys may
423
+ * validate here is this party's owners' decision) and one bound to a strand not seated here,
424
+ * whether refused above or no longer held by the exporting party (`unpublishStrand` leaves a
425
+ * bound row behind): the formation recorder would refuse every redemption as a missing host.
426
+ * Dropped silently: one that expired since the export. One bound to a strand that failed this
427
+ * time is left for the retry that seats the strand.
428
+ */
429
+ async function adoptFormationInvite(
430
+ node: CadreNode,
431
+ database: ControlDatabase,
432
+ sign: OwnerSign,
433
+ invite: FormationInviteEntry,
434
+ settled: SettledStrands,
435
+ report: StrandMoveReport,
436
+ now: number
437
+ ): Promise<void> {
438
+ if (invite.strandId !== null && settled.failed.has(invite.strandId)) {
439
+ return;
440
+ }
441
+ const hostMissing = invite.strandId !== null && !settled.moved.has(invite.strandId);
442
+ if (invite.validationUrl !== null || hostMissing) {
443
+ report.invitationsDropped += 1;
444
+ return;
445
+ }
446
+ if (isExpired(invite.expiresAtMs, now)) {
447
+ return;
448
+ }
449
+ try {
450
+ if (await database.queryFormationInvite(invite.token) === null) {
451
+ await node.publishFormationInvite(invite.token, invite.sAppId, {
452
+ expiresAtMs: invite.expiresAtMs ?? undefined,
453
+ totalUses: invite.usesLeft ?? undefined,
454
+ strandId: invite.strandId ?? undefined
455
+ }, sign);
456
+ }
457
+ report.invitationsMoved += 1;
458
+ } catch (error) {
459
+ log('adopt: invitation for sApp %s not seated this time; adopt the same bundle again: %o', invite.sAppId, error);
460
+ report.failed.push({ kind: 'invitation', id: pendingJoinId(invite.token), reason: describeThrown(error) });
461
+ }
462
+ }
463
+
464
+ /**
465
+ * Re-seat one join the exporting party asked for, with its outcome, under a fresh request
466
+ * stamp. A `joined` outcome's membership invitation matters: for a closed strand it is the seat
467
+ * the party's membership reconciler has not redeemed yet, and this node's retry loop re-stages
468
+ * it from the moved row at its next read. A `failed` outcome is history for the user to
469
+ * dismiss; the seven-day removal cleans it up.
470
+ *
471
+ * A request this party already holds for the invitation is read as done, whether an earlier
472
+ * adoption seated it or the user asked for the same invitation from here. Its outcome is written
473
+ * only when the live request is still pending and is this bundle's own (every request column
474
+ * equal), which closes the crash window between the request insert and its outcome insert
475
+ * without touching a request this party made on its own. A `joined` outcome whose strand was
476
+ * refused above moves too: its invitation is staged like any other, and the reconciler, finding
477
+ * the party's member row already seated, burns it unspent or drops it dead.
478
+ *
479
+ * NOTE: if party-private app tables land in the control database
480
+ * (tickets/blocked/decide-party-private-labels-and-app-state.md), they must move with the
481
+ * strands, and this is the site: one more per-row idempotent write beside the join.
482
+ */
483
+ async function adoptPendingJoin(
484
+ database: ControlDatabase,
485
+ approval: OwnerApproval,
486
+ join: PendingJoin,
487
+ report: StrandMoveReport
488
+ ): Promise<void> {
489
+ const { StampId: _stampId, outcome, ...request } = join;
490
+ try {
491
+ const live = await seatJoinRequest(database, approval, request);
492
+ if (live !== null && outcome !== null && live.outcome === null) {
493
+ await database.recordJoinOutcome(live, outcome, approval.ownerKey, approval.sign);
494
+ }
495
+ report.pendingJoinsMoved += 1;
496
+ } catch (error) {
497
+ log('adopt: pending join %s not seated this time; adopt the same bundle again: %o', join.Id, error);
498
+ report.failed.push({ kind: 'pending-join', id: join.Id, reason: describeThrown(error) });
499
+ }
500
+ }
501
+
502
+ /**
503
+ * The live request for `request` after its insert: the row just written, the identical row
504
+ * already there, or null when the party holds a different request for the invitation (its
505
+ * own ask, left alone) or a dismissed one whose retired stamp is still held until the reap
506
+ * pass (the party chose not to have it).
507
+ */
508
+ async function seatJoinRequest(database: ControlDatabase, approval: OwnerApproval, request: JoinRequestFields): Promise<PendingJoin | null> {
509
+ try {
510
+ return await database.insertJoinRequest(request, approval.ownerKey, approval.sign);
511
+ } catch (error) {
512
+ if (!isPendingJoinConflict(error)) {
513
+ throw error;
514
+ }
515
+ const existing = await database.queryPendingJoin(request.Id);
516
+ return existing !== null && sameRequest(existing, request) ? existing : null;
517
+ }
518
+ }
519
+
520
+ function sameRequest(live: PendingJoin, request: JoinRequestFields): boolean {
521
+ return live.Invitation === request.Invitation
522
+ && live.Disclosure === request.Disclosure
523
+ && live.RequestedAt === request.RequestedAt
524
+ && live.ExpiresAt === request.ExpiresAt;
525
+ }
526
+
527
+ /** What a party already holds of strands and joins, read from its running node. */
528
+ export interface StrandHoldings {
529
+ strandIds: ReadonlySet<string>;
530
+ pendingJoinIds: ReadonlySet<string>;
531
+ }
532
+
533
+ /**
534
+ * Every strand id the node's party holds, of either kind (`Strand`, `JoinedStrand` and this
535
+ * machine's unpublished joins), and every pending join id it holds, whatever the outcome.
536
+ *
537
+ * @throws when the node is not started.
538
+ */
539
+ export async function readStrandHoldings(node: CadreNode): Promise<StrandHoldings> {
540
+ const database = requireControlDatabase(node, 'read its strand holdings');
541
+ const strands = [
542
+ ...await database.queryStrands(),
543
+ ...await database.queryJoinedStrands(),
544
+ ...await node.listUnpublishedJoinedStrands()
545
+ ];
546
+ return {
547
+ strandIds: new Set(strands.map((row) => row.Id)),
548
+ pendingJoinIds: new Set((await database.queryPendingJoins()).map((join) => join.Id))
549
+ };
550
+ }
551
+
552
+ /**
553
+ * What of `bundle` a party with `holdings` lacks, so the exporting party can be dissolved only
554
+ * when this is empty. A strand counts as held under any kind: one the adoption refused is in
555
+ * the holdings (that is why it was refused), so its data stays reachable and only the
556
+ * exporting party's seat in it is lost. A pending join counts only while open at `nowMs`: a
557
+ * `joined` one's strand is covered by the strand check, a `failed` one is history, and an
558
+ * expired one can never be attempted. Formation invitations are not compared: the exporting
559
+ * node never runs again once dissolved, so one the adoption dropped was unredeemable from then.
560
+ */
561
+ export function unheldBundleContent(bundle: StrandBundle, holdings: StrandHoldings, nowMs: number): {
562
+ strandIds: string[];
563
+ pendingJoinIds: string[];
564
+ } {
565
+ return {
566
+ strandIds: bundle.strands.map((entry) => entry.row.Id).filter((strandId) => !holdings.strandIds.has(strandId)),
567
+ pendingJoinIds: bundle.pendingJoins
568
+ .filter((join) => isOpenJoin(join, nowMs) && !holdings.pendingJoinIds.has(join.Id))
569
+ .map((join) => join.Id)
570
+ };
571
+ }
572
+
573
+ /** No outcome yet, and before `ExpiresAt`: the pending-join runner attempts nothing at or after it. */
574
+ function isOpenJoin(join: PendingJoin, nowMs: number): boolean {
575
+ return join.outcome === null && nowMs < join.ExpiresAt;
576
+ }
577
+
578
+ /** Content only: `Type` and the read secret. The founder columns are provenance, and a moved strand's change. */
579
+ function sameStrandContent(live: StrandRow, desired: StrandBundleEntry['row']): boolean {
580
+ return live.Type === desired.Type && (live.MemberPrivateKey ?? null) === (desired.MemberPrivateKey ?? null);
581
+ }
582
+
583
+ /** The comparison `hasOutstandingFormationInvite` makes, so an invitation the responder would refuse is never copied. */
584
+ function isExpired(expiresAtMs: number | null, now: number): boolean {
585
+ return expiresAtMs !== null && expiresAtMs <= now;
586
+ }
587
+
588
+ function requireControlDatabase(node: CadreNode, action: string): ControlDatabase {
589
+ const database = node.getControlDatabase();
590
+ if (database === null) {
591
+ throw new Error(`CadreNode must be started before it can ${action}`);
592
+ }
593
+ return database;
594
+ }