@serfab/cadre-core 1.7.0 → 1.8.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 (162) hide show
  1. package/README.md +8 -6
  2. package/dist/cadre-node.d.ts +386 -114
  3. package/dist/cadre-node.js +887 -359
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +2 -2
  6. package/dist/control-authorization.js +1 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-cohort.d.ts +6 -0
  9. package/dist/control-cohort.js +6 -0
  10. package/dist/control-cohort.js.map +1 -1
  11. package/dist/control-database.d.ts +46 -8
  12. package/dist/control-database.js +97 -18
  13. package/dist/control-database.js.map +1 -1
  14. package/dist/control-formation-recorder.d.ts +37 -14
  15. package/dist/control-formation-recorder.js +60 -10
  16. package/dist/control-formation-recorder.js.map +1 -1
  17. package/dist/control-read-retry.d.ts +13 -12
  18. package/dist/control-read-retry.js +14 -12
  19. package/dist/control-read-retry.js.map +1 -1
  20. package/dist/control-schema.d.ts +1 -1
  21. package/dist/control-schema.js +67 -5
  22. package/dist/control-schema.js.map +1 -1
  23. package/dist/control-stream.d.ts +9 -1
  24. package/dist/control-stream.js +24 -1
  25. package/dist/control-stream.js.map +1 -1
  26. package/dist/control-write-retry.d.ts +12 -2
  27. package/dist/control-write-retry.js +13 -2
  28. package/dist/control-write-retry.js.map +1 -1
  29. package/dist/delegate-admission.d.ts +11 -8
  30. package/dist/delegate-admission.js +19 -11
  31. package/dist/delegate-admission.js.map +1 -1
  32. package/dist/diagnostics/connection-path.d.ts +0 -7
  33. package/dist/diagnostics/connection-path.js +0 -7
  34. package/dist/diagnostics/connection-path.js.map +1 -1
  35. package/dist/formation-approval.d.ts +7 -0
  36. package/dist/formation-approval.js +9 -3
  37. package/dist/formation-approval.js.map +1 -1
  38. package/dist/fs-atomic.d.ts +11 -2
  39. package/dist/fs-atomic.js +13 -3
  40. package/dist/fs-atomic.js.map +1 -1
  41. package/dist/hibernation-manager.d.ts +111 -8
  42. package/dist/hibernation-manager.js +234 -49
  43. package/dist/hibernation-manager.js.map +1 -1
  44. package/dist/index.d.ts +8 -6
  45. package/dist/index.js +15 -9
  46. package/dist/index.js.map +1 -1
  47. package/dist/joined-strand-store.d.ts +90 -25
  48. package/dist/joined-strand-store.js +223 -55
  49. package/dist/joined-strand-store.js.map +1 -1
  50. package/dist/key-store-file.js +14 -5
  51. package/dist/key-store-file.js.map +1 -1
  52. package/dist/link-budget.d.ts +367 -69
  53. package/dist/link-budget.js +375 -72
  54. package/dist/link-budget.js.map +1 -1
  55. package/dist/membership-connection-gater.d.ts +30 -43
  56. package/dist/membership-connection-gater.js +31 -42
  57. package/dist/membership-connection-gater.js.map +1 -1
  58. package/dist/peer-dial.d.ts +24 -4
  59. package/dist/peer-dial.js +74 -5
  60. package/dist/peer-dial.js.map +1 -1
  61. package/dist/peer-join-backfill.d.ts +2 -1
  62. package/dist/peer-join-backfill.js +6 -5
  63. package/dist/peer-join-backfill.js.map +1 -1
  64. package/dist/push-fanout.d.ts +6 -0
  65. package/dist/push-fanout.js +6 -0
  66. package/dist/push-fanout.js.map +1 -1
  67. package/dist/relay-reservation.d.ts +3 -1
  68. package/dist/relay-reservation.js +3 -1
  69. package/dist/relay-reservation.js.map +1 -1
  70. package/dist/relay-server.d.ts +79 -0
  71. package/dist/relay-server.js +74 -0
  72. package/dist/relay-server.js.map +1 -0
  73. package/dist/seed-bootstrap.d.ts +57 -4
  74. package/dist/seed-bootstrap.js +107 -83
  75. package/dist/seed-bootstrap.js.map +1 -1
  76. package/dist/storage-scope.d.ts +33 -17
  77. package/dist/storage-scope.js +44 -23
  78. package/dist/storage-scope.js.map +1 -1
  79. package/dist/strand-addr-protocol.d.ts +58 -21
  80. package/dist/strand-addr-protocol.js +133 -85
  81. package/dist/strand-addr-protocol.js.map +1 -1
  82. package/dist/strand-database.d.ts +20 -2
  83. package/dist/strand-database.js +42 -5
  84. package/dist/strand-database.js.map +1 -1
  85. package/dist/strand-first-sync-gate.d.ts +59 -21
  86. package/dist/strand-first-sync-gate.js +58 -19
  87. package/dist/strand-first-sync-gate.js.map +1 -1
  88. package/dist/strand-formation-deadlines.d.ts +151 -0
  89. package/dist/strand-formation-deadlines.js +171 -0
  90. package/dist/strand-formation-deadlines.js.map +1 -0
  91. package/dist/strand-formation-manager.d.ts +63 -30
  92. package/dist/strand-formation-manager.js +67 -41
  93. package/dist/strand-formation-manager.js.map +1 -1
  94. package/dist/strand-formation-protocol.d.ts +45 -35
  95. package/dist/strand-formation-protocol.js +59 -122
  96. package/dist/strand-formation-protocol.js.map +1 -1
  97. package/dist/strand-instance-manager.d.ts +113 -6
  98. package/dist/strand-instance-manager.js +257 -41
  99. package/dist/strand-instance-manager.js.map +1 -1
  100. package/dist/strand-membership-writer.d.ts +6 -0
  101. package/dist/strand-membership-writer.js +11 -0
  102. package/dist/strand-membership-writer.js.map +1 -1
  103. package/dist/strand-peer-book-protocol.d.ts +13 -4
  104. package/dist/strand-peer-book-protocol.js +3 -7
  105. package/dist/strand-peer-book-protocol.js.map +1 -1
  106. package/dist/strand-peer-book.d.ts +1 -1
  107. package/dist/strand-peer-book.js +8 -1
  108. package/dist/strand-peer-book.js.map +1 -1
  109. package/dist/strand-peer-observer.js +1 -1
  110. package/dist/strand-revocation-enforcer.js +2 -1
  111. package/dist/strand-revocation-enforcer.js.map +1 -1
  112. package/dist/strand-solicitation.d.ts +36 -20
  113. package/dist/strand-solicitation.js +4 -4
  114. package/dist/strand-solicitation.js.map +1 -1
  115. package/dist/strand-wake-protocol.d.ts +80 -23
  116. package/dist/strand-wake-protocol.js +89 -64
  117. package/dist/strand-wake-protocol.js.map +1 -1
  118. package/dist/types.d.ts +128 -38
  119. package/dist/types.js +4 -3
  120. package/dist/types.js.map +1 -1
  121. package/package.json +7 -7
  122. package/src/cadre-node.ts +8367 -7776
  123. package/src/control-authorization.ts +2 -1
  124. package/src/control-cohort.ts +6 -0
  125. package/src/control-database.ts +122 -18
  126. package/src/control-formation-recorder.ts +354 -305
  127. package/src/control-read-retry.ts +14 -12
  128. package/src/control-schema.ts +67 -5
  129. package/src/control-stream.ts +25 -1
  130. package/src/control-write-retry.ts +13 -2
  131. package/src/delegate-admission.ts +23 -13
  132. package/src/diagnostics/connection-path.ts +0 -7
  133. package/src/formation-approval.ts +610 -604
  134. package/src/fs-atomic.ts +14 -4
  135. package/src/hibernation-manager.ts +638 -437
  136. package/src/index.ts +28 -10
  137. package/src/joined-strand-store.ts +247 -57
  138. package/src/key-store-file.ts +14 -5
  139. package/src/link-budget.ts +393 -74
  140. package/src/membership-connection-gater.ts +31 -45
  141. package/src/peer-dial.ts +81 -7
  142. package/src/peer-join-backfill.ts +8 -6
  143. package/src/push-fanout.ts +6 -0
  144. package/src/relay-reservation.ts +3 -1
  145. package/src/relay-server.ts +98 -0
  146. package/src/seed-bootstrap.ts +133 -91
  147. package/src/storage-scope.ts +44 -23
  148. package/src/strand-addr-protocol.ts +547 -458
  149. package/src/strand-database.ts +287 -242
  150. package/src/strand-first-sync-gate.ts +58 -19
  151. package/src/strand-formation-deadlines.ts +227 -0
  152. package/src/strand-formation-manager.ts +700 -647
  153. package/src/strand-formation-protocol.ts +103 -150
  154. package/src/strand-instance-manager.ts +287 -44
  155. package/src/strand-membership-writer.ts +12 -0
  156. package/src/strand-peer-book-protocol.ts +16 -13
  157. package/src/strand-peer-book.ts +8 -1
  158. package/src/strand-peer-observer.ts +1 -1
  159. package/src/strand-revocation-enforcer.ts +2 -1
  160. package/src/strand-solicitation.ts +519 -500
  161. package/src/strand-wake-protocol.ts +401 -355
  162. package/src/types.ts +130 -38
