@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
@@ -9,6 +9,7 @@ import { controlClusterPolicy, CONTROL_REPLICATION_BREADTH, DEFAULT_CHECKIN_WIND
9
9
  import { generatePrivateKey } from '@optimystic/quereus-plugin-crypto';
10
10
  import { ed25519KeyPairFromLibp2p, ed25519PublicKeyFromPrivate, requireEd25519PublicKeyB64 } from './ed25519-key.js';
11
11
  import { strandTransportKey } from './strand-transport-key.js';
12
+ import { isSendingStatus, StrandOfflineUnavailableError, StrandQueueNotEmptyError } from './strand-offline.js';
12
13
  import { assertScopeKeyCharset, assertStrandScopeKey, controlStorageScope, InvalidStrandIdError, isValidStrandScopeKey } from './storage-scope.js';
13
14
  import { generateStrandMemberKey, strandMemberKeyPair } from './strand-member-key.js';
14
15
  import { assertNotPreSplitStrand, issueInvite, PreSplitStrandIdentityError, readStrandHeaderSAppId } from './strand-membership-writer.js';
@@ -66,6 +67,7 @@ import { superviseRelayReservation, resolveRelayReservationState } from './relay
66
67
  import { PushFanoutService } from './push-fanout.js';
67
68
  import { summarizeConnectionPaths } from './diagnostics/connection-path.js';
68
69
  import { timedStep } from './timed-step.js';
70
+ import { describeThrown, toError } from './describe-thrown.js';
69
71
  const log = debug('sereus:cadre:node');
70
72
  const timing = debug('sereus:cadre:timing');
71
73
  /**
@@ -877,6 +879,13 @@ export class CadreNode {
877
879
  this.reissuedHeldRevocations = false;
878
880
  /** This node's own `CadrePeer` self-write committed local-only (re-touched on growth). */
879
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;
880
889
  /** This node's own `DeviceToken` self-write committed local-only (re-touched on growth). */
881
890
  this.pendingSelfDeviceWrite = false;
882
891
  /**
@@ -2848,14 +2857,18 @@ export class CadreNode {
2848
2857
  * so the timer is harmless even when registration only becomes possible later.
2849
2858
  * A record this process already put in place that is still current (a founding owner's
2850
2859
  * explicit publish, a redeemed invitation's admission, a restart's first-growth re-touch) is
2851
- * not written again ({@link publishSelfRecordUnlessCurrent}). Whether the node is connected
2852
- * 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.
2853
2866
  */
2854
2867
  scheduleSelfRegistration() {
2855
2868
  this.selfRegistrationTimer = setTimeout(() => {
2856
2869
  void (async () => {
2857
2870
  try {
2858
- await this.publishSelfRecordUnlessCurrent();
2871
+ await this.publishSelfRecordInBackground('boot', () => this.publishSelfRecordUnlessCurrent());
2859
2872
  }
2860
2873
  catch (error) {
2861
2874
  // Background task — a failed publish must not crash the node. A publish that loses
@@ -2875,6 +2888,33 @@ export class CadreNode {
2875
2888
  // Node-only: don't keep the event loop alive solely for this timer.
2876
2889
  this.selfRegistrationTimer?.unref?.();
2877
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
+ }
2878
2918
  /**
2879
2919
  * Publish (or refresh) this node's own signed `CadrePeer` address record so
2880
2920
  * other members can resolve its current signaling/relay multiaddrs from its
@@ -3111,7 +3151,7 @@ export class CadreNode {
3111
3151
  this.selfRecordStaleWarned = true;
3112
3152
  console.warn(`[sereus] this machine has not published its own address record for ${Math.round(staleForMs / 60000)} `
3113
3153
  + `minutes. The latest attempt (${reason}) failed with: `
3114
- + `${error instanceof Error ? error.message : String(error)}. `
3154
+ + `${describeThrown(error)}. `
3115
3155
  + 'Other machines in the party discard an address record older than '
3116
3156
  + `${Math.round(DEFAULT_PEER_RECORD_MAX_AGE_MS / 60000)} minutes, so any of them not already `
3117
3157
  + 'connected to this one can no longer reach it. Publishing keeps retrying; this is reported once.');
@@ -3187,8 +3227,8 @@ export class CadreNode {
3187
3227
  * would write its row on the stale side of the fork, and then never see rows written while it
3188
3228
  * was down (`cadre-invite-any-member` runs that pass and fails every time without this
3189
3229
  * condition). A connection is not enough: until the sibling identifies, the write's cohort is
3190
- * this node alone. The boot-time publish and the first-growth drain already try at the
3191
- * 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.
3192
3232
  *
3193
3233
  * A machine admitted by invitation finds its row already holding the record its redemption
3194
3234
  * carried, and writes nothing ({@link publishSelfRecordUnlessCurrent}).
@@ -3227,7 +3267,7 @@ export class CadreNode {
3227
3267
  return;
3228
3268
  }
3229
3269
  const republish = (reason) => {
3230
- void this.registerSelf().catch((error) => {
3270
+ void this.publishSelfRecordInBackground(reason, () => this.registerSelf()).catch((error) => {
3231
3271
  log('Record refresh (%s) failed: %o', reason, error);
3232
3272
  // The only failure in this file that degrades the whole party on its own, so it is
3233
3273
  // the only one that escalates past `debug`. See escalateIfSelfRecordStale.
@@ -3338,6 +3378,7 @@ export class CadreNode {
3338
3378
  this.pendingPeerWrites.clear();
3339
3379
  this.pendingRevocations.clear();
3340
3380
  this.pendingSelfPeerWrite = false;
3381
+ this.selfPeerPublishDeferred = false;
3341
3382
  this.pendingSelfDeviceWrite = false;
3342
3383
  // Self-record publication history is per-session too: a restarted node re-publishes
3343
3384
  // from scratch, and carrying the previous lifetime's stamp forward would either
@@ -4333,14 +4374,20 @@ export class CadreNode {
4333
4374
  await this.drainPendingRevocations();
4334
4375
  // 2. Self rows. A self write made while alone is always re-touched: the re-touch
4335
4376
  // is what carries it to the cohort. Otherwise the first growth re-touches a row
4336
- // a prior process may have committed local-only, unless the row already holds a
4337
- // 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.
4338
4382
  // registerSelf is idempotent + single-flight, so this never races a
4339
4383
  // duplicate publish with the heartbeat republish.
4340
- if (firstGrowth || this.pendingSelfPeerWrite) {
4341
- 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();
4342
4390
  await publish.catch((error) => log('drain: registerSelf failed: %o', error));
4343
- this.pendingSelfPeerWrite = false;
4344
4391
  }
4345
4392
  if (firstGrowth || this.pendingSelfDeviceWrite) {
4346
4393
  await this.retouchSelfDeviceToken();
@@ -4356,8 +4403,10 @@ export class CadreNode {
4356
4403
  }
4357
4404
  // 4. In-session pending owner authorize writes.
4358
4405
  await this.drainPendingPeerWrites();
4359
- // 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.
4360
4408
  await this.pendingJoinRunner?.reissueWritesMadeAlone();
4409
+ this.pendingJoinRunner?.resumeDeferredWrites();
4361
4410
  }
4362
4411
  /**
4363
4412
  * Re-touch this node's own `DeviceToken` row (re-sign + bump `UpdatedAt` via
@@ -5005,7 +5054,7 @@ export class CadreNode {
5005
5054
  log('Error starting strand %s: %o', strand.Id, error);
5006
5055
  this.emit('strand:error', {
5007
5056
  strandId: strand.Id,
5008
- error: error instanceof Error ? error : new Error(String(error))
5057
+ error: toError(error)
5009
5058
  });
5010
5059
  // Rethrow after the event: the only caller is the StrandWatcher's
5011
5060
  // onStrandAdded callback, which uses the rejection to decide whether the
@@ -5081,7 +5130,7 @@ export class CadreNode {
5081
5130
  log('Error stopping strand %s: %o', strandId, error);
5082
5131
  this.emit('strand:error', {
5083
5132
  strandId,
5084
- error: error instanceof Error ? error : new Error(String(error))
5133
+ error: toError(error)
5085
5134
  });
5086
5135
  }
5087
5136
  }
@@ -5242,6 +5291,23 @@ export class CadreNode {
5242
5291
  void this.recordReplicaSAppId(strandId);
5243
5292
  this.emit('strand:writable', { strandId });
5244
5293
  }
5294
+ /**
5295
+ * A status from a strand's offline queue (`StartStrandConfig.offline`). The queue sending counts
5296
+ * as activity ({@link isSendingStatus}), so a check-in window that finds the cohort reachable stays
5297
+ * up while the queue drains, and the idle timer does not cut a drain short. Recorded through the
5298
+ * hibernation manager, not {@link recordStrandActivity}, whose push fan-out would wake other phones.
5299
+ *
5300
+ * Not on a strand being quiesced: activity there wakes it again once the quiesce ends, which would
5301
+ * undo a `hibernateAll` made as the app went to the background. A send that quiesce cuts short was
5302
+ * journaled before it went out, and the next build's restore re-sends it under the same action id.
5303
+ */
5304
+ handleOfflineStatus(event) {
5305
+ const instance = this.strandManager.getInstance(event.strandId);
5306
+ if (instance && isSendingStatus(event.status) && !this.strandManager.isQuiescing(event.strandId)) {
5307
+ this.hibernationManager.recordActivity(instance);
5308
+ }
5309
+ this.emit('strand:offline-status', event);
5310
+ }
5245
5311
  // Hibernation callbacks
5246
5312
  async handleStrandIdle(strandId) {
5247
5313
  const instance = this.strandManager.getInstance(strandId);
@@ -5644,6 +5710,31 @@ export class CadreNode {
5644
5710
  timeoutMs: options?.timeoutMs ?? this.config.strandFirstSync?.timeoutMs
5645
5711
  });
5646
5712
  }
5713
+ /**
5714
+ * Switch a strand between offline mode, where a commit resolves once the transaction is queued on
5715
+ * this machine, and online mode (docs/strands.md → "Offline mode"). Affects transactions begun from
5716
+ * now on; one already open keeps the acknowledgement it began with. The mode belongs to the strand:
5717
+ * a hibernating strand takes it at its next build, and it lasts across hibernation and every
5718
+ * rebuild until the process exits, after which the strand starts in `strandOffline.initialMode`.
5719
+ *
5720
+ * @throws StrandOfflineUnavailableError when `CadreNodeConfig.strandOffline` is not configured.
5721
+ * @throws when this node does not run the strand.
5722
+ */
5723
+ setStrandOfflineMode(strandId, mode) {
5724
+ if (!this.config.strandOffline) {
5725
+ throw new StrandOfflineUnavailableError(strandId);
5726
+ }
5727
+ this.strandManager.setOfflineMode(strandId, mode);
5728
+ }
5729
+ /**
5730
+ * A strand's offline mode ({@link setStrandOfflineMode}); `'online'` on a node without
5731
+ * `strandOffline`. The queue's own view, with what it holds, is `strand.database.offline.queueState()`.
5732
+ *
5733
+ * @throws when this node does not run the strand.
5734
+ */
5735
+ getStrandOfflineMode(strandId) {
5736
+ return this.strandManager.offlineMode(strandId);
5737
+ }
5647
5738
  /**
5648
5739
  * Publish a strand row to the shared control database under this node's own
5649
5740
  * owner identity, so other cadre members discover it via control-network
@@ -6012,16 +6103,25 @@ export class CadreNode {
6012
6103
  * caller ever needs removal to mean "and erase the local copy", that is a separate purge
6013
6104
  * step, not a widening of this method.
6014
6105
  *
6106
+ * Refuses while the strand's offline queue on this machine holds transactions, unless
6107
+ * `options.discardQueued` (docs/strands.md → "Leaving a strand with unsent transactions"). The
6108
+ * check and the discard run before the control-plane delete, so a delete refused afterwards
6109
+ * leaves the discarded transactions discarded.
6110
+ *
6015
6111
  * @param strandId - The `Strand` row id to remove (as passed to {@link publishStrand}).
6112
+ * @param options - `discardQueued`: withdraw the queued transactions that were never sent, and remove.
6113
+ * @throws StrandQueueNotEmptyError when the queue holds transactions and `discardQueued` is not
6114
+ * set; nothing was removed.
6016
6115
  * @throws if the node is not started, has no owner signer wired, the id is blank, or
6017
6116
  * the signer is not an enrolled owner (the schema's `Strand.AuthorizedDelete` rejects
6018
6117
  * the write and the row survives). A rejection does NOT imply the row survived: the
6019
6118
  * local stop runs after the control-plane delete has already committed, so a failure
6020
6119
  * there throws over a completed removal.
6021
6120
  */
6022
- async unpublishStrand(strandId) {
6121
+ async unpublishStrand(strandId, options) {
6023
6122
  const signer = this.requireOwnerSigner(`unpublish strand ${strandId}`);
6024
6123
  const trimmed = requireNonBlank(strandId, 'strand id');
6124
+ await this.settleQueueBeforeLeave(trimmed, options);
6025
6125
  // One approval: the strand delete and its party key's, each with its tombstone.
6026
6126
  const removed = await signer.approve({ partyId: this.partyId, action: `Remove the strand ${trimmed} from the cadre` }, (sign) => this.controlDatabase.deleteStrand(trimmed, signer.publicKey, sign));
6027
6127
  // Gate on `removed`: the absent-row no-op wrote nothing, so warning about an
@@ -6178,6 +6278,11 @@ export class CadreNode {
6178
6278
  // NOTE: founder-ness no longer waits for the owner signer, so a founding machine's launch
6179
6279
  // that runs before the embedder wires it throws here and the watcher retries on its backoff;
6180
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.
6181
6286
  return await this.ensureStrandPartyKey(strand.Id);
6182
6287
  }
6183
6288
  /**
@@ -6458,6 +6563,16 @@ export class CadreNode {
6458
6563
  onWritable: (writableStrandId) => this.handleStrandWritable(writableStrandId),
6459
6564
  onCommitDurability: (commit) => this.emit('strand:commit-durability', commit),
6460
6565
  onCommitHeld: (held) => this.emit('strand:commit-held', held),
6566
+ offline: this.config.strandOffline && {
6567
+ ...this.config.strandOffline,
6568
+ onOfflineStatus: (event) => this.handleOfflineStatus(event),
6569
+ onQueueState: (event) => this.emit('strand:queue-state', event)
6570
+ },
6571
+ appSchema: {
6572
+ onAppSchemaDeferred: (event) => this.emit('strand:app-schema-deferred', event),
6573
+ onAppSchemaApplied: (event) => this.emit('strand:app-schema-applied', event),
6574
+ onAppSchemaFailed: (event) => this.emit('strand:error', event)
6575
+ },
6461
6576
  // Re-announce the delegate to ONE relay before the strand node's reservation
6462
6577
  // supervisor re-drives it (see announceDelegateToRelay). Retained with the
6463
6578
  // launch config, so a hibernation wake's rebuilt supervisors get it too.
@@ -7132,18 +7247,70 @@ export class CadreNode {
7132
7247
  * The other members of the strand are not told, and this party's membership row in the
7133
7248
  * strand stays, so a later re-formation reuses the same identity.
7134
7249
  *
7250
+ * Refuses while the strand's offline queue on this machine holds transactions, unless
7251
+ * `options.discardQueued` (docs/strands.md → "Leaving a strand with unsent transactions"). The
7252
+ * check and the discard run before the party-wide row is removed, so a removal refused
7253
+ * afterwards leaves the discarded transactions discarded.
7254
+ *
7255
+ * @param options - `discardQueued`: withdraw the queued transactions that were never sent, and leave.
7256
+ * @throws StrandQueueNotEmptyError when the queue holds transactions and `discardQueued` is not
7257
+ * set; nothing was left.
7135
7258
  * @throws when a party-wide row exists and this machine cannot sign its removal (not an
7136
7259
  * enrolled owner) — {@link stopStrand} stops the strand on this machine only — or when
7137
7260
  * the party-wide table cannot be read.
7138
7261
  */
7139
- async forgetJoinedStrand(strandId) {
7262
+ async forgetJoinedStrand(strandId, options) {
7140
7263
  if (!this._running) {
7141
7264
  throw new Error('CadreNode not running');
7142
7265
  }
7266
+ await this.settleQueueBeforeLeave(strandId, options);
7143
7267
  await this.joinedStrands.leave(strandId);
7144
7268
  this.forgetStrandPeers(strandId, 'forgetJoinedStrand');
7145
7269
  await this.stopStrand(strandId);
7146
7270
  }
7271
+ /**
7272
+ * Before a leave changes anything: refuse while the strand's offline queue holds transactions,
7273
+ * unless the app asked to discard them (docs/strands.md → "Leaving a strand with unsent
7274
+ * transactions"). Transactions Optimystic will not withdraw stay in the journal, named in one
7275
+ * warning, and the leave goes on: they may already be saved, and a cohort that never returns
7276
+ * would otherwise block the leave forever.
7277
+ *
7278
+ * @throws StrandQueueNotEmptyError when the queue holds transactions and `discardQueued` is not set.
7279
+ * @throws when a hibernating strand has to be woken to discard and the wake fails.
7280
+ */
7281
+ async settleQueueBeforeLeave(strandId, options) {
7282
+ const queued = this.strandManager.queuedTransactionIds(strandId);
7283
+ if (queued.length === 0) {
7284
+ return;
7285
+ }
7286
+ if (options?.discardQueued !== true) {
7287
+ throw new StrandQueueNotEmptyError(strandId, queued);
7288
+ }
7289
+ const kept = await this.discardQueuedForLeave(strandId);
7290
+ if (kept === undefined) {
7291
+ console.warn(`[sereus] strand ${strandId}: leaving with ${queued.length} queued transaction(s) not discarded ` +
7292
+ `(${queued.join(', ')}): the strand's database could not be built to reach its queue. They stay in ` +
7293
+ 'this machine\'s offline journal and come back if this machine attaches the strand again.');
7294
+ }
7295
+ else if (kept.length > 0) {
7296
+ console.warn(`[sereus] strand ${strandId}: leaving with ${kept.length} queued transaction(s) that could not be ` +
7297
+ `discarded (${kept.join(', ')}): each was sent, or is being sent, and the strand's members may already ` +
7298
+ 'hold it. They stay in this machine\'s offline journal and settle if this machine attaches the strand again.');
7299
+ }
7300
+ }
7301
+ /**
7302
+ * Discard from the strand's live queue, waking a hibernating strand first (its queue is back
7303
+ * once a build restores it from the journal), and return what was kept. `undefined` when the
7304
+ * wake built no database (no seed peer has answered), so there was no queue to discard from.
7305
+ */
7306
+ async discardQueuedForLeave(strandId) {
7307
+ const kept = this.strandManager.discardQueuedTransactions(strandId);
7308
+ if (kept !== undefined) {
7309
+ return kept;
7310
+ }
7311
+ await this.wakeStrand(strandId);
7312
+ return this.strandManager.discardQueuedTransactions(strandId);
7313
+ }
7147
7314
  /**
7148
7315
  * Record `row` as a join from another party when this party's control database names it
7149
7316
  * neither as its own strand nor as a party-wide join — the one case nothing else would
@@ -8427,8 +8594,8 @@ export class CadreNode {
8427
8594
  * `OwnerKey.Authorized`; the row stores the vouching pair). The write notifies the
8428
8595
  * membership hub, so the refresh it triggers has run by the time this resolves.
8429
8596
  *
8430
- * Refused while alone ({@link ownerKeyWriteAlone}): an `OwnerKey` add has no re-issue path,
8431
- * 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.
8432
8599
  *
8433
8600
  * @param ownerPublicKeyB64 - the new owner's ed25519 public key (base64url).
8434
8601
  * @param options.label - the user's name for the key ("phone", "paper backup"), bound into
@@ -8441,7 +8608,7 @@ export class CadreNode {
8441
8608
  throw new Error('Seed bootstrap service not initialized. Call initializeSeedBootstrap() first.');
8442
8609
  }
8443
8610
  const key = requireEd25519PublicKeyB64(ownerPublicKeyB64, 'owner key');
8444
- if (await this.ownerKeyWriteAlone()) {
8611
+ if (await this.controlWriteCouldFork()) {
8445
8612
  throw new OwnerKeyAddRefusedError(key, 'alone');
8446
8613
  }
8447
8614
  const added = await this.seedBootstrapService.addOwner(key, options.label);
@@ -8455,17 +8622,27 @@ export class CadreNode {
8455
8622
  return added;
8456
8623
  }
8457
8624
  /**
8458
- * Whether an `OwnerKey` add made now ({@link addOwner}, or the re-add of
8459
- * {@link removeOwner}'s re-vouch) is refused `alone`: this node holds no control connection
8460
- * while the party has other members. An `OwnerKey` row has no update to re-touch, so nothing
8461
- * re-issues it on cohort growth, and a row written now would fork this node's history. A
8462
- * party with no other members cannot fork, so a solo founder adding an owner key is not
8463
- * 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.
8464
8636
  *
8465
8637
  * Waits out an in-flight membership refresh first: until `start`'s first one lands the
8466
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.
8467
8644
  */
8468
- async ownerKeyWriteAlone() {
8645
+ async controlWriteCouldFork() {
8469
8646
  await this.membershipGateDrain;
8470
8647
  return this.committedAlone() && this.authorizedControlPeers.size > 0;
8471
8648
  }
@@ -8505,7 +8682,7 @@ export class CadreNode {
8505
8682
  *
8506
8683
  * Steps: re-plan ({@link planOwnerKeyRemoval}) and throw {@link OwnerKeyRemovalRefusedError}
8507
8684
  * on a refusal; check `options.revouch` against the plan's dependents and throw before any
8508
- * 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
8509
8686
  * `OwnerKey` row is to be re-vouched, since that re-add has no re-issue path; **re-vouch
8510
8687
  * first**, under this node's key, the dependents the caller chose to keep and this node's own
8511
8688
  * row when the key vouched it (`ControlDatabase.revouchOwnerKey`, `reauthorizePeer`), so they
@@ -8530,7 +8707,7 @@ export class CadreNode {
8530
8707
  throw new OwnerKeyRemovalRefusedError(key, plan.refusal);
8531
8708
  }
8532
8709
  const revouch = revouchWithinPlan(plan, options.revouch, this.peerId?.toString() ?? null);
8533
- if (revouch.owners.length > 0 && await this.ownerKeyWriteAlone()) {
8710
+ if (revouch.owners.length > 0 && await this.controlWriteCouldFork()) {
8534
8711
  throw new OwnerKeyRemovalRefusedError(key, 'alone');
8535
8712
  }
8536
8713
  // The plan already refused 'not-an-owner' when no enrolled signer is wired.
@@ -9398,7 +9575,8 @@ export class CadreNode {
9398
9575
  async redeemOwnerGrant(bundle, signer, options = {}) {
9399
9576
  const { controlDatabase } = this.requireStartedForGrant(bundle, 'redeeming an owner grant');
9400
9577
  // An enrolled owner machine is a party machine whether or not its own row is published yet
9401
- // (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.
9402
9580
  if (await this.isLiveMemberSelf() || await this.isOwner()) {
9403
9581
  return await this.redeemOwnerGrantLocally(controlDatabase, bundle, signer);
9404
9582
  }
@@ -9415,7 +9593,7 @@ export class CadreNode {
9415
9593
  * check and the write, as the member handler carries it (`MemberRedemptionHandler`).
9416
9594
  */
9417
9595
  async redeemOwnerGrantLocally(controlDatabase, bundle, signer) {
9418
- if (await this.ownerKeyWriteAlone()) {
9596
+ if (await this.controlWriteCouldFork()) {
9419
9597
  throw new OwnerKeyAddRefusedError(signer.publicKey, 'alone');
9420
9598
  }
9421
9599
  const held = await controlDatabase.queryOwnerGrant(bundle.grant.key);
@@ -9900,6 +10078,7 @@ export class CadreNode {
9900
10078
  rewrite: (expectedStampId, next) => ownerWrite(`Re-send the pending join ${next.Id} to the cadre`, (ownerKey, sign) => database().rewritePendingJoin(expectedStampId, next, ownerKey, sign)),
9901
10079
  remove: (id) => ownerWrite(`Clean up the finished pending join ${id}`, (ownerKey, sign) => database().deletePendingJoin(id, ownerKey, sign)),
9902
10080
  isAlone: () => this.committedAlone(),
10081
+ deferBackgroundWrites: () => this.controlWriteCouldFork(),
9903
10082
  sAppIdOf: (row) => this.pendingJoinSAppId(row),
9904
10083
  observeRows: (rows) => this.stageMembershipInvitesFromPendingJoins(rows),
9905
10084
  emit: (status) => this.emit('pendingJoin:changed', status),