@serfab/cadre-core 1.19.1 → 1.21.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 (103) hide show
  1. package/dist/cadre-node.d.ts +53 -14
  2. package/dist/cadre-node.js +97 -30
  3. package/dist/cadre-node.js.map +1 -1
  4. package/dist/control-database.d.ts +2 -1
  5. package/dist/control-database.js +146 -135
  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-stream.js +2 -1
  10. package/dist/control-stream.js.map +1 -1
  11. package/dist/describe-thrown.d.ts +12 -0
  12. package/dist/describe-thrown.js +59 -0
  13. package/dist/describe-thrown.js.map +1 -0
  14. package/dist/edge-node/dissolve.d.ts +1 -1
  15. package/dist/edge-node/dissolve.js +1 -1
  16. package/dist/edge-node/dissolve.js.map +1 -1
  17. package/dist/edge-node/edge-join.js +2 -1
  18. package/dist/edge-node/edge-join.js.map +1 -1
  19. package/dist/edge-node/edge-node.js +2 -1
  20. package/dist/edge-node/edge-node.js.map +1 -1
  21. package/dist/edge-node/strand-move.d.ts +0 -2
  22. package/dist/edge-node/strand-move.js +1 -4
  23. package/dist/edge-node/strand-move.js.map +1 -1
  24. package/dist/edge-node/strands.js +2 -1
  25. package/dist/edge-node/strands.js.map +1 -1
  26. package/dist/enrollment.js +2 -1
  27. package/dist/enrollment.js.map +1 -1
  28. package/dist/index.d.ts +3 -1
  29. package/dist/index.js +3 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/member-redemption.js +3 -9
  32. package/dist/member-redemption.js.map +1 -1
  33. package/dist/node-local-snapshot.js +2 -1
  34. package/dist/node-local-snapshot.js.map +1 -1
  35. package/dist/peer-dial.js +3 -2
  36. package/dist/peer-dial.js.map +1 -1
  37. package/dist/pending-join-runner.d.ts +29 -2
  38. package/dist/pending-join-runner.js +60 -20
  39. package/dist/pending-join-runner.js.map +1 -1
  40. package/dist/push-notifier-apns.js +8 -7
  41. package/dist/push-notifier-apns.js.map +1 -1
  42. package/dist/push-notifier-fcm.js +6 -5
  43. package/dist/push-notifier-fcm.js.map +1 -1
  44. package/dist/push-notifier-shared.d.ts +0 -2
  45. package/dist/push-notifier-shared.js +4 -4
  46. package/dist/push-notifier-shared.js.map +1 -1
  47. package/dist/relay-reservation.js +24 -4
  48. package/dist/relay-reservation.js.map +1 -1
  49. package/dist/strand-addr-protocol.js +2 -1
  50. package/dist/strand-addr-protocol.js.map +1 -1
  51. package/dist/strand-app-schema-report.d.ts +56 -0
  52. package/dist/strand-app-schema-report.js +83 -0
  53. package/dist/strand-app-schema-report.js.map +1 -0
  54. package/dist/strand-database.d.ts +9 -5
  55. package/dist/strand-database.js +12 -6
  56. package/dist/strand-database.js.map +1 -1
  57. package/dist/strand-first-sync-gate.js +4 -3
  58. package/dist/strand-first-sync-gate.js.map +1 -1
  59. package/dist/strand-formation-protocol.js +4 -3
  60. package/dist/strand-formation-protocol.js.map +1 -1
  61. package/dist/strand-instance-manager.d.ts +8 -2
  62. package/dist/strand-instance-manager.js +8 -6
  63. package/dist/strand-instance-manager.js.map +1 -1
  64. package/dist/strand-membership-reconciler.js +9 -11
  65. package/dist/strand-membership-reconciler.js.map +1 -1
  66. package/dist/strand-move.js +4 -6
  67. package/dist/strand-move.js.map +1 -1
  68. package/dist/strand-offline.d.ts +10 -39
  69. package/dist/strand-offline.js +9 -54
  70. package/dist/strand-offline.js.map +1 -1
  71. package/dist/types.d.ts +8 -5
  72. package/dist/types.js.map +1 -1
  73. package/package.json +8 -8
  74. package/src/cadre-node.ts +11528 -11456
  75. package/src/control-database.ts +5603 -5592
  76. package/src/control-protocol-guard.ts +3 -2
  77. package/src/control-stream.ts +2 -1
  78. package/src/describe-thrown.ts +60 -0
  79. package/src/edge-node/dissolve.ts +2 -1
  80. package/src/edge-node/edge-join.ts +1 -1
  81. package/src/edge-node/edge-node.ts +2 -1
  82. package/src/edge-node/strand-move.ts +1 -5
  83. package/src/edge-node/strands.ts +74 -73
  84. package/src/enrollment.ts +2 -1
  85. package/src/index.ts +924 -917
  86. package/src/member-redemption.ts +3 -9
  87. package/src/node-local-snapshot.ts +2 -1
  88. package/src/peer-dial.ts +605 -604
  89. package/src/pending-join-runner.ts +68 -22
  90. package/src/push-notifier-apns.ts +8 -7
  91. package/src/push-notifier-fcm.ts +6 -5
  92. package/src/push-notifier-shared.ts +5 -5
  93. package/src/relay-reservation.ts +1239 -1211
  94. package/src/strand-addr-protocol.ts +2 -1
  95. package/src/strand-app-schema-report.ts +122 -0
  96. package/src/strand-database.ts +474 -466
  97. package/src/strand-first-sync-gate.ts +600 -599
  98. package/src/strand-formation-protocol.ts +4 -3
  99. package/src/strand-instance-manager.ts +2219 -2210
  100. package/src/strand-membership-reconciler.ts +942 -945
  101. package/src/strand-move.ts +594 -597
  102. package/src/strand-offline.ts +11 -80
  103. package/src/types.ts +2963 -2960