@@ -11,7 +11,7 @@ import { ed25519KeyPairFromLibp2p, ed25519PublicKeyFromPrivate, requireEd25519Pu
11
11
  import { strandTransportKey } from './strand-transport-key.js';
12
12
  import { assertScopeKeyCharset, assertStrandScopeKey, controlStorageScope, InvalidStrandIdError, isValidStrandScopeKey } from './storage-scope.js';
13
13
  import { generateStrandMemberKey, strandMemberKeyPair } from './strand-member-key.js';
14
- import { assertNotPreSplitStrand, issueInvite, PreSplitStrandIdentityError } from './strand-membership-writer.js';
14
+ import { assertNotPreSplitStrand, issueInvite, PreSplitStrandIdentityError, readStrandHeaderSAppId } from './strand-membership-writer.js';
15
15
  import { MEMBERSHIP_INVITE_TTL_MS } from './strand-formation-manager.js';
16
16
  import { DEFAULT_IDENTITY_KEY_ID } from './key-store.js';
17
17
  import { loadOrCreateIdentityKey } from './identity-key.js';
@@ -19,7 +19,7 @@ import { MemoryTrustedOwnerStore } from './trusted-owner-store.js';
19
19
  import { MemoryBootstrapPeerStore } from './bootstrap-peer-store.js';
20
20
  import { MemoryStrandPeerBookStore } from './strand-peer-book.js';
21
21
  import { MemoryEnrolledMachineStore } from './enrolled-machine-store.js';
22
- import { JoinedStrandRows, KeyStoreJoinedStrandStore, MemoryJoinedStrandStore } from './joined-strand-store.js';
22
+ import { JoinedStrandSession, KeyStoreJoinedStrandStore, MemoryJoinedStrandStore } from './joined-strand-store.js';
23
23
  import { mergePeerAddrs, groupAddrsByPeerId } from './peer-addr-book.js';
24
24
  import { verifyCadrePeerVoucher } from './peer-authorization.js';
25
25
  import { ed25519PublicKeyB64FromPeerId } from './seed-bootstrap.js';
@@ -30,8 +30,8 @@ import { StrandInstanceManager, liveStrandStatus } from './strand-instance-manag
30
30
  import { PeerJoinBackfill } from './peer-join-backfill.js';
31
31
  import { deriveCohortMembers } from './strand-cohort.js';
32
32
  import { selectControlCohortDials, DEFAULT_CONTROL_COHORT_RECONCILE_MS, DEFAULT_CONTROL_COHORT_TARGET_DEGREE } from './control-cohort.js';
33
- import { dialPeerAddrs, CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS } from './peer-dial.js';
34
- import { connectionManagerTimeouts, peerJoinPushBudget, relayReservationBudgetMs, relayedDialBudgetMs, resolveLinkRoundTripMs } from './link-budget.js';
33
+ import { dialPeerAddrs, SelfRelayOnlyError, CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS } from './peer-dial.js';
34
+ import { ADMISSION_DECISION_TIMEOUT_MS, declaredCohortReadDeadlineMs, peerJoinPushBudget, relayAdmissionReserveDeadlineMs, relayReservationBudgetMs, relayedDialBudgetMs, resolveLinkRoundTripMs } from './link-budget.js';
35
35
  import { EnrollmentService } from './enrollment.js';
36
36
  import { HibernationManager } from './hibernation-manager.js';
37
37
  import { ControlDatabase, isStrandIdConflict } from './control-database.js';
@@ -40,8 +40,9 @@ import { StrandSolicitationService } from './strand-solicitation.js';
40
40
  import { createMembershipConnectionGater, DEFAULT_ENROLLMENT_WINDOW_MS, UnauthorizedReservationBudget } from './membership-connection-gater.js';
41
41
  import { StrandWakeService, dialWake } from './strand-wake-protocol.js';
42
42
  import { StrandAddrService, collectStrandAddrs } from './strand-addr-protocol.js';
43
- import { DelegateAdmissionStore, extractCircuitRelayTargets, dueRelayAnnounces, pruneStoppedStrandAnnounces, peerStrandKey } from './delegate-admission.js';
43
+ import { DelegateAdmissionStore, extractCircuitRelayTargets, dueRelayAnnounces, prunePeerStrandKeys, peerStrandKey } from './delegate-admission.js';
44
44
  import { relayCircuitAddrs, resolveListenAddrs, resolveTransportOptions, RelayReservationFailedError } from './relay-addrs.js';
45
+ import { resolveRelayServer } from './relay-server.js';
45
46
  import { replacesAdvertisedAddrs, resolveAnnounceAddrs } from './announce-addrs.js';
46
47
  import { superviseRelayReservation, resolveRelayReservationState } from './relay-reservation.js';
47
48
  import { PushFanoutService } from './push-fanout.js';
@@ -57,10 +58,10 @@ const timing = debug('sereus:cadre:timing');
57
58
  */
58
59
  const TURN_CONSUME_WINDOW_MS = 1000;
59
60
  /**
60
- * How often a running strand re-resolves its siblings' strand-network addresses
61
- * and re-merges them into its own libp2p address book
62
- * ({@link CadreNode.refreshStrandPeerAddrs}). Overridable per node via
63
- * `network.controlCohort.strandAddrRefreshMs`.
61
+ * How often a running strand re-asks each connected sibling that last ANSWERED
62
+ * (even with nothing) for its strand-network addresses, and re-merges them into
63
+ * its own libp2p address book ({@link CadreNode.refreshStrandPeerAddrs}).
64
+ * Overridable per node via `network.controlCohort.strandAddrRefreshMs`.
64
65
  *
65
66
  * Ten minutes sits comfortably inside the peerStore's one-hour address expiry
66
67
  * (`MAX_ADDRESS_AGE`, see `peer-addr-book.ts`) with headroom for several missed
@@ -68,6 +69,16 @@ const TURN_CONSUME_WINDOW_MS = 1000;
68
69
  * strand-addr RPC fan-out stays cheap.
69
70
  */
70
71
  export const STRAND_PEER_ADDR_REFRESH_MS = 10 * 60 * 1000;
72
+ /**
73
+ * How soon {@link CadreNode.refreshStrandPeerAddrs} re-asks a sibling that did NOT
74
+ * answer — unreachable, `unavailable`, or `refused`. A refusal matters most: a
75
+ * phone asking before its `CadrePeer` row has replicated to the sibling is refused
76
+ * and its delegate grant goes unrecorded, and waiting the full
77
+ * {@link STRAND_PEER_ADDR_REFRESH_MS} for the next try is the delay this bounds.
78
+ * Four reconcile ticks, so a sibling that keeps failing costs one timed-out RPC a
79
+ * minute rather than one a tick.
80
+ */
81
+ export const STRAND_PEER_ADDR_RETRY_MS = 60 * 1000;
71
82
  /**
72
83
  * A circuit relay as a strand-addr RPC target: dialed by peerId, with its
73
84
  * direct addr riding along as the fallback for a relay we hold no connection to.
@@ -75,6 +86,14 @@ export const STRAND_PEER_ADDR_REFRESH_MS = 10 * 60 * 1000;
75
86
  function relayStrandAddrPeer(relay) {
76
87
  return { peerId: relay.relayPeerId, addrs: [multiaddr(relay.relayAddr)] };
77
88
  }
89
+ /**
90
+ * Whether a sibling actually answered a strand-addr RPC — with addresses or
91
+ * without — as opposed to being unreachable, unavailable, or refusing us. Decides
92
+ * which of the refresh and retry intervals it waits before the next ask.
93
+ */
94
+ function siblingAnswered(outcome) {
95
+ return outcome === 'answered' || outcome === 'empty';
96
+ }
78
97
  /**
79
98
  * `primary` followed by the entries of `extra` it does not already contain, de-duplicated
80
99
  * and order-preserving.
@@ -169,6 +188,34 @@ function requireMatchingStrandRow(live, desired, situation) {
169
188
  }
170
189
  return live;
171
190
  }
191
+ /**
192
+ * Await `work` unless `signal` aborts first: `true` once `work` resolves, `false` when the
193
+ * signal aborted before it did (already at the call, or during the wait). A rejection of
194
+ * `work` that lands before the abort propagates. `work` is NOT cancelled — a caller that
195
+ * gets `false` owns its late settlement. The abort listener is detached on both endings, so
196
+ * a long-lived signal does not collect listeners.
197
+ */
198
+ async function resolvesBeforeAbort(work, signal) {
199
+ if (!signal) {
200
+ await work;
201
+ return true;
202
+ }
203
+ if (signal.aborted) {
204
+ return false;
205
+ }
206
+ let detach = () => { };
207
+ const abortedFirst = new Promise((resolve) => {
208
+ const onAbort = () => resolve(false);
209
+ signal.addEventListener('abort', onAbort, { once: true });
210
+ detach = () => signal.removeEventListener('abort', onAbort);
211
+ });
212
+ try {
213
+ return await Promise.race([work.then(() => true), abortedFirst]);
214
+ }
215
+ finally {
216
+ detach();
217
+ }
218
+ }
172
219
  /**
173
220
  * CadreNode is the main entry point for a cadre member.
174
221
  * It manages:
@@ -289,6 +336,19 @@ export class CadreNode {
289
336
  * {@link getDiscoveredStrands}.
290
337
  */
291
338
  this.discoveredStrands = new Map();
339
+ /**
340
+ * The sApp id each storage replica read from its own `Strand.Header` — {@link getSAppId}'s
341
+ * answer for a strand no local config claims, so an `sAppId` strand filter can reject a
342
+ * replica of some other app instead of admitting it provisionally forever.
343
+ *
344
+ * Cleared by {@link cleanup} only, deliberately NOT by {@link detachStrand}: the watcher's
345
+ * filter rejection stops a replica through that very method, and forgetting the id there
346
+ * would have the next poll find it unknown again, re-admit the strand provisionally and
347
+ * relaunch the replica — once every other poll, forever. A strand id's sApp never changes,
348
+ * and the map is bounded by the strands this party has published, like
349
+ * {@link discoveredStrands}.
350
+ */
351
+ this.replicaSAppIds = new Map();
292
352
  /**
293
353
  * Most-recently pushed invite addresses (see {@link setInviteAddresses}).
294
354
  * When non-null these take priority over `libp2pNode.getMultiaddrs()` when
@@ -365,15 +425,18 @@ export class CadreNode {
365
425
  */
366
426
  this.delegateAnnounceAt = new Map();
367
427
  /**
368
- * When each running strand last had its siblings' strand addresses re-resolved
369
- * into its own address book, keyed by strandId. Throttles
370
- * {@link refreshStrandPeerAddrs} to once per {@link STRAND_PEER_ADDR_REFRESH_MS}
371
- * per strand so the 15 s reconcile tick never becomes per-tick RPC chatter.
372
- * Entries for strands that are no longer running are pruned on each pass, so a
373
- * hibernated-then-resumed strand refreshes immediately rather than inheriting a
374
- * stale stamp.
428
+ * When each connected sibling is next due a strand-addr RPC for each running
429
+ * strand, keyed `peerStrandKey(siblingControlPeerId, strandId)` → epoch ms; a
430
+ * missing key is due. Bounds {@link refreshStrandPeerAddrs}'s fan-out per
431
+ * (sibling, strand) rather than per strand, so a sibling that connects after a
432
+ * pass is asked on the next 15 s tick instead of waiting out a stamp another
433
+ * sibling's answer set. An answer (even an empty one) makes the sibling due again
434
+ * in {@link STRAND_PEER_ADDR_REFRESH_MS}; no answer, in
435
+ * {@link STRAND_PEER_ADDR_RETRY_MS}. Keys whose strand stopped running or whose
436
+ * sibling is no longer connected are pruned every pass, so a resumed strand and a
437
+ * reconnected sibling are both asked at once.
375
438
  */
376
- this.strandPeerAddrRefreshAt = new Map();
439
+ this.strandAddrAskDueAt = new Map();
377
440
  /**
378
441
  * Node-local strand peer book (see `strand-peer-book.ts`): per strand, the strand
379
442
  * peers this node has met and their last-known strand-network addresses. Three
@@ -504,22 +567,22 @@ export class CadreNode {
504
567
  */
505
568
  this.enrolledMachineStore = null;
506
569
  /**
507
- * Node-local record of the strands this node joined from ANOTHER party (see
508
- * `joined-strand-store.ts`) — the only thing that names them after a restart, since
509
- * this party's control database holds no row for them. Written by {@link formStrand}
510
- * and by an {@link addStrand} of a foreign row; forgotten by {@link forgetJoinedStrand}
511
- * and on self-revocation. Adopted from `config.joinedStrands.store`, else built over
570
+ * Node-local record of the strands this node joined from ANOTHER party and has not yet
571
+ * published party-wide (see `joined-strand-store.ts`). Written by {@link formStrand}
572
+ * and by an {@link addStrand} of a foreign row; drained once the party-wide
573
+ * `JoinedStrand` row is visible. Adopted from `config.joinedStrands.store`, else built over
512
574
  * `config.keyStore`, else in-memory, by {@link initializeJoinedStrandStore}. Like
513
575
  * {@link bootstrapPeerStore} it is deliberately NOT cleared by {@link cleanup}.
514
576
  */
515
577
  this.joinedStrandStore = null;
516
578
  /**
517
- * The strand watcher's view of {@link joinedStrandStore}: its records unioned with the
518
- * control rows each poll. Per SESSION, unlike the store — rebuilt at every
579
+ * This session's joined strands: {@link joinedStrandStore} and the party-wide
580
+ * `JoinedStrand` table, unioned with the control rows each watcher poll, published and
581
+ * removed by the reconcile pass. Per SESSION, unlike the store — rebuilt at every
519
582
  * {@link start}, which is what ends a revoked join's "keep offering until this session
520
- * ends" (see `JoinedStrandRows.forgetAfterThisSession`).
583
+ * ends" (see `JoinedStrandSession.forgetAfterThisSession`).
521
584
  */
522
- this.joinedStrandRows = null;
585
+ this.joinedStrands = null;
523
586
  /** Initial self-registration timer (see {@link scheduleSelfRegistration}). */
524
587
  this.selfRegistrationTimer = null;
525
588
  /** TTL heartbeat that re-publishes the self record before it goes stale. */
@@ -644,24 +707,28 @@ export class CadreNode {
644
707
  /** `connection:close` listener clearing a peer's TURN flag (teardown in {@link stopRecordRefresh}). */
645
708
  this.turnConnectionCloseHandler = null;
646
709
  this.config = config;
710
+ this.hostUnclaimedStrands = config.hostUnclaimedStrands ?? config.profile === 'storage';
647
711
  this.strandManager = new StrandInstanceManager();
648
712
  this.enrollmentService = new EnrollmentService();
649
- this.unauthorizedRelayReservations = new UnauthorizedReservationBudget(config.network?.unauthorizedRelayReservationCap);
713
+ this.relayServer = resolveRelayServer(config.network, config.profile);
714
+ this.unauthorizedRelayReservations = new UnauthorizedReservationBudget(config.network?.unauthorizedRelayReservationCap, this.relayServer.init.reservations.reservationTtl);
650
715
  // Create hibernation manager with callbacks
651
716
  const hibernationCallbacks = {
652
717
  onIdle: async (strandId) => this.handleStrandIdle(strandId),
653
718
  onHibernate: async (strandId) => this.handleStrandHibernate(strandId),
654
719
  onWake: async (strandId) => this.handleStrandWake(strandId),
655
- onCheckIn: async (strandId) => this.handleStrandCheckIn(strandId)
720
+ onCheckIn: async (strandId) => this.handleStrandCheckIn(strandId),
721
+ isQuiescing: (strandId) => this.strandManager.isQuiescing(strandId)
656
722
  };
657
723
  this.hibernationManager = new HibernationManager(config.hibernation ?? { enabled: false }, hibernationCallbacks);
658
724
  log('CadreNode created for party: %s', config.controlNetwork.partyId);
659
725
  }
660
726
  /**
661
- * SAppIdLookup implementation - get sAppId for a strand
727
+ * SAppIdLookup implementation - get sAppId for a strand: the claiming config's, else
728
+ * the one a storage replica read from the strand's own `Strand.Header`.
662
729
  */
663
730
  getSAppId(strandId) {
664
- return this.sAppConfigs.get(strandId)?.id;
731
+ return this.sAppConfigs.get(strandId)?.id ?? this.replicaSAppIds.get(strandId);
665
732
  }
666
733
  /**
667
734
  * Get the peer ID of this node (available after start)
@@ -777,6 +844,7 @@ export class CadreNode {
777
844
  return;
778
845
  }
779
846
  log('Starting CadreNode for party: %s', this.config.controlNetwork.partyId);
847
+ this.logRelayServerSettings();
780
848
  try {
781
849
  const tTotal = performance.now();
782
850
  // Config pre-flight, inside the guarded region: resolving the listen addrs it reads
@@ -907,7 +975,7 @@ export class CadreNode {
907
975
  getStrand: (strandId) => this.strandManager.getInstance(strandId),
908
976
  wake: (strandId) => this.wakeStrand(strandId),
909
977
  });
910
- this.strandWakeService.initialize(this.controlNode);
978
+ await this.strandWakeService.initialize(this.controlNode);
911
979
  // Register the control-network strand-address responder: a same-cadre peer
912
980
  // resolving a strand's bootstrap seed asks us for our live strand-network
913
981
  // multiaddrs (its CadrePeer row only knows our *control* address). Gated on
@@ -921,7 +989,7 @@ export class CadreNode {
921
989
  getStrandMultiaddrs: (strandId) => this.getStrandMultiaddrs(strandId),
922
990
  onDelegateAnnounce: (announcer, strandId, delegate) => this.grantDelegateAdmission(announcer, strandId, delegate),
923
991
  });
924
- this.strandAddrService.initialize(this.controlNode);
992
+ await this.strandAddrService.initialize(this.controlNode);
925
993
  // Server-side push-wake fan-out: only when push is configured.
926
994
  if (this.config.push) {
927
995
  this.pushFanoutService = this.buildPushFanout(this.config.push);
@@ -1161,7 +1229,7 @@ export class CadreNode {
1161
1229
  }
1162
1230
  /**
1163
1231
  * Construct (or adopt) the node-local joined-strand store (see
1164
- * {@link joinedStrandStore}) and this session's watcher view over it.
1232
+ * {@link joinedStrandStore}) and this session's {@link joinedStrands} over it.
1165
1233
  *
1166
1234
  * The store instance is kept across stop()→start(); the view is rebuilt. A store
1167
1235
  * scoped to a different party is a configuration error, fail closed: its joins
@@ -1178,7 +1246,7 @@ export class CadreNode {
1178
1246
  `but this node serves party ${partyId} — refusing to offer another party's joined strands`);
1179
1247
  }
1180
1248
  this.joinedStrandStore = store;
1181
- this.joinedStrandRows = new JoinedStrandRows(store);
1249
+ this.joinedStrands = new JoinedStrandSession(store, this.createPartyJoinedStrandLedger());
1182
1250
  }
1183
1251
  /**
1184
1252
  * Construct (or adopt) the node-local strand peer book (see
@@ -1391,7 +1459,7 @@ export class CadreNode {
1391
1459
  const scope = controlStorageScope(this.config.controlNetwork.partyId);
1392
1460
  // The second seam that hands a scope key to an embedder's provider; the first
1393
1461
  // (`StrandInstanceManager.startStrand`) asserts the stricter strand rule. Holds by
1394
- // construction today — base64url is inside the charset — so this guards a future
1462
+ // construction today — lowercase hex is inside the charset — so this guards a future
1395
1463
  // edit to `controlStorageScope`, not a reachable input.
1396
1464
  assertScopeKeyCharset(scope);
1397
1465
  const resolved = typeof provider === 'function' ? provider(scope) : provider;
@@ -1458,7 +1526,6 @@ export class CadreNode {
1458
1526
  // nothing); anything outside {tcp, ws/wss, p2p-circuit} throws here rather than
1459
1527
  // being silently dropped at bring-up. See `relay-addrs.ts`.
1460
1528
  const transportOptions = resolveTransportOptions(network, listenAddrs);
1461
- const enableRelay = this.relayServerEnabled();
1462
1529
  // The control node's own storage, resolved once per runtime (see
1463
1530
  // {@link resolveControlStorage}) rather than per call.
1464
1531
  const controlStorageProvider = this.resolveControlStorage();
@@ -1468,7 +1535,10 @@ export class CadreNode {
1468
1535
  networkName: this.controlNetworkName(),
1469
1536
  storage: controlStorageProvider,
1470
1537
  fretProfile: profile === 'storage' ? 'core' : 'edge',
1471
- relay: enableRelay,
1538
+ relay: this.relayServer.enabled,
1539
+ // Merged party-run defaults: no per-connection data/duration cap, a store sized for
1540
+ // one party's NAT'd machines. Strand nodes get the same init (`relay-server.ts`).
1541
+ ...(this.relayServer.enabled && { relayServerInit: this.relayServer.init }),
1472
1542
  // Fixed, and deliberately above any party's node count: every member reads the
1473
1543
  // whole control database, so a cohort that excludes a member leaves it dependent
1474
1544
  // on read repair — which cannot converge at a two-member cohort. Not a knob;
@@ -1484,12 +1554,14 @@ export class CadreNode {
1484
1554
  // itself, so the unknown case is provably byte-for-byte the old behaviour.
1485
1555
  // The yardstick moves ALONE: `assumedClusterSize` stays pinned at 2, because a
1486
1556
  // party of phones cannot promise three quarters of its machines are awake.
1487
- // With neither declared this is still the frozen constant by identity, which is the
1488
- // production path. A degenerate deadline is Optimystic's to refuse, in
1489
- // createControlNode below.
1557
+ // The read deadline is the host's own, else two link round trips at the declared
1558
+ // `linkRoundTripMs`, else nothing — the frozen constant already carries the same
1559
+ // derivation at the default declaration (`link-budget.ts`). With neither declared this
1560
+ // is still the frozen constant by identity, which is the production path. A degenerate
1561
+ // deadline is Optimystic's to refuse, in createControlNode below.
1490
1562
  clusterPolicy: controlClusterPolicy({
1491
1563
  enrolledMachines: this.declaredEnrolledMachines,
1492
- cohortQueryTimeoutMs: network?.cohortQueryTimeoutMs
1564
+ cohortQueryTimeoutMs: declaredCohortReadDeadlineMs(network)
1493
1565
  }),
1494
1566
  arachnode: { enableRingZulu: profile === 'storage' },
1495
1567
  ...(identityKey && { privateKey: identityKey }),
@@ -1500,10 +1572,12 @@ export class CadreNode {
1500
1572
  // whose event loop is saturated by pure-JS Noise crypto. A configured value
1501
1573
  // replaces the default whole (see DEFAULT_CONNECTION_MONITOR).
1502
1574
  connectionMonitor: network?.connectionMonitor ?? DEFAULT_CONNECTION_MONITOR,
1503
- // libp2p's own dial and inbound-upgrade limits, from the same declared link as every
1504
- // cadre dial budget. Left to db-p2p, both stay at 10 s, which cannot open a relayed
1505
- // connection above a 2.5 s round trip — and the listener's side of that fails silently.
1506
- connectionManager: connectionManagerTimeouts(network?.linkRoundTripMs),
1575
+ // The declared link every cadre budget is derived from, stated to Optimystic too so it
1576
+ // derives its own deadlines from the same number: its request dials and responses, its
1577
+ // block pushes, and libp2p's `dialTimeout` and `inboundUpgradeTimeout`. Always stated,
1578
+ // default included: undeclared, Optimystic keeps LAN deadlines that cannot open a
1579
+ // relayed connection at the link sereus supports (`link-budget.ts`).
1580
+ linkRoundTripMs: resolveLinkRoundTripMs(network?.linkRoundTripMs),
1507
1581
  // `{ wsPort }` when a listen entry names WebSocket, otherwise `{}` — and always
1508
1582
  // `{}` when `network.transports` is set, since the embedder owns transport policy
1509
1583
  // then. Spread NEXT to `transports` because the two answer the same question.
@@ -1526,7 +1600,7 @@ export class CadreNode {
1526
1600
  admitInbound: (remotePeerId) => this.admitInboundControlConnection(remotePeerId),
1527
1601
  admitRelayReservation: (remotePeerId) => this.admitControlRelayReservation(remotePeerId),
1528
1602
  bringUpInFlight: () => this.controlBringUpInFlight
1529
- }, network?.connectionGater),
1603
+ }, network?.connectionGater, ADMISSION_DECISION_TIMEOUT_MS, relayAdmissionReserveDeadlineMs(network?.linkRoundTripMs)),
1530
1604
  // Fail-closed per-stream authorization for the four Optimystic control-DB
1531
1605
  // protocols — the members-only layer the connection gater's stranger
1532
1606
  // carve-outs cannot express (see authorizeInboundControlStream). Control
@@ -1536,15 +1610,17 @@ export class CadreNode {
1536
1610
  return nodeOptions;
1537
1611
  }
1538
1612
  /**
1539
- * Does this node's CONTROL libp2p run the circuit-relay server? An explicit
1540
- * `network.enableRelay` wins; otherwise storage-profile nodes default to on
1541
- * (better connectivity/uptime). Shared by {@link buildControlNodeOptions}
1542
- * (which configures the server from it) and
1543
- * {@link admitInboundControlConnection} (whose deny/admit-for-relay branch
1544
- * must agree with whether a reservation is even servable here).
1613
+ * One debug line naming what this machine's relay server forwards and holds —
1614
+ * the same fields the dedicated relay container prints at boot
1615
+ * (`ops/docker/libp2p-infra/src/main.ts`). Once per start, not per strand:
1616
+ * strand nodes resolve the same settings from the same config.
1545
1617
  */
1546
- relayServerEnabled() {
1547
- return this.config.network?.enableRelay ?? (this.config.profile === 'storage');
1618
+ logRelayServerSettings() {
1619
+ if (!this.relayServer.enabled) {
1620
+ return;
1621
+ }
1622
+ const { applyDefaultLimit, maxReservations, reservationTtl } = this.relayServer.init.reservations;
1623
+ log('Relay server on: applyDefaultLimit=%s maxReservations=%d reservationTtl=%dms unauthorizedCap=%d', applyDefaultLimit, maxReservations, reservationTtl, this.unauthorizedRelayReservations.cap);
1548
1624
  }
1549
1625
  /**
1550
1626
  * Decide whether an inbound CONTROL-network connection from `remotePeerId`
@@ -1593,7 +1669,7 @@ export class CadreNode {
1593
1669
  * accepted it, exactly like the unreplicated-membership-row case below.
1594
1670
  *
1595
1671
  * When every check falls through, the verdict depends on whether this node
1596
- * runs the circuit-relay server ({@link relayServerEnabled}): without one,
1672
+ * runs the circuit-relay server ({@link relayServer}): without one,
1597
1673
  * `'deny'`; with one, `'admit-for-relay'` — a circuit-relay reservation is
1598
1674
  * established by the reserving peer DIALING the relay, so a connection deny
1599
1675
  * here kills the reservation, and that deny is NOT self-healing: an outbound
@@ -1643,7 +1719,7 @@ export class CadreNode {
1643
1719
  log('admitInboundControlConnection: outstanding-invitation check threw for %s — admitting (fail-open): %o', remotePeerId, error);
1644
1720
  return 'admit';
1645
1721
  }
1646
- if (this.relayServerEnabled()) {
1722
+ if (this.relayServer.enabled) {
1647
1723
  log('admitInboundControlConnection: admitting %s FOR RELAY ONLY — not an authorized member and no enrollment path open; the gater drops the connection unless a reservation is admitted', remotePeerId);
1648
1724
  return 'admit-for-relay';
1649
1725
  }
@@ -1847,7 +1923,9 @@ export class CadreNode {
1847
1923
  // the count of machines serving the network — the quantity
1848
1924
  // `resolveRepairYardstick` asks for. It is NOT that quantity for a strand, which
1849
1925
  // launches only on machines whose embedder registered its sApp config (see
1850
- // {@link addStrand}), so this number must never be routed to a strand node:
1926
+ // {@link addStrand}) plus storage-profile machines hosting it as a storage replica
1927
+ // ({@link CadreNodeConfig.hostUnclaimedStrands}) whose filter admits it — phones
1928
+ // serve only what their app claims — so this number must never be routed to a strand node:
1851
1929
  // over-declaring pins Optimystic's repair corroboration floor at two peers and a
1852
1930
  // strand that can field only one can then never repair. `launchStrand` therefore
1853
1931
  // declares nothing; see the NOTE there.
@@ -1935,9 +2013,9 @@ export class CadreNode {
1935
2013
  return this.bootstrapPeerIds;
1936
2014
  }
1937
2015
  /**
1938
- * What the strand watcher polls: this party's control rows plus a row per remembered
1939
- * cross-party join (see {@link joinedStrandRows}), so a joined strand is re-offered
1940
- * and relaunched on the same path as the party's own.
2016
+ * What the strand watcher polls: this party's control rows plus a row per cross-party
2017
+ * join (see {@link joinedStrands}), so a joined strand is offered and relaunched on
2018
+ * the same path as the party's own.
1941
2019
  */
1942
2020
  createStrandQueryable() {
1943
2021
  return {
@@ -1948,10 +2026,73 @@ export class CadreNode {
1948
2026
  }
1949
2027
  log('Querying strands from control database');
1950
2028
  const control = await this.controlDatabase.queryStrands();
1951
- return this.joinedStrandRows ? await this.joinedStrandRows.withControlRows(control) : control;
2029
+ return this.joinedStrands ? await this.joinedStrands.withControlRows(control) : control;
1952
2030
  }
1953
2031
  };
1954
2032
  }
2033
+ /**
2034
+ * The party-wide `JoinedStrand` table as {@link joinedStrands} reads and writes it.
2035
+ * Reads {@link controlDatabase} at call time, so start-up order does not matter.
2036
+ */
2037
+ createPartyJoinedStrandLedger() {
2038
+ const database = () => {
2039
+ if (!this.controlDatabase) {
2040
+ throw new Error('CadreNode must be started before using the party-wide joined-strand table');
2041
+ }
2042
+ return this.controlDatabase;
2043
+ };
2044
+ return {
2045
+ // NOTE: one more control read per watcher poll (5 s), and for a party that never
2046
+ // joined anything it reads a never-written block, which consults the cohort. If poll
2047
+ // cost shows up in a device profile, cache the list and re-read it on the reconcile
2048
+ // cadence.
2049
+ list: () => database().queryJoinedStrands(),
2050
+ names: async (strandId) => (await database().queryStrand(strandId)) !== null
2051
+ || (await database().queryJoinedStrand(strandId)) !== null,
2052
+ canSign: async () => (await this.enrolledOwnerSigningKey()) !== null,
2053
+ publish: async (record) => {
2054
+ const signingKey = await this.enrolledOwnerSigningKey();
2055
+ if (!signingKey) {
2056
+ throw new Error(`Cannot publish joined strand ${record.Id}: this machine is not an enrolled owner`);
2057
+ }
2058
+ try {
2059
+ await database().insertJoinedStrand(record, signingKey.publicKeyB64, signMessageWith(signingKey.privateKeyB64));
2060
+ }
2061
+ catch (error) {
2062
+ // Another machine of the party published this join first; its row wins.
2063
+ if (!isStrandIdConflict(error, 'JoinedStrand')) {
2064
+ throw error;
2065
+ }
2066
+ }
2067
+ },
2068
+ remove: async (strandId) => {
2069
+ const signingKey = await this.enrolledOwnerSigningKey();
2070
+ if (signingKey) {
2071
+ return database().deleteJoinedStrand(strandId, signingKey.publicKeyB64, signMessageWith(signingKey.privateKeyB64));
2072
+ }
2073
+ if (await database().queryJoinedStrand(strandId)) {
2074
+ throw new Error(`Cannot leave strand ${strandId} for the whole party: the join is recorded party-wide, and ` +
2075
+ `removing it takes an owner machine, which this one is not. stopStrand('${strandId}') stops ` +
2076
+ 'it on this machine only.');
2077
+ }
2078
+ return false;
2079
+ }
2080
+ };
2081
+ }
2082
+ /**
2083
+ * This machine's owner signing key when it can make owner-gated control writes: its seed
2084
+ * bootstrap holds an owner key (`SeedBootstrapService.canAuthorize`) and the party's
2085
+ * `OwnerKey` table enrolls it. A phone that ran self-genesis after another machine
2086
+ * founded the party passes the first test and not the second (`runOwnerGenesis` in the
2087
+ * reference apps), and a write it signed would only be refused.
2088
+ */
2089
+ async enrolledOwnerSigningKey() {
2090
+ const signingKey = this.seedBootstrapService?.canAuthorize() ? this.getSelfSigningKey() : null;
2091
+ if (!signingKey || !this.controlDatabase) {
2092
+ return null;
2093
+ }
2094
+ return (await this.controlDatabase.getOwnerKeys()).has(signingKey.publicKeyB64) ? signingKey : null;
2095
+ }
1955
2096
  /**
1956
2097
  * Schedule the node's initial self-record publish + ongoing refresh shortly
1957
2098
  * after start (non-blocking). {@link registerSelf} is idempotent and safely
@@ -2569,14 +2710,18 @@ export class CadreNode {
2569
2710
  // Ride this pass's cadence to refresh the per-stream gate's materialized
2570
2711
  // authorized set — membership changes that ARRIVED BY REPLICATION (rather
2571
2712
  // than a local write) are picked up here, bounding the snapshot's staleness
2572
- // to the reconcile interval.
2713
+ // to the time between pass starts: the reconcile interval, or the previous
2714
+ // pass's length when that is longer (passes are single-flight, and one
2715
+ // unreachable sibling's dial alone can take `controlDialBudget().totalMs`).
2573
2716
  // NOTE: this refresh and the sibling enumeration below each run their own
2574
2717
  // CadrePeer query (two reads per pass), plus a third from
2575
- // `refreshStrandPeerAddrs` on the passes where a strand is due AND this node
2576
- // holds a control connection (one read for the whole pass, not one per
2577
- // strand). Each also reads Revocation first. Before the Revocation ledger
2578
- // marker exists (filed below, once connected) that block is missing, so every
2579
- // one of those reads consults the cohort about it; once the marker exists every
2718
+ // `refreshStrandPeerAddrs` on every pass where a strand is running AND this
2719
+ // node holds a control connection (one read for the whole pass, not one per
2720
+ // strand; it runs even when no sibling is due, because pruning departed
2721
+ // siblings needs the current target set). Each also reads Revocation first.
2722
+ // Before the Revocation ledger marker exists (filed below, once connected)
2723
+ // that block is missing, so every one of those reads consults the cohort
2724
+ // about it; once the marker exists every
2580
2725
  // block they touch is held and none of them does (both states pinned in
2581
2726
  // control-founding-consult-budget.spec.ts). If those reads ever get costly,
2582
2727
  // share one row-set across all three.
@@ -2592,8 +2737,8 @@ export class CadreNode {
2592
2737
  if (!this._running || !this.controlNode || !this.controlDatabase) {
2593
2738
  return { dialed: [] };
2594
2739
  }
2595
- // Then re-warm each running strand's own address book from its siblings, on
2596
- // its own (much longer) throttle. Same reasoning as warmSiblingAddrBook
2740
+ // Then re-warm each running strand's own address book from its peer book and
2741
+ // from whichever siblings are due an ask. Same reasoning as warmSiblingAddrBook
2597
2742
  // below, one layer down: replication runs on the STRAND network, and every
2598
2743
  // layer under cadre-core dials strand peers by bare peer id.
2599
2744
  await this.refreshStrandPeerAddrs();
@@ -2662,6 +2807,19 @@ export class CadreNode {
2662
2807
  if (!this._running || !this.controlNode || !this.controlDatabase) {
2663
2808
  return { dialed: [] };
2664
2809
  }
2810
+ // Publish this machine's unpublished cross-party joins party-wide and remove the rows a
2811
+ // self-revocation queued (JoinedStrandSession.syncWithParty). Connected-only for the
2812
+ // reap's reason above; owner-only by the session's own signer check. Nothing is urgent:
2813
+ // a join reaches the party within one pass of this machine being connected.
2814
+ try {
2815
+ await this.joinedStrands?.syncWithParty();
2816
+ }
2817
+ catch (error) {
2818
+ log('reconcileControlCohort: joined-strand sync failed (retrying next pass): %o', error);
2819
+ }
2820
+ if (!this._running || !this.controlNode || !this.controlDatabase) {
2821
+ return { dialed: [] };
2822
+ }
2665
2823
  }
2666
2824
  // 1. Enumerate known siblings. This membership read is itself a pull-on-read
2667
2825
  // that helps the CadrePeer table converge — a reader-only node converges
@@ -2875,6 +3033,27 @@ export class CadreNode {
2875
3033
  totalMs: cohort?.dialTimeoutMs ?? CONTROL_COHORT_DIAL_ADDRESS_ATTEMPTS * perAddressMs,
2876
3034
  };
2877
3035
  }
3036
+ /**
3037
+ * The link-derived limits shared by every {@link SeedBootstrapService} this node builds: its
3038
+ * owner and invite dials ({@link controlDialBudget}) and its seed delivery deadline, derived
3039
+ * from `network.linkRoundTripMs`. One helper so the four construction sites cannot drift.
3040
+ */
3041
+ seedServiceBudgets() {
3042
+ return {
3043
+ dialBudget: this.controlDialBudget(),
3044
+ linkRoundTripMs: this.config.network?.linkRoundTripMs,
3045
+ };
3046
+ }
3047
+ /**
3048
+ * {@link collectStrandAddrs} at this node's declared `network.linkRoundTripMs`, so each ask's
3049
+ * deadline derives from it. One helper so the four call sites cannot drift.
3050
+ */
3051
+ async collectSiblingStrandAddrs(controlNode, peers, strandId, delegatePeerId) {
3052
+ return await collectStrandAddrs(controlNode, peers, strandId, {
3053
+ delegatePeerId,
3054
+ linkRoundTripMs: this.config.network?.linkRoundTripMs,
3055
+ });
3056
+ }
2878
3057
  /**
2879
3058
  * Dial one sibling from its already-resolved addresses, best-effort. Returns
2880
3059
  * whether the dial resolved (false when no address resolves or the dial fails).
@@ -2883,7 +3062,9 @@ export class CadreNode {
2883
3062
  * the {@link controlDialBudget} expiring) is logged and swallowed so one
2884
3063
  * unreachable sibling never aborts the pass — exactly like
2885
3064
  * {@link SeedBootstrapService.applySeed}'s owner-dial loop. A failed dial is
2886
- * simply retried on the next pass.
3065
+ * simply retried on the next pass. A sibling whose every address relays
3066
+ * through this node ({@link SelfRelayOnlyError}) is not dialed at all and gets
3067
+ * a one-line log instead: only the sibling can reconnect.
2887
3068
  */
2888
3069
  async dialControlSibling(sibling, resolved) {
2889
3070
  const controlNode = this.controlNode;
@@ -2901,7 +3082,12 @@ export class CadreNode {
2901
3082
  return true;
2902
3083
  }
2903
3084
  catch (error) {
2904
- log('reconcileControlCohort: dial of sibling %s failed (continuing): %o', sibling.peerId, error);
3085
+ if (error instanceof SelfRelayOnlyError) {
3086
+ log('reconcileControlCohort: sibling %s is reachable only by relaying through this node; waiting for it to reconnect', sibling.peerId);
3087
+ }
3088
+ else {
3089
+ log('reconcileControlCohort: dial of sibling %s failed (continuing): %o', sibling.peerId, error);
3090
+ }
2905
3091
  return false;
2906
3092
  }
2907
3093
  }
@@ -3145,7 +3331,12 @@ export class CadreNode {
3145
3331
  return true;
3146
3332
  }
3147
3333
  catch (error) {
3148
- log('reconcileControlCohort(cold-start): dial of bootstrap peer %s failed (continuing): %o', peerId, error);
3334
+ if (error instanceof SelfRelayOnlyError) {
3335
+ log('reconcileControlCohort(cold-start): bootstrap peer %s is reachable only by relaying through this node; waiting for it to reconnect', peerId);
3336
+ }
3337
+ else {
3338
+ log('reconcileControlCohort(cold-start): dial of bootstrap peer %s failed (continuing): %o', peerId, error);
3339
+ }
3149
3340
  return false;
3150
3341
  }
3151
3342
  }
@@ -3162,7 +3353,7 @@ export class CadreNode {
3162
3353
  // local-only). The remedy: detect "wrote while alone" (0 connections is a sound
3163
3354
  // lower bound), queue the affected row, and RE-ISSUE the write once the cohort
3164
3355
  // grows (0→≥1 connection), as an idempotent monotonic update that now broadcasts.
3165
- // See docs/architecture.md (Control Network → write-while-alone durability).
3356
+ // See docs/architecture.md (Control Network Convergence → "Writes made while alone").
3166
3357
  // ============================================================================
3167
3358
  /**
3168
3359
  * Whether a control write happening now would commit local-only. A sound lower
@@ -3819,26 +4010,20 @@ export class CadreNode {
3819
4010
  // Check if we have sApp config for this strand
3820
4011
  const sAppConfig = this.sAppConfigs.get(strand.Id);
3821
4012
  if (!sAppConfig) {
3822
- log('No sAppConfig registered for strand %s - emitting strand:discovered', strand.Id);
3823
- // Strand created by another member and not yet configured locally. Surface
3824
- // it as a discovery event so the hosting app can decide whether to join
3825
- // (register a config + addStrand); the strand-agnostic seam keeps this
3826
- // class free of any app's join policy. A self-configured strand (config
3827
- // already present) keeps auto-starting below, unchanged.
3828
- //
3829
- // Recorded BEFORE the emit so a handler that synchronously drains
3830
- // `getDiscoveredStrands()` sees this strand too. The watcher does not offer the
3831
- // same strand twice — its `knownStrands` retains the id, and the one thing that
3832
- // un-retains it (a failed `addStrand`, via `StrandWatcher.forgetStrand`) leaves the
3833
- // sApp config registered, so the retry takes the auto-launch branch below rather
3834
- // than this one. So this map — not the event — is what a late subscriber reads.
3835
- // See the `strand:discovered` doc in types.ts.
3836
- this.discoveredStrands.set(strand.Id, strand);
3837
- this.emit('strand:discovered', { strandId: strand.Id, strand });
3838
- return;
4013
+ this.announceDiscoveredStrand(strand);
4014
+ // Announce-only unless this node hosts storage replicas. Also skipped when a
4015
+ // listener claimed the strand synchronously (an `addStrand` call registers its
4016
+ // config before its first await): that claim is launching it with the app's schema,
4017
+ // and a replica launch here would only race it.
4018
+ if (!this.hostUnclaimedStrands || this.sAppConfigs.has(strand.Id)) {
4019
+ return;
4020
+ }
3839
4021
  }
3840
4022
  try {
3841
- await this.launchStrand(strand, sAppConfig);
4023
+ const instance = await this.launchStrand(strand, sAppConfig);
4024
+ if (!sAppConfig) {
4025
+ void this.recordReplicaSAppId(instance.strandId);
4026
+ }
3842
4027
  }
3843
4028
  catch (error) {
3844
4029
  log('Error starting strand %s: %o', strand.Id, error);
@@ -3855,6 +4040,59 @@ export class CadreNode {
3855
4040
  throw error;
3856
4041
  }
3857
4042
  }
4043
+ /**
4044
+ * Offer a strand no local config claims to the hosting app as `strand:discovered`, so
4045
+ * it can decide whether to join (register a config + addStrand); the strand-agnostic
4046
+ * seam keeps this class free of any app's join policy.
4047
+ *
4048
+ * Once per strand: a storage-replica launch that fails is retried by the watcher
4049
+ * (`StrandWatcher.forgetStrand` + backoff), and each retry comes back through
4050
+ * {@link handleStrandAdded} with no config — the app must still see one announcement.
4051
+ * The other thing that un-retains a strand in the watcher (a failed `addStrand`) leaves
4052
+ * the sApp config registered, so that retry takes the claimed branch instead.
4053
+ *
4054
+ * Recorded BEFORE the emit so a handler that synchronously drains
4055
+ * `getDiscoveredStrands()` sees this strand too. So this map — not the event — is what
4056
+ * a late subscriber reads. See the `strand:discovered` doc in types.ts.
4057
+ *
4058
+ * NOTE: a replica launch that keeps failing leaves the watcher not tracking the strand,
4059
+ * so if its control row is removed during the backoff no `handleStrandRemoved` arrives
4060
+ * and this entry outlives the row. Needs a persistently failing launch AND a removal
4061
+ * inside the backoff; if it is ever seen, have the watcher report removal of rows it
4062
+ * forgot, since `detachStrand` is already a no-op for an untracked instance.
4063
+ */
4064
+ announceDiscoveredStrand(strand) {
4065
+ if (this.discoveredStrands.has(strand.Id)) {
4066
+ return;
4067
+ }
4068
+ log('No sAppConfig registered for strand %s - emitting strand:discovered', strand.Id);
4069
+ this.discoveredStrands.set(strand.Id, strand);
4070
+ this.emit('strand:discovered', { strandId: strand.Id, strand });
4071
+ }
4072
+ /**
4073
+ * Record the sApp id a storage replica's `Strand.Header` names, for {@link getSAppId}.
4074
+ * Runs whenever a replica's database may have just been published (launch, the
4075
+ * first-sync gate opening, a wake); a no-op for a claimed strand, an unpublished
4076
+ * database, or an id already recorded. Never throws: a failed read logs and leaves the
4077
+ * id unknown, so an `sAppId` filter keeps the strand provisionally admitted — a
4078
+ * syncing replica, which is harmless.
4079
+ */
4080
+ async recordReplicaSAppId(strandId) {
4081
+ const database = this.strandManager.getInstance(strandId)?.database;
4082
+ if (!database || this.sAppConfigs.has(strandId) || this.replicaSAppIds.has(strandId)) {
4083
+ return;
4084
+ }
4085
+ try {
4086
+ const sAppId = await readStrandHeaderSAppId(database.getDatabase());
4087
+ if (sAppId !== undefined) {
4088
+ this.replicaSAppIds.set(strandId, sAppId);
4089
+ log('Storage replica %s serves sApp %s', strandId, sAppId);
4090
+ }
4091
+ }
4092
+ catch (error) {
4093
+ log('Could not read the sApp id of storage replica %s (left unknown): %o', strandId, error);
4094
+ }
4095
+ }
3858
4096
  async handleStrandRemoved(strandId) {
3859
4097
  log('Handling strand removed: %s', strandId);
3860
4098
  try {
@@ -3929,7 +4167,7 @@ export class CadreNode {
3929
4167
  }
3930
4168
  // Unregister strand solicitation service
3931
4169
  if (this.strandSolicitationService && this.controlNode) {
3932
- this.strandSolicitationService.unregisterResponder(this.controlNode);
4170
+ await this.strandSolicitationService.unregisterResponder(this.controlNode);
3933
4171
  this.strandSolicitationService = null;
3934
4172
  }
3935
4173
  // Stop strand watcher
@@ -3943,6 +4181,7 @@ export class CadreNode {
3943
4181
  this.sAppConfigs.clear();
3944
4182
  this.strandLaunchRefusals.clear();
3945
4183
  this.discoveredStrands.clear();
4184
+ this.replicaSAppIds.clear();
3946
4185
  // Drop delegate-admission state: the grants are scoped to the session that
3947
4186
  // recorded them, so a stop()/start() cycle on this object must not keep
3948
4187
  // admitting delegates announced under the previous one, nor carry stale
@@ -4003,6 +4242,7 @@ export class CadreNode {
4003
4242
  if (instance) {
4004
4243
  this.hibernationManager.recordActivity(instance);
4005
4244
  }
4245
+ void this.recordReplicaSAppId(strandId);
4006
4246
  this.emit('strand:writable', { strandId });
4007
4247
  }
4008
4248
  // Hibernation callbacks
@@ -4016,27 +4256,18 @@ export class CadreNode {
4016
4256
  }
4017
4257
  /**
4018
4258
  * Hibernate a strand: release its strand-network resources via the strand
4019
- * manager (stop the libp2p node, close the StrandDatabase) and mark it
4259
+ * manager (stop the libp2p node, close the StrandDatabase), which marks it
4020
4260
  * `hibernating`. A quiesced strand holds no open strand-network connections,
4021
- * transports, or DB handles. No-ops if the strand is missing; if already
4022
- * quiesced (defensive), just marks status and emits.
4261
+ * transports, or DB handles. No-ops if the strand is missing; one already quiesced
4262
+ * is only marked, and still emits.
4023
4263
  */
4024
4264
  async handleStrandHibernate(strandId) {
4025
- const instance = this.strandManager.getInstance(strandId);
4026
- if (!instance) {
4265
+ if (!this.strandManager.getInstance(strandId)) {
4027
4266
  log('handleStrandHibernate: strand %s not found', strandId);
4028
4267
  return;
4029
4268
  }
4030
- if (!instance.libp2pNode && !instance.database) {
4031
- // Already quiesced — only the status flag needs updating.
4032
- instance.status = 'hibernating';
4033
- log('Strand %s already quiesced; marked hibernating', strandId);
4034
- this.emit('strand:hibernating', { strandId });
4035
- return;
4036
- }
4037
4269
  log('Hibernating strand %s — releasing strand-network resources', strandId);
4038
4270
  await this.strandManager.quiesceStrand(strandId);
4039
- instance.status = 'hibernating';
4040
4271
  this.emit('strand:hibernating', { strandId });
4041
4272
  log('Strand %s hibernating (resources released)', strandId);
4042
4273
  }
@@ -4046,7 +4277,13 @@ export class CadreNode {
4046
4277
  * its runtime via the strand manager. If it is still live (e.g. waking an idle
4047
4278
  * strand, which retains its resources), just flip the status. Overlapping wake
4048
4279
  * triggers are coalesced upstream by `HibernationManager`, so this runs once
4049
- * per wake; `resumeStrand` is itself idempotent as a backstop.
4280
+ * per wake; a wake racing a check-in joins the check-in's rebuild in `resumeStrand`.
4281
+ *
4282
+ * A failed rebuild re-hibernates the strand (see {@link rehibernateIfResumeFailed});
4283
+ * every failure rethrows, so the waker still sees the error.
4284
+ *
4285
+ * Records no activity itself: whoever asked for the wake did ({@link wakeStrand},
4286
+ * `HibernationManager.recordActivity`), and {@link serviceWake}'s own probe must not.
4050
4287
  */
4051
4288
  async handleStrandWake(strandId) {
4052
4289
  const instance = this.strandManager.getInstance(strandId);
@@ -4055,10 +4292,14 @@ export class CadreNode {
4055
4292
  return;
4056
4293
  }
4057
4294
  // Still live (idle wake, or defensive double-wake): no rebuild needed. A joiner
4058
- // still behind its first-sync gate wakes back to `'syncing'`, not `'active'`.
4059
- if (instance.libp2pNode || instance.database) {
4295
+ // still behind its first-sync gate wakes back to `'syncing'`, not `'active'`. A
4296
+ // `'starting'` strand is mid-build (a check-in's resume, or its launch) with the node
4297
+ // attached before the database: not live yet, so it falls through and joins that build.
4298
+ // A strand being quiesced still holds its handles but is on its way down: it falls
4299
+ // through too, and its resume runs after the quiesce.
4300
+ if (instance.status !== 'starting' && (instance.libp2pNode || instance.database)
4301
+ && !this.strandManager.isQuiescing(strandId)) {
4060
4302
  instance.status = liveStrandStatus(instance);
4061
- instance.lastActivity = new Date();
4062
4303
  log('Strand %s woke (already live)', strandId);
4063
4304
  this.emit('strand:waking', { strandId });
4064
4305
  return;
@@ -4066,17 +4307,58 @@ export class CadreNode {
4066
4307
  // Quiesced: re-resolve the volatile cohort input (the seed may have grown)
4067
4308
  // and rebuild the runtime.
4068
4309
  log('Waking strand %s — rebuilding strand-network resources', strandId);
4069
- await this.resumeStrandRuntime(strandId);
4070
- instance.lastActivity = new Date();
4310
+ try {
4311
+ await this.resumeStrandRuntime(strandId);
4312
+ }
4313
+ catch (error) {
4314
+ await this.rehibernateIfResumeFailed(instance, 'Wake', error);
4315
+ throw error;
4316
+ }
4071
4317
  this.emit('strand:waking', { strandId });
4072
4318
  log('Strand %s awake (resources rebuilt)', strandId);
4073
4319
  }
4320
+ /**
4321
+ * Undo a failed {@link resumeStrandRuntime}, but only when the rebuild itself failed — this
4322
+ * caller's, or the one it joined in `resumeStrand` — which leaves the instance `'error'`. A
4323
+ * failure before the rebuild (the cohort seed read) built nothing, and may find the strand
4324
+ * mid-build or just brought up by a concurrent wake or check-in; that runtime belongs to
4325
+ * whoever is building or holding it, so quiescing it here would stop a node still in use.
4326
+ */
4327
+ async rehibernateIfResumeFailed(instance, context, error) {
4328
+ if (instance.status !== 'error') {
4329
+ log('%s of strand %s failed before its rebuild (status=%s); leaving the strand as it is: %o', context, instance.strandId, instance.status, error);
4330
+ return;
4331
+ }
4332
+ log('%s of strand %s failed; re-hibernating so a later wake or check-in retries: %o', context, instance.strandId, error);
4333
+ await this.rehibernateAfterFailedResume(instance, context);
4334
+ }
4335
+ /**
4336
+ * Put a strand whose rebuild or wake window failed back to `'hibernating'`, through a
4337
+ * best-effort quiesce that releases any runtime left up. `resumeStrand` leaves a failed
4338
+ * strand `'error'`, which nothing retries: `HibernationManager` wakes only
4339
+ * `idle`/`hibernating` strands, and reads any other status after a check-in as "woke",
4340
+ * ending its chain. Safe to run twice for one failure (a wake that joined a failed
4341
+ * check-in's rebuild): quiescing a quiesced strand only marks it.
4342
+ *
4343
+ * The quiesce writes the status itself, ordered before any resume requested meanwhile;
4344
+ * this writes it only when the quiesce failed, since a failed release leaves the status
4345
+ * alone.
4346
+ */
4347
+ async rehibernateAfterFailedResume(instance, context) {
4348
+ try {
4349
+ await this.strandManager.quiesceStrand(instance.strandId);
4350
+ }
4351
+ catch (cleanupErr) {
4352
+ log('%s cleanup quiesce for strand %s failed: %o', context, instance.strandId, cleanupErr);
4353
+ instance.status = 'hibernating';
4354
+ }
4355
+ }
4074
4356
  /**
4075
4357
  * Rebuild a quiesced strand's runtime, re-resolving the volatile cohort input
4076
4358
  * first: the discovery seed may have grown since the strand last ran. Shared by
4077
4359
  * the wake (`handleStrandWake`) and check-in (`handleStrandCheckIn`) paths so both
4078
- * apply the same fresh resolution. `resumeStrand` is idempotent
4079
- * (returns the live instance unchanged) as a backstop against double-resume.
4360
+ * apply the same fresh resolution. `resumeStrand` returns a live instance unchanged
4361
+ * and joins a rebuild already in flight, so the two paths never build twice.
4080
4362
  */
4081
4363
  async resumeStrandRuntime(strandId) {
4082
4364
  // Re-derive the transport peerId (deterministic and cheap — a quiesced
@@ -4095,6 +4377,7 @@ export class CadreNode {
4095
4377
  if (instance.libp2pNode) {
4096
4378
  await this.mergeStrandPeerAddrs(instance.libp2pNode, bootstrapNodes, strandId);
4097
4379
  }
4380
+ void this.recordReplicaSAppId(strandId);
4098
4381
  }
4099
4382
  /**
4100
4383
  * Real cohort check-in for a hibernating strand (the `onCheckIn` callback).
@@ -4127,62 +4410,77 @@ export class CadreNode {
4127
4410
  log('handleStrandCheckIn: strand %s not hibernating (status=%s); skipping', strandId, instance.status);
4128
4411
  return;
4129
4412
  }
4413
+ // Before the resume, so a wake that joins this rebuild, or activity recorded while it
4414
+ // runs, counts: the window then leaves the strand up for it.
4415
+ const activityMark = instance.lastActivity;
4416
+ // 1. Resume exactly as a wake does: re-resolve the (possibly grown) cohort
4417
+ // seed, then rebuild the runtime.
4418
+ log('Check-in: resuming strand %s to probe the cohort for pending activity', strandId);
4130
4419
  try {
4131
- // 1. Resume exactly as a wake does: re-resolve the (possibly grown) cohort
4132
- // seed, then rebuild the runtime.
4133
- log('Check-in: resuming strand %s to probe the cohort for pending activity', strandId);
4134
4420
  await this.resumeStrandRuntime(strandId);
4135
- // 2-3. Bounded window for the strand network to connect + the app to act,
4136
- // then re-hibernate-if-idle. Shared with the on-demand serviceWake.
4137
- const windowMs = this.config.hibernation?.checkInWindowMs ?? DEFAULT_CHECKIN_WINDOW_MS;
4138
- await this.runWakeWindow(instance, windowMs);
4139
4421
  }
4140
4422
  catch (err) {
4141
- // A check-in that throws part-way — resume failing on a flaky network (the
4142
- // very scenario hibernation targets), the window rejecting, or quiesce
4143
- // throwing — must leave the strand HIBERNATING, not in the `error` status
4144
- // that `resumeStrand` sets on failure. `HibernationManager.runCheckIn`
4145
- // decides wake-vs-escalate purely from `instance.status` after this
4146
- // resolves: an `error` status reads as "woke", which STOPS the check-in
4147
- // chain and strands the strand with no runtime and no future check-in.
4148
- // Forcing it back to `hibernating` (after a best-effort quiesce to release
4149
- // any partially-rebuilt runtime) makes the manager escalate the backoff and
4150
- // retry on the next tick.
4151
- log('Check-in failed for strand %s; re-hibernating to retry on backoff: %o', strandId, err);
4152
- await this.strandManager.quiesceStrand(strandId).catch((cleanupErr) => {
4153
- log('Check-in cleanup quiesce for strand %s failed: %o', strandId, cleanupErr);
4154
- });
4155
- instance.status = 'hibernating';
4423
+ // Every failure resolves: `HibernationManager.runCheckIn` decides wake-vs-escalate
4424
+ // from `instance.status` alone. A failed rebuild — on a flaky network, the very
4425
+ // scenario hibernation targets — leaves `resumeStrand`'s `error`, which reads as
4426
+ // "woke" and would STOP the chain with no runtime and no future check-in, so it goes
4427
+ // back to `hibernating` and the manager escalates the backoff and retries. A failure
4428
+ // before the rebuild (the seed read) built nothing: the strand is still `hibernating`
4429
+ // (the manager escalates), or a wake that began meanwhile is building or holding it,
4430
+ // and the manager hands the chain to that wake, whose outcome restores or ends it.
4431
+ await this.rehibernateIfResumeFailed(instance, 'Check-in', err);
4432
+ return;
4433
+ }
4434
+ // 2-3. Bounded window for the strand network to connect + the app to act,
4435
+ // then re-hibernate-if-idle. Shared with the on-demand serviceWake.
4436
+ const windowMs = this.config.hibernation?.checkInWindowMs ?? DEFAULT_CHECKIN_WINDOW_MS;
4437
+ try {
4438
+ await this.runWakeWindow(instance, activityMark, windowMs);
4439
+ }
4440
+ catch (err) {
4441
+ // The window's quiesce threw with the rebuilt runtime up: release it best-effort and
4442
+ // leave the strand `hibernating`, for the same reason as a failed rebuild above.
4443
+ log('Check-in window failed for strand %s; re-hibernating to retry on backoff: %o', strandId, err);
4444
+ await this.rehibernateAfterFailedResume(instance, 'Check-in');
4156
4445
  }
4157
4446
  }
4158
4447
  /**
4159
4448
  * Window-then-decide for a just-resumed strand, shared by the check-in timer
4160
4449
  * path ({@link handleStrandCheckIn}) and the on-demand {@link serviceWake}:
4161
4450
  *
4162
- * 1. Capture the post-resume activity marker. `recordActivity` assigns a
4163
- * FRESH `Date`, so a changed reference after the window means real
4164
- * activity landed during it — not millisecond-resolution noise.
4165
- * 2. Hold the strand live for `windowMs` so its strand network reaches the
4451
+ * 1. Hold the strand live for `windowMs` so its strand network reaches the
4166
4452
  * cohort and the app can drive pull-on-read activity.
4167
- * 3. If activity landed, leave the strand `active` (return `true`); otherwise
4168
- * quiesce and mark it `hibernating` again (return `false`).
4453
+ * 2. If activity landed since `activityMark`, leave the strand `active` (return
4454
+ * `true`); otherwise quiesce it, which marks it `hibernating` again (return `false`).
4455
+ * A wake or activity that lands during that quiesce rebuilds the strand after it.
4169
4456
  *
4170
- * @returns whether activity was observed during the window (strand left active).
4457
+ * @param activityMark - `instance.lastActivity` as the caller read it BEFORE bringing the
4458
+ * strand up. The bring-up records none, and every writer assigns a FRESH `Date`, so a
4459
+ * changed reference means a wake or activity landed during the resume or the window —
4460
+ * not millisecond-resolution noise.
4461
+ * @returns whether activity was observed (strand left active).
4171
4462
  */
4172
- async runWakeWindow(instance, windowMs) {
4463
+ async runWakeWindow(instance, activityMark, windowMs) {
4173
4464
  const strandId = instance.strandId;
4174
- const activityMark = instance.lastActivity;
4465
+ // NOTE: activity during the window arms the idle countdown, so a window longer than the
4466
+ // hint's idle + hibernate timeouts (only reachable with a custom `windowMs`; the shortest
4467
+ // default pair, archive's, is 40 s vs a 15 s window) can let the timer path quiesce the
4468
+ // strand mid-window, which this then marks live. If such windows become real, suspend the
4469
+ // idle countdown while a window holds the strand.
4175
4470
  await this.holdWakeWindow(instance, windowMs);
4176
4471
  const sawActivity = instance.lastActivity !== activityMark;
4177
4472
  if (sawActivity) {
4178
- instance.status = liveStrandStatus(instance);
4179
- this.emit('strand:waking', { strandId });
4180
- log('Wake window: strand %s saw activity during the window; staying active', strandId);
4473
+ // A force-hibernate during the window has released the runtime and marked the strand
4474
+ // `hibernating`, which stands; a wake queued behind it writes its own status.
4475
+ if (instance.libp2pNode || instance.database) {
4476
+ instance.status = liveStrandStatus(instance);
4477
+ this.emit('strand:waking', { strandId });
4478
+ }
4479
+ log('Wake window: strand %s saw activity during the window; not re-hibernating', strandId);
4181
4480
  return true;
4182
4481
  }
4183
4482
  log('Wake window: no activity for strand %s; re-hibernating', strandId);
4184
4483
  await this.strandManager.quiesceStrand(strandId);
4185
- instance.status = 'hibernating';
4186
4484
  return false;
4187
4485
  }
4188
4486
  /**
@@ -4230,9 +4528,10 @@ export class CadreNode {
4230
4528
  * published (e.g. re-attaching its own orphan after a restart) founds it, and attaching
4231
4529
  * anyone else's row joins, without the caller needing to know which it is.
4232
4530
  *
4233
- * A joined row (no `founder: true`) this party's control database does not hold — a
4234
- * strand joined from another party — is remembered in the node's joined-strand store, so it is re-offered as
4235
- * `strand:discovered` after a restart (see {@link forgetJoinedStrand}).
4531
+ * A joined row (no `founder: true`) this party's control database does not name — a
4532
+ * strand joined from another party — is remembered in the node's joined-strand store, so it
4533
+ * is re-offered as `strand:discovered` after a restart, and published party-wide by an
4534
+ * owner machine's reconcile pass (see {@link forgetJoinedStrand}).
4236
4535
  *
4237
4536
  * A rejected call leaves nothing running but DOES leave the sApp config
4238
4537
  * registered, deliberately: both an explicit retry and the {@link StrandWatcher}'s
@@ -4458,7 +4757,7 @@ export class CadreNode {
4458
4757
  catch (error) {
4459
4758
  // Only the uniqueness collision is a candidate for the idempotent reading; every
4460
4759
  // other rejection (unauthorized signer, retired stamp) must keep surfacing.
4461
- if (!isStrandIdConflict(error)) {
4760
+ if (!isStrandIdConflict(error, 'Strand')) {
4462
4761
  throw error;
4463
4762
  }
4464
4763
  const landed = await this.controlDatabase.queryStrand(trimmed);
@@ -4606,7 +4905,7 @@ export class CadreNode {
4606
4905
  * — and with it the consent re-seat foreclosure — does propagate; but the physical row
4607
4906
  * deletion cannot be replayed, and `queryStrands` reads raw (no retired-stamp filter),
4608
4907
  * so siblings that already hold the row keep running the strand until the collection
4609
- * itself converges (logged loudly; see the delete-while-alone durability note in
4908
+ * itself converges (logged loudly; see "Deletes made while alone" in
4610
4909
  * docs/architecture.md).
4611
4910
  *
4612
4911
  * A no-op (no throw, no tombstone) when the row is already absent — but a
@@ -4752,10 +5051,10 @@ export class CadreNode {
4752
5051
  * NOTE: "founding machine" here is the ROW's provenance, not the launch's resolved
4753
5052
  * `founder` flag — so an explicit `founder: false` over a row this machine published
4754
5053
  * still mints, an owner-signed write a caller that said "I am not founding" did not ask
4755
- * for. Harmless (the party needs that identity for the strand either way, and the mint
4756
- * is insert-if-absent) and unreachable today: the one explicit `founder: false` caller
4757
- * passes a row with a null `FounderOwnerKey`. If a caller ever pairs `founder: false`
4758
- * with its own published row, gate the mint on the resolved flag too.
5054
+ * for. Reached by a storage replica of a row this machine published (always a joiner,
5055
+ * see {@link launchStrand}) and kept on purpose: the party needs that identity for the
5056
+ * strand either way, the mint is insert-if-absent, and a closed-strand replica runs its
5057
+ * membership reconciler — which seats its own `MemberPeer` binding — only with a party key.
4759
5058
  */
4760
5059
  async resolveStrandPartyKey(strand, explicitKey) {
4761
5060
  if (explicitKey !== undefined) {
@@ -4921,9 +5220,18 @@ export class CadreNode {
4921
5220
  * A founder launch refused as pre-split (`PreSplitStrandIdentityError`) is recorded in
4922
5221
  * {@link strandLaunchRefusals} for the formation arm, then rethrown; a founder launch
4923
5222
  * that succeeds clears the record (it ran the bootstrap's pre-split check and passed).
5223
+ *
5224
+ * An absent `sAppConfig` launches a storage replica ({@link CadreNodeConfig.hostUnclaimedStrands}),
5225
+ * which is ALWAYS a joiner whatever the row says: the founder bootstrap writes the sApp
5226
+ * into `Strand.Header`, and a replica has none. So a self-founded row whose watcher poll
5227
+ * wins the race against its app's `addStrand` after a restart comes up as a replica — and
5228
+ * so does a `foundStrand` whose publish a watcher poll saw before its attach. A claim
5229
+ * that finds a tracked replica upgrades it in place, over the same node and store
5230
+ * ({@link StrandInstanceManager.attachSApp}), BEFORE any founding: the founder bootstrap
5231
+ * needs the sApp the attach supplies.
4924
5232
  */
4925
5233
  async launchStrand(strand, sAppConfig, founder, explicitPartyKey) {
4926
- const resolvedFounder = founder ?? this.isSelfFoundedRow(strand);
5234
+ const resolvedFounder = sAppConfig ? (founder ?? this.isSelfFoundedRow(strand)) : false;
4927
5235
  try {
4928
5236
  const instance = await this.startOrFoundStrand(strand, sAppConfig, resolvedFounder, explicitPartyKey);
4929
5237
  if (resolvedFounder) {
@@ -4944,41 +5252,8 @@ export class CadreNode {
4944
5252
  */
4945
5253
  async startOrFoundStrand(strand, sAppConfig, resolvedFounder, explicitPartyKey) {
4946
5254
  const timed = (step, op) => timedStep('startOrFoundStrand', strand.Id, step, op);
4947
- const existing = this.strandManager.getInstance(strand.Id);
4948
- if (existing) {
4949
- if (resolvedFounder) {
4950
- // The resolver runs only when the retained config lacks a party key for a
4951
- // closed strand (see foundExistingStrand), so the common watcher re-entry
4952
- // ('already-founder') still costs no control read.
4953
- const outcome = await timed('foundExistingStrand', () => this.strandManager.foundExistingStrand(strand.Id, () => this.resolveStrandPartyKey(strand, explicitPartyKey)));
4954
- if (outcome === 'needs-resume') {
4955
- try {
4956
- // Quiesced instance: the retained config now founds, but founding promises
4957
- // the bootstrap has RUN by the time the caller resolves — wake through the
4958
- // hibernation manager (coalesced with any in-flight wake, timer-aware) so
4959
- // the rebuild executes it now rather than at some eventual wake.
4960
- await timed('wakeStrand', () => this.wakeStrand(strand.Id));
4961
- // The wake's rebuild founds — UNLESS a wake was already in flight when the
4962
- // config flipped, in which case it had already read the pre-flip config and
4963
- // rebuilt as a joiner, and `wakeStrand` merely coalesced onto it. Re-run the
4964
- // (insert-if-absent) bootstrap so founding never resolves headerless.
4965
- await timed('ensureFounderBootstrap', () => this.strandManager.ensureFounderBootstrap(strand.Id));
4966
- }
4967
- catch (error) {
4968
- // The founding did not happen (e.g. the rebuild refused a pre-split strand and
4969
- // rolled back, leaving the instance tracked with no runtime): withdraw the flip
4970
- // so the next attempt re-runs the founding instead of resolving
4971
- // 'already-founder' over an instance that never founded.
4972
- this.strandManager.withdrawFounderRequest(strand.Id);
4973
- throw error;
4974
- }
4975
- }
4976
- log('launchStrand: strand %s already tracked — founder request honored (%s)', strand.Id, outcome);
4977
- }
4978
- else {
4979
- log('launchStrand: strand %s already tracked locally — skipping re-launch', strand.Id);
4980
- }
4981
- return existing;
5255
+ if (this.strandManager.getInstance(strand.Id)) {
5256
+ return this.claimTrackedStrand(strand, sAppConfig, resolvedFounder, explicitPartyKey);
4982
5257
  }
4983
5258
  // A closed strand's launch carries the party's OWN membership identity key: the
4984
5259
  // explicit attach-time key, else the control-layer StrandPartyKey row — minted here
@@ -5021,6 +5296,14 @@ export class CadreNode {
5021
5296
  // client awaits the replies).
5022
5297
  const delegatePeerId = transportKey ? peerIdFromPrivateKey(transportKey).toString() : undefined;
5023
5298
  const bootstrapNodes = await timed('resolveCohortSeed', () => this.resolveCohortSeed(strand.Id, delegatePeerId));
5299
+ // Checked again after the awaits above: another launch of this strand may have started
5300
+ // meanwhile (a replica's watcher launch racing an app's claim, in either order), and
5301
+ // `startStrand` would hand its instance back unchanged — a claim holding a replica with
5302
+ // no `App` tables, a founder request dropped. Nothing awaits between this check and
5303
+ // `startStrand`'s own, so no third launch can slip in.
5304
+ if (this.strandManager.getInstance(strand.Id)) {
5305
+ return this.claimTrackedStrand(strand, sAppConfig, resolvedFounder, explicitPartyKey);
5306
+ }
5024
5307
  const instance = await timed('strandManager.startStrand', () => this.strandManager.startStrand({
5025
5308
  strandRow: strand,
5026
5309
  sAppConfig,
@@ -5089,6 +5372,63 @@ export class CadreNode {
5089
5372
  this.emit('strand:started', { strandId: strand.Id });
5090
5373
  return instance;
5091
5374
  }
5375
+ /**
5376
+ * {@link startOrFoundStrand} for a strand the manager already tracks: a claim of a
5377
+ * storage replica gives it the app's schema in place, then a founder request founds it,
5378
+ * waking a quiesced instance so the bootstrap has run before this resolves. Emits
5379
+ * nothing — `strand:started` fired when the instance launched.
5380
+ *
5381
+ * A launch of the strand still in flight (the watcher's launch racing an app's
5382
+ * `addStrand`, in either order) is waited out first: until its build settles the tracked
5383
+ * instance is `'starting'` with no database, and returning it would resolve `addStrand`
5384
+ * with a strand the app cannot use — and skip that call's first-sync wait, which only a
5385
+ * `'syncing'` instance gets. If that launch fails, this rejects too: its record is gone.
5386
+ */
5387
+ async claimTrackedStrand(strand, sAppConfig, resolvedFounder, explicitPartyKey) {
5388
+ const timed = (step, op) => timedStep('startOrFoundStrand', strand.Id, step, op);
5389
+ const existing = await this.strandManager.whenRuntimeBuilt(strand.Id);
5390
+ if (!existing) {
5391
+ throw new Error(`Strand ${strand.Id}: the launch this one waited on failed (reported by the call that started it)`);
5392
+ }
5393
+ // Before the founder branch: the founder bootstrap writes the sApp into Strand.Header,
5394
+ // so it must run against the attached config.
5395
+ if (sAppConfig && !existing.sAppInfo) {
5396
+ const attached = await timed('attachSApp', () => this.strandManager.attachSApp(strand.Id, sAppConfig, { requireSignedSchemas: this.config.requireSignedSchemas }));
5397
+ log('launchStrand: strand %s was running as a storage replica — sApp %s claimed it (%s)', strand.Id, sAppConfig.id, attached);
5398
+ }
5399
+ if (!resolvedFounder) {
5400
+ log('launchStrand: strand %s already tracked locally — skipping re-launch', strand.Id);
5401
+ return existing;
5402
+ }
5403
+ // The resolver runs only when the retained config lacks a party key for a
5404
+ // closed strand (see foundExistingStrand), so the common watcher re-entry
5405
+ // ('already-founder') still costs no control read.
5406
+ const outcome = await timed('foundExistingStrand', () => this.strandManager.foundExistingStrand(strand.Id, () => this.resolveStrandPartyKey(strand, explicitPartyKey)));
5407
+ if (outcome === 'needs-resume') {
5408
+ try {
5409
+ // Quiesced instance: the retained config now founds, but founding promises
5410
+ // the bootstrap has RUN by the time the caller resolves — wake through the
5411
+ // hibernation manager (coalesced with any in-flight wake, timer-aware) so
5412
+ // the rebuild executes it now rather than at some eventual wake.
5413
+ await timed('wakeStrand', () => this.wakeStrand(strand.Id));
5414
+ // The wake's rebuild founds — UNLESS a wake was already in flight when the
5415
+ // config flipped, in which case it had already read the pre-flip config and
5416
+ // rebuilt as a joiner, and `wakeStrand` merely coalesced onto it. Re-run the
5417
+ // (insert-if-absent) bootstrap so founding never resolves headerless.
5418
+ await timed('ensureFounderBootstrap', () => this.strandManager.ensureFounderBootstrap(strand.Id));
5419
+ }
5420
+ catch (error) {
5421
+ // The founding did not happen (e.g. the rebuild refused a pre-split strand and
5422
+ // rolled back, leaving the instance tracked with no runtime): withdraw the flip
5423
+ // so the next attempt re-runs the founding instead of resolving
5424
+ // 'already-founder' over an instance that never founded.
5425
+ this.strandManager.withdrawFounderRequest(strand.Id);
5426
+ throw error;
5427
+ }
5428
+ }
5429
+ log('launchStrand: strand %s already tracked — founder request honored (%s)', strand.Id, outcome);
5430
+ return existing;
5431
+ }
5092
5432
  /**
5093
5433
  * Resolve a strand's discovery seed — the dialable strand-network multiaddr
5094
5434
  * strings for cohort siblings. Membership comes from the control network's
@@ -5111,7 +5451,7 @@ export class CadreNode {
5111
5451
  * relay reservation — the gate denial there is fatal, not degraded. A
5112
5452
  * party-member relay answers the RPC (its control node admits us as a
5113
5453
  * member); a dedicated ops/ relay does not speak the protocol and the
5114
- * per-peer failure folds to `[]` — harmless, it has no membership gate and
5454
+ * per-peer failure comes back `unreachable` — harmless, it has no membership gate and
5115
5455
  * needs no grant. The relay's direct addr rides along as the dial fallback
5116
5456
  * for a relay we are not yet connected to.
5117
5457
  */
@@ -5161,10 +5501,13 @@ export class CadreNode {
5161
5501
  }
5162
5502
  }
5163
5503
  const bootstrapNodes = targets.length
5164
- ? await collectStrandAddrs(this.controlNode, targets, strandId, { delegatePeerId })
5504
+ ? (await this.collectSiblingStrandAddrs(this.controlNode, targets, strandId, delegatePeerId)).addrs
5165
5505
  : [];
5166
5506
  // Throttle state for the RELAY targets only — refreshDelegateGrants never
5167
- // looks up a sibling key, so recording one would only be dead weight.
5507
+ // looks up a sibling key, so recording one would only be dead weight. The
5508
+ // siblings' refresh due times are deliberately left alone too: stamping here
5509
+ // would race the refresh pass's pruning while the strand node is still coming
5510
+ // up, and all it would save is one extra RPC per sibling on the first tick.
5168
5511
  this.recordDelegateAnnounces(relays.map((r) => r.relayPeerId), strandId);
5169
5512
  return bootstrapNodes;
5170
5513
  }
@@ -5246,9 +5589,10 @@ export class CadreNode {
5246
5589
  * Record the announce timestamps {@link refreshDelegateGrants} throttles on,
5247
5590
  * for every relay a delegate-carrying announce pass dialed.
5248
5591
  *
5249
- * Recorded OPTIMISTICALLY at announce time: `collectStrandAddrs` folds
5250
- * per-peer failure to `[]` and reports no per-peer success, and threading
5251
- * success out would change its API for little gain. A failed INITIAL announce
5592
+ * Recorded OPTIMISTICALLY at announce time, whatever `collectStrandAddrs`
5593
+ * reports per peer: a dedicated `ops/` relay never speaks the strand-addr
5594
+ * protocol, so recording only on success would re-announce to it on every
5595
+ * reconcile tick, one wasted protocol negotiation each. A failed INITIAL announce
5252
5596
  * costs the strand supervisor its first attempt only (the relay denies the
5253
5597
  * reservation; every re-drive re-announces first through
5254
5598
  * {@link announceDelegateToRelay}); a failed REFRESH retries within
@@ -5284,7 +5628,7 @@ export class CadreNode {
5284
5628
  running.set(strandId, instance.libp2pNode.peerId.toString());
5285
5629
  }
5286
5630
  }
5287
- pruneStoppedStrandAnnounces(this.delegateAnnounceAt, new Set(running.keys()));
5631
+ prunePeerStrandKeys(this.delegateAnnounceAt, new Set(running.keys()));
5288
5632
  if (running.size === 0) {
5289
5633
  return;
5290
5634
  }
@@ -5311,16 +5655,16 @@ export class CadreNode {
5311
5655
  * again right away.
5312
5656
  *
5313
5657
  * Against a dedicated ops relay (no strand-addr RPC) the request fails per-peer
5314
- * and `collectStrandAddrs` folds it to `[]`: one wasted protocol negotiation per
5658
+ * and `collectStrandAddrs` reports it `unreachable`: one wasted protocol negotiation per
5315
5659
  * re-drive attempt, bounded by the supervisor's backoff. Never throws on that
5316
5660
  * path; a relay addr that names no peer id is logged and skipped (the hook's
5317
5661
  * caller runs the drive regardless).
5318
5662
  *
5319
5663
  * NOTE: against a relay that is DOWN this hook costs up to two strand-addr
5320
- * timeouts (10 s each: dial by peer id, then by addr) before the reservation drive even
5321
- * starts, so one failed re-drive holds the supervisor `driving` for those 20 s plus the
5322
- * drive's own deadline — 34 s at the default declared link round trip, and longer on a host
5323
- * that declared a slower one (`link-budget.ts`).
5664
+ * timeouts (dial by peer id, then by addr; 23 s each at the default declared link round trip)
5665
+ * before the reservation drive even starts, so one failed re-drive holds the supervisor
5666
+ * `driving` for those 46 s plus the drive's own deadline — 64 s at the default, and longer on
5667
+ * a host that declared a slower one (`link-budget.ts`).
5324
5668
  * Bounded and harmless while the relay is unreachable anyway; if recovery
5325
5669
  * latency after a relay comes back ever matters, skip the announce when the
5326
5670
  * control node holds no connection to the relay (the drive's own dial fails
@@ -5336,7 +5680,7 @@ export class CadreNode {
5336
5680
  log('announceDelegateToRelay: relay addr %s names no peer id; strand %s not announced', relayAddr, strandId);
5337
5681
  return;
5338
5682
  }
5339
- await collectStrandAddrs(controlNode, [{ peerId: relayPeerId, addrs: [multiaddr(relayAddr)] }], strandId, { delegatePeerId });
5683
+ await this.collectSiblingStrandAddrs(controlNode, [{ peerId: relayPeerId, addrs: [multiaddr(relayAddr)] }], strandId, delegatePeerId);
5340
5684
  this.recordDelegateAnnounces([relayPeerId], strandId);
5341
5685
  }
5342
5686
  /** One strand's share of {@link refreshDelegateGrants}: announce to the relays whose grant is due. */
@@ -5349,13 +5693,14 @@ export class CadreNode {
5349
5693
  if (due.length === 0) {
5350
5694
  return;
5351
5695
  }
5352
- await collectStrandAddrs(controlNode, due.map(relayStrandAddrPeer), strandId, { delegatePeerId });
5696
+ await this.collectSiblingStrandAddrs(controlNode, due.map(relayStrandAddrPeer), strandId, delegatePeerId);
5353
5697
  this.recordDelegateAnnounces(due.map((relay) => relay.relayPeerId), strandId, now);
5354
5698
  }
5355
5699
  /**
5356
- * Re-resolve each running strand's SIBLING addresses over the control mesh and
5357
- * merge them into that strand's own libp2p address book, throttled to once per
5358
- * {@link STRAND_PEER_ADDR_REFRESH_MS} per strand.
5700
+ * Keep each running strand's own libp2p address book warm: re-merge its strand
5701
+ * peer book on every pass, and re-ask each connected SIBLING for its strand
5702
+ * addresses over the control mesh when that (sibling, strand) is due
5703
+ * ({@link strandAddrAskDueAt}).
5359
5704
  *
5360
5705
  * Without this, a strand's address book is written exactly once — the
5361
5706
  * launch/resume seed — and everything below cadre-core that dials a strand peer
@@ -5365,6 +5710,12 @@ export class CadreNode {
5365
5710
  * re-resolved, and even the original seed addresses fall off at the peerStore's
5366
5711
  * one-hour expiry (see `peer-addr-book.ts`).
5367
5712
  *
5713
+ * Due times are per (sibling, strand) and set from each sibling's own outcome, so
5714
+ * a sibling that connects late — a phone joining after the party's always-on
5715
+ * machines — is asked on the next tick, and one that could not answer or refused
5716
+ * (its view of the membership may not include us yet) is retried within
5717
+ * {@link STRAND_PEER_ADDR_RETRY_MS} rather than {@link STRAND_PEER_ADDR_REFRESH_MS}.
5718
+ *
5368
5719
  * Distinct from {@link refreshDelegateGrants}, deliberately: that pass covers
5369
5720
  * RELAYS on a `DELEGATE_GRANT_TTL_MS / 2` throttle to keep circuit-relay
5370
5721
  * admission grants alive, this one covers SIBLINGS on an address-expiry
@@ -5388,54 +5739,65 @@ export class CadreNode {
5388
5739
  running.add(strandId);
5389
5740
  }
5390
5741
  }
5391
- // Drop stamps for strands no longer running: the map must not grow for the
5392
- // node's lifetime, and a resumed strand should refresh immediately rather
5393
- // than inherit the stamp its previous incarnation left.
5394
- for (const strandId of this.strandPeerAddrRefreshAt.keys()) {
5395
- if (!running.has(strandId)) {
5396
- this.strandPeerAddrRefreshAt.delete(strandId);
5397
- }
5398
- }
5399
- const refreshMs = this.config.network?.controlCohort?.strandAddrRefreshMs ?? STRAND_PEER_ADDR_REFRESH_MS;
5400
- const due = [...running].filter((strandId) => now - (this.strandPeerAddrRefreshAt.get(strandId) ?? 0) >= refreshMs);
5401
- if (due.length === 0) {
5742
+ if (running.size === 0) {
5743
+ this.strandAddrAskDueAt.clear();
5402
5744
  return;
5403
5745
  }
5404
- // `connectedSiblingTargets`' membership read is unbounded, and with zero
5405
- // connections its answer is empty whatever the table holds, so decide it from the
5406
- // connection list instead of paying for the read once a tick. Note this only skips
5407
- // the RPC: a strand with peer-book entries still refreshes below, because those
5408
- // never came from a sibling in the first place.
5409
- //
5410
- // NOTE: one strand-addr RPC per (due strand × connected sibling) per refresh
5411
- // interval — each a tiny request/response on an already-open control
5412
- // connection. If a node ever runs MANY strands at once, batch the RPC to
5413
- // carry several strand ids per request rather than one fan-out per strand.
5414
- const targets = this.controlNode.getConnections().length === 0
5415
- ? []
5416
- : await this.connectedSiblingTargets().catch((error) => {
5417
- log('refreshStrandPeerAddrs: sibling enumeration failed (skipping pass): %o', error);
5418
- return [];
5419
- });
5746
+ const targets = await this.strandAddrRefreshTargets();
5420
5747
  // A shutdown landed mid-enumeration.
5421
5748
  if (!this._running || !this.controlNode) {
5422
5749
  return;
5423
5750
  }
5424
- await Promise.all(due.map((strandId) => this.refreshOneStrandPeerAddrs(strandId, targets, now)));
5751
+ // Drop due times for strands no longer running and siblings no longer connected:
5752
+ // the map must not grow for the node's lifetime, a resumed strand must not
5753
+ // inherit its previous incarnation's due times, and a sibling that reconnects (a
5754
+ // phone restart, a new relay reservation) must be asked on its next connected
5755
+ // tick. An enumeration failure prunes everything, which costs one extra round of
5756
+ // asks, never a missed one.
5757
+ prunePeerStrandKeys(this.strandAddrAskDueAt, running, new Set(targets.map((t) => t.peerId)));
5758
+ await Promise.all([...running].map((strandId) => this.refreshOneStrandPeerAddrs(strandId, targets, now)));
5759
+ }
5760
+ /**
5761
+ * The siblings {@link refreshStrandPeerAddrs} may ask this pass: the connected
5762
+ * cohort, or none when enumeration fails (logged, never thrown).
5763
+ *
5764
+ * `connectedSiblingTargets`' membership read is unbounded, and with zero
5765
+ * connections its answer is empty whatever the table holds, so decide it from the
5766
+ * connection list instead of paying for the read once a tick.
5767
+ *
5768
+ * NOTE: otherwise the read runs on EVERY tick with a running strand, not only when
5769
+ * some (sibling, strand) is due: pruning a departed sibling needs the current
5770
+ * target set, and whether anyone is due cannot be told without it (a connected
5771
+ * non-member never gets a due time to compare). One more `CadrePeer` read per 15 s
5772
+ * tick, on top of the two `runReconcileControlCohort` already makes; if those reads
5773
+ * get costly, share one row-set across the pass (see the NOTE there) rather than
5774
+ * skipping ticks here.
5775
+ *
5776
+ * NOTE: one strand-addr RPC per (running strand × due sibling) — each a tiny
5777
+ * request/response on an already-open control connection. If a node ever runs
5778
+ * MANY strands at once, batch the RPC to carry several strand ids per request
5779
+ * rather than one fan-out per strand.
5780
+ */
5781
+ async strandAddrRefreshTargets() {
5782
+ if (this.controlNode?.getConnections().length === 0) {
5783
+ return [];
5784
+ }
5785
+ return this.connectedSiblingTargets().catch((error) => {
5786
+ log('refreshStrandPeerAddrs: sibling enumeration failed (asking nobody this pass): %o', error);
5787
+ return [];
5788
+ });
5425
5789
  }
5426
5790
  /**
5427
- * One strand's share of {@link refreshStrandPeerAddrs}: RPC the siblings, union their
5428
- * answers with this strand's peer-book addresses, and merge the lot into the strand's
5429
- * address book. Errors are logged and swallowed so one strand's failure never costs
5430
- * the others their refresh.
5791
+ * One strand's share of {@link refreshStrandPeerAddrs}: RPC the siblings that are
5792
+ * due, union their answers with this strand's peer-book addresses, and merge the
5793
+ * lot into the strand's address book. Errors are logged and swallowed so one
5794
+ * strand's failure never costs the others their refresh.
5431
5795
  *
5432
- * `targets` may be EMPTY — a solo node, or one whose only control peers are strangers.
5433
- * The peer-book addresses still have to be re-merged in that case: nothing re-resolves
5434
- * another party's addresses, so this periodic re-merge is the ONLY thing standing
5435
- * between them and the peerStore's one-hour expiry. A strand with neither a sibling to
5436
- * ask nor a book entry does nothing and leaves its throttle unstamped, so the next
5437
- * reconcile tick retries rather than sitting out the whole refresh interval having
5438
- * done nothing.
5796
+ * The peer book merges on EVERY pass, whether or not any sibling is due or
5797
+ * connected: nothing re-resolves another party's addresses, so this re-merge is the
5798
+ * ONLY thing standing between them and the peerStore's one-hour expiry — and it is
5799
+ * also how a re-formation's freshly carried addresses reach a running strand on the
5800
+ * next tick. A strand with nobody due and no book entry does nothing.
5439
5801
  */
5440
5802
  async refreshOneStrandPeerAddrs(strandId, targets, now) {
5441
5803
  const controlNode = this.controlNode;
@@ -5446,32 +5808,54 @@ export class CadreNode {
5446
5808
  try {
5447
5809
  // Inside the try: a strand node torn down mid-pass may throw on any read, and one
5448
5810
  // strand's failure must never cost the others their refresh.
5449
- const contactAddrs = this.strandPeerBookAddrs(strandId, strandNode.peerId.toString());
5450
- if (targets.length === 0 && contactAddrs.length === 0) {
5451
- return;
5452
- }
5811
+ const strandPeerId = strandNode.peerId.toString();
5812
+ const contactAddrs = this.strandPeerBookAddrs(strandId, strandPeerId);
5813
+ const due = targets.filter((target) => now >= (this.strandAddrAskDueAt.get(peerStrandKey(target.peerId, strandId)) ?? 0));
5453
5814
  // The running strand node's own peerId is the delegate to announce — see
5454
5815
  // the relationship note on refreshStrandPeerAddrs.
5455
- const siblingAddrs = targets.length === 0
5816
+ const siblingAddrs = due.length === 0
5456
5817
  ? []
5457
- : await collectStrandAddrs(controlNode, [...targets], strandId, {
5458
- delegatePeerId: strandNode.peerId.toString()
5459
- });
5460
- // Stamped on the pass having happened, not on its answer: the fan-out is
5461
- // what the throttle exists to bound, and an all-empty round is a normal
5462
- // steady state for a strand no connected sibling currently runs.
5463
- this.strandPeerAddrRefreshAt.set(strandId, now);
5818
+ : await this.askSiblingsForStrandAddrs(controlNode, due, strandId, strandPeerId, now);
5464
5819
  // Re-read the instance after the await — a strand stopped mid-pass (or one
5465
5820
  // already restarted onto a new node) must never have its store written to.
5466
5821
  if (!this._running || this.strandManager.getInstance(strandId)?.libp2pNode !== strandNode) {
5467
5822
  return;
5468
5823
  }
5469
- await this.mergeStrandPeerAddrs(strandNode, unionAddrs(siblingAddrs, contactAddrs), strandId);
5824
+ const addrs = unionAddrs(siblingAddrs, contactAddrs);
5825
+ if (addrs.length === 0) {
5826
+ return;
5827
+ }
5828
+ // NOTE: with no sibling due this still merges the whole book — up to 16 peers ×
5829
+ // 16 addrs, so 16 `peerStore.merge` calls per running strand per 15 s tick. An
5830
+ // unchanged address set writes nothing in libp2p's persistent peer store, so it
5831
+ // is cheap today; if many strands run at once, merge only book entries changed
5832
+ // since the last tick plus those nearing the one-hour expiry.
5833
+ await this.mergeStrandPeerAddrs(strandNode, addrs, strandId);
5470
5834
  }
5471
5835
  catch (error) {
5472
5836
  log('refreshStrandPeerAddrs: strand %s refresh failed (continuing): %o', strandId, error);
5473
5837
  }
5474
5838
  }
5839
+ /**
5840
+ * RPC `due` siblings for `strandId` and set each one's next due time from its own
5841
+ * outcome: an answer, even an empty one, waits the full refresh interval; anything
5842
+ * else retries in {@link STRAND_PEER_ADDR_RETRY_MS} (or the refresh interval, if
5843
+ * configured shorter). Stamped before the caller
5844
+ * re-checks that the strand is still running, so a strand torn down mid-pass still
5845
+ * records who was asked.
5846
+ */
5847
+ async askSiblingsForStrandAddrs(controlNode, due, strandId, delegatePeerId, now) {
5848
+ const { addrs, outcomes } = await this.collectSiblingStrandAddrs(controlNode, [...due], strandId, delegatePeerId);
5849
+ const refreshMs = this.config.network?.controlCohort?.strandAddrRefreshMs ?? STRAND_PEER_ADDR_REFRESH_MS;
5850
+ // A configured refresh shorter than the retry must not leave a failing sibling
5851
+ // waiting longer than a healthy one.
5852
+ const retryMs = Math.min(refreshMs, STRAND_PEER_ADDR_RETRY_MS);
5853
+ for (const [peerId, outcome] of outcomes) {
5854
+ const waitMs = siblingAnswered(outcome) ? refreshMs : retryMs;
5855
+ this.strandAddrAskDueAt.set(peerStrandKey(peerId, strandId), now + waitMs);
5856
+ }
5857
+ return addrs;
5858
+ }
5475
5859
  /**
5476
5860
  * Merge strand-network addresses into ONE strand node's libp2p address book,
5477
5861
  * attributed per peer. Best-effort throughout: an address-book write must never
@@ -5565,27 +5949,35 @@ export class CadreNode {
5565
5949
  return orderSignalingFirst(addrs);
5566
5950
  }
5567
5951
  /**
5568
- * Leave a strand joined from another party: forget its remembered join, so no later
5569
- * start re-offers it, then {@link stopStrand} it here. The "leave" a joiner has, since it
5570
- * cannot {@link unpublishStrand} a row its party's control database never held. For one
5571
- * of this party's own strands the forget is a no-op and this is just {@link stopStrand}.
5952
+ * Leave a strand joined from another party, for the whole party: remove its party-wide
5953
+ * `JoinedStrand` row (owner-signed, with a `Revocation` tombstone), then this machine's
5954
+ * unpublished record, its strand peer book entries and any session-kept entry, then
5955
+ * {@link stopStrand} it here. Every other machine's watcher then sees the row gone and
5956
+ * detaches the strand, a storage replica included; a machine offline at the time reaps the
5957
+ * row once the tombstone reaches it. The joiner's counterpart of {@link unpublishStrand},
5958
+ * which only works on a row the party's own `Strand` table holds. For one of those, or for
5959
+ * a join still local-only, there is no party-wide row and this is a local forget plus
5960
+ * {@link stopStrand}.
5572
5961
  *
5573
- * Touches nothing beyond this node — the other members are not told, and this party's
5574
- * membership row in the strand stays.
5962
+ * The other members of the strand are not told, and this party's membership row in the
5963
+ * strand stays, so a later re-formation reuses the same identity.
5964
+ *
5965
+ * @throws when a party-wide row exists and this machine cannot sign its removal (not an
5966
+ * enrolled owner) — {@link stopStrand} stops the strand on this machine only — or when
5967
+ * the party-wide table cannot be read.
5575
5968
  */
5576
5969
  async forgetJoinedStrand(strandId) {
5577
5970
  if (!this._running) {
5578
5971
  throw new Error('CadreNode not running');
5579
5972
  }
5580
- await this.joinedStrandRows.forget(strandId);
5973
+ await this.joinedStrands.leave(strandId);
5581
5974
  this.forgetStrandPeers(strandId, 'forgetJoinedStrand');
5582
5975
  await this.stopStrand(strandId);
5583
5976
  }
5584
5977
  /**
5585
- * Record `row` as a join from another party when this party's control database holds no
5586
- * row for it — the one case nothing else would re-offer after a restart. Skips the write
5587
- * when an identical record is already there (an app re-claiming a remembered join on
5588
- * every start), and keeps the first `joinedAt`.
5978
+ * Record `row` as a join from another party when this party's control database names it
5979
+ * neither as its own strand nor as a party-wide join — the one case nothing else would
5980
+ * re-offer after a restart (`JoinedStrandSession.rememberForeign`).
5589
5981
  *
5590
5982
  * Best-effort, for {@link addStrand}: a failure costs the strand its re-offer after the
5591
5983
  * next restart, not this attach, so it is reported and the attach goes on.
@@ -5599,24 +5991,11 @@ export class CadreNode {
5599
5991
  * tombstone here before recording.
5600
5992
  */
5601
5993
  async rememberForeignStrand(row) {
5602
- const store = this.joinedStrandStore;
5603
- if (!store || !this.controlDatabase) {
5994
+ if (!this.joinedStrands || !this.controlDatabase) {
5604
5995
  return;
5605
5996
  }
5606
5997
  try {
5607
- if (await this.controlDatabase.queryStrand(row.Id)) {
5608
- return;
5609
- }
5610
- const existing = (await store.list()).find((record) => record.Id === row.Id);
5611
- if (existing?.Type === row.Type && existing.MemberPrivateKey === row.MemberPrivateKey) {
5612
- return;
5613
- }
5614
- await store.record({
5615
- Id: row.Id,
5616
- Type: row.Type,
5617
- MemberPrivateKey: row.MemberPrivateKey,
5618
- joinedAt: existing?.joinedAt ?? Date.now()
5619
- });
5998
+ await this.joinedStrands.rememberForeign(row);
5620
5999
  }
5621
6000
  catch (error) {
5622
6001
  console.warn(`addStrand(${row.Id}): could not remember this strand as joined from another party, ` +
@@ -5624,21 +6003,30 @@ export class CadreNode {
5624
6003
  }
5625
6004
  }
5626
6005
  /**
5627
- * Self-revocation arm of the joined-strand record: a party removed from a strand must
5628
- * not re-attach it on every launch. The strand keeps running this session — the
5629
- * `strand:revoked` contract is that nothing is torn down for the app — and is gone
5630
- * after the next start. The join record is a no-op for this party's own strands, which
5631
- * have none; the strand peer book is forgotten either way, since a removed party must
5632
- * not keep dialing the strand's peers.
6006
+ * Self-revocation arm of the joined-strand records: a party removed from a strand must
6007
+ * not re-attach it on every launch of every machine. The strand keeps running this
6008
+ * session here — the `strand:revoked` contract is that nothing is torn down for the app —
6009
+ * and its party-wide row is queued for removal by the next connected owner reconcile pass
6010
+ * (`JoinedStrandSession.forgetAfterThisSession`). A no-op for this party's own strands,
6011
+ * which have neither record; the strand peer book is forgotten either way, since a
6012
+ * removed party must not keep dialing the strand's peers.
6013
+ *
6014
+ * NOTE: accepted tradeoff — a sibling machine that has not raised `strand:revoked` itself
6015
+ * detaches the strand (`strand:stopped`) when the party-wide removal reaches it, instead
6016
+ * of keeping it for the session, which weakens "nothing is stopped on the removed
6017
+ * machine's behalf" for siblings. Weighed against a party-wide row that brings a revoked
6018
+ * strand back on every start of every machine. Revisit if apps need the "you were
6019
+ * removed" screen on every device: the sibling could re-check its own revocation state
6020
+ * (`refreshRevocationEnforcement`) before detaching a vanished joined row.
5633
6021
  *
5634
6022
  * NOTE: a manager can re-admit a removed party directly (`addMemberByManager`), and the
5635
- * membership loop then finishes the join on its own — but the record is gone by then, so
5636
- * the next start does not re-attach the strand. Re-forming records it again. If direct
6023
+ * membership loop then finishes the join on its own — but the records are gone by then,
6024
+ * so the next start does not re-attach the strand. Re-forming records it again. If direct
5637
6025
  * re-admission becomes a routine flow, re-record the join when the revoked-peer gate
5638
6026
  * clears for this node.
5639
6027
  */
5640
6028
  forgetRevokedJoin(strandId) {
5641
- void this.joinedStrandRows?.forgetAfterThisSession(strandId).catch((error) => {
6029
+ void this.joinedStrands?.forgetAfterThisSession(strandId).catch((error) => {
5642
6030
  log('forgetting revoked joined strand %s failed; it will be re-offered on the next start: %o', strandId, error);
5643
6031
  });
5644
6032
  // The strand's peers go with the join: a removed party must not keep dialing them.
@@ -5774,10 +6162,19 @@ export class CadreNode {
5774
6162
  void this.pushFanoutService?.notify(strandId, reason);
5775
6163
  }
5776
6164
  /**
5777
- * Force wake a hibernating strand
6165
+ * Force wake a hibernating strand. A requested wake is activity, recorded before the
6166
+ * wake starts: a check-in holding the strand — or rebuilding it, a rebuild this wake then
6167
+ * joins — leaves it up instead of re-quiescing it at the end of its window. Once awake the
6168
+ * strand's idle countdown runs, so it hibernates again if nothing uses it.
5778
6169
  */
5779
6170
  async wakeStrand(strandId) {
5780
- await this.hibernationManager.wakeStrand(strandId);
6171
+ const instance = this.strandManager.getInstance(strandId);
6172
+ if (!instance) {
6173
+ log('wakeStrand: strand %s not found; nothing to wake', strandId);
6174
+ return;
6175
+ }
6176
+ instance.lastActivity = new Date();
6177
+ await this.hibernationManager.wakeStrand(instance);
5781
6178
  }
5782
6179
  // ============================================================================
5783
6180
  // Mobile background lifecycle primitives
@@ -5793,7 +6190,7 @@ export class CadreNode {
5793
6190
  * Routes through {@link HibernationManager.forceHibernate}, which cancels the
5794
6191
  * strand's pending idle/hibernate (and check-in) timers — so a stale timer
5795
6192
  * can't re-fire on or resurrect the strand — then runs the same `onHibernate`
5796
- * path as the timer (`quiesceStrand` + `status='hibernating'` +
6193
+ * path as the timer (`quiesceStrand`, which marks it `hibernating`, then
5797
6194
  * `strand:hibernating`). Unlike the timer path it does NOT re-arm check-ins:
5798
6195
  * the strand stays down until the caller drives a wake (e.g. {@link serviceWake}).
5799
6196
  */
@@ -5854,9 +6251,14 @@ export class CadreNode {
5854
6251
  * strand share one in-flight operation ({@link serviceWakePromises}), and the
5855
6252
  * underlying resume coalesces with a racing push-wake via
5856
6253
  * {@link HibernationManager}'s wake coalescing — one runtime build, one window,
5857
- * one re-hibernate decision. Returns `{ serviced: false }` (never throws) when
5858
- * the node is not running or the strand is unknown, and surfaces a resume
5859
- * failure as `{ serviced: true, hadActivity: false }` after re-hibernating.
6254
+ * one re-hibernate decision. A wake or activity from elsewhere that lands during
6255
+ * the resume or the window leaves the strand up; this call's own wake does not.
6256
+ * Afterwards a strand left up has its idle countdown running, and a re-hibernated one
6257
+ * gets back the check-in chain this call interrupted — it never gains one it lacked,
6258
+ * so a strand the mobile runner force-hibernated stays down until the next push.
6259
+ * Returns `{ serviced: false }` (never throws) when
6260
+ * the node is not running or the strand is unknown, and surfaces a wake or
6261
+ * window failure as `{ serviced: true, hadActivity: false }`.
5860
6262
  *
5861
6263
  * @param strandId - the strand a push said has pending activity.
5862
6264
  * @param opts.windowMs - override the live-window duration (defaults to the
@@ -5890,30 +6292,58 @@ export class CadreNode {
5890
6292
  log('serviceWake: strand %s unknown to this node; not serviced', strandId);
5891
6293
  return { strandId, serviced: false, hadActivity: false };
5892
6294
  }
5893
- // Already live (active or idle — both retain their runtime): servicing is a
5894
- // no-op success. Do NOT run a window that would re-hibernate a strand the app
5895
- // may be actively using, and do NOT rebuild a second runtime.
5896
- if (instance.libp2pNode || instance.database) {
6295
+ // Already live (active or idle — both retain their runtime) or coming up (a launch,
6296
+ // or a check-in with its own window): servicing is a no-op success. Do NOT run a
6297
+ // window that would re-hibernate a strand the app may be actively using, and do NOT
6298
+ // rebuild a second runtime. `'starting'` counts before any handle is attached. A strand
6299
+ // being quiesced does not count: the wake below rebuilds it after the quiesce.
6300
+ if (!this.strandManager.isQuiescing(strandId)
6301
+ && (instance.status === 'starting' || instance.libp2pNode || instance.database)) {
5897
6302
  log('serviceWake: strand %s already live; no-op success', strandId);
5898
6303
  return { strandId, serviced: true, hadActivity: true };
5899
6304
  }
6305
+ // Before the resume, as the check-in takes it (see handleStrandCheckIn).
6306
+ // NOTE: a `wakeStrand` already resuming when this runs stamped its activity before this
6307
+ // mark, so the probe joins it without counting it and the window can re-hibernate a strand
6308
+ // that wake asked to keep up; if foreground wakes and serviceWake overlap in practice, mark
6309
+ // before the joined wake's stamp instead.
6310
+ const activityMark = instance.lastActivity;
6311
+ const windowMs = opts?.windowMs ?? this.config.hibernation?.checkInWindowMs ?? DEFAULT_CHECKIN_WINDOW_MS;
5900
6312
  try {
5901
- // Coalesced resume: routes through wakeStrand → HibernationManager.beginWake
5902
- // so a racing push-wake shares this single runtime build.
5903
- await this.wakeStrand(strandId);
5904
- const windowMs = opts?.windowMs ?? this.config.hibernation?.checkInWindowMs ?? DEFAULT_CHECKIN_WINDOW_MS;
5905
- const hadActivity = await this.runWakeWindow(instance, windowMs);
6313
+ return await this.wakeAndHoldForService(instance, activityMark, windowMs);
6314
+ }
6315
+ finally {
6316
+ // After the window (or a failure) decided the state: the idle countdown if the strand
6317
+ // stayed up, else the check-in chain this probe interrupted, if any.
6318
+ this.hibernationManager.endProbe(instance);
6319
+ }
6320
+ }
6321
+ /**
6322
+ * The wake and window of {@link runServiceWake}. A failure in either — the network
6323
+ * unreachable inside a Doze grant, say — must not throw out of a background task, so it
6324
+ * reports no activity. Each stage cleans up only what it owns.
6325
+ */
6326
+ async wakeAndHoldForService(instance, activityMark, windowMs) {
6327
+ const { strandId } = instance;
6328
+ try {
6329
+ // Coalesced resume: HibernationManager.beginWake, so a racing push-wake shares this
6330
+ // single runtime build. Not through `wakeStrand`, which records the wake as activity:
6331
+ // this probe's own wake must not count as a reason to stay up.
6332
+ await this.hibernationManager.probeWake(instance);
6333
+ }
6334
+ catch (error) {
6335
+ // handleStrandWake has already re-hibernated a failed rebuild, and left alone a strand
6336
+ // it failed before building, which may be a check-in's.
6337
+ log('serviceWake: wake of strand %s failed: %o', strandId, error);
6338
+ return { strandId, serviced: true, hadActivity: false };
6339
+ }
6340
+ try {
6341
+ const hadActivity = await this.runWakeWindow(instance, activityMark, windowMs);
5906
6342
  return { strandId, serviced: true, hadActivity };
5907
6343
  }
5908
6344
  catch (error) {
5909
- // Resume failing mid-window (network unreachable inside a Doze grant, etc.)
5910
- // must not throw out of a background task: re-hibernate and report no
5911
- // activity, mirroring handleStrandCheckIn's re-hibernate-on-error.
5912
6345
  log('serviceWake: strand %s failed during wake window; re-hibernating: %o', strandId, error);
5913
- await this.strandManager.quiesceStrand(strandId).catch((cleanupErr) => {
5914
- log('serviceWake cleanup quiesce for strand %s failed: %o', strandId, cleanupErr);
5915
- });
5916
- instance.status = 'hibernating';
6346
+ await this.rehibernateAfterFailedResume(instance, 'serviceWake');
5917
6347
  return { strandId, serviced: true, hadActivity: false };
5918
6348
  }
5919
6349
  }
@@ -5946,8 +6376,8 @@ export class CadreNode {
5946
6376
  *
5947
6377
  * BUDGET: the supervisor's first attempt is what `start()` waits on — deliberately the drive's
5948
6378
  * ordinary deadline rather than a boot-specific one. That deadline is now COUNTED, four link
5949
- * round trips at the declared `network.linkRoundTripMs` (14 s at its default, where it was a
5950
- * fixed 10 s): a healthy dial-plus-reserve is sub-second even over a WAN, so this is slack for
6379
+ * round trips at the declared `network.linkRoundTripMs` plus the relay's two admission
6380
+ * decisions (18 s at its default, where it was a fixed 10 s): a healthy dial-plus-reserve is sub-second even over a WAN, so this is slack for
5951
6381
  * a slow link, while going much longer would make a dead relay indistinguishable from a hung
5952
6382
  * start and much shorter would fail nodes on links that were merely slow. A host that declares
5953
6383
  * a slower link lengthens it without touching this path — `link-budget.ts`. The retries carry
@@ -6086,7 +6516,7 @@ export class CadreNode {
6086
6516
  *
6087
6517
  * @param ownerPrivateKey - The owner's private key (base64url encoded)
6088
6518
  */
6089
- initializeSeedBootstrap(ownerPrivateKey) {
6519
+ async initializeSeedBootstrap(ownerPrivateKey) {
6090
6520
  if (!this.controlNode || !this.controlDatabase) {
6091
6521
  throw new Error('CadreNode must be started before initializing seed bootstrap');
6092
6522
  }
@@ -6110,18 +6540,16 @@ export class CadreNode {
6110
6540
  .trust(ed25519PublicKeyFromPrivate(ownerPrivateKey), 'genesis')
6111
6541
  .catch((error) => log('Trusted-owner genesis anchor persist failed: %o', error));
6112
6542
  }
6113
- this.seedBootstrapService = new SeedBootstrapService({
6543
+ await this.installSeedBootstrapService(new SeedBootstrapService({
6114
6544
  partyId: this.config.controlNetwork.partyId,
6115
6545
  ownerPrivateKey,
6116
6546
  inviteAddressResolver: () => this.resolveInviteAddresses(),
6117
- dialBudget: this.controlDialBudget(),
6547
+ ...this.seedServiceBudgets(),
6118
6548
  trustPolicy: this.config.seedTrustPolicy,
6119
6549
  // Seed trust anchors on the node-local store (seeded just above with this
6120
6550
  // node's own genesis key), never on the replicated OwnerKey table.
6121
6551
  ...(this.trustedOwnerStore ? { trustedOwners: this.trustedOwnerStore } : {}),
6122
- });
6123
- this.seedBootstrapService.setEventCallbacks(this.seedEventCallbacks());
6124
- this.seedBootstrapService.initialize(this.controlNode, this.controlDatabase);
6552
+ }), this.controlNode, this.controlDatabase);
6125
6553
  log('Seed bootstrap service initialized');
6126
6554
  }
6127
6555
  /**
@@ -6318,7 +6746,8 @@ export class CadreNode {
6318
6746
  * is reachable through its circuit-relay address), dials `WAKE_PROTOCOL`, sends
6319
6747
  * the {@link WakeRequest}, and returns the peer's {@link WakeAck}. The receiver
6320
6748
  * gates the request on cadre membership and only resumes a strand it already
6321
- * participates in.
6749
+ * participates in; it acks once it has decided, before the strand is up. The
6750
+ * dial deadlines derive from this node's `network.linkRoundTripMs`.
6322
6751
  *
6323
6752
  * @param targetPeerId - The hibernating cadre peer to wake.
6324
6753
  * @param strandId - The strand the caller knows has pending activity.
@@ -6334,14 +6763,14 @@ export class CadreNode {
6334
6763
  throw new Error(`No dialable control-network address for peer ${targetPeerId}`);
6335
6764
  }
6336
6765
  const request = { strandId, reason };
6337
- return await dialWake(this.controlNode, addrs, request);
6766
+ return await dialWake(this.controlNode, addrs, request, { linkRoundTripMs: this.config.network?.linkRoundTripMs });
6338
6767
  }
6339
6768
  /**
6340
6769
  * Enable the seed listener for receiving seeds via the /sereus/seed/1.0.0 protocol.
6341
6770
  * This is for drone nodes that need to receive seeds without being an owner.
6342
6771
  * Does not require an owner key.
6343
6772
  */
6344
- enableSeedListener() {
6773
+ async enableSeedListener() {
6345
6774
  if (!this.controlNode || !this.controlDatabase) {
6346
6775
  throw new Error('CadreNode must be started before enabling seed listener');
6347
6776
  }
@@ -6350,19 +6779,17 @@ export class CadreNode {
6350
6779
  log('Seed bootstrap service already initialized');
6351
6780
  return;
6352
6781
  }
6353
- this.seedBootstrapService = new SeedBootstrapService({
6782
+ await this.installSeedBootstrapService(new SeedBootstrapService({
6354
6783
  partyId: this.config.controlNetwork.partyId,
6355
6784
  // No owner key - this node only receives seeds
6356
6785
  inviteAddressResolver: () => this.resolveInviteAddresses(),
6357
- dialBudget: this.controlDialBudget(),
6786
+ ...this.seedServiceBudgets(),
6358
6787
  trustPolicy: this.config.seedTrustPolicy,
6359
6788
  // A listener-only node accepts a wire-delivered seed solely against this
6360
6789
  // anchor (there is no per-call override on the inbound handler): with no
6361
6790
  // genesis/invite/operator pin it authorizes nobody, which is the point.
6362
6791
  ...(this.trustedOwnerStore ? { trustedOwners: this.trustedOwnerStore } : {}),
6363
- });
6364
- this.seedBootstrapService.setEventCallbacks(this.seedEventCallbacks());
6365
- this.seedBootstrapService.initialize(this.controlNode, this.controlDatabase);
6792
+ }), this.controlNode, this.controlDatabase);
6366
6793
  log('Seed listener enabled');
6367
6794
  }
6368
6795
  /**
@@ -6371,6 +6798,30 @@ export class CadreNode {
6371
6798
  getSeedBootstrapService() {
6372
6799
  return this.seedBootstrapService;
6373
6800
  }
6801
+ /**
6802
+ * Make `service` this node's seed service and register its inbound seed handler.
6803
+ * The field is set before the registration is awaited, so a concurrent
6804
+ * {@link enableSeedListener} finds it and does not register a second handler; a
6805
+ * failed registration puts the previous service back and rethrows.
6806
+ *
6807
+ * NOTE: libp2p's registrar stores the handler before its peer-store merge, so a
6808
+ * failed merge leaves SEED_PROTOCOL registered with no service owning it and a retry
6809
+ * here rejects as a duplicate; if peer-store writes can fail in practice, unhandle on
6810
+ * a non-duplicate failure (never on a duplicate — that handler belongs to someone else).
6811
+ */
6812
+ async installSeedBootstrapService(service, controlNode, controlDatabase) {
6813
+ service.setEventCallbacks(this.seedEventCallbacks());
6814
+ const previous = this.seedBootstrapService;
6815
+ this.seedBootstrapService = service;
6816
+ try {
6817
+ await service.initialize(controlNode, controlDatabase);
6818
+ }
6819
+ catch (error) {
6820
+ if (this.seedBootstrapService === service)
6821
+ this.seedBootstrapService = previous;
6822
+ throw error;
6823
+ }
6824
+ }
6374
6825
  /**
6375
6826
  * The event callbacks every {@link SeedBootstrapService} this node owns is
6376
6827
  * wired with — shared by the owner-capable service ({@link initializeSeedBootstrap})
@@ -6585,7 +7036,7 @@ export class CadreNode {
6585
7036
  const tempService = new SeedBootstrapService({
6586
7037
  partyId: seed.partyId,
6587
7038
  trustPolicy: this.config.seedTrustPolicy,
6588
- dialBudget: this.controlDialBudget(),
7039
+ ...this.seedServiceBudgets(),
6589
7040
  // The anchor is node-scoped, not service-scoped: a throwaway service
6590
7041
  // must consult (and persist an accepted signer into) the SAME store the
6591
7042
  // persistent one would, or a cold-start enrollment via this path would
@@ -6593,7 +7044,7 @@ export class CadreNode {
6593
7044
  ...(this.trustedOwnerStore ? { trustedOwners: this.trustedOwnerStore } : {}),
6594
7045
  });
6595
7046
  if (this.controlNode && this.controlDatabase) {
6596
- tempService.initialize(this.controlNode, this.controlDatabase, { registerHandler: false });
7047
+ await tempService.initialize(this.controlNode, this.controlDatabase, { registerHandler: false });
6597
7048
  }
6598
7049
  const tempResult = await tempService.applySeed(seed, options);
6599
7050
  this.noteAppliedSeed(tempResult, seed);
@@ -6765,10 +7216,10 @@ export class CadreNode {
6765
7216
  const tempService = new SeedBootstrapService({
6766
7217
  partyId: invite.partyId,
6767
7218
  trustPolicy: this.config.seedTrustPolicy,
6768
- dialBudget: this.controlDialBudget(),
7219
+ ...this.seedServiceBudgets(),
6769
7220
  });
6770
7221
  if (this.controlNode && this.controlDatabase) {
6771
- tempService.initialize(this.controlNode, this.controlDatabase, { registerHandler: false });
7222
+ await tempService.initialize(this.controlNode, this.controlDatabase, { registerHandler: false });
6772
7223
  }
6773
7224
  await tempService.dialInvite(invite);
6774
7225
  return;
@@ -6784,14 +7235,20 @@ export class CadreNode {
6784
7235
  *
6785
7236
  * @param options - Configuration for the solicitation service
6786
7237
  */
6787
- initializeStrandSolicitation(options) {
7238
+ async initializeStrandSolicitation(options) {
6788
7239
  if (!this.controlNode) {
6789
7240
  throw new Error('CadreNode must be started before initializing strand solicitation');
6790
7241
  }
6791
- this.strandSolicitationService = new StrandSolicitationService({
7242
+ const service = new StrandSolicitationService({
6792
7243
  ...options,
6793
7244
  partyId: this.config.controlNetwork.partyId,
6794
7245
  cadrePeerAddrs: this.getMultiaddrs(),
7246
+ // Every formation deadline derives from this node's declared link, like every other
7247
+ // dial budget here; a caller's own declaration on the formation config still wins.
7248
+ formationConfig: {
7249
+ linkRoundTripMs: this.config.network?.linkRoundTripMs,
7250
+ ...options?.formationConfig
7251
+ },
6795
7252
  // Overrides any caller-supplied hook, exactly like partyId/cadrePeerAddrs: only
6796
7253
  // this node can say which strand-network addresses it is actually listening on,
6797
7254
  // and a wrong answer here seeds a joiner's mesh with addresses that reach nobody.
@@ -6799,10 +7256,23 @@ export class CadreNode {
6799
7256
  // Overridden on the same grounds: only this node holds the running strand
6800
7257
  // instance's database and this party's `StrandPartyKey` identity, and a wrong
6801
7258
  // issuer here would admit joiners under someone else's authority.
6802
- issueMembershipInvite: (strandId) => this.issueStrandMembershipInvite(strandId)
7259
+ issueMembershipInvite: (strandId, signal) => this.issueStrandMembershipInvite(strandId, signal)
6803
7260
  });
6804
- // Register as responder on the control node
6805
- this.strandSolicitationService.registerResponder(this.controlNode);
7261
+ // Set before the registration is awaited, so a concurrent createOpenInvitation /
7262
+ // formStrand uses this service instead of building a second one whose handler
7263
+ // would collide; a failed registration puts the previous service back.
7264
+ // NOTE: same stray-handler caveat as installSeedBootstrapService — a failed
7265
+ // peer-store merge leaves the formation handler registered, so a retry is a duplicate.
7266
+ const previous = this.strandSolicitationService;
7267
+ this.strandSolicitationService = service;
7268
+ try {
7269
+ await service.registerResponder(this.controlNode);
7270
+ }
7271
+ catch (error) {
7272
+ if (this.strandSolicitationService === service)
7273
+ this.strandSolicitationService = previous;
7274
+ throw error;
7275
+ }
6806
7276
  log('Strand solicitation service initialized');
6807
7277
  }
6808
7278
  /**
@@ -6822,7 +7292,7 @@ export class CadreNode {
6822
7292
  ) {
6823
7293
  if (!this.strandSolicitationService) {
6824
7294
  // Create a temporary service for creating invitations
6825
- this.initializeStrandSolicitation();
7295
+ await this.initializeStrandSolicitation();
6826
7296
  }
6827
7297
  const bootstrap = this.getMultiaddrs();
6828
7298
  if (bootstrap.length === 0) {
@@ -6842,7 +7312,7 @@ export class CadreNode {
6842
7312
  throw new Error('CadreNode must be started before forming strands');
6843
7313
  }
6844
7314
  if (!this.strandSolicitationService) {
6845
- this.initializeStrandSolicitation();
7315
+ await this.initializeStrandSolicitation();
6846
7316
  }
6847
7317
  const result = await this.strandSolicitationService.formStrand(invitation, disclosure, this.controlNode);
6848
7318
  this.recordFormationStrandPeers(result.strandId, result.strandAddrs);
@@ -6858,7 +7328,9 @@ export class CadreNode {
6858
7328
  }
6859
7329
  /**
6860
7330
  * Remember the strand a formation just joined (see {@link joinedStrandStore}), so it
6861
- * is re-offered after a restart even when the app is killed before its `addStrand`.
7331
+ * is re-offered after a restart even when the app is killed before its `addStrand`, and
7332
+ * published party-wide by the next connected owner reconcile pass. A re-join also
7333
+ * cancels a party-wide removal a self-revocation queued for the strand.
6862
7334
  * Last in {@link formStrand}, after the membership adoption, so a failure here leaves
6863
7335
  * the party key and staged invitation in place for the re-formation it asks for.
6864
7336
  *
@@ -6867,7 +7339,7 @@ export class CadreNode {
6867
7339
  */
6868
7340
  async rememberFormedStrand(result) {
6869
7341
  try {
6870
- await this.joinedStrandStore.record({
7342
+ await this.joinedStrands.remember({
6871
7343
  Id: result.strandId,
6872
7344
  Type: result.memberPrivateKey ? 'c' : 'o',
6873
7345
  MemberPrivateKey: result.memberPrivateKey ?? null,
@@ -6958,9 +7430,15 @@ export class CadreNode {
6958
7430
  * founder's publish/launch paths mint it, so this is a not-yet-converged sibling.)
6959
7431
  * The manager maps the throw to a clean retryable rejection BEFORE the formation
6960
7432
  * token is spent.
6961
- * - Closed host strand with no running local instance/database → throw, same mapping:
6962
- * a joiner admitted without an invitation would look joined and never become a
6963
- * member, and a responder not running the strand cannot serve its sync anyway.
7433
+ * - Closed host strand whose runtime is HIBERNATING or being quiesced → woken first
7434
+ * ({@link wakeHostStrandForFormation}, bounded by `signal`), then issued as below. In
7435
+ * every state the redemption counts as activity, so the host stays up for the
7436
+ * joiner's first sync.
7437
+ * - Closed host strand with no running local instance/database (never launched, still
7438
+ * starting, or a hibernating one whose wake failed or outran `signal`) →
7439
+ * throw, same mapping: a joiner admitted without an invitation would look joined and
7440
+ * never become a member, and a responder not running the strand cannot serve its sync
7441
+ * anyway.
6964
7442
  * - Closed host strand whose LIVE rows carry the pre-split fingerprint
6965
7443
  * (`assertNotPreSplitStrand`) → throw `PreSplitStrandIdentityError`, same mapping as
6966
7444
  * the recorded refusal. Covers the responders that never ran a refused founder launch:
@@ -6970,7 +7448,12 @@ export class CadreNode {
6970
7448
  * permanent diagnosis. Identity is checked BEFORE the runtime: it is the cheaper read
6971
7449
  * and the more actionable diagnosis when both are missing (a missing runtime is
6972
7450
  * transient, a missing identity is not), and it keeps the branch reachable without
6973
- * standing a strand runtime up.
7451
+ * standing a strand runtime up. For the same reason every control-database check runs
7452
+ * before a wake: a strand that cannot issue anyway is not woken.
7453
+ *
7454
+ * `signal` is the formation's provisioning budget. Once it has aborted nothing is
7455
+ * issued — the joiner has already been told to retry, and an invitation written now
7456
+ * would only sit in the strand until it expires.
6974
7457
  *
6975
7458
  * The invitation expires `MEMBERSHIP_INVITE_TTL_MS` from now — see that constant for
6976
7459
  * the slow-joiner / lost-result tradeoff.
@@ -6985,7 +7468,7 @@ export class CadreNode {
6985
7468
  * `MEMBERSHIP_INVITE_UNAVAILABLE_REASON` forever; that flow needs manager delegation,
6986
7469
  * not a retry.
6987
7470
  */
6988
- async issueStrandMembershipInvite(strandId) {
7471
+ async issueStrandMembershipInvite(strandId, signal) {
6989
7472
  if (!this.controlDatabase) {
6990
7473
  throw new Error(`Cannot issue a membership invitation for strand ${strandId}: control database unavailable`);
6991
7474
  }
@@ -7007,19 +7490,65 @@ export class CadreNode {
7007
7490
  throw new Error(`Cannot issue a membership invitation for closed strand ${strandId}: this party holds ` +
7008
7491
  'no StrandPartyKey row for it (identity not yet converged from the machine that published it)');
7009
7492
  }
7493
+ await this.wakeHostStrandForFormation(strandId, signal);
7010
7494
  const db = this.strandManager.getInstance(strandId)?.database?.getDatabase();
7011
7495
  if (!db) {
7012
7496
  throw new Error(`Cannot issue a membership invitation for closed strand ${strandId}: its runtime is ` +
7013
- 'not live on this responder (not launched, hibernating, or quiescing)');
7497
+ 'not live on this responder (not launched, or still starting)');
7014
7498
  }
7015
7499
  if (row.MemberPrivateKey) {
7016
7500
  await assertNotPreSplitStrand(db, strandId, strandMemberKeyPair(row.MemberPrivateKey).publicKeyB64);
7017
7501
  }
7502
+ if (signal?.aborted) {
7503
+ throw new Error(`Cannot issue a membership invitation for closed strand ${strandId}: the formation ` +
7504
+ 'provisioning budget expired before issuance');
7505
+ }
7018
7506
  return await issueInvite(db, {
7019
7507
  managerKeyPair: strandMemberKeyPair(partyKey),
7020
7508
  expiration: Date.now() + MEMBERSHIP_INVITE_TTL_MS
7021
7509
  });
7022
7510
  }
7511
+ /**
7512
+ * Count a bound closed-strand redemption as activity on the host strand, and wake the
7513
+ * strand when it is HIBERNATING or being quiesced (its database is closing) so the
7514
+ * membership invitation can be issued. Only reached after the formation manager has
7515
+ * authorized the redemption (token, disclosure, outside approval, seat pre-check), so only
7516
+ * a caller already entitled to the strand's member key can cause a wake. No other state is
7517
+ * woken — never launched or still starting is not something this node recovers from on
7518
+ * demand; the caller's live-database check refuses those.
7519
+ *
7520
+ * The activity is recorded in every state, through the hibernation manager rather than
7521
+ * {@link recordStrandActivity}, whose push fan-out would wake this party's phones for
7522
+ * nothing. It keeps the host up for the joiner's first sync: a live strand's idle timer
7523
+ * restarts, a check-in window that happens to have the strand live sees activity and
7524
+ * leaves it up instead of re-quiescing it, and a hibernating strand has its idle →
7525
+ * hibernate timers re-armed once the wake leaves it `active`. The explicit
7526
+ * {@link wakeStrand} coalesces onto the wake `recordActivity` began, and still wakes when
7527
+ * `recordActivity` is a no-op (hibernation disabled but the strand force-hibernated, or
7528
+ * the manager stopped).
7529
+ *
7530
+ * Bounded by `signal` (the formation's provisioning budget): when it aborts first this
7531
+ * throws — a retryable rejection, token unspent — and leaves the wake running, so the
7532
+ * joiner's retry finds the strand live.
7533
+ */
7534
+ async wakeHostStrandForFormation(strandId, signal) {
7535
+ const instance = this.strandManager.getInstance(strandId);
7536
+ if (!instance) {
7537
+ return;
7538
+ }
7539
+ this.hibernationManager.recordActivity(instance);
7540
+ if (!this.strandManager.isQuiescing(strandId) && (instance.status !== 'hibernating' || instance.database)) {
7541
+ return;
7542
+ }
7543
+ log('wakeHostStrandForFormation: waking host strand %s (%s) for an authorized formation', strandId, instance.status);
7544
+ const wake = this.wakeStrand(strandId);
7545
+ if (await resolvesBeforeAbort(wake, signal)) {
7546
+ return;
7547
+ }
7548
+ void wake.catch((error) => log('wakeHostStrandForFormation: background wake of host strand %s failed: %o', strandId, error));
7549
+ throw new Error(`Cannot issue a membership invitation for closed strand ${strandId}: its hibernating ` +
7550
+ 'runtime did not wake within the formation provisioning budget (still waking)');
7551
+ }
7023
7552
  /**
7024
7553
  * Remember the responder's strand-network addresses for a strand this node just
7025
7554
  * formed in the strand peer book (see {@link strandPeerBookStore}), so the strand's
@@ -7051,11 +7580,10 @@ export class CadreNode {
7051
7580
  }, 'formStrand');
7052
7581
  peers++;
7053
7582
  }
7054
- // A strand already running when this lands (a re-formation) would otherwise wait out
7055
- // the rest of its ~10-minute refresh throttle before the new addresses reached its
7056
- // address book. Clearing the stamp makes the next 15 s reconcile tick merge them,
7057
- // which matters precisely because re-forming is the recovery path for a dead entry.
7058
- this.strandPeerAddrRefreshAt.delete(strandId);
7583
+ // A strand already running when this lands (a re-formation) needs nothing more: the
7584
+ // refresh pass merges the book into its address book on every reconcile tick, so the
7585
+ // new addresses land within 15 s — which matters because re-forming is the recovery
7586
+ // path for a dead entry.
7059
7587
  log('formStrand: recorded %d cross-party strand addr(s) for %s under %d peer(s)', strandAddrs.length, strandId, peers);
7060
7588
  }
7061
7589
  /**