@@ -701,6 +701,13 @@ export declare class CadreNode implements SAppIdLookup {
701
701
  private reissuedHeldRevocations;
702
702
  /** This node's own `CadrePeer` self-write committed local-only (re-touched on growth). */
703
703
  private pendingSelfPeerWrite;
704
+ /**
705
+ * A background self-record publish was deferred because a write then could have forked the
706
+ * party ({@link publishSelfRecordInBackground}); the next growth drain publishes unless the
707
+ * record is current. Distinct from {@link pendingSelfPeerWrite}, which re-touches a record
708
+ * already written, current or not.
709
+ */
710
+ private selfPeerPublishDeferred;
704
711
  /** This node's own `DeviceToken` self-write committed local-only (re-touched on growth). */
705
712
  private pendingSelfDeviceWrite;
706
713
  /**
@@ -1528,10 +1535,32 @@ export declare class CadreNode implements SAppIdLookup {
1528
1535
  * so the timer is harmless even when registration only becomes possible later.
1529
1536
  * A record this process already put in place that is still current (a founding owner's
1530
1537
  * explicit publish, a redeemed invitation's admission, a restart's first-growth re-touch) is
1531
- * not written again ({@link publishSelfRecordUnlessCurrent}). Whether the node is connected
1532
- * yet does not matter: a device that redeems within a second of starting is.
1538
+ * not written again ({@link publishSelfRecordUnlessCurrent}); that check, not connectivity,
1539
+ * is what spares a device that redeemed within a second of starting a second write.
1540
+ *
1541
+ * A background publish ({@link publishSelfRecordInBackground}): in a party with other members
1542
+ * it waits for a reachable sibling, so two members restarted together, each alone at this
1543
+ * moment, do not each write the `CadrePeer` collection to the same revision.
1533
1544
  */
1534
1545
  private scheduleSelfRegistration;
1546
+ /**
1547
+ * Run `publish`, a self-record publish nothing needs made now (the boot one-shot, the heartbeat,
1548
+ * an address change, {@link registerSelfUnlessCouldFork}), unless a write now could fork the
1549
+ * party ({@link controlWriteCouldFork}). Then nothing is written: {@link selfPeerPublishDeferred}
1550
+ * is set, and the next growth drain publishes the record as it is by then. A deferral is not a
1551
+ * failure, so it neither stamps {@link lastSelfRecordPublishAt} (the reconcile pass's
1552
+ * {@link publishFirstSelfRecord} keeps trying) nor escalates a stale record.
1553
+ */
1554
+ private publishSelfRecordInBackground;
1555
+ /**
1556
+ * {@link registerSelf} for a caller that wants the record in place but cannot wait for a
1557
+ * sibling (`cadre start --owner`, so the first seed it mints carries its address). A party with
1558
+ * no other members writes at once; otherwise the write waits for a reachable sibling, as the
1559
+ * boot publish does, and this returns `'deferred'`. Two owner machines restarted together that
1560
+ * each called {@link registerSelf} here would fork the `CadrePeer` collection
1561
+ * ({@link controlWriteCouldFork}).
1562
+ */
1563
+ registerSelfUnlessCouldFork(): Promise<SelfRegistrationOutcome | 'deferred'>;
1535
1564
  /**
1536
1565
  * Publish (or refresh) this node's own signed `CadrePeer` address record so
1537
1566
  * other members can resolve its current signaling/relay multiaddrs from its
@@ -1689,8 +1718,8 @@ export declare class CadreNode implements SAppIdLookup {
1689
1718
  * would write its row on the stale side of the fork, and then never see rows written while it
1690
1719
  * was down (`cadre-invite-any-member` runs that pass and fails every time without this
1691
1720
  * condition). A connection is not enough: until the sibling identifies, the write's cohort is
1692
- * this node alone. The boot-time publish and the first-growth drain already try at the
1693
- * node's lone and first-sibling moments; this retries on the passes after.
1721
+ * this node alone. The boot-time publish (alone only in a party with no other members) and the
1722
+ * first-growth drain already try; this retries on the passes after.
1694
1723
  *
1695
1724
  * A machine admitted by invitation finds its row already holding the record its redemption
1696
1725
  * carried, and writes nothing ({@link publishSelfRecordUnlessCurrent}).
@@ -4178,8 +4207,8 @@ export declare class CadreNode implements SAppIdLookup {
4178
4207
  * `OwnerKey.Authorized`; the row stores the vouching pair). The write notifies the
4179
4208
  * membership hub, so the refresh it triggers has run by the time this resolves.
4180
4209
  *
4181
- * Refused while alone ({@link ownerKeyWriteAlone}): an `OwnerKey` add has no re-issue path,
4182
- * so one committed with no control connection would stay on this node.
4210
+ * Refused while alone ({@link controlWriteCouldFork}): an `OwnerKey` add has no re-issue path,
4211
+ * so one committed with no sibling reachable would stay on this node.
4183
4212
  *
4184
4213
  * @param ownerPublicKeyB64 - the new owner's ed25519 public key (base64url).
4185
4214
  * @param options.label - the user's name for the key ("phone", "paper backup"), bound into
@@ -4191,17 +4220,27 @@ export declare class CadreNode implements SAppIdLookup {
4191
4220
  label?: string;
4192
4221
  }): Promise<boolean>;
4193
4222
  /**
4194
- * Whether an `OwnerKey` add made now ({@link addOwner}, or the re-add of
4195
- * {@link removeOwner}'s re-vouch) is refused `alone`: this node holds no control connection
4196
- * while the party has other members. An `OwnerKey` row has no update to re-touch, so nothing
4197
- * re-issues it on cohort growth, and a row written now would fork this node's history. A
4198
- * party with no other members cannot fork, so a solo founder adding an owner key is not
4199
- * refused.
4223
+ * Whether a control write made now could fork the party's history: no sibling is reachable
4224
+ * ({@link committedAlone}) while the party has other members. Such a write commits on this
4225
+ * node alone, and if another member writes the same collection meanwhile, both take it to the
4226
+ * same revision with different content, which no re-issue heals (docs/architecture.md →
4227
+ * "Writes made while alone"). A party with no other members cannot fork.
4228
+ *
4229
+ * What a caller does on `true` depends on the write. An `OwnerKey` add has no re-issue path at
4230
+ * all, so {@link addOwner}, {@link removeOwner}'s re-vouch and a local owner grant redemption
4231
+ * refuse it `alone`. A background write nothing waits on (the self-record publishes
4232
+ * {@link publishSelfRecordInBackground} makes, the pending-join runner's background attempts)
4233
+ * waits for a reachable sibling.
4200
4234
  *
4201
4235
  * Waits out an in-flight membership refresh first: until `start`'s first one lands the
4202
4236
  * member snapshot is empty, which would read as a party with no other members.
4237
+ *
4238
+ * NOTE: a snapshot that stays empty on a node that has members (a failed first membership
4239
+ * read keeps the empty snapshot; an anchor never seeded trusts no row) also reads as "no
4240
+ * other members", so such a node writes alone as before this check existed. If a fork is
4241
+ * ever traced to that state, count the party from the unfiltered `CadrePeer` rows here.
4203
4242
  */
4204
- private ownerKeyWriteAlone;
4243
+ private controlWriteCouldFork;
4205
4244
  /**
4206
4245
  * Every live owner key with its label, who vouched it, whether this node's owner signer
4207
4246
  * holds it and whether this node's trusted-owner anchor trusts it ({@link CadreOwnerKey}),
@@ -4226,7 +4265,7 @@ export declare class CadreNode implements SAppIdLookup {
4226
4265
  *
4227
4266
  * Steps: re-plan ({@link planOwnerKeyRemoval}) and throw {@link OwnerKeyRemovalRefusedError}
4228
4267
  * on a refusal; check `options.revouch` against the plan's dependents and throw before any
4229
- * write when it names anything else; refuse `alone` ({@link ownerKeyWriteAlone}) when an
4268
+ * write when it names anything else; refuse `alone` ({@link controlWriteCouldFork}) when an
4230
4269
  * `OwnerKey` row is to be re-vouched, since that re-add has no re-issue path; **re-vouch
4231
4270
  * first**, under this node's key, the dependents the caller chose to keep and this node's own
4232
4271
  * row when the key vouched it (`ControlDatabase.revouchOwnerKey`, `reauthorizePeer`), so they
@@ -67,6 +67,7 @@ import { superviseRelayReservation, resolveRelayReservationState } from './relay
67
67
  import { PushFanoutService } from './push-fanout.js';
68
68
  import { summarizeConnectionPaths } from './diagnostics/connection-path.js';
69
69
  import { timedStep } from './timed-step.js';
70
+ import { describeThrown, toError } from './describe-thrown.js';
70
71
  const log = debug('sereus:cadre:node');
71
72
  const timing = debug('sereus:cadre:timing');
72
73
  /**
@@ -878,6 +879,13 @@ export class CadreNode {
878
879
  this.reissuedHeldRevocations = false;
879
880
  /** This node's own `CadrePeer` self-write committed local-only (re-touched on growth). */
880
881
  this.pendingSelfPeerWrite = false;
882
+ /**
883
+ * A background self-record publish was deferred because a write then could have forked the
884
+ * party ({@link publishSelfRecordInBackground}); the next growth drain publishes unless the
885
+ * record is current. Distinct from {@link pendingSelfPeerWrite}, which re-touches a record
886
+ * already written, current or not.
887
+ */
888
+ this.selfPeerPublishDeferred = false;
881
889
  /** This node's own `DeviceToken` self-write committed local-only (re-touched on growth). */
882
890
  this.pendingSelfDeviceWrite = false;
883
891
  /**
@@ -2849,14 +2857,18 @@ export class CadreNode {
2849
2857
  * so the timer is harmless even when registration only becomes possible later.
2850
2858
  * A record this process already put in place that is still current (a founding owner's
2851
2859
  * explicit publish, a redeemed invitation's admission, a restart's first-growth re-touch) is
2852
- * not written again ({@link publishSelfRecordUnlessCurrent}). Whether the node is connected
2853
- * yet does not matter: a device that redeems within a second of starting is.
2860
+ * not written again ({@link publishSelfRecordUnlessCurrent}); that check, not connectivity,
2861
+ * is what spares a device that redeemed within a second of starting a second write.
2862
+ *
2863
+ * A background publish ({@link publishSelfRecordInBackground}): in a party with other members
2864
+ * it waits for a reachable sibling, so two members restarted together, each alone at this
2865
+ * moment, do not each write the `CadrePeer` collection to the same revision.
2854
2866
  */
2855
2867
  scheduleSelfRegistration() {
2856
2868
  this.selfRegistrationTimer = setTimeout(() => {
2857
2869
  void (async () => {
2858
2870
  try {
2859
- await this.publishSelfRecordUnlessCurrent();
2871
+ await this.publishSelfRecordInBackground('boot', () => this.publishSelfRecordUnlessCurrent());
2860
2872
  }
2861
2873
  catch (error) {
2862
2874
  // Background task — a failed publish must not crash the node. A publish that loses
@@ -2876,6 +2888,33 @@ export class CadreNode {
2876
2888
  // Node-only: don't keep the event loop alive solely for this timer.
2877
2889
  this.selfRegistrationTimer?.unref?.();
2878
2890
  }
2891
+ /**
2892
+ * Run `publish`, a self-record publish nothing needs made now (the boot one-shot, the heartbeat,
2893
+ * an address change, {@link registerSelfUnlessCouldFork}), unless a write now could fork the
2894
+ * party ({@link controlWriteCouldFork}). Then nothing is written: {@link selfPeerPublishDeferred}
2895
+ * is set, and the next growth drain publishes the record as it is by then. A deferral is not a
2896
+ * failure, so it neither stamps {@link lastSelfRecordPublishAt} (the reconcile pass's
2897
+ * {@link publishFirstSelfRecord} keeps trying) nor escalates a stale record.
2898
+ */
2899
+ async publishSelfRecordInBackground(reason, publish) {
2900
+ if (await this.controlWriteCouldFork()) {
2901
+ this.selfPeerPublishDeferred = true;
2902
+ log('Self-record publish (%s) deferred: no sibling reachable and the party has other members; the next growth drain publishes', reason);
2903
+ return 'deferred';
2904
+ }
2905
+ return await publish();
2906
+ }
2907
+ /**
2908
+ * {@link registerSelf} for a caller that wants the record in place but cannot wait for a
2909
+ * sibling (`cadre start --owner`, so the first seed it mints carries its address). A party with
2910
+ * no other members writes at once; otherwise the write waits for a reachable sibling, as the
2911
+ * boot publish does, and this returns `'deferred'`. Two owner machines restarted together that
2912
+ * each called {@link registerSelf} here would fork the `CadrePeer` collection
2913
+ * ({@link controlWriteCouldFork}).
2914
+ */
2915
+ async registerSelfUnlessCouldFork() {
2916
+ return await this.publishSelfRecordInBackground('startup', () => this.registerSelf());
2917
+ }
2879
2918
  /**
2880
2919
  * Publish (or refresh) this node's own signed `CadrePeer` address record so
2881
2920
  * other members can resolve its current signaling/relay multiaddrs from its
@@ -3112,7 +3151,7 @@ export class CadreNode {
3112
3151
  this.selfRecordStaleWarned = true;
3113
3152
  console.warn(`[sereus] this machine has not published its own address record for ${Math.round(staleForMs / 60000)} `
3114
3153
  + `minutes. The latest attempt (${reason}) failed with: `
3115
- + `${error instanceof Error ? error.message : String(error)}. `
3154
+ + `${describeThrown(error)}. `
3116
3155
  + 'Other machines in the party discard an address record older than '
3117
3156
  + `${Math.round(DEFAULT_PEER_RECORD_MAX_AGE_MS / 60000)} minutes, so any of them not already `
3118
3157
  + 'connected to this one can no longer reach it. Publishing keeps retrying; this is reported once.');
@@ -3188,8 +3227,8 @@ export class CadreNode {
3188
3227
  * would write its row on the stale side of the fork, and then never see rows written while it
3189
3228
  * was down (`cadre-invite-any-member` runs that pass and fails every time without this
3190
3229
  * condition). A connection is not enough: until the sibling identifies, the write's cohort is
3191
- * this node alone. The boot-time publish and the first-growth drain already try at the
3192
- * node's lone and first-sibling moments; this retries on the passes after.
3230
+ * this node alone. The boot-time publish (alone only in a party with no other members) and the
3231
+ * first-growth drain already try; this retries on the passes after.
3193
3232
  *
3194
3233
  * A machine admitted by invitation finds its row already holding the record its redemption
3195
3234
  * carried, and writes nothing ({@link publishSelfRecordUnlessCurrent}).
@@ -3228,7 +3267,7 @@ export class CadreNode {
3228
3267
  return;
3229
3268
  }
3230
3269
  const republish = (reason) => {
3231
- void this.registerSelf().catch((error) => {
3270
+ void this.publishSelfRecordInBackground(reason, () => this.registerSelf()).catch((error) => {
3232
3271
  log('Record refresh (%s) failed: %o', reason, error);
3233
3272
  // The only failure in this file that degrades the whole party on its own, so it is
3234
3273
  // the only one that escalates past `debug`. See escalateIfSelfRecordStale.
@@ -3339,6 +3378,7 @@ export class CadreNode {
3339
3378
  this.pendingPeerWrites.clear();
3340
3379
  this.pendingRevocations.clear();
3341
3380
  this.pendingSelfPeerWrite = false;
3381
+ this.selfPeerPublishDeferred = false;
3342
3382
  this.pendingSelfDeviceWrite = false;
3343
3383
  // Self-record publication history is per-session too: a restarted node re-publishes
3344
3384
  // from scratch, and carrying the previous lifetime's stamp forward would either
@@ -4334,14 +4374,20 @@ export class CadreNode {
4334
4374
  await this.drainPendingRevocations();
4335
4375
  // 2. Self rows. A self write made while alone is always re-touched: the re-touch
4336
4376
  // is what carries it to the cohort. Otherwise the first growth re-touches a row
4337
- // a prior process may have committed local-only, unless the row already holds a
4338
- // current record this process signed (a redeemed invitation's admission).
4377
+ // a prior process may have committed local-only, and a background publish deferred
4378
+ // while alone is made now, each unless the row already holds a current record this
4379
+ // process signed (a redeemed invitation's admission). Both flags are taken before
4380
+ // the publish, so one set again while it runs (the write committed alone after all,
4381
+ // a heartbeat deferred meanwhile) waits for the next growth.
4339
4382
  // registerSelf is idempotent + single-flight, so this never races a
4340
4383
  // duplicate publish with the heartbeat republish.
4341
- if (firstGrowth || this.pendingSelfPeerWrite) {
4342
- const publish = this.pendingSelfPeerWrite ? this.registerSelf() : this.publishSelfRecordUnlessCurrent();
4384
+ const retouchSelf = this.pendingSelfPeerWrite;
4385
+ const publishDeferred = this.selfPeerPublishDeferred;
4386
+ this.pendingSelfPeerWrite = false;
4387
+ this.selfPeerPublishDeferred = false;
4388
+ if (firstGrowth || retouchSelf || publishDeferred) {
4389
+ const publish = retouchSelf ? this.registerSelf() : this.publishSelfRecordUnlessCurrent();
4343
4390
  await publish.catch((error) => log('drain: registerSelf failed: %o', error));
4344
- this.pendingSelfPeerWrite = false;
4345
4391
  }
4346
4392
  if (firstGrowth || this.pendingSelfDeviceWrite) {
4347
4393
  await this.retouchSelfDeviceToken();
@@ -4357,8 +4403,10 @@ export class CadreNode {
4357
4403
  }
4358
4404
  // 4. In-session pending owner authorize writes.
4359
4405
  await this.drainPendingPeerWrites();
4360
- // 5. Pending joins this process wrote while alone. Their tombstones went out in step 1.
4406
+ // 5. Pending joins this process wrote while alone (their tombstones went out in step 1),
4407
+ // then the background attempts it deferred while alone.
4361
4408
  await this.pendingJoinRunner?.reissueWritesMadeAlone();
4409
+ this.pendingJoinRunner?.resumeDeferredWrites();
4362
4410
  }
4363
4411
  /**
4364
4412
  * Re-touch this node's own `DeviceToken` row (re-sign + bump `UpdatedAt` via
@@ -5006,7 +5054,7 @@ export class CadreNode {
5006
5054
  log('Error starting strand %s: %o', strand.Id, error);
5007
5055
  this.emit('strand:error', {
5008
5056
  strandId: strand.Id,
5009
- error: error instanceof Error ? error : new Error(String(error))
5057
+ error: toError(error)
5010
5058
  });
5011
5059
  // Rethrow after the event: the only caller is the StrandWatcher's
5012
5060
  // onStrandAdded callback, which uses the rejection to decide whether the
@@ -5082,7 +5130,7 @@ export class CadreNode {
5082
5130
  log('Error stopping strand %s: %o', strandId, error);
5083
5131
  this.emit('strand:error', {
5084
5132
  strandId,
5085
- error: error instanceof Error ? error : new Error(String(error))
5133
+ error: toError(error)
5086
5134
  });
5087
5135
  }
5088
5136
  }
@@ -6230,6 +6278,11 @@ export class CadreNode {
6230
6278
  // NOTE: founder-ness no longer waits for the owner signer, so a founding machine's launch
6231
6279
  // that runs before the embedder wires it throws here and the watcher retries on its backoff;
6232
6280
  // if that shows up as restart noise, skip the heal until `getOwnerSigner()` is set.
6281
+ // NOTE: a control write the strand watcher's launch makes in the background, not deferred
6282
+ // while a write could fork the party (`controlWriteCouldFork`): only the row's founder mints,
6283
+ // and only for a closed row stored without its key, so two machines forking `StrandPartyKey`
6284
+ // at once needs two such rows launching alone together. If this heal comes to run routinely
6285
+ // at boot, defer it the same way.
6233
6286
  return await this.ensureStrandPartyKey(strand.Id);
6234
6287
  }
6235
6288
  /**
@@ -6513,7 +6566,9 @@ export class CadreNode {
6513
6566
  offline: this.config.strandOffline && {
6514
6567
  ...this.config.strandOffline,
6515
6568
  onOfflineStatus: (event) => this.handleOfflineStatus(event),
6516
- onQueueState: (event) => this.emit('strand:queue-state', event),
6569
+ onQueueState: (event) => this.emit('strand:queue-state', event)
6570
+ },
6571
+ appSchema: {
6517
6572
  onAppSchemaDeferred: (event) => this.emit('strand:app-schema-deferred', event),
6518
6573
  onAppSchemaApplied: (event) => this.emit('strand:app-schema-applied', event),
6519
6574
  onAppSchemaFailed: (event) => this.emit('strand:error', event)
@@ -8539,8 +8594,8 @@ export class CadreNode {
8539
8594
  * `OwnerKey.Authorized`; the row stores the vouching pair). The write notifies the
8540
8595
  * membership hub, so the refresh it triggers has run by the time this resolves.
8541
8596
  *
8542
- * Refused while alone ({@link ownerKeyWriteAlone}): an `OwnerKey` add has no re-issue path,
8543
- * so one committed with no control connection would stay on this node.
8597
+ * Refused while alone ({@link controlWriteCouldFork}): an `OwnerKey` add has no re-issue path,
8598
+ * so one committed with no sibling reachable would stay on this node.
8544
8599
  *
8545
8600
  * @param ownerPublicKeyB64 - the new owner's ed25519 public key (base64url).
8546
8601
  * @param options.label - the user's name for the key ("phone", "paper backup"), bound into
@@ -8553,7 +8608,7 @@ export class CadreNode {
8553
8608
  throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
8554
8609
  }
8555
8610
  const key = requireEd25519PublicKeyB64(ownerPublicKeyB64, 'owner key');
8556
- if (await this.ownerKeyWriteAlone()) {
8611
+ if (await this.controlWriteCouldFork()) {
8557
8612
  throw new OwnerKeyAddRefusedError(key, 'alone');
8558
8613
  }
8559
8614
  const added = await this.seedBootstrapService.addOwner(key, options.label);
@@ -8567,17 +8622,27 @@ export class CadreNode {
8567
8622
  return added;
8568
8623
  }
8569
8624
  /**
8570
- * Whether an `OwnerKey` add made now ({@link addOwner}, or the re-add of
8571
- * {@link removeOwner}'s re-vouch) is refused `alone`: this node holds no control connection
8572
- * while the party has other members. An `OwnerKey` row has no update to re-touch, so nothing
8573
- * re-issues it on cohort growth, and a row written now would fork this node's history. A
8574
- * party with no other members cannot fork, so a solo founder adding an owner key is not
8575
- * refused.
8625
+ * Whether a control write made now could fork the party's history: no sibling is reachable
8626
+ * ({@link committedAlone}) while the party has other members. Such a write commits on this
8627
+ * node alone, and if another member writes the same collection meanwhile, both take it to the
8628
+ * same revision with different content, which no re-issue heals (docs/architecture.md →
8629
+ * "Writes made while alone"). A party with no other members cannot fork.
8630
+ *
8631
+ * What a caller does on `true` depends on the write. An `OwnerKey` add has no re-issue path at
8632
+ * all, so {@link addOwner}, {@link removeOwner}'s re-vouch and a local owner grant redemption
8633
+ * refuse it `alone`. A background write nothing waits on (the self-record publishes
8634
+ * {@link publishSelfRecordInBackground} makes, the pending-join runner's background attempts)
8635
+ * waits for a reachable sibling.
8576
8636
  *
8577
8637
  * Waits out an in-flight membership refresh first: until `start`'s first one lands the
8578
8638
  * member snapshot is empty, which would read as a party with no other members.
8639
+ *
8640
+ * NOTE: a snapshot that stays empty on a node that has members (a failed first membership
8641
+ * read keeps the empty snapshot; an anchor never seeded trusts no row) also reads as "no
8642
+ * other members", so such a node writes alone as before this check existed. If a fork is
8643
+ * ever traced to that state, count the party from the unfiltered `CadrePeer` rows here.
8579
8644
  */
8580
- async ownerKeyWriteAlone() {
8645
+ async controlWriteCouldFork() {
8581
8646
  await this.membershipGateDrain;
8582
8647
  return this.committedAlone() && this.authorizedControlPeers.size > 0;
8583
8648
  }
@@ -8617,7 +8682,7 @@ export class CadreNode {
8617
8682
  *
8618
8683
  * Steps: re-plan ({@link planOwnerKeyRemoval}) and throw {@link OwnerKeyRemovalRefusedError}
8619
8684
  * on a refusal; check `options.revouch` against the plan's dependents and throw before any
8620
- * write when it names anything else; refuse `alone` ({@link ownerKeyWriteAlone}) when an
8685
+ * write when it names anything else; refuse `alone` ({@link controlWriteCouldFork}) when an
8621
8686
  * `OwnerKey` row is to be re-vouched, since that re-add has no re-issue path; **re-vouch
8622
8687
  * first**, under this node's key, the dependents the caller chose to keep and this node's own
8623
8688
  * row when the key vouched it (`ControlDatabase.revouchOwnerKey`, `reauthorizePeer`), so they
@@ -8642,7 +8707,7 @@ export class CadreNode {
8642
8707
  throw new OwnerKeyRemovalRefusedError(key, plan.refusal);
8643
8708
  }
8644
8709
  const revouch = revouchWithinPlan(plan, options.revouch, this.peerId?.toString() ?? null);
8645
- if (revouch.owners.length > 0 && await this.ownerKeyWriteAlone()) {
8710
+ if (revouch.owners.length > 0 && await this.controlWriteCouldFork()) {
8646
8711
  throw new OwnerKeyRemovalRefusedError(key, 'alone');
8647
8712
  }
8648
8713
  // The plan already refused 'not-an-owner' when no enrolled signer is wired.
@@ -9510,7 +9575,8 @@ export class CadreNode {
9510
9575
  async redeemOwnerGrant(bundle, signer, options = {}) {
9511
9576
  const { controlDatabase } = this.requireStartedForGrant(bundle, 'redeeming an owner grant');
9512
9577
  // An enrolled owner machine is a party machine whether or not its own row is published yet
9513
- // (the first self-record lands a second after start), so it writes locally too.
9578
+ // (its first self-record lands a second after start, or once it reaches a sibling in a party
9579
+ // with other members), so it writes locally too.
9514
9580
  if (await this.isLiveMemberSelf() || await this.isOwner()) {
9515
9581
  return await this.redeemOwnerGrantLocally(controlDatabase, bundle, signer);
9516
9582
  }
@@ -9527,7 +9593,7 @@ export class CadreNode {
9527
9593
  * check and the write, as the member handler carries it (`MemberRedemptionHandler`).
9528
9594
  */
9529
9595
  async redeemOwnerGrantLocally(controlDatabase, bundle, signer) {
9530
- if (await this.ownerKeyWriteAlone()) {
9596
+ if (await this.controlWriteCouldFork()) {
9531
9597
  throw new OwnerKeyAddRefusedError(signer.publicKey, 'alone');
9532
9598
  }
9533
9599
  const held = await controlDatabase.queryOwnerGrant(bundle.grant.key);
@@ -10012,6 +10078,7 @@ export class CadreNode {
10012
10078
  rewrite: (expectedStampId, next) => ownerWrite(`Re-send the pending join ${next.Id} to the cadre`, (ownerKey, sign) => database().rewritePendingJoin(expectedStampId, next, ownerKey, sign)),
10013
10079
  remove: (id) => ownerWrite(`Clean up the finished pending join ${id}`, (ownerKey, sign) => database().deletePendingJoin(id, ownerKey, sign)),
10014
10080
  isAlone: () => this.committedAlone(),
10081
+ deferBackgroundWrites: () => this.controlWriteCouldFork(),
10015
10082
  sAppIdOf: (row) => this.pendingJoinSAppId(row),
10016
10083
  observeRows: (rows) => this.stageMembershipInvitesFromPendingJoins(rows),
10017
10084
  emit: (status) => this.emit('pendingJoin:changed', status),