@serfab/cadre-core 1.13.0 → 1.15.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 (230) hide show
  1. package/README.md +293 -274
  2. package/dist/cadre-invite-protocol.d.ts +383 -0
  3. package/dist/cadre-invite-protocol.js +774 -0
  4. package/dist/cadre-invite-protocol.js.map +1 -0
  5. package/dist/cadre-join-request.d.ts +42 -0
  6. package/dist/cadre-join-request.js +144 -0
  7. package/dist/cadre-join-request.js.map +1 -0
  8. package/dist/cadre-node.d.ts +849 -210
  9. package/dist/cadre-node.js +1574 -374
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/claim-proof.d.ts +45 -0
  12. package/dist/claim-proof.js +132 -0
  13. package/dist/claim-proof.js.map +1 -0
  14. package/dist/control-authorization.d.ts +80 -19
  15. package/dist/control-authorization.js +55 -13
  16. package/dist/control-authorization.js.map +1 -1
  17. package/dist/control-cohort.js +1 -1
  18. package/dist/control-cohort.js.map +1 -1
  19. package/dist/control-database.d.ts +605 -108
  20. package/dist/control-database.js +1299 -280
  21. package/dist/control-database.js.map +1 -1
  22. package/dist/control-protocol-guard.d.ts +142 -0
  23. package/dist/control-protocol-guard.js +293 -0
  24. package/dist/control-protocol-guard.js.map +1 -0
  25. package/dist/control-schema.d.ts +1 -1
  26. package/dist/control-schema.js +817 -1067
  27. package/dist/control-schema.js.map +1 -1
  28. package/dist/control-stream.d.ts +4 -0
  29. package/dist/control-stream.js +22 -7
  30. package/dist/control-stream.js.map +1 -1
  31. package/dist/delegate-admission.d.ts +1 -1
  32. package/dist/delegate-admission.js +1 -1
  33. package/dist/device-token.d.ts +11 -9
  34. package/dist/device-token.js +14 -12
  35. package/dist/device-token.js.map +1 -1
  36. package/dist/ed25519-key.d.ts +22 -9
  37. package/dist/ed25519-key.js +47 -10
  38. package/dist/ed25519-key.js.map +1 -1
  39. package/dist/fetch-impl.d.ts +12 -0
  40. package/dist/fetch-impl.js +23 -0
  41. package/dist/fetch-impl.js.map +1 -0
  42. package/dist/file-durable-slot.js +2 -1
  43. package/dist/file-durable-slot.js.map +1 -1
  44. package/dist/file-safe-name.d.ts +25 -0
  45. package/dist/file-safe-name.js +29 -0
  46. package/dist/file-safe-name.js.map +1 -0
  47. package/dist/formation-approval.js +5 -11
  48. package/dist/formation-approval.js.map +1 -1
  49. package/dist/fs-atomic.d.ts +0 -19
  50. package/dist/fs-atomic.js +3 -24
  51. package/dist/fs-atomic.js.map +1 -1
  52. package/dist/index.d.ts +22 -10
  53. package/dist/index.js +54 -11
  54. package/dist/index.js.map +1 -1
  55. package/dist/invitation-bootstrap.d.ts +50 -12
  56. package/dist/invitation-bootstrap.js +76 -13
  57. package/dist/invitation-bootstrap.js.map +1 -1
  58. package/dist/joined-strand-store.d.ts +7 -0
  59. package/dist/joined-strand-store.js +9 -0
  60. package/dist/joined-strand-store.js.map +1 -1
  61. package/dist/key-store-file.js +2 -1
  62. package/dist/key-store-file.js.map +1 -1
  63. package/dist/link-budget.d.ts +25 -33
  64. package/dist/link-budget.js +25 -35
  65. package/dist/link-budget.js.map +1 -1
  66. package/dist/machine-removal.d.ts +78 -0
  67. package/dist/machine-removal.js +166 -0
  68. package/dist/machine-removal.js.map +1 -0
  69. package/dist/membership-connection-gater.d.ts +191 -151
  70. package/dist/membership-connection-gater.js +236 -173
  71. package/dist/membership-connection-gater.js.map +1 -1
  72. package/dist/node-claim-payload.d.ts +74 -0
  73. package/dist/node-claim-payload.js +224 -0
  74. package/dist/node-claim-payload.js.map +1 -0
  75. package/dist/node-default-transports.d.ts +27 -0
  76. package/dist/node-default-transports.js +35 -0
  77. package/dist/node-default-transports.js.map +1 -0
  78. package/dist/node-transports.d.ts +30 -0
  79. package/dist/node-transports.js +40 -0
  80. package/dist/node-transports.js.map +1 -0
  81. package/dist/owner-anchor-sync.d.ts +22 -0
  82. package/dist/owner-anchor-sync.js +143 -0
  83. package/dist/owner-anchor-sync.js.map +1 -0
  84. package/dist/peer-authorization.d.ts +113 -18
  85. package/dist/peer-authorization.js +225 -29
  86. package/dist/peer-authorization.js.map +1 -1
  87. package/dist/peer-dial.d.ts +143 -27
  88. package/dist/peer-dial.js +276 -31
  89. package/dist/peer-dial.js.map +1 -1
  90. package/dist/peer-join-backfill.d.ts +26 -2
  91. package/dist/peer-join-backfill.js +60 -12
  92. package/dist/peer-join-backfill.js.map +1 -1
  93. package/dist/peer-record.d.ts +17 -52
  94. package/dist/peer-record.js +20 -58
  95. package/dist/peer-record.js.map +1 -1
  96. package/dist/pending-join-runner.d.ts +66 -58
  97. package/dist/pending-join-runner.js +136 -145
  98. package/dist/pending-join-runner.js.map +1 -1
  99. package/dist/primary-lan-address.d.ts +8 -0
  100. package/dist/primary-lan-address.js +46 -0
  101. package/dist/primary-lan-address.js.map +1 -0
  102. package/dist/provider/client.d.ts +131 -0
  103. package/dist/provider/client.js +226 -0
  104. package/dist/provider/client.js.map +1 -0
  105. package/dist/provider/descriptor.d.ts +41 -0
  106. package/dist/provider/descriptor.js +103 -0
  107. package/dist/provider/descriptor.js.map +1 -0
  108. package/dist/provider/index.d.ts +9 -0
  109. package/dist/provider/index.js +10 -0
  110. package/dist/provider/index.js.map +1 -0
  111. package/dist/provider/oauth.d.ts +125 -0
  112. package/dist/provider/oauth.js +199 -0
  113. package/dist/provider/oauth.js.map +1 -0
  114. package/dist/provider/rent-node.d.ts +101 -0
  115. package/dist/provider/rent-node.js +220 -0
  116. package/dist/provider/rent-node.js.map +1 -0
  117. package/dist/push-fanout.d.ts +8 -2
  118. package/dist/push-fanout.js +8 -2
  119. package/dist/push-fanout.js.map +1 -1
  120. package/dist/relay-addrs.d.ts +9 -4
  121. package/dist/relay-addrs.js +9 -4
  122. package/dist/relay-addrs.js.map +1 -1
  123. package/dist/relay-reservation.d.ts +51 -16
  124. package/dist/relay-reservation.js +107 -24
  125. package/dist/relay-reservation.js.map +1 -1
  126. package/dist/seed-bootstrap.d.ts +165 -123
  127. package/dist/seed-bootstrap.js +313 -275
  128. package/dist/seed-bootstrap.js.map +1 -1
  129. package/dist/seed-trust-policy.d.ts +98 -37
  130. package/dist/seed-trust-policy.js +188 -2
  131. package/dist/seed-trust-policy.js.map +1 -1
  132. package/dist/strand-addr-protocol.d.ts +24 -26
  133. package/dist/strand-addr-protocol.js +19 -26
  134. package/dist/strand-addr-protocol.js.map +1 -1
  135. package/dist/strand-commit-durability.d.ts +54 -0
  136. package/dist/strand-commit-durability.js +74 -0
  137. package/dist/strand-commit-durability.js.map +1 -0
  138. package/dist/strand-database.d.ts +23 -8
  139. package/dist/strand-database.js +41 -13
  140. package/dist/strand-database.js.map +1 -1
  141. package/dist/strand-first-sync-gate.d.ts +7 -1
  142. package/dist/strand-first-sync-gate.js +7 -1
  143. package/dist/strand-first-sync-gate.js.map +1 -1
  144. package/dist/strand-formation-protocol.js +5 -2
  145. package/dist/strand-formation-protocol.js.map +1 -1
  146. package/dist/strand-fret-addrs.d.ts +19 -1
  147. package/dist/strand-fret-addrs.js +27 -9
  148. package/dist/strand-fret-addrs.js.map +1 -1
  149. package/dist/strand-instance-manager.d.ts +81 -19
  150. package/dist/strand-instance-manager.js +216 -105
  151. package/dist/strand-instance-manager.js.map +1 -1
  152. package/dist/strand-move.d.ts +124 -0
  153. package/dist/strand-move.js +438 -0
  154. package/dist/strand-move.js.map +1 -0
  155. package/dist/strand-network-config.js +7 -6
  156. package/dist/strand-network-config.js.map +1 -1
  157. package/dist/strand-peer-redial.d.ts +113 -0
  158. package/dist/strand-peer-redial.js +236 -0
  159. package/dist/strand-peer-redial.js.map +1 -0
  160. package/dist/strand-revocation-enforcer.d.ts +11 -11
  161. package/dist/strand-revocation-enforcer.js +11 -11
  162. package/dist/strand-wake-protocol.d.ts +13 -16
  163. package/dist/strand-wake-protocol.js +23 -27
  164. package/dist/strand-wake-protocol.js.map +1 -1
  165. package/dist/trusted-owner-store.d.ts +35 -5
  166. package/dist/trusted-owner-store.js +50 -8
  167. package/dist/trusted-owner-store.js.map +1 -1
  168. package/dist/types.d.ts +512 -89
  169. package/dist/types.js +10 -0
  170. package/dist/types.js.map +1 -1
  171. package/package.json +19 -10
  172. package/src/cadre-invite-protocol.ts +1052 -0
  173. package/src/cadre-join-request.ts +167 -0
  174. package/src/cadre-node.ts +1703 -386
  175. package/src/claim-proof.ts +147 -0
  176. package/src/control-authorization.ts +203 -117
  177. package/src/control-cohort.ts +1 -1
  178. package/src/control-database.ts +4663 -3453
  179. package/src/control-protocol-guard.ts +348 -0
  180. package/src/control-schema.ts +828 -1078
  181. package/src/control-stream.ts +26 -7
  182. package/src/delegate-admission.ts +1 -1
  183. package/src/device-token.ts +14 -10
  184. package/src/ed25519-key.ts +47 -10
  185. package/src/fetch-impl.ts +23 -0
  186. package/src/file-durable-slot.ts +64 -63
  187. package/src/file-safe-name.ts +32 -0
  188. package/src/formation-approval.ts +604 -610
  189. package/src/fs-atomic.ts +92 -117
  190. package/src/index.ts +789 -648
  191. package/src/invitation-bootstrap.ts +91 -13
  192. package/src/joined-strand-store.ts +508 -498
  193. package/src/key-store-file.ts +142 -141
  194. package/src/link-budget.ts +25 -36
  195. package/src/machine-removal.ts +216 -0
  196. package/src/membership-connection-gater.ts +259 -191
  197. package/src/node-claim-payload.ts +259 -0
  198. package/src/node-default-transports.ts +38 -0
  199. package/src/node-transports.ts +49 -0
  200. package/src/owner-anchor-sync.ts +171 -0
  201. package/src/peer-authorization.ts +258 -29
  202. package/src/peer-dial.ts +604 -315
  203. package/src/peer-join-backfill.ts +62 -11
  204. package/src/peer-record.ts +159 -197
  205. package/src/pending-join-runner.ts +729 -735
  206. package/src/primary-lan-address.ts +47 -0
  207. package/src/provider/client.ts +326 -0
  208. package/src/provider/descriptor.ts +129 -0
  209. package/src/provider/index.ts +59 -0
  210. package/src/provider/oauth.ts +285 -0
  211. package/src/provider/rent-node.ts +275 -0
  212. package/src/push-fanout.ts +8 -2
  213. package/src/relay-addrs.ts +9 -4
  214. package/src/relay-reservation.ts +1211 -1121
  215. package/src/seed-bootstrap.ts +1502 -1448
  216. package/src/seed-trust-policy.ts +353 -140
  217. package/src/strand-addr-protocol.ts +26 -35
  218. package/src/strand-commit-durability.ts +116 -0
  219. package/src/strand-database.ts +46 -14
  220. package/src/strand-first-sync-gate.ts +7 -1
  221. package/src/strand-formation-protocol.ts +1039 -1036
  222. package/src/strand-fret-addrs.ts +179 -145
  223. package/src/strand-instance-manager.ts +2026 -1883
  224. package/src/strand-move.ts +585 -0
  225. package/src/strand-network-config.ts +7 -6
  226. package/src/strand-peer-redial.ts +307 -0
  227. package/src/strand-revocation-enforcer.ts +11 -11
  228. package/src/strand-wake-protocol.ts +23 -30
  229. package/src/trusted-owner-store.ts +242 -171
  230. package/src/types.ts +2687 -2242
@@ -1,1883 +1,2026 @@
1
- import debug from 'debug';
2
- import type { PrivateKey } from '@libp2p/interface';
3
- import { createLibp2pNode, type IRawStorage } from '@optimystic/db-p2p';
4
- import { wrapStorageWithCache, disposeStorageCache } from '@serfab/quereus-plugin-sereus';
5
- import { StrandDatabase } from './strand-database.js';
6
- import { PeerJoinBackfill, type PeerJoinBackfillConfig } from './peer-join-backfill.js';
7
- import { strandNetworkStatePersistence, type StrandNetworkStateStore } from './strand-network-state.js';
8
- import {
9
- StrandRevocationEnforcer,
10
- createRevocationConnectionGater,
11
- readStrandRevocationRows,
12
- type StrandRevocationEnforcementConfig
13
- } from './strand-revocation-enforcer.js';
14
- import {
15
- StrandMembershipReconciler,
16
- type PendingMembershipInviteSource,
17
- type StrandMembershipReconciliationConfig
18
- } from './strand-membership-reconciler.js';
19
- import { removeMemberPeer } from './strand-membership-writer.js';
20
- import { strandMemberKeyPair } from './strand-member-key.js';
21
- import { assertSchemaSignature } from './schema-verification.js';
22
- import { assertStrandScopeKey } from './storage-scope.js';
23
- import {
24
- StrandFirstSyncGate,
25
- StrandAwaitingFirstSyncError,
26
- strandFirstSyncComplete,
27
- DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS,
28
- type StrandFirstSyncConfig
29
- } from './strand-first-sync-gate.js';
30
- import type {
31
- StrandInstance,
32
- StrandRow,
33
- StorageConfig,
34
- NetworkConfig,
35
- LatencyHint,
36
- NodeProfile,
37
- SAppConfig,
38
- SAppInfo,
39
- RawStorageProvider,
40
- Libp2pNodeWithRepo
41
- } from './types.js';
42
- import { DEFAULT_CONNECTION_MONITOR, resolveStrandClusterSize, strandClusterPolicy } from './types.js';
43
- import { strandNodeAddrs } from './strand-network-config.js';
44
- import { resolveRelayServer } from './relay-server.js';
45
- import { strandCohortTopicOption, type StrandReactivityConfig } from './strand-reactivity.js';
46
- import { superviseRelayReservation, type RelayReservationSupervisor } from './relay-reservation.js';
47
- import { isCohortUnreachableRead } from './control-read-retry.js';
48
- import { declaredCohortReadDeadlineMs, optimysticDialLimits, peerJoinPushBudget, relayReservationBudgetMs, resolveLinkRoundTripMs } from './link-budget.js';
49
-
50
- const log = debug('sereus:cadre:strand-manager');
51
-
52
- /**
53
- * How often a joining launch that could not build its database, because no seed peer had
54
- * answered, rebuilds its runtime (`StrandInstanceManager.deferUnreachableJoin`). Each attempt
55
- * starts a libp2p node and dials the seed, so it is spaced well above the first-sync gate's
56
- * probe cadence.
57
- */
58
- export const UNREACHABLE_JOIN_RETRY_MS = 5_000;
59
- const timing = debug('sereus:cadre:timing');
60
-
61
- /** One caller blocked in {@link StrandInstanceManager.whenWritable}. */
62
- interface WritableWaiter {
63
- resolve: () => void;
64
- reject: (error: Error) => void;
65
- }
66
-
67
- /**
68
- * Whether a tracked instance is launched but waiting for its first sync: the runtime is
69
- * up (`libp2pNode` set) while the database is still withheld (`database` unset). That
70
- * is the first-sync gate's state regardless of what `status` says — the hibernation
71
- * manager's idle timer can flip a long-gated joiner to `'idle'` without changing it.
72
- *
73
- * NOTE: `status` is therefore not the source of truth for "gated": a joiner that reaches
74
- * nobody for `idleTimeout` (5 min at the interactive hint) reads `'idle'`, then
75
- * `'hibernating'`, while still holding no database. Harmless today — every decision the
76
- * runtime makes goes through this predicate, {@link StrandInstanceManager.publishDatabase}
77
- * announces on the idle-flipped instance exactly as on a `'syncing'` one, and an app that
78
- * shows "waiting for the other member" on `'syncing'` merely sees "idle" instead after
79
- * five minutes. If an app ever needs the gated LABEL to survive the idle flip, make the
80
- * hibernation manager's idle transition preserve `'syncing'` rather than adding a flag.
81
- */
82
- export function isAwaitingFirstSync(instance: StrandInstance): boolean {
83
- return instance.libp2pNode !== undefined && instance.database === undefined;
84
- }
85
-
86
- /**
87
- * The status a LIVE instance (runtime rebuilt or woken) should report: `'active'` once its
88
- * database is published, `'syncing'` while the first-sync gate still withholds it. Every
89
- * site that would otherwise write `'active'` after a build or a wake goes through this,
90
- * so a gated joiner never reads as writable.
91
- */
92
- export function liveStrandStatus(instance: StrandInstance): 'active' | 'syncing' {
93
- return instance.database ? 'active' : 'syncing';
94
- }
95
-
96
- /**
97
- * Configuration for starting a strand instance
98
- */
99
- export interface StartStrandConfig {
100
- strandRow: StrandRow;
101
- /**
102
- * sApp configuration provided by the hosting application. Absent for a **storage
103
- * replica** — a strand this node stores and serves without the app installed
104
- * (`CadreNodeConfig.hostUnclaimedStrands`): no schema signature check, no `App`
105
- * schema, no `sAppInfo` on the instance, and the default latency hint. A replica is
106
- * always a joiner; `StrandDatabase` refuses to found one. An app that later claims the
107
- * strand upgrades the running replica in place ({@link StrandInstanceManager.attachSApp}).
108
- */
109
- sAppConfig?: SAppConfig;
110
- storage?: StorageConfig;
111
- network?: NetworkConfig;
112
- profile: NodeProfile;
113
- defaultLatencyHint: LatencyHint;
114
- privateKey?: PrivateKey;
115
- /** Cohort-derived discovery seed (multiaddr strings). Defaults to [] when omitted. */
116
- bootstrapNodes?: string[];
117
- /**
118
- * Require a valid author signature on the sApp schema before bring-up.
119
- * Defaults to true (fail closed) when omitted; set false only for dev/test
120
- * with unsigned demo schemas. Mirrors {@link CadreNodeConfig.requireSignedSchemas}.
121
- */
122
- requireSignedSchemas?: boolean;
123
- /**
124
- * Whether this node founds the strand (vs. joins it). Forwarded to the
125
- * StrandDatabase so the founder bootstrap (Header, founding Member/Manager)
126
- * runs once at bring-up. Joiners leave this unset and write nothing. Callers
127
- * resolve it BEFORE calling `startStrand` (`CadreNode.launchStrand` derives it
128
- * from the row's `FounderOwnerKey` when no explicit flag is given — see
129
- * {@link StrandConfig.founder}); a founder request that arrives while the
130
- * instance is already tracked goes through {@link StrandInstanceManager.foundExistingStrand},
131
- * never through a repeat `startStrand`.
132
- */
133
- founder?: boolean;
134
- /**
135
- * THIS party's own strand membership private key (base64 protobuf) for a closed
136
- * strand — the identity the founder bootstrap derives `Member.Key` /
137
- * `Manager.MemberKey` from. Resolved by the caller (`CadreNode.launchStrand`: an
138
- * explicit attach-time key, else the control-layer `StrandPartyKey` row, healed by
139
- * mint-on-launch for the founding machine) and retained with the launch config, so a
140
- * hibernation wake rebuilds under the same identity. Deliberately NOT the strand
141
- * row's shared `MemberPrivateKey` (see `StrandDatabaseConfig.partyMemberPrivateKey`).
142
- * Absent for open strands, and for joiners with no persisted party key.
143
- */
144
- partyMemberPrivateKey?: string;
145
- /**
146
- * Number of nodes Optimystic is told this strand's replication cluster should
147
- * have. Same rule as {@link CadreNodeConfig.strandClusterSize}, which CadreNode
148
- * forwards here: every node on the strand should use the same value, and it is
149
- * frozen when the strand's libp2p node is created. Defaults to
150
- * `DEFAULT_STRAND_CLUSTER_SIZE` (4); values below `MIN_CLUSTER_SIZE` (2) are
151
- * rejected by `resolveStrandClusterSize`. Strand-only — the
152
- * control network's breadth is the fixed `CONTROL_REPLICATION_BREADTH`.
153
- */
154
- clusterSize?: number;
155
- /**
156
- * Machines that SERVE THIS STRAND (this node included), for the strand node's
157
- * block-repair corroboration yardstick — see `resolveRepairYardstick`. It must be
158
- * an authenticated per-strand count: the machines that actually run a node for this
159
- * strand, not the machines that exist.
160
- *
161
- * **The party's enrolled-machine count is NOT this number and must never be passed
162
- * here.** A strand launches only on machines whose embedding app registered its sApp
163
- * config (`CadreNode.addStrand`), so a closed strand shared by two machines of a
164
- * three-machine party is served by two. Passing three over-declares, and
165
- * over-declaring is the unsafe direction: at a declaration of 3 or more Optimystic
166
- * pins the repair corroboration floor at two corroborating peers, which a cohort
167
- * that can only ever field one peer can never reach — so the strand can never repair
168
- * a block (`cluster-fetch:no-quorum`, surfacing as reads failing with `Missing
169
- * block`). That regression is why this field was renamed off "enrolledMachines":
170
- * `bug-strand-yardstick-counts-party-machines`.
171
- *
172
- * **Nothing feeds it in production today.** No authenticated per-strand serving count
173
- * exists yet, so `CadreNode` passes nothing and the strand node runs the frozen
174
- * `STRAND_CLUSTER_POLICY` — declaring no yardstick, which leaves the known,
175
- * upstream-tracked single-voter exposure
176
- * (`backlog/debt-read-repair-single-voter-corroboration`). Building the count is
177
- * `backlog/feat-strand-yardstick-from-serving-machines`; this field and its
178
- * threading are the seam it plugs into.
179
- *
180
- * Volatile when a source does exist: re-resolve it on every resume beside the cohort
181
- * seed, since machines join and leave a strand while it hibernates. Omitting it means
182
- * "this node does not know", which declares nothing.
183
- */
184
- servingMachines?: number;
185
- /**
186
- * Tuning for the strand peer-join block catch-up ({@link PeerJoinBackfill}),
187
- * forwarded from {@link CadreNodeConfig.strandBackfill}. When the strand's
188
- * libp2p node connects to a peer this runtime has not yet caught up, every
189
- * block in the strand's own raw store is pushed to it. Runs only on strands
190
- * with per-strand storage; `{ enabled: false }` restores the pre-existing
191
- * no-backfill behaviour.
192
- */
193
- backfill?: PeerJoinBackfillConfig;
194
- /**
195
- * Whether this strand's libp2p node is built with Optimystic's change notifications,
196
- * forwarded from {@link CadreNodeConfig.strandReactivity} and resolved per strand by
197
- * `strandCohortTopicOption`. Retained with the launch config, so a hibernation wake
198
- * rebuilds the node with the same setting.
199
- */
200
- reactivity?: StrandReactivityConfig;
201
- /**
202
- * Tuning for the CLOSED-strand revoked-peer gate
203
- * ({@link StrandRevocationEnforcer}), forwarded from
204
- * {@link CadreNodeConfig.strandRevocationEnforcement}. Armed only for
205
- * `strandRow.Type === 'c'` (an open strand has no membership rows to derive a
206
- * deny set from); `{ enabled: false }` restores the pre-existing behaviour
207
- * (a removed party's peers keep being served).
208
- */
209
- revocationEnforcement?: StrandRevocationEnforcementConfig;
210
-
211
- /**
212
- * The staged formation membership invitation for THIS strand — the seam the
213
- * bring-up membership reconciler (`strand-membership-reconciler.ts`) reads to
214
- * redeem the party's `Strand.Member` seat, and clears once the invitation is
215
- * spent, burned, or dead. `CadreNode.launchStrand` wires it over its in-memory
216
- * `pendingMembershipInvites` map; read lazily per pass, so a re-formation that
217
- * replaces the entry between passes is picked up. Only consulted for closed
218
- * strands launched with a {@link partyMemberPrivateKey}; harmless otherwise.
219
- */
220
- pendingMembershipInvite?: PendingMembershipInviteSource;
221
-
222
- /**
223
- * Tuning for the CLOSED-strand membership reconciler, forwarded from
224
- * {@link CadreNodeConfig.strandMembershipReconciliation}. Armed only for
225
- * closed strands launched with a {@link partyMemberPrivateKey};
226
- * `{ enabled: false }` disarms the loop (test fixtures that hand-drive the
227
- * membership writers). When it names no `pollIntervalMs` the reconciler
228
- * mirrors {@link revocationEnforcement}'s cadence — as its IDLE cadence and
229
- * the cap of its unfinished-join retry ladder, not as a flat retry interval.
230
- */
231
- membershipReconciliation?: StrandMembershipReconciliationConfig;
232
-
233
- /**
234
- * Called when THIS node's own peer id turns up in the strand's revoked set —
235
- * this node's party was removed from the closed strand, or left it. Fires once
236
- * per removal (re-armed if the party is re-admitted; a resume also rebuilds the
237
- * enforcer and may legitimately re-fire), and only for closed strands with the
238
- * gate armed. `CadreNode`
239
- * wires it to its `strand:revoked` event; nothing is stopped or torn down on
240
- * this node's behalf — what to do about it is the app's call.
241
- */
242
- onSelfRevoked?: (strandId: string) => void;
243
-
244
- /**
245
- * Called when the membership reconciler reports a blocked re-join — this node holds a
246
- * staged membership invitation for the strand that its writes cannot redeem, which is
247
- * what a REMOVED party handed a fresh invitation hits (see "Reporting a blocked
248
- * re-join" in `strand-membership-reconciler.ts` for the two triggers, one of them a
249
- * suspicion rather than a verdict). At most once per re-arm of the loop — a further
250
- * invitation staged while the loop is still running does not reset the report — and
251
- * only for closed strands with a party key. `CadreNode` wires it to its `strand:rejoin-blocked`
252
- * event; nothing is stopped or torn down — a remaining manager admitting this party's
253
- * key directly is the remedy, and the loop finishes the join by itself once that lands.
254
- */
255
- onRejoinBlocked?: (strandId: string) => void;
256
-
257
- /**
258
- * Tuning for the JOINING machine's first-sync write gate (`strand-first-sync-gate.ts`),
259
- * forwarded from {@link CadreNodeConfig.strandFirstSync}: the Header probe cadence while
260
- * a non-founder launch is `'syncing'`, and the default budget {@link whenWritable} waits
261
- * before rejecting. Founders and machines that already hold the Header are never gated.
262
- */
263
- firstSync?: StrandFirstSyncConfig;
264
-
265
- /**
266
- * Called when a launch that came up `'syncing'` (see {@link firstSync}) becomes
267
- * writable: the strand's `Strand.Header` arrived from a peer — or a founder request
268
- * ran the bootstrap against the gated database — and `instance.database` is now set.
269
- * Never called for a launch that was writable when `startStrand`/`resumeStrand`
270
- * resolved. `CadreNode` wires it to its `strand:writable` event. Retained with the
271
- * launch config, so a hibernation resume that comes up gated announces too.
272
- */
273
- onWritable?: (strandId: string) => void;
274
-
275
- /**
276
- * Re-announce this strand's delegate peer id (`delegatePeerId` — the strand
277
- * node's own transport peer id) to ONE relay (`relayAddr`, a direct dial addr
278
- * with a trailing `/p2p/<relayPeerId>`), unthrottled. Awaited before every
279
- * relay-reservation RE-drive of that relay — never before the first attempt,
280
- * which the launch/resume seed pass has already announced for.
281
- *
282
- * Why: a party control node running the relay server admits the strand node on
283
- * an in-memory delegate grant that a relay restart drops, so a re-drive that did
284
- * not re-announce first would be denied at the relay's gate. `CadreNode` wires
285
- * its own control-mesh announce here; a throw or rejection is logged by the
286
- * supervisor and the re-drive still runs. Retained with the launch config, so a
287
- * hibernation wake's rebuilt supervisors carry it too.
288
- */
289
- announceDelegateToRelay?: (strandId: string, relayAddr: string, delegatePeerId: string) => Promise<void>;
290
-
291
- /**
292
- * The node-local strand network state (`strand-network-state.ts`): this strand's
293
- * slice of it is handed to db-p2p as `persistence`, so the strand node saves its
294
- * FRET routing table (with each peer's signed address record) on every connection
295
- * and re-imports it when it is next built. Absent ⇒ nothing is saved and the node
296
- * starts with an empty table. `CadreNode` passes its store. Retained with the launch
297
- * config, so a hibernation wake rebuilds the node over the same state.
298
- */
299
- networkState?: StrandNetworkStateStore;
300
- }
301
-
302
- /**
303
- * Volatile inputs re-resolved when resuming a quiesced strand — the ones that can
304
- * have moved since it last ran, and that the rebuilt libp2p node freezes again. Each
305
- * one omitted keeps the value the retained launch config already holds, so a resume
306
- * that passes nothing rebuilds the strand exactly as it last ran.
307
- */
308
- export interface ResumeStrandOverrides {
309
- /**
310
- * Freshly-resolved cohort discovery seed (multiaddr strings). Grows as peers are
311
- * learned since the strand first launched.
312
- */
313
- bootstrapNodes?: string[];
314
- /**
315
- * Freshly-read count of the machines serving this strand, for the repair yardstick
316
- * (see {@link StartStrandConfig.servingMachines} — including why the party's
317
- * enrolled-machine count is not it). Moves whenever a machine starts or stops
318
- * serving the strand, which a hibernating strand does not otherwise notice. Nothing
319
- * passes it today. Omitting it here does NOT mean "unknown" the way omitting it from
320
- * {@link StartStrandConfig} does — it retains the last value; see `resumeStrand`.
321
- */
322
- servingMachines?: number;
323
- }
324
-
325
- /** A {@link StrandInstanceManager.resumeStrand} or {@link StrandInstanceManager.quiesceStrand} of one strand. */
326
- type RuntimeTransition =
327
- | { kind: 'resume'; operation: Promise<StrandInstance> }
328
- | { kind: 'quiesce'; operation: Promise<void> };
329
-
330
- /**
331
- * Get the isolated storage path for a specific strand.
332
- *
333
- * @deprecated This helper is Node-only and throws in React Native (it assumes a
334
- * filesystem layout). Use a storage provider factory function instead, which
335
- * receives the strandId and can create strand-specific storage paths using
336
- * platform-appropriate methods.
337
- *
338
- * @example
339
- * // Instead of using getStrandStoragePath, use a storage provider factory:
340
- * const storage = {
341
- * provider: (strandId: string) => new FileRawStorage(`./data/strands/${strandId}`)
342
- * };
343
- */
344
- export function getStrandStoragePath(basePath: string, strandId: string): string {
345
- // Check if we're in a Node.js environment
346
- if (typeof process === 'undefined' || !process.versions?.node) {
347
- throw new Error(
348
- 'getStrandStoragePath is not available in React Native. ' +
349
- 'Use a storage provider factory function instead.'
350
- );
351
- }
352
-
353
- // Sanitize strandId for filesystem safety (UUIDs should be safe, but just in case)
354
- const safeId = strandId.replace(/[^a-zA-Z0-9-]/g, '_');
355
-
356
- // Build the path with plain string joins rather than the Node `path` module.
357
- // A static `require('path')` forces RN bundlers (e.g. Metro) to *resolve* the
358
- // module at bundle time even though this Node-only helper throws above before
359
- // ever reaching here — joining by hand keeps the module free of any Node
360
- // built-in reference, so RN bundles need no `path` shim.
361
- const trimmedBase = basePath.replace(/[\\/]+$/, '');
362
- return `${trimmedBase}/strands/${safeId}`;
363
- }
364
-
365
- /**
366
- * Resolve a storage provider for a specific strand.
367
- * If the provider is a factory function, call it with the strandId.
368
- *
369
- * Called only from {@link StrandInstanceManager.startStrand}, which owns the result
370
- * for the instance's lifetime — see `strandStorages`, and which has already asserted
371
- * the id is usable as a scope key. Do not move that assertion here: this function
372
- * returns early when no provider is configured, and the id becomes a libp2p protocol
373
- * prefix on that path too.
374
- *
375
- * @param provider - Storage provider (instance or factory)
376
- * @param strandId - The strand ID to create storage for
377
- * @returns The resolved IRawStorage instance, or undefined if no provider
378
- */
379
- function resolveStrandStorage(
380
- provider: RawStorageProvider | undefined,
381
- strandId: string
382
- ): IRawStorage | undefined {
383
- if (!provider) {
384
- return undefined;
385
- }
386
- const storage = typeof provider === 'function' ? provider(strandId) : provider;
387
- // Wrapped in the write-through raw-storage cache (quereus-plugin-sereus's cached-storage.ts).
388
- // Called ONCE per strand launch — `startStrand` keeps the result for the instance's
389
- // lifetime — so the wrap survives every runtime rebuild the instance goes through.
390
- return wrapStorageWithCache(storage, strandId);
391
- }
392
-
393
- /**
394
- * Verify an sApp's schema signature (fail-closed unless `requireSignedSchemas` is
395
- * false) and project the config onto the instance's `sAppInfo`.
396
- */
397
- function verifiedSAppInfo(strandId: string, sAppConfig: SAppConfig, requireSignedSchemas: boolean | undefined): SAppInfo {
398
- assertSchemaSignature(sAppConfig, { requireSignature: requireSignedSchemas ?? true });
399
- log('Strand %s sApp schema signature verified (author: %s)', strandId, sAppConfig.id);
400
- return {
401
- id: sAppConfig.id,
402
- version: sAppConfig.version,
403
- schema: sAppConfig.schema,
404
- signature: sAppConfig.signature
405
- };
406
- }
407
-
408
- /** Log wording for what a launch runs: the sApp and its version, or a storage replica. */
409
- function describeSApp(sAppConfig: SAppConfig | undefined): string {
410
- return sAppConfig ? `sApp: ${sAppConfig.id} v${sAppConfig.version}` : 'storage replica';
411
- }
412
-
413
- /**
414
- * Manages individual strand instances - creates and destroys isolated libp2p nodes
415
- * for each strand the cadre participates in.
416
- */
417
- export class StrandInstanceManager {
418
- private instances: Map<string, StrandInstance> = new Map();
419
- /**
420
- * Retained launch config per strand, captured in `startStrand` and cleared in
421
- * `stopStrand`. `resumeStrand` reuses it to rebuild a quiesced strand's runtime
422
- * without the caller re-threading storage/network/profile/key/sApp config.
423
- */
424
- private launchConfigs: Map<string, StartStrandConfig> = new Map();
425
- /**
426
- * The per-strand peer-join block catch-up, keyed by strand id. Private (not on
427
- * the public {@link StrandInstance}) because it is runtime plumbing with the
428
- * same lifetime as the strand's libp2p node: created in `buildStrandRuntime`,
429
- * stopped and dropped in `releaseRuntime` — so quiesce → resume rebuilds it
430
- * with a fresh caught-up-peer memo, which is intended (a resumed node may have
431
- * missed writes).
432
- */
433
- private backfills: Map<string, PeerJoinBackfill> = new Map();
434
- /**
435
- * The per-strand revoked-peer enforcer (closed strands only), keyed by strand
436
- * id. Same lifecycle rationale as {@link backfills}: created in
437
- * `buildStrandRuntime`, stopped and dropped in `releaseRuntime`, so quiesce →
438
- * resume rebuilds it with a fresh (initially empty, fail-open) snapshot.
439
- */
440
- private revocationEnforcers: Map<string, StrandRevocationEnforcer> = new Map();
441
- /**
442
- * The per-strand membership reconciler (closed strands launched with a party
443
- * key only), keyed by strand id. Same lifecycle rationale as {@link backfills}:
444
- * created in `buildStrandRuntime`, stopped and dropped in `releaseRuntime`, so
445
- * quiesce → resume rebuilds it and re-runs the idempotent join ladder (redeem a
446
- * staged invitation, write this machine's own `MemberPeer` binding) from scratch.
447
- */
448
- private membershipReconcilers: Map<string, StrandMembershipReconciler> = new Map();
449
- /**
450
- * The per-strand first-sync gate (`strand-first-sync-gate.ts`), keyed by strand id:
451
- * holds a launch's `StrandDatabase` while it is NOT yet published on the instance.
452
- * Present from the moment the database object exists in `buildStrandRuntime` until
453
- * {@link publishDatabase} hands it to the app — so it doubles as the rollback handle
454
- * for a failed `initialize()` — and, for a joiner that holds no `Strand.Header` yet,
455
- * for as long as the launch stays `'syncing'`. Same lifecycle as {@link backfills}:
456
- * stopped (its database closed) and dropped in `releaseRuntime`, so a quiesce →
457
- * resume rebuild re-probes over the same store. An entry and `instance.database`
458
- * are mutually exclusive.
459
- */
460
- private firstSyncGates: Map<string, StrandFirstSyncGate> = new Map();
461
- /**
462
- * Callers blocked in {@link whenWritable}, keyed by strand id. Resolved by
463
- * {@link publishDatabase}, rejected by {@link stopStrand}; each waiter also carries
464
- * its own timeout. Deliberately NOT cleared by `releaseRuntime`: a waiter outlives a
465
- * quiesce → resume cycle, since the rebuild is what may finally publish the database.
466
- */
467
- private writableWaiters: Map<string, Set<WritableWaiter>> = new Map();
468
- /**
469
- * The per-strand relay-reservation supervisors — ONE PER CONFIGURED RELAY, each
470
- * over the node's own bare `/p2p-circuit` listener for that relay
471
- * (`strand-network-config.ts`) — keyed by strand id. Same lifecycle rationale as
472
- * {@link backfills}: started in `buildStrandRuntime` right after the libp2p node
473
- * exists, stopped FIRST and dropped in `releaseRuntime` (before the database
474
- * closes and the node stops, so no re-drive dials a node being torn down), so
475
- * quiesce → resume rebuilds them over the new node. What makes a strand node's
476
- * lost relay slot come back on its own — the control node has the same loop in
477
- * `CadreNode.reserveRelays`.
478
- */
479
- private relaySupervisors: Map<string, RelayReservationSupervisor[]> = new Map();
480
- /**
481
- * The resolved (cache-wrapped) raw storage per strand id — the instance's OWN
482
- * store, resolved once in `startStrand` and held until `stopStrand` disposes it.
483
- * Private for the same reason `backfills` is: runtime plumbing, not part of the
484
- * public {@link StrandInstance}.
485
- *
486
- * Deliberately NOT touched by `releaseRuntime`: that is what lets a quiesce →
487
- * resume cycle rebuild the libp2p node over the SAME store, keeping its
488
- * write-through cache warm (and, on an in-memory backend, keeping the strand's
489
- * blocks at all). An entry exists iff `instances` does AND the launch config
490
- * supplied a storage provider.
491
- *
492
- * NOTE: a hibernating strand therefore keeps its store — and its share of the
493
- * process-wide cache pool — resident for as long as the instance is tracked. That
494
- * is the point (a warm wake), and the pool evicts under pressure, so the cost is
495
- * one map entry per hibernating strand today. If a device ever hibernates strands
496
- * by the hundred, revisit: dropping the store at quiesce and paying for a cold
497
- * wake becomes the better trade.
498
- */
499
- private strandStorages: Map<string, IRawStorage> = new Map();
500
- /**
501
- * The runtime build in flight per strand id (`buildStrandRuntime`, from `startStrand` or
502
- * `resumeStrand`), present until it settles. The instance is tracked for the whole build,
503
- * with its database not yet constructed or not yet initialized, so a caller that must act
504
- * on the FINISHED runtime ({@link attachSApp}, {@link whenRuntimeBuilt}) waits on this instead. A failed build's
505
- * rejection belongs to the call that started it.
506
- */
507
- private runtimeBuilds: Map<string, Promise<void>> = new Map();
508
- /**
509
- * The latest resume or quiesce requested per strand id, present until it settles. Each one
510
- * starts only once the one requested before it has settled, so a wake that lands during a
511
- * quiesce rebuilds after it, and a quiesce requested during a rebuild releases what that
512
- * rebuild finished. The WHOLE operation, not its entry in {@link runtimeBuilds}: that settles
513
- * before a resume's own catch records `'error'`, so a joiner awaiting it could read a stale
514
- * status.
515
- */
516
- private transitions: Map<string, RuntimeTransition> = new Map();
517
- /**
518
- * The pending rebuild per strand id of a launch whose database could not be built
519
- * because no seed peer had answered yet ({@link deferUnreachableJoin}). Cleared by
520
- * {@link releaseRuntime}, so a stop, a quiesce or a resume cancels it.
521
- */
522
- private unreachableJoinRetries: Map<string, unknown> = new Map();
523
- private stopping = false;
524
-
525
- constructor() {
526
- log('StrandInstanceManager created');
527
- }
528
-
529
- /**
530
- * Get all current strand instances
531
- */
532
- getInstances(): Map<string, StrandInstance> {
533
- return new Map(this.instances);
534
- }
535
-
536
- /**
537
- * Get a specific strand instance
538
- */
539
- getInstance(strandId: string): StrandInstance | undefined {
540
- return this.instances.get(strandId);
541
- }
542
-
543
- /**
544
- * Check if a strand is currently running
545
- */
546
- hasStrand(strandId: string): boolean {
547
- return this.instances.has(strandId);
548
- }
549
-
550
- /**
551
- * Start a new strand instance.
552
- *
553
- * A failed launch leaves NOTHING tracked: the instance and its retained launch
554
- * config are both dropped before the error is rethrown, so the strand id is
555
- * free for a genuine retry. This matches the pre-registration failure path
556
- * (a rejected schema signature, which throws before anything is recorded) —
557
- * both failure modes of this call leave the same residue: none. Callers learn
558
- * of the failure from the rejected promise (and, on the control-discovered
559
- * path, from CadreNode's `strand:error` event), not from an error record left
560
- * behind in `instances`.
561
- *
562
- * The strand's raw storage is resolved HERE, once, and held for the instance's
563
- * lifetime (see `strandStorages`) — `buildStrandRuntime` only reads it, so a
564
- * hibernation wake never re-enters the embedder's provider.
565
- */
566
- async startStrand(config: StartStrandConfig): Promise<StrandInstance> {
567
- const { strandRow, sAppConfig } = config;
568
- const strandId = strandRow.Id;
569
-
570
- if (this.stopping) {
571
- throw new Error('StrandInstanceManager is stopping');
572
- }
573
-
574
- if (this.instances.has(strandId)) {
575
- // Callers resolve founder-ness BEFORE reaching here (CadreNode.launchStrand) and
576
- // honor a founder request on a tracked instance via foundExistingStrand — so a
577
- // founder flag arriving at this early return against a non-founder retained
578
- // config is a dropped bootstrap, and must never again be silent.
579
- if (config.founder === true && this.launchConfigs.get(strandId)?.founder !== true) {
580
- log('startStrand: strand %s is already running but was NOT launched as founder — ' +
581
- 'this early return DROPS the founder request; use foundExistingStrand', strandId);
582
- }
583
- log('Strand %s already running', strandId);
584
- return this.instances.get(strandId)!;
585
- }
586
-
587
- log('Starting strand instance: %s (%s)', strandId, describeSApp(sAppConfig));
588
- const tTotal = performance.now();
589
-
590
- // The id becomes two names below: the storage scope key the embedder's provider
591
- // turns into a directory or database name, and `networkName` in buildStrandRuntime,
592
- // from which the libp2p protocol prefix `/optimystic/strand-<id>` is built. A
593
- // replicated strand row carries whatever id the founding node wrote, so neither is
594
- // safe unchecked. Asserted HERE rather than in `resolveStrandStorage` because that
595
- // function returns early when no provider is configured — a node with no storage
596
- // still reaches buildStrandRuntime and still mints the protocol prefix.
597
- assertStrandScopeKey(strandId);
598
-
599
- const sAppInfo = sAppConfig ? verifiedSAppInfo(strandId, sAppConfig, config.requireSignedSchemas) : undefined;
600
-
601
- // Resolve this strand's storage ONCE, before anything is recorded. If a factory
602
- // function is provided, it is called with the strandId to create strand-specific
603
- // storage (e.g. strand-isolated directories). A provider that throws therefore
604
- // fails the launch alongside the schema-signature check, leaving nothing tracked.
605
- const strandStorage = resolveStrandStorage(config.storage?.provider, strandId);
606
- if (strandStorage) {
607
- log('Strand %s using provided storage provider', strandId);
608
- }
609
-
610
- // Determine latency hint: sApp config > default
611
- const latencyHint = sAppConfig?.latencyHint ?? config.defaultLatencyHint;
612
-
613
- const instance: StrandInstance = {
614
- strandId,
615
- status: 'starting',
616
- sAppInfo,
617
- memberPrivateKey: strandRow.MemberPrivateKey ?? undefined,
618
- connectedPeers: 0,
619
- lastActivity: new Date(),
620
- latencyHint
621
- };
622
-
623
- this.instances.set(strandId, instance);
624
- this.launchConfigs.set(strandId, config);
625
- if (strandStorage) {
626
- this.strandStorages.set(strandId, strandStorage);
627
- }
628
-
629
- try {
630
- await this.trackRuntimeBuild(strandId, this.buildStrandRuntime(instance, config));
631
- timing('[startStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
632
- log('Strand %s started successfully (%s)', strandId, describeSApp(sAppConfig));
633
- return instance;
634
- } catch (error) {
635
- // Status/error first — the (now discarded) record is still what `log` reports on.
636
- instance.status = 'error';
637
- instance.error = error instanceof Error ? error.message : String(error);
638
- log('Failed to start strand %s: %s', strandId, instance.error);
639
- // Drop the dead record so this strand id can be launched again. Keep the
640
- // `launchConfigs` has an entry iff `instances` does invariant — resumeStrand
641
- // reads both, and a config without an instance would strand the config.
642
- this.instances.delete(strandId);
643
- this.launchConfigs.delete(strandId);
644
- // The store this launch resolved goes with it: nothing owns it any more, and a
645
- // retained cache wrapper would be handed back (already retired) on a retry.
646
- await this.disposeStrandStorage(strandId);
647
- throw error;
648
- }
649
- }
650
-
651
- /** Hold `build` in {@link runtimeBuilds} until it settles, and settle as it does. */
652
- private async trackRuntimeBuild(strandId: string, build: Promise<void>): Promise<void> {
653
- this.runtimeBuilds.set(strandId, build);
654
- try {
655
- await build;
656
- } finally {
657
- if (this.runtimeBuilds.get(strandId) === build) {
658
- this.runtimeBuilds.delete(strandId);
659
- }
660
- }
661
- }
662
-
663
- /**
664
- * Wait until no runtime build of `strandId` is in flight. Never rejects: a failed build
665
- * is reported by the call that started it, and the caller re-reads the instance after.
666
- *
667
- * NOTE: after a failed launch the re-read sees the instance gone only because
668
- * `startStrand`'s catch deletes it synchronously, and its continuation is queued before
669
- * this waiter's. If that cleanup ever awaits before `instances.delete`, a waiter can act
670
- * on the dying record; move the cleanup inside the tracked promise then.
671
- */
672
- private async settleRuntimeBuilds(strandId: string): Promise<void> {
673
- for (let build = this.runtimeBuilds.get(strandId); build; build = this.runtimeBuilds.get(strandId)) {
674
- await build.catch((error: unknown) => {
675
- log('Strand %s: the runtime build waited on failed (reported by its launcher): %o', strandId, error);
676
- });
677
- }
678
- }
679
-
680
- /**
681
- * Build (or rebuild) the libp2p node + StrandDatabase for an instance and
682
- * attach them, transitioning it to `active`. Shared by `startStrand` (fresh
683
- * launch) and `resumeStrand` (rehydrating a quiesced instance). Reads all
684
- * volatile inputs (bootstrapNodes, servingMachines, network, profile,
685
- * privateKey, sApp config) from `config`, so the caller controls the
686
- * cohort-derived values. Storage is the
687
- * one input it does NOT re-read from `config`: that belongs to the instance and
688
- * comes from `strandStorages`.
689
- */
690
- private async buildStrandRuntime(instance: StrandInstance, config: StartStrandConfig): Promise<void> {
691
- const strandId = instance.strandId;
692
- const { sAppConfig } = config;
693
-
694
- // Refuse a bad `linkRoundTripMs` before any strand bring-up, for the reason
695
- // `CadreNode.start()` does: every budget derived from it here is behind a condition
696
- // (backfill disabled, no relay addrs), so a zero or NaN declaration would otherwise
697
- // surface later inside a path that logs and carries on. `link-budget.ts`.
698
- resolveLinkRoundTripMs(config.network?.linkRoundTripMs);
699
-
700
- // The store the instance OWNS (resolved once in `startStrand`), not a fresh
701
- // resolution: a rebuild must reach the same backend through the same warm cache.
702
- const strandStorage = this.strandStorages.get(strandId);
703
-
704
- // db-p2p namespaces every one of the node's protocol ids by network name
705
- // (`/optimystic/<networkName>/...`), so anything dialing this node's own
706
- // services must derive its prefix from the SAME string the node was built
707
- // with — hence one binding for both, not two literals that can drift.
708
- const networkName = `strand-${strandId}`;
709
- // Set when the database build failed only because no seed peer has answered yet; see
710
- // {@link deferUnreachableJoin}.
711
- let joinWaitsForSeed = false;
712
- const protocolPrefix = `/optimystic/${networkName}`;
713
-
714
- // Whether this node runs the circuit-relay server, and its init — the same
715
- // resolution the control node takes from the same config (`relay-server.ts`).
716
- const relayServer = resolveRelayServer(config.network, config.profile);
717
- // The strand-node VIEW of the machine's one `NetworkConfig`, not the control
718
- // node's resolution: fixed direct listen ports become ephemeral (two nodes cannot
719
- // bind one port), the announce config is dropped (it names the control node's
720
- // address), and every configured relay becomes one bare `/p2p-circuit` SEARCH
721
- // listener plus a dial addr in `relayAddrs` for the per-relay supervisor started
722
- // below — the same route the control node takes, because the configured
723
- // `<relay>/p2p-circuit` shape loses its address on a relay restart, a hangup, or
724
- // libp2p's own reservation refresh and recovers from none of them. See
725
- // `strand-network-config.ts` for all three, and `relay-reservation.ts`.
726
- //
727
- // `relayAddrs` is destructured OFF: it is not a `createLibp2pNode` option, and
728
- // spreading it would hand db-p2p a key it does not know.
729
- const { relayAddrs: relayDialAddrs = [], ...addrOptions } = strandNodeAddrs(config.network);
730
-
731
- // The CLOSED-strand revoked-peer gate (see strand-revocation-enforcer.ts).
732
- // Constructed BEFORE the libp2p node because the node's options embed its
733
- // predicates; its deny set starts empty (admit everything — fail-open, same
734
- // posture as bring-up everywhere here) and is first populated after the
735
- // strand database initializes below. Registered in the map immediately so
736
- // the failure rollback (releaseRuntime) tears it down like every other
737
- // runtime component. Open strands skip it entirely: their Member/MemberPeer
738
- // tables are empty by schema (`OnlyClosed`), so there is nothing to derive
739
- // a deny set from — arming would be pointless polling.
740
- const revocationEnforcer =
741
- config.strandRow.Type === 'c' && config.revocationEnforcement?.enabled !== false
742
- ? new StrandRevocationEnforcer({
743
- label: strandId,
744
- readRows: () => {
745
- const database = instance.database;
746
- if (!database) {
747
- throw new Error(`strand ${strandId} has no live database`);
748
- }
749
- return readStrandRevocationRows(database.getDatabase());
750
- },
751
- // Read per sweep, never captured: this closure is built BEFORE the
752
- // libp2p node exists (its options embed the enforcer's predicates),
753
- // and `releaseRuntime` clears the field again on quiesce. Undefined
754
- // therefore means "no transport right now", which the enforcer
755
- // treats as "nothing to tear down".
756
- getNetwork: () => instance.libp2pNode,
757
- onSelfRevoked: () => config.onSelfRevoked?.(strandId)
758
- }, config.revocationEnforcement)
759
- : undefined;
760
- if (revocationEnforcer) {
761
- this.revocationEnforcers.set(strandId, revocationEnforcer);
762
- }
763
-
764
- // Closed strands compose revoked-peer denial onto the caller's gater and arm
765
- // the fail-closed per-stream gate; open strands keep the raw configured gater
766
- // (their peers are legitimately cross-party and nothing is ever revoked).
767
- const revocationGateOptions = revocationEnforcer
768
- ? {
769
- connectionGater: createRevocationConnectionGater(revocationEnforcer, config.network?.connectionGater),
770
- authorizeInboundStream: (remotePeerId: string, protocol: string) =>
771
- revocationEnforcer.authorizeStream(remotePeerId, protocol)
772
- }
773
- : config.network?.connectionGater
774
- ? { connectionGater: config.network.connectionGater }
775
- : {};
776
-
777
- const reactivityOption = strandCohortTopicOption(config.reactivity, strandId);
778
- if (reactivityOption.cohortTopic) {
779
- log('strand %s: change notifications on', strandId);
780
- }
781
-
782
- try {
783
- // Bound once: the breadth is also the ceiling on the repair yardstick below, and the
784
- // two must be derived from the same resolution. Inside the `try` deliberately — a
785
- // rejected clusterSize is a build failure that runs the same cleanup as any other.
786
- const strandClusterSize = resolveStrandClusterSize(config.clusterSize);
787
-
788
- let t0 = performance.now();
789
- const node = await createLibp2pNode({
790
- port: 0, // Random port
791
- bootstrapNodes: config.bootstrapNodes ?? [],
792
- networkName,
793
- storage: strandStorage,
794
- fretProfile: config.profile === 'storage' ? 'core' : 'edge',
795
- relay: relayServer.enabled,
796
- // NOTE: unlike the control node, a strand node has no unauthorized-reservation budget,
797
- // so with the per-connection cap off any peer that reaches this node can hold one of
798
- // `maxReservations` slots and forward uncapped through it. If strand relays are ever
799
- // abused for bandwidth, give strand nodes a budget or a capped init of their own.
800
- ...(relayServer.enabled && { relayServerInit: relayServer.init }),
801
- clusterSize: strandClusterSize,
802
- // Deliberately NOT CONTROL_CLUSTER_POLICY: a strand is application data with its own
803
- // breadth reasoning, and the shape match with the control policy is a coincidence.
804
- //
805
- // The builder declares this node's block-repair corroboration yardstick from the
806
- // count of machines SERVING this strand, capped at the breadth above (a block
807
- // never lives on more machines than the cohort is wide). Given no count — the
808
- // production path today, since no per-strand serving count exists yet — it
809
- // returns the frozen STRAND_CLUSTER_POLICY itself, declaring nothing. Resolved
810
- // HERE rather than at `startStrand`, so a wake from hibernation would pick up a
811
- // serving set that changed while the strand slept.
812
- // The read deadline is settled by the same helper the control node uses, because the
813
- // two networks ride one link: the host's own, else derived from its declared
814
- // `linkRoundTripMs`, else nothing, and the base policy's COHORT_READ_DEADLINE_MS stands.
815
- clusterPolicy: strandClusterPolicy(strandClusterSize, {
816
- servingMachines: config.servingMachines,
817
- cohortQueryTimeoutMs: declaredCohortReadDeadlineMs(config.network)
818
- }),
819
- arachnode: {
820
- enableRingZulu: config.profile === 'storage'
821
- },
822
- ...(config.privateKey && { privateKey: config.privateKey }),
823
- // Built per runtime, not per launch: the adapter stops saving once the strand's
824
- // state is forgotten, and a rebuilt runtime is what starts it saving again.
825
- //
826
- // NOTE: the saved state also restores which peers db-p2p saw serving the strand,
827
- // and it counts them in the cohort until FRET finds them unreachable. A node built
828
- // while every other member is offline therefore fails its first writes ("Failed to
829
- // get super-majority") — for 4-6 s on loopback, the window a running node already
830
- // sees when a member drops. If apps report failed sends after relaunching alone on
831
- // a slow relayed link, retry the write in the app or raise it upstream (db-p2p's
832
- // remembered-serving fallback); dropping `persistence` brings back the split
833
- // restart.
834
- ...(config.networkState && { persistence: strandNetworkStatePersistence(config.networkState, strandId) }),
835
- ...(config.network?.transports && { transports: config.network.transports }),
836
- ...(config.network?.noiseCrypto && { noiseCrypto: config.network.noiseCrypto }),
837
- // Unconditional, and the same default the control node takes: every node of
838
- // every party runs the monitor over its connection to a slow phone, so the
839
- // widened ping deadline has to reach the strand nodes too (see
840
- // DEFAULT_CONNECTION_MONITOR).
841
- connectionMonitor: config.network?.connectionMonitor ?? DEFAULT_CONNECTION_MONITOR,
842
- // The same declared link the control node states, and for the same reason: a strand
843
- // node is also the listener for every other member's strand node, and Optimystic
844
- // derives that listener's limit from this (`link-budget.ts`).
845
- linkRoundTripMs: resolveLinkRoundTripMs(config.network?.linkRoundTripMs),
846
- // The same dial limits as the control node: a strand node dials the same machines,
847
- // through the same relays and gates.
848
- ...optimysticDialLimits(config.network?.linkRoundTripMs),
849
- // Listen entries plus the WebSocket transport switch they imply — a strand node
850
- // announces nothing the operator configured (`strand-network-config.ts`), and
851
- // spreads AFTER `transports` above because the switch is a no-op whenever the
852
- // embedder supplied its own factories. The bare `/p2p-circuit` entries (one per
853
- // relay) open no connection here; each registers a pending reservation that the
854
- // matching supervisor below fills, which is what gives a NAT'd strand node a
855
- // reachable relay slot — and works against a party-run relay because the launch
856
- // path announced this strand's derived peerId to it first (delegate admission;
857
- // see cadre-node.ts).
858
- ...addrOptions,
859
- // The raw configured gater (open strands), or the revocation-composed
860
- // gater plus the fail-closed per-stream revoked-peer gate (closed
861
- // strands) — resolved above, before the try.
862
- ...revocationGateOptions,
863
- // `{}` unless the operator enabled change notifications for this strand (`strand-reactivity.ts`).
864
- ...reactivityOption
865
- }) as Libp2pNodeWithRepo;
866
- timing('[buildStrandRuntime:%s] createLibp2pNode: %dms', strandId, Math.round(performance.now() - t0));
867
-
868
- instance.libp2pNode = node;
869
-
870
- // One reservation supervisor PER RELAY, started now so the first attempts
871
- // overlap the database bring-up below (the relay is never in a strand's
872
- // Optimystic cohort — its protocol ids are namespaced `/optimystic/strand-<id>/…`
873
- // — so an open relay connection cannot disturb that bring-up). Their first
874
- // attempts are awaited before the strand goes `active`, below. Registered in the
875
- // map immediately so the failure rollback (releaseRuntime) stops them like every
876
- // other runtime component.
877
- this.relaySupervisors.set(strandId, this.startRelaySupervisors(strandId, node, relayDialAddrs, config));
878
-
879
- // Create and initialize the StrandDatabase.
880
- //
881
- // Held by the first-sync gate (registered before initialize) rather than attached
882
- // to the instance: a failed init is then cleaned up by releaseRuntime below through
883
- // the gate (close() is safe on a partially-initialized db), and the app only ever
884
- // sees `instance.database` once this machine is allowed to write to the strand.
885
- t0 = performance.now();
886
- const strandDb = new StrandDatabase({
887
- strandId,
888
- sAppConfig,
889
- libp2pNode: node,
890
- coordinatedRepo: node.coordinatedRepo,
891
- // Founder bootstrap inputs: the strand's type drives which membership rows
892
- // are written, and the PARTY's own key (partyMemberPrivateKey, resolved by the
893
- // caller from the control-layer StrandPartyKey row) derives the founding
894
- // Member/Manager key. The row's shared MemberPrivateKey rides along as the
895
- // read-gating secret only — it derives nobody's identity.
896
- strandType: config.strandRow.Type,
897
- memberPrivateKey: config.strandRow.MemberPrivateKey ?? undefined,
898
- partyMemberPrivateKey: config.partyMemberPrivateKey,
899
- founder: config.founder
900
- });
901
- const gate = new StrandFirstSyncGate({
902
- label: strandId,
903
- database: strandDb,
904
- onHeaderHeld: () => this.publishDatabase(instance, strandDb)
905
- }, config.firstSync);
906
- this.firstSyncGates.set(strandId, gate);
907
- try {
908
- await strandDb.initialize();
909
- } catch (error) {
910
- joinWaitsForSeed = isCohortUnreachableRead(error);
911
- throw error;
912
- }
913
- timing('[buildStrandRuntime:%s] strandDatabase.initialize: %dms', strandId, Math.round(performance.now() - t0));
914
-
915
- // The first-sync write gate. A founder just wrote the Header in its bootstrap; any
916
- // other machine may commit only once it holds the Header — which it can only have
917
- // received from a peer (now, or on an earlier run over the same store) — and has read
918
- // each App table once, so their collections are fetched too. Publishing the database
919
- // is what makes the strand writable to the app; until then the instance stays
920
- // `'syncing'` and the gate re-probes on its cadence. Everything armed below reads
921
- // `instance.database` lazily, so the reconciler and enforcer wait with it — and
922
- // `publishDatabase` kicks the reconciler when the wait ends, so a joiner's membership
923
- // rows land with the strand rather than one retry later.
924
- t0 = performance.now();
925
- if (config.founder === true || await strandFirstSyncComplete(strandDb.getDatabase(), strandId)) {
926
- this.publishDatabase(instance, strandDb);
927
- } else {
928
- gate.start();
929
- }
930
- timing('[buildStrandRuntime:%s] first-sync probe: %dms', strandId, Math.round(performance.now() - t0));
931
-
932
- // The membership reconciler: finish this party's join on every machine —
933
- // redeem a staged formation invitation if one is pending, then write the
934
- // durable machine→party binding (Strand.MemberPeer). Armed here, the one
935
- // seam where the strand's transport peer id and a live Database both exist
936
- // for launch AND hibernation resume, for closed strands that carry the
937
- // party's own membership key. start() kicks an immediate pass WITHOUT
938
- // awaiting it — a joiner at this instant has not synced the founder's rows
939
- // and may lack write quorum, so bring-up is never blocked; an unfinished join
940
- // then retries on a short doubling ladder capped at the configured
941
- // pollIntervalMs (which is also the flat cadence while nobody has admitted this
942
- // party yet), and the loop stops once the member row and this machine's own
943
- // binding are both in place. Armed AFTER the gate above, so a gated launch
944
- // always has a reconciler registered by the time the gate can publish.
945
- if (config.strandRow.Type === 'c' && config.partyMemberPrivateKey
946
- && config.membershipReconciliation?.enabled !== false) {
947
- const reconciler = new StrandMembershipReconciler({
948
- label: strandId,
949
- partyMemberPrivateKey: config.partyMemberPrivateKey,
950
- // Read per pass, never captured — same lifecycle argument as the
951
- // enforcer's getNetwork: quiesce drops both handles.
952
- getDatabase: () => instance.database?.getDatabase(),
953
- getOwnPeerId: () => instance.libp2pNode?.peerId.toString(),
954
- pendingInvite: config.pendingMembershipInvite,
955
- // The enforcer's CURRENT snapshot view of this node's own peer id — the
956
- // reconciler stops rather than fight a self-revocation. Absent when the
957
- // gate is disarmed (fail-open: the loop just runs).
958
- isSelfRevoked: revocationEnforcer
959
- ? () => {
960
- const ownPeerId = instance.libp2pNode?.peerId.toString();
961
- return ownPeerId !== undefined && revocationEnforcer.isRevoked(ownPeerId);
962
- }
963
- : undefined,
964
- onRejoinBlocked: () => config.onRejoinBlocked?.(strandId)
965
- }, {
966
- pollIntervalMs: config.membershipReconciliation?.pollIntervalMs
967
- ?? config.revocationEnforcement?.pollIntervalMs
968
- });
969
- this.membershipReconcilers.set(strandId, reconciler);
970
- reconciler.start();
971
- }
972
-
973
- // Arm the revoked-peer deny-set poll now that the database it reads
974
- // exists. start() kicks an immediate refresh WITHOUT awaiting it —
975
- // bring-up and resume are never blocked on a membership read; until the
976
- // first read lands the empty snapshot admits everyone (fail-open).
977
- revocationEnforcer?.start();
978
-
979
- // Peer-join block catch-up: push this strand's own blocks to each newly
980
- // connected peer, so a machine that joined after blocks were committed
981
- // still ends up physically holding them (without per-strand storage there
982
- // is nothing to copy). Armed for EVERY stored strand: `PeerJoinBackfill`
983
- // only does work when the strand's libp2p node reports a peer connection,
984
- // so on a device that is genuinely alone it is inert, and arming it at
985
- // launch is what closes the "founded alone, never replicates" hole — a
986
- // peer that joins later gets the founder's blocks without any relaunch.
987
- // No `authorizePeer` gate, deliberately — see the module comment in
988
- // peer-join-backfill.ts for the strand-side argument (and why the control
989
- // network, which DOES gate, is different).
990
- //
991
- // NOTE: cost is one PeerJoinBackfill object + one `peer:identify` listener
992
- // per running strand — linear in strand count, negligible at the handful a
993
- // device or host runs today. If a node ever hosts strands by the hundred,
994
- // move to one shared listener that dispatches by strand id.
995
- if (strandStorage && config.backfill?.enabled !== false) {
996
- if (node.keyNetwork) {
997
- const backfill = new PeerJoinBackfill({
998
- label: strandId,
999
- libp2p: node,
1000
- peerNetwork: node.keyNetwork,
1001
- storage: strandStorage,
1002
- // The same prefix the receiver registered its block-transfer handler
1003
- // under — derived from networkName above, never re-spelled here.
1004
- protocolPrefix
1005
- }, {
1006
- // Dial and response deadlines counted in link round trips, not fixed milliseconds:
1007
- // a relayed dial costs a fixed number of exchanges, so a fixed budget has a link
1008
- // speed above which this catch-up can never reach the peer at all. See
1009
- // `link-budget.ts`. Spread BEFORE the host's own config so an explicit
1010
- // `strandBackfill.dialTimeoutMs` still wins.
1011
- ...peerJoinPushBudget(config.network?.linkRoundTripMs),
1012
- ...config.backfill
1013
- });
1014
- backfill.start();
1015
- this.backfills.set(strandId, backfill);
1016
- } else {
1017
- log('Strand %s: libp2p node exposes no keyNetwork; peer-join block catch-up is inert', strandId);
1018
- }
1019
- }
1020
-
1021
- // The relay supervisors' FIRST attempts, all of them, before `active`: the happy
1022
- // path still publishes its circuit addr before `addStrand` resolves (the
1023
- // strand-addr RPC answers read it, and the same-party circuit scenario asserts
1024
- // it). Fail-SOFT — a first attempt that lands nothing does not fail the launch.
1025
- // The strand's database is up, and the supervisor keeps trying on its backoff;
1026
- // failing here would only trade that for `StrandWatcher`'s full-rebuild retry.
1027
- //
1028
- // NOTE: a relay that is down costs this launch one full drive — the reservation budget
1029
- // counted from the declared link round trip, 18 s at its default (`link-budget.ts`) — and
1030
- // `StrandWatcher` launches strands one at a time, so N strands cost N of those in
1031
- // bring-up during a relay outage, and MORE on a host that declared a slower link. If that
1032
- // ever matters, stop awaiting here (the circuit addr then lands after `active`) rather
1033
- // than shortening the drive.
1034
- t0 = performance.now();
1035
- await this.awaitFirstRelayAttempts(strandId);
1036
- timing('[buildStrandRuntime:%s] relay first attempts: %dms', strandId, Math.round(performance.now() - t0));
1037
-
1038
- // No `lastActivity` stamp: bringing a runtime up is not activity. A check-in marks
1039
- // activity before its resume and must see only what landed while the strand was up.
1040
- instance.status = liveStrandStatus(instance);
1041
- if (instance.status === 'syncing') {
1042
- log('Strand %s launched as a joiner with no Strand.Header held yet — writes are withheld until ' +
1043
- 'a member of the strand is reached', strandId);
1044
- }
1045
- } catch (error) {
1046
- // Roll back any partially-attached runtime so the instance is left with
1047
- // NEITHER handle. Otherwise the `libp2pNode || database` "already live"
1048
- // guard in resumeStrand/handleStrandWake would treat a half-built strand
1049
- // as healthy — leaking the libp2p node and never retrying the rebuild.
1050
- await this.releaseRuntime(instance).catch((cleanupErr) => {
1051
- log('buildStrandRuntime cleanup for strand %s also failed: %o', strandId, cleanupErr);
1052
- });
1053
- if (joinWaitsForSeed) {
1054
- this.deferUnreachableJoin(instance, error);
1055
- return;
1056
- }
1057
- throw error;
1058
- }
1059
- }
1060
-
1061
- /**
1062
- * Keep a launch `'syncing'` when its database could not be built because no seed peer has
1063
- * answered yet, and rebuild the runtime every {@link UNREACHABLE_JOIN_RETRY_MS}.
1064
- *
1065
- * Optimystic (since 1.11.0) will not rule a block never-created while any of a node's
1066
- * `bootstrapNodes` is unheard, so a joiner alone with an unreachable seed cannot build even
1067
- * the schema catalog: `strandDb.initialize()` fails with `cohort-unreachable`. A founder
1068
- * given a seed is refused the same way (normally it has none: no sibling runs the strand yet). Refusing is
1069
- * right (building it alone would fork the catalog), but failing the launch would drop the
1070
- * strand until the watcher relaunched it, and `addStrand` would reject with a raw Optimystic
1071
- * error. Deferring gives a joiner the same contract the first-sync gate gives one that did
1072
- * build: the strand stays tracked, {@link whenWritable} waits and rejects with the retryable
1073
- * `StrandAwaitingFirstSyncError`, and the launch proceeds once a seed peer answers. A failed
1074
- * composition stops the injected libp2p node, so each retry rebuilds the whole runtime.
1075
- */
1076
- private deferUnreachableJoin(instance: StrandInstance, error: unknown): void {
1077
- const strandId = instance.strandId;
1078
- instance.status = 'syncing';
1079
- log('Strand %s: no seed peer has answered yet, so this joiner cannot build its database (%s); ' +
1080
- 'retrying in %dms', strandId, error instanceof Error ? error.message : String(error), UNREACHABLE_JOIN_RETRY_MS);
1081
- const timer = setTimeout(() => {
1082
- this.unreachableJoinRetries.delete(strandId);
1083
- void this.retryUnreachableJoin(instance);
1084
- }, UNREACHABLE_JOIN_RETRY_MS);
1085
- (timer as { unref?: () => void }).unref?.();
1086
- this.unreachableJoinRetries.set(strandId, timer);
1087
- }
1088
-
1089
- /** One retry scheduled by {@link deferUnreachableJoin}, unless the strand was stopped or rebuilt since. */
1090
- private async retryUnreachableJoin(instance: StrandInstance): Promise<void> {
1091
- const strandId = instance.strandId;
1092
- const config = this.launchConfigs.get(strandId);
1093
- if (this.stopping || this.instances.get(strandId) !== instance || !config
1094
- || instance.libp2pNode || this.runtimeBuilds.has(strandId) || this.transitions.has(strandId)) {
1095
- return;
1096
- }
1097
- try {
1098
- await this.trackRuntimeBuild(strandId, this.buildStrandRuntime(instance, config));
1099
- } catch (error) {
1100
- instance.status = 'error';
1101
- instance.error = error instanceof Error ? error.message : String(error);
1102
- log('Strand %s: rebuilding a joiner that was waiting for a seed peer failed: %s', strandId, instance.error);
1103
- }
1104
- }
1105
-
1106
- /**
1107
- * Release an instance's strand-network runtime: stop the relay supervisors and
1108
- * the other background loops, close the StrandDatabase, then stop the libp2p
1109
- * node (construction order in reverse), clearing both fields and zeroing
1110
- * connectedPeers. Tolerant of partially-built state — either handle may be
1111
- * absent — so it doubles as rollback for a failed `buildStrandRuntime`. Shared
1112
- * by `quiesceStrand`, `stopStrand`, and that rollback path.
1113
- *
1114
- * Leaves `strandStorages` untouched by design — the store outlives the runtime it
1115
- * was built into, which is what makes a resume warm. Only `stopStrand` disposes it.
1116
- */
1117
- private async releaseRuntime(instance: StrandInstance): Promise<void> {
1118
- // Relay supervisors FIRST of all — before anything below is torn down — so no
1119
- // re-drive is scheduled against a node being stopped. `stop()` is synchronous
1120
- // and never awaits a drive, so a relay that is down cannot delay this teardown.
1121
- // `stop()` also cancels the drive already in flight, so an attempt started
1122
- // moments before this does not keep dialing and polling the node the lines
1123
- // below are stopping; its result is discarded either way.
1124
- const unreachableJoinRetry = this.unreachableJoinRetries.get(instance.strandId);
1125
- if (unreachableJoinRetry !== undefined) {
1126
- clearTimeout(unreachableJoinRetry as ReturnType<typeof setTimeout>);
1127
- this.unreachableJoinRetries.delete(instance.strandId);
1128
- }
1129
- const relaySupervisors = this.relaySupervisors.get(instance.strandId);
1130
- if (relaySupervisors) {
1131
- relaySupervisors.forEach((supervisor) => supervisor.stop());
1132
- this.relaySupervisors.delete(instance.strandId);
1133
- }
1134
- // Backfill next — before the database closes and the libp2p node stops — so
1135
- // no NEW catch-up push is issued against a torn-down transport. A push already
1136
- // in flight is not awaited; it fails into the module's own per-chunk catch.
1137
- const backfill = this.backfills.get(instance.strandId);
1138
- if (backfill) {
1139
- backfill.stop();
1140
- this.backfills.delete(instance.strandId);
1141
- }
1142
- // The revoked-peer enforcer goes with the runtime it gated: a resume
1143
- // rebuilds it with a fresh (initially empty, fail-open) snapshot.
1144
- const revocationEnforcer = this.revocationEnforcers.get(instance.strandId);
1145
- if (revocationEnforcer) {
1146
- revocationEnforcer.stop();
1147
- this.revocationEnforcers.delete(instance.strandId);
1148
- }
1149
- // The membership reconciler likewise: a resume rebuilds it and re-runs the
1150
- // idempotent ladder, which is what makes resume-after-partial-join heal.
1151
- const membershipReconciler = this.membershipReconcilers.get(instance.strandId);
1152
- if (membershipReconciler) {
1153
- membershipReconciler.stop();
1154
- this.membershipReconcilers.delete(instance.strandId);
1155
- }
1156
- // A still-gated database (a joiner that never received the Header, or a launch whose
1157
- // initialize() failed) is closed through its gate; a published one through the
1158
- // instance. Never both — publishing moves the handle from the gate to the instance.
1159
- const gate = this.firstSyncGates.get(instance.strandId);
1160
- if (gate) {
1161
- gate.stop();
1162
- this.firstSyncGates.delete(instance.strandId);
1163
- await gate.database.close();
1164
- }
1165
- if (instance.database) {
1166
- await instance.database.close();
1167
- instance.database = undefined;
1168
- }
1169
- if (instance.libp2pNode) {
1170
- await instance.libp2pNode.stop();
1171
- instance.libp2pNode = undefined;
1172
- }
1173
- instance.connectedPeers = 0;
1174
- }
1175
-
1176
- /**
1177
- * One {@link superviseRelayReservation} per relay dial addr, each over exactly
1178
- * that relay so "held" is judged per relay (`circuitMultiaddrsVia`) and losing
1179
- * one relay re-drives only that one. Default retry timings — the control node's (2 s
1180
- * doubling to 60 s between failed attempts, a 5 s liveness check while held). Each DRIVE's
1181
- * own deadline is counted in link round trips at this host's declared
1182
- * `network.linkRoundTripMs` (`link-budget.ts`), so the same declaration that lengthens the
1183
- * control node's drive lengthens these.
1184
- *
1185
- * Each supervisor's `beforeRedrive` is the caller's
1186
- * {@link StartStrandConfig.announceDelegateToRelay} for THIS relay and THIS
1187
- * node's peer id, so a re-drive after a relay restart is preceded by a fresh
1188
- * delegate grant on the relay about to be dialed. Returns `[]` when no relay is
1189
- * configured — the strand then simply has no circuit listener to fill.
1190
- */
1191
- private startRelaySupervisors(
1192
- strandId: string,
1193
- node: Libp2pNodeWithRepo,
1194
- relayDialAddrs: readonly string[],
1195
- config: StartStrandConfig
1196
- ): RelayReservationSupervisor[] {
1197
- if (relayDialAddrs.length === 0) {
1198
- return [];
1199
- }
1200
- const announce = config.announceDelegateToRelay;
1201
- const delegatePeerId = node.peerId.toString();
1202
- const timeoutMs = relayReservationBudgetMs(config.network?.linkRoundTripMs);
1203
- return relayDialAddrs.map((relayAddr) => superviseRelayReservation(node, [relayAddr], {
1204
- timeoutMs,
1205
- ...(announce && { beforeRedrive: () => announce(strandId, relayAddr, delegatePeerId) })
1206
- }));
1207
- }
1208
-
1209
- /**
1210
- * Wait for every relay supervisor's first attempt to settle, concurrently, and log
1211
- * the ones that landed nothing. Never throws — a strand whose relay is unreachable
1212
- * at launch still comes up, with its supervisors retrying in the background.
1213
- */
1214
- private async awaitFirstRelayAttempts(strandId: string): Promise<void> {
1215
- const supervisors = this.relaySupervisors.get(strandId) ?? [];
1216
- if (supervisors.length === 0) {
1217
- return;
1218
- }
1219
- await Promise.all(supervisors.map((supervisor) => supervisor.firstAttempt));
1220
- supervisors.forEach((supervisor) => {
1221
- if (supervisor.lastError !== null) {
1222
- log('Strand %s: relay reservation not held after the first attempt (retrying in the background): %s',
1223
- strandId, supervisor.lastError);
1224
- }
1225
- });
1226
- }
1227
-
1228
- /**
1229
- * Drop the strand's owned store and release this strand's claim on its cache. The
1230
- * wrapper counts holders, so the cache is emptied and unregistered from the shared
1231
- * pool only if no other scope still holds it. Called only where the strand's whole
1232
- * lifetime ends (`stopStrand`, and the failed-launch rollback) — never on a quiesce.
1233
- *
1234
- * A dispose failure is logged, not thrown: the store is already unreferenced here,
1235
- * and failing the stop over a cache-bookkeeping error would leave the caller unable
1236
- * to tear the strand down. `disposeStorageCache` no-ops for an unwrapped store
1237
- * (e.g. `MemoryRawStorage`), so no instanceof test is needed.
1238
- */
1239
- private async disposeStrandStorage(strandId: string): Promise<void> {
1240
- const storage = this.strandStorages.get(strandId);
1241
- if (!storage) {
1242
- return;
1243
- }
1244
- this.strandStorages.delete(strandId);
1245
- try {
1246
- await disposeStorageCache(storage);
1247
- } catch (error) {
1248
- log('Failed to dispose storage cache for strand %s: %o', strandId, error);
1249
- }
1250
- }
1251
-
1252
- /**
1253
- * Refresh a strand's revoked-peer deny set NOW — and, with it, run the
1254
- * teardown sweep that hangs up every connected revoked peer.
1255
- *
1256
- * The gate is otherwise poll-driven (default
1257
- * `DEFAULT_REVOCATION_POLL_INTERVAL_MS`), because neither a replicated
1258
- * revocation nor a local `revokeMember`/`leaveStrand` raises anything this
1259
- * runtime can hook. A caller that just wrote a revocation against the
1260
- * strand's database should follow it with this call, which makes the cut
1261
- * immediate instead of waiting out the interval.
1262
- *
1263
- * Quiet no-op — matching `quiesceStrand`'s posture — when the strand is not
1264
- * tracked, is quiesced, is open, or has the gate disabled: in every one of
1265
- * those cases there is no enforcer to refresh. Never rejects (the enforcer's
1266
- * refresh contains its own failures), and resolves only once the sweep has
1267
- * finished.
1268
- */
1269
- async refreshRevocationEnforcement(strandId: string): Promise<void> {
1270
- const enforcer = this.revocationEnforcers.get(strandId);
1271
- if (!enforcer) {
1272
- log('refreshRevocationEnforcement: strand %s has no armed revocation enforcer', strandId);
1273
- return;
1274
- }
1275
- await enforcer.refresh();
1276
- }
1277
-
1278
- /**
1279
- * A fresh membership invitation was staged for `strandId` (`CadreNode`'s
1280
- * `adoptFormationMembershipInvite`): re-arm the strand's membership reconciler so the
1281
- * invitation is attempted now rather than never — the loop finished during the first
1282
- * join and would otherwise stay stopped until a relaunch. Quiet no-op when no reconciler
1283
- * is armed: a first formation stages before the strand is added, and bring-up then arms
1284
- * a loop that finds the invitation by itself. Returns at once; the pass runs on the
1285
- * loop's own serialized chain and never rejects.
1286
- */
1287
- notifyMembershipInviteStaged(strandId: string): void {
1288
- const reconciler = this.membershipReconcilers.get(strandId);
1289
- if (!reconciler) {
1290
- log('notifyMembershipInviteStaged: strand %s has no armed membership reconciler — bring-up will find the invitation', strandId);
1291
- return;
1292
- }
1293
- void reconciler.rearm();
1294
- }
1295
-
1296
- /**
1297
- * Best-effort removal of THIS machine's own `Strand.MemberPeer` binding — the
1298
- * self arm of `removeMemberPeer`, signed with the retained launch config's party
1299
- * key. Called by `CadreNode.unpublishStrand` BEFORE the local stop, while the
1300
- * strand database and transport are still live: after the unpublish commits, the
1301
- * party's `StrandPartyKey` control row is gone, so no restart could ever sign
1302
- * this removal again — the in-memory retained key is the last chance.
1303
- *
1304
- * Never throws. Quiet no-op for a strand that is untracked, open, or launched
1305
- * without a party key; a quiesced (hibernating) strand, or a strand whose write
1306
- * quorum is already unreachable, leaves the stale binding behind with a log —
1307
- * it grants nothing today (admission is not allowlist-gated) and only
1308
- * mis-credits diversity. The strand's own membership reconciler is stopped —
1309
- * and its in-flight pass awaited — FIRST, so a pass that was already past its
1310
- * own stopped check cannot re-register the binding this is about to clear.
1311
- *
1312
- * NOTE: deliberately NOT handled here (or anywhere yet): clearing the bindings
1313
- * of a machine removed from the CADRE at the control layer, or of a party's
1314
- * OTHER machines when the party unpublishes — the party still holds the key on
1315
- * every surviving machine and can clear from any of them, and the stale rows
1316
- * grant nothing while admission is deny-list only. Revisit when
1317
- * `feat-strand-member-allowlist-admission` lands and a stale binding starts
1318
- * granting admission rather than merely mis-crediting diversity.
1319
- */
1320
- async clearOwnMemberPeerBinding(strandId: string): Promise<void> {
1321
- const instance = this.instances.get(strandId);
1322
- const config = this.launchConfigs.get(strandId);
1323
- if (!instance || !config || config.strandRow.Type !== 'c' || !config.partyMemberPrivateKey) {
1324
- return;
1325
- }
1326
- const reconciler = this.membershipReconcilers.get(strandId);
1327
- if (reconciler) {
1328
- reconciler.stop();
1329
- await reconciler.settle();
1330
- }
1331
- const db = instance.database?.getDatabase();
1332
- const peerId = instance.libp2pNode?.peerId.toString();
1333
- if (!db || !peerId) {
1334
- log('clearOwnMemberPeerBinding: strand %s has no live runtime — own MemberPeer binding left in place', strandId);
1335
- return;
1336
- }
1337
- try {
1338
- // Background write on the app's database: never join a transaction the app has open.
1339
- await removeMemberPeer(db, {
1340
- memberKeyPair: strandMemberKeyPair(config.partyMemberPrivateKey),
1341
- peerId
1342
- }, { joinOpenTransaction: false });
1343
- log('clearOwnMemberPeerBinding: strand %s — own binding for peer %s cleared', strandId, peerId);
1344
- } catch (error) {
1345
- log('clearOwnMemberPeerBinding: strand %s — best-effort clear failed (strand may already be unreachable): %o',
1346
- strandId, error);
1347
- }
1348
- }
1349
-
1350
- /**
1351
- * Quiesce a strand: release its strand-network resources (stop the libp2p node,
1352
- * close the StrandDatabase) while RETAINING the instance record — identity,
1353
- * sAppInfo, keys, latency hint, metadata — and its launch config so it can be
1354
- * resumed later, then mark it `hibernating`. Mechanically this is `stopStrand` minus
1355
- * the instance/config deletion. A tracked strand with no runtime left (a failed
1356
- * rebuild already released it) is only marked; an untracked one is left alone.
1357
- *
1358
- * Ordered with {@link resumeStrand} (see {@link transitions}): it starts once the resume
1359
- * or launch build before it has settled, so it releases a finished runtime, and the
1360
- * status write is its last step, so a resume requested meanwhile writes after it. A call
1361
- * made while another quiesce is the latest request joins it. A failed release leaves the
1362
- * status as it was and rejects.
1363
- */
1364
- async quiesceStrand(strandId: string): Promise<void> {
1365
- const previous = this.transitions.get(strandId);
1366
- if (previous?.kind === 'quiesce') {
1367
- log('quiesceStrand: strand %s — joining the quiesce already requested', strandId);
1368
- return previous.operation;
1369
- }
1370
- const operation = this.runQuiesce(strandId, previous);
1371
- this.holdTransition(strandId, { kind: 'quiesce', operation });
1372
- return operation;
1373
- }
1374
-
1375
- /** Body of {@link quiesceStrand}. */
1376
- private async runQuiesce(strandId: string, previous: RuntimeTransition | undefined): Promise<void> {
1377
- await this.settleTransition(strandId, previous);
1378
- await this.settleRuntimeBuilds(strandId);
1379
- const instance = this.instances.get(strandId);
1380
- if (!instance) {
1381
- log('quiesceStrand: strand %s not found', strandId);
1382
- return;
1383
- }
1384
- if (instance.libp2pNode || instance.database) {
1385
- log('Quiescing strand instance: %s', strandId);
1386
- await this.releaseRuntime(instance);
1387
- log('Strand %s quiesced (resources released, instance retained)', strandId);
1388
- } else {
1389
- log('quiesceStrand: strand %s already quiesced', strandId);
1390
- }
1391
- instance.status = 'hibernating';
1392
- }
1393
-
1394
- /**
1395
- * Whether the latest runtime transition requested for `strandId` is a quiesce that has
1396
- * not finished. Its handles may still be attached and its status still live, but it is on
1397
- * its way to `hibernating`, so a caller that needs it up must {@link resumeStrand} it — the
1398
- * resume runs after the quiesce — rather than treat it as live.
1399
- */
1400
- isQuiescing(strandId: string): boolean {
1401
- return this.transitions.get(strandId)?.kind === 'quiesce';
1402
- }
1403
-
1404
- /**
1405
- * Resume a previously-quiesced strand: rebuild its libp2p node + StrandDatabase
1406
- * from the retained launch config and re-attach them, transitioning it back to
1407
- * `active`. `overrides` re-applies volatile inputs that may have changed since
1408
- * launch (the cohort `bootstrapNodes` seed and the strand's `servingMachines`
1409
- * count) and updates the retained config so a later resume reuses the latest
1410
- * values. Returns the live instance unchanged if it is already running.
1411
- *
1412
- * Overlapping calls share one rebuild: a call made while a resume is the latest request
1413
- * for the strand — a wake landing during a check-in — joins it and settles exactly as it
1414
- * does, `'error'` status included. The joiner's own `overrides` are ignored; the first
1415
- * resume's seed wins, and both callers resolved the cohort seed moments apart. A call made
1416
- * while a quiesce is the latest request runs after that quiesce and rebuilds (see
1417
- * {@link transitions}), and one made while `startStrand` is still building waits for that
1418
- * build rather than starting a second.
1419
- */
1420
- async resumeStrand(strandId: string, overrides?: ResumeStrandOverrides): Promise<StrandInstance> {
1421
- if (this.stopping) {
1422
- throw new Error('StrandInstanceManager is stopping');
1423
- }
1424
- // No `await` between this read and `holdTransition`, or a second caller slips through
1425
- // and builds.
1426
- const previous = this.transitions.get(strandId);
1427
- if (previous?.kind === 'resume') {
1428
- log('resumeStrand: strand %s — joining the resume already in flight', strandId);
1429
- return previous.operation;
1430
- }
1431
- const operation = this.runResume(strandId, previous, overrides);
1432
- this.holdTransition(strandId, { kind: 'resume', operation });
1433
- return operation;
1434
- }
1435
-
1436
- /** Record `transition` as the latest for `strandId` until it settles. */
1437
- private holdTransition(strandId: string, transition: RuntimeTransition): void {
1438
- this.transitions.set(strandId, transition);
1439
- const release = (): void => {
1440
- if (this.transitions.get(strandId) === transition) {
1441
- this.transitions.delete(strandId);
1442
- }
1443
- };
1444
- // The rejection itself reaches the caller through the operation returned to it.
1445
- void transition.operation.then(release, release);
1446
- }
1447
-
1448
- /** Wait for the transition requested before this one. Never rejects: its failure belongs to its caller. */
1449
- private async settleTransition(strandId: string, previous: RuntimeTransition | undefined): Promise<void> {
1450
- if (!previous) {
1451
- return;
1452
- }
1453
- await (previous.operation as Promise<unknown>).catch((error: unknown) => {
1454
- log('Strand %s: the %s queued ahead failed (reported by its caller): %o', strandId, previous.kind, error);
1455
- });
1456
- }
1457
-
1458
- /** Body of {@link resumeStrand}; at most one runs per strand at a time. */
1459
- private async runResume(
1460
- strandId: string,
1461
- previous: RuntimeTransition | undefined,
1462
- overrides?: ResumeStrandOverrides
1463
- ): Promise<StrandInstance> {
1464
- // Before any "already live" test: a quiesce ahead still has the handles attached, and
1465
- // mid-build (a launch still building) the libp2p node is attached while the database is
1466
- // not. A failed launch has already dropped the instance, and the check below reports it
1467
- // untracked.
1468
- await this.settleTransition(strandId, previous);
1469
- await this.settleRuntimeBuilds(strandId);
1470
- const instance = this.instances.get(strandId);
1471
- if (!instance) {
1472
- throw new Error(`Cannot resume strand ${strandId}: not tracked`);
1473
- }
1474
- const launchConfig = this.launchConfigs.get(strandId);
1475
- if (!launchConfig) {
1476
- throw new Error(`Cannot resume strand ${strandId}: no retained launch config`);
1477
- }
1478
- if (instance.libp2pNode || instance.database) {
1479
- log('resumeStrand: strand %s already live', strandId);
1480
- return instance;
1481
- }
1482
-
1483
- log('Resuming strand instance: %s', strandId);
1484
- const tTotal = performance.now();
1485
-
1486
- // Re-apply volatile inputs and persist them so a subsequent resume reuses them.
1487
- // Each `??` matters: a resume that passes no override must keep the retained value,
1488
- // and a resume that passes one must leave it retained for the next resume — otherwise
1489
- // a later no-override wake silently reverts to whatever launch time saw.
1490
- const resumeConfig: StartStrandConfig = {
1491
- ...launchConfig,
1492
- bootstrapNodes: overrides?.bootstrapNodes ?? launchConfig.bootstrapNodes,
1493
- // NOTE: `??` retains, so an override can raise or lower the count but cannot CLEAR it
1494
- // back to "this node no longer knows" — the direction that would declare nothing. Moot
1495
- // while nothing feeds `servingMachines` at all; if a source lands
1496
- // (`backlog/feat-strand-yardstick-from-serving-machines`) that can legitimately lose the
1497
- // count — a strand whose member rows became unreadable — this merge must gain an explicit
1498
- // clear rather than silently declaring a stale number over a serving set it can no longer
1499
- // see. Same applies to `bootstrapNodes` above, where a stale seed is harmless.
1500
- servingMachines: overrides?.servingMachines ?? launchConfig.servingMachines
1501
- };
1502
- this.launchConfigs.set(strandId, resumeConfig);
1503
-
1504
- instance.status = 'starting';
1505
- try {
1506
- await this.trackRuntimeBuild(strandId, this.buildStrandRuntime(instance, resumeConfig));
1507
- timing('[resumeStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
1508
- log('Strand %s resumed successfully', strandId);
1509
- return instance;
1510
- } catch (error) {
1511
- instance.status = 'error';
1512
- instance.error = error instanceof Error ? error.message : String(error);
1513
- log('Failed to resume strand %s: %s', strandId, instance.error);
1514
- throw error;
1515
- }
1516
- }
1517
-
1518
- /**
1519
- * Honor a founder request against an ALREADY-TRACKED strand — the seam that
1520
- * closes the "whoever launches first decides whether the bootstrap runs" gap:
1521
- * an instance first launched as a joiner (an app's own attach, or a watcher
1522
- * poll winning the launch race) used to swallow a later founder request
1523
- * silently, leaving the strand active with no `Strand.Header`.
1524
- *
1525
- * Flips the RETAINED launch config's `founder` to true, so every later
1526
- * quiesce → resume rebuild founds as well (the bootstrap is insert-if-absent —
1527
- * {@link StrandDatabase.ensureFounderBootstrap} — so re-running it per rebuild
1528
- * writes nothing twice), and runs the bootstrap against the live database now.
1529
- *
1530
- * @returns how the request resolved:
1531
- * - `'already-founder'` — the retained config already founds; nothing to do.
1532
- * - `'bootstrapped'` — config flipped and the live database ran the bootstrap.
1533
- * - `'needs-resume'` — config flipped, but the instance is quiesced (no live
1534
- * database) or being quiesced (its database is closing), so the bootstrap could
1535
- * not run here: the CALLER must wake the
1536
- * strand (`CadreNode.wakeStrand`, which owns the hibernation bookkeeping this
1537
- * manager does not) so the rebuild — which now founds — runs it.
1538
- * @param resolvePartyKey - Asked for the party's own membership key when (and only
1539
- * when) a CLOSED strand's retained config carries none — the instance was launched
1540
- * as a joiner before its `StrandPartyKey` row existed or replicated. The resolved
1541
- * key is retained alongside the founder flip so the bootstrap (now, or on the
1542
- * caller's wake for `'needs-resume'`) can seat the founding Member/Manager.
1543
- * @throws when the strand is not tracked — this seam exists only for the
1544
- * tracked-instance launch path; an untracked id is a caller bug.
1545
- * @throws whatever the live bootstrap throws (e.g. `PreSplitStrandIdentityError`),
1546
- * after {@link withdrawFounderRequest} — so a retry re-attempts the founding rather
1547
- * than resolving `'already-founder'` over an instance that never founded. A caller
1548
- * whose `'needs-resume'` wake fails owes the same withdrawal.
1549
- */
1550
- async foundExistingStrand(
1551
- strandId: string,
1552
- resolvePartyKey?: () => Promise<string | undefined>
1553
- ): Promise<'already-founder' | 'bootstrapped' | 'needs-resume'> {
1554
- const instance = this.instances.get(strandId);
1555
- const config = this.launchConfigs.get(strandId);
1556
- if (!instance || !config) {
1557
- throw new Error(`Cannot found strand ${strandId}: not tracked`);
1558
- }
1559
- if (config.founder === true) {
1560
- return 'already-founder';
1561
- }
1562
- const partyMemberPrivateKey =
1563
- config.partyMemberPrivateKey
1564
- ?? (config.strandRow.Type === 'c' ? await resolvePartyKey?.() : undefined);
1565
- // A fresh object rather than mutating in place: startStrand retains the CALLER'S
1566
- // config object, which is not ours to rewrite.
1567
- this.launchConfigs.set(strandId, { ...config, founder: true, partyMemberPrivateKey });
1568
- if (this.isQuiescing(strandId) || (!instance.database && !this.firstSyncGates.has(strandId))) {
1569
- return 'needs-resume';
1570
- }
1571
- try {
1572
- await this.ensureFounderBootstrap(strandId);
1573
- } catch (error) {
1574
- this.withdrawFounderRequest(strandId);
1575
- throw error;
1576
- }
1577
- return 'bootstrapped';
1578
- }
1579
-
1580
- /**
1581
- * Give a tracked storage replica ({@link StartStrandConfig.sAppConfig} absent) the app's
1582
- * schema in place — the seam for an app on this machine claiming a strand this node was
1583
- * already hosting. No runtime rebuild: the libp2p node, its peer id and connections, the
1584
- * store and its warm cache all stay, and the new `App` tables read the blocks the replica
1585
- * already holds. Callers attach BEFORE {@link foundExistingStrand}: the founder bootstrap
1586
- * writes the sApp into `Strand.Header` and refuses a database that has none.
1587
- *
1588
- * A runtime build in flight (the replica's launch, or a hibernation wake) is waited out
1589
- * first, so the attach acts on the database that build produced. Then, in order: the
1590
- * schema signature is checked before anything changes; the retained launch config takes
1591
- * the sApp, so every later rebuild applies it through `composeStrand`; the live database —
1592
- * published, or still held by the first-sync gate — gets the schema; and only then does
1593
- * the instance record `sAppInfo` and the sApp's latency hint. A quiesced instance gets the
1594
- * config alone, and its next resume applies the schema.
1595
- *
1596
- * @returns `'already-attached'` when the instance already runs an sApp — a DIFFERENT one
1597
- * is logged and left as it is, as a second claim of a claimed strand always has been —
1598
- * else `'attached'`.
1599
- * @throws when the strand is not tracked (a caller bug, or a launch that failed while
1600
- * this waited on it); when the schema signature is refused, having changed nothing; and
1601
- * whatever the live apply throws (e.g. a quiesce closed the database mid-apply) — the
1602
- * retained config then still carries the sApp and `sAppInfo` stays unset, so the next
1603
- * claim retries the apply.
1604
- *
1605
- * NOTE: two claims of one replica racing each other both pass the `sAppInfo` check and
1606
- * apply concurrently; the loser of the declarative diff can reject, and its `addStrand`
1607
- * retry then resolves `'already-attached'`. Needs an app calling `addStrand` twice at once
1608
- * (or beside a watcher retry); if it is ever seen, chain attaches per strand id.
1609
- */
1610
- async attachSApp(
1611
- strandId: string,
1612
- sAppConfig: SAppConfig,
1613
- options: { requireSignedSchemas?: boolean } = {}
1614
- ): Promise<'attached' | 'already-attached'> {
1615
- await this.settleRuntimeBuilds(strandId);
1616
- const instance = this.instances.get(strandId);
1617
- const config = this.launchConfigs.get(strandId);
1618
- if (!instance || !config) {
1619
- throw new Error(`Cannot attach an sApp to strand ${strandId}: not tracked`);
1620
- }
1621
- if (instance.sAppInfo) {
1622
- if (instance.sAppInfo.id !== sAppConfig.id) {
1623
- log('attachSApp: strand %s already runs sApp %s — the claim for sApp %s is ignored',
1624
- strandId, instance.sAppInfo.id, sAppConfig.id);
1625
- }
1626
- return 'already-attached';
1627
- }
1628
- const sAppInfo = verifiedSAppInfo(strandId, sAppConfig, options.requireSignedSchemas);
1629
- // A fresh object rather than mutating in place: startStrand retains the CALLER'S
1630
- // config object, which is not ours to rewrite.
1631
- this.launchConfigs.set(strandId, { ...config, sAppConfig });
1632
- const database = instance.database ?? this.firstSyncGates.get(strandId)?.database;
1633
- if (database) {
1634
- await database.attachAppSchema(sAppConfig);
1635
- } else {
1636
- log('attachSApp: strand %s is quiesced — its next resume applies the sApp schema', strandId);
1637
- }
1638
- instance.sAppInfo = sAppInfo;
1639
- if (sAppConfig.latencyHint) {
1640
- // HibernationManager reads the hint whenever it arms a timer, so the app's hint governs
1641
- // from the next one: a timer already armed runs once at the old duration, and a replica
1642
- // launched under a realtime default was never tracked, so it stays up until relaunched.
1643
- instance.latencyHint = sAppConfig.latencyHint;
1644
- }
1645
- log('Strand %s upgraded from storage replica to %s', strandId, describeSApp(sAppConfig));
1646
- return 'attached';
1647
- }
1648
-
1649
- /**
1650
- * Whether `strandId` is launched but still waiting for its first sync — a joiner whose
1651
- * runtime is up while its database is withheld (status `'syncing'`, or `'idle'` after
1652
- * the hibernation manager's idle timer fired on it), or one waiting to rebuild because no
1653
- * seed peer had answered ({@link deferUnreachableJoin}). `false` for a writable, quiesced,
1654
- * or untracked strand. The predicate {@link whenWritable}'s callers gate on.
1655
- */
1656
- isAwaitingFirstSync(strandId: string): boolean {
1657
- const instance = this.instances.get(strandId);
1658
- return instance !== undefined
1659
- && (isAwaitingFirstSync(instance) || this.unreachableJoinRetries.has(strandId));
1660
- }
1661
-
1662
- /**
1663
- * Resolve once the strand's database is published to the app — immediately for a
1664
- * writable strand — or reject with {@link StrandAwaitingFirstSyncError} after
1665
- * `timeoutMs` (default: the retained launch config's `firstSync.timeoutMs`, else
1666
- * {@link DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS}). The rejection is RETRYABLE: nothing is
1667
- * torn down, the gate keeps probing, and a later call waits afresh. A quiesced
1668
- * (hibernating) strand is not woken here — the wait spans a resume, so a caller that
1669
- * wants one wakes it (`CadreNode.wakeStrand`) and waits. Rejects immediately for an
1670
- * untracked strand, and whenever the strand is stopped while a wait is pending.
1671
- */
1672
- whenWritable(strandId: string, options?: { timeoutMs?: number }): Promise<StrandInstance> {
1673
- const instance = this.instances.get(strandId);
1674
- if (!instance) {
1675
- return Promise.reject(new Error(`Cannot wait for strand ${strandId} to become writable: not tracked`));
1676
- }
1677
- if (instance.database) {
1678
- return Promise.resolve(instance);
1679
- }
1680
- const timeoutMs = options?.timeoutMs
1681
- ?? this.launchConfigs.get(strandId)?.firstSync?.timeoutMs
1682
- ?? DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS;
1683
- const startedAt = Date.now();
1684
- return new Promise<StrandInstance>((resolve, reject) => {
1685
- const waiters = this.writableWaiters.get(strandId) ?? new Set<WritableWaiter>();
1686
- this.writableWaiters.set(strandId, waiters);
1687
- const settle = (): void => {
1688
- clearTimeout(timer);
1689
- waiters.delete(waiter);
1690
- if (waiters.size === 0) {
1691
- this.writableWaiters.delete(strandId);
1692
- }
1693
- };
1694
- const waiter: WritableWaiter = {
1695
- resolve: () => { settle(); resolve(instance); },
1696
- reject: (error) => { settle(); reject(error); }
1697
- };
1698
- const timer = setTimeout(
1699
- () => waiter.reject(new StrandAwaitingFirstSyncError(strandId, Date.now() - startedAt)),
1700
- timeoutMs);
1701
- (timer as { unref?: () => void }).unref?.();
1702
- waiters.add(waiter);
1703
- });
1704
- }
1705
-
1706
- /**
1707
- * The tracked instance once no runtime build of it is in flight, or `undefined` when none
1708
- * is tracked by then — never launched, or the launch waited on failed and dropped its
1709
- * record. For a caller about to hand a tracked instance to an app: until its build settles
1710
- * the instance is `'starting'` with no database, and a failed launch leaves no instance.
1711
- * Never rejects; a failed build is reported by the call that started it.
1712
- */
1713
- async whenRuntimeBuilt(strandId: string): Promise<StrandInstance | undefined> {
1714
- await this.settleRuntimeBuilds(strandId);
1715
- return this.instances.get(strandId);
1716
- }
1717
-
1718
- /**
1719
- * Hand a launch's database to the app: set `instance.database`, retire the gate that
1720
- * held it, release every {@link whenWritable} waiter, and — when the launch had already
1721
- * been reported gated — flip it `'active'` and announce it through the retained config's
1722
- * `onWritable`. "Reported gated" is any status but `'starting'`: `'syncing'`, or the
1723
- * `'idle'` the hibernation manager's idle timer flips a long-gated joiner to (see
1724
- * {@link isAwaitingFirstSync}) — the Header arriving after that flip must announce too,
1725
- * or an app hanging on `strand:writable` never learns the strand opened. A publish that
1726
- * lands while the instance is still `'starting'` (the Header arrived during the rest of
1727
- * bring-up) announces nothing: `startStrand` / `resumeStrand` are about to report the
1728
- * strand `'active'`, and `strand:writable` is defined as the follow-up to a gated
1729
- * launch, never a duplicate of `strand:started`.
1730
- *
1731
- * It is also the one seam where a WITHHELD database becomes available, so it kicks the
1732
- * membership reconciler: on a gated launch that loop's own immediate pass ran while
1733
- * `instance.database` was still unset, found no database, and would otherwise not try
1734
- * again until its retry timer fired. A launch that was never gated publishes here BEFORE
1735
- * the reconciler is constructed, so there is nothing registered to kick and the loop's own
1736
- * immediate pass already sees the database — which is why the kick needs no `wasGated`
1737
- * test of its own.
1738
- */
1739
- private publishDatabase(instance: StrandInstance, database: StrandDatabase): void {
1740
- const strandId = instance.strandId;
1741
- const gate = this.firstSyncGates.get(strandId);
1742
- if (gate) {
1743
- gate.open();
1744
- this.firstSyncGates.delete(strandId);
1745
- }
1746
- instance.database = database;
1747
- const wasGated = instance.status !== 'starting';
1748
- if (wasGated) {
1749
- // A Header delivered by a peer is strand activity; a publish during bring-up is not
1750
- // (see the build's end in `buildStrandRuntime`).
1751
- instance.lastActivity = new Date();
1752
- instance.status = 'active';
1753
- log('Strand %s is now writable: Strand.Header held', strandId);
1754
- }
1755
- const waiters = this.writableWaiters.get(strandId);
1756
- if (waiters) {
1757
- this.writableWaiters.delete(strandId);
1758
- waiters.forEach((waiter) => waiter.resolve());
1759
- }
1760
- if (wasGated) {
1761
- this.launchConfigs.get(strandId)?.onWritable?.(strandId);
1762
- }
1763
- // Not awaited: publishing must stay synchronous, and the pass chains on the loop's own
1764
- // tail, so it cannot overlap a pass already in flight.
1765
- void this.membershipReconcilers.get(strandId)?.reconcile();
1766
- }
1767
-
1768
- /** Reject every {@link whenWritable} waiter for a strand that is going away. */
1769
- private rejectWritableWaiters(strandId: string, reason: string): void {
1770
- const waiters = this.writableWaiters.get(strandId);
1771
- if (!waiters) {
1772
- return;
1773
- }
1774
- this.writableWaiters.delete(strandId);
1775
- waiters.forEach((waiter) => waiter.reject(new Error(`Strand ${strandId} ${reason} before becoming writable`)));
1776
- }
1777
-
1778
- /**
1779
- * Undo {@link foundExistingStrand}'s founder flip after the founding it promised
1780
- * failed, so the retained config again says what this instance actually runs as (a
1781
- * joiner) and the next founder request re-attempts the bootstrap. The resolved party
1782
- * key stays retained — it is this party's identity for the strand either way. No-op
1783
- * when the strand is untracked or its config does not found.
1784
- */
1785
- withdrawFounderRequest(strandId: string): void {
1786
- const config = this.launchConfigs.get(strandId);
1787
- if (config?.founder === true) {
1788
- this.launchConfigs.set(strandId, { ...config, founder: false });
1789
- }
1790
- }
1791
-
1792
- /**
1793
- * Run the (idempotent) founder bootstrap against a tracked strand's LIVE
1794
- * database, independently of what the retained launch config says.
1795
- *
1796
- * Separate from {@link foundExistingStrand} because a caller that resolved
1797
- * `'needs-resume'` and woke the strand must not assume the wake's own rebuild
1798
- * founded it: `HibernationManager` COALESCES wakes, so a wake already in flight
1799
- * when the config flipped had already read the PRE-flip config and rebuilt as a
1800
- * joiner. Re-running the bootstrap costs one insert-if-absent probe per table
1801
- * and is the only thing that makes "founding resolves once the Header is
1802
- * written" true on that path.
1803
- *
1804
- * A strand still `'syncing'` (its database withheld behind the first-sync gate) is
1805
- * founded through the gate: the bootstrap writes the Header this machine was waiting
1806
- * to receive, so a successful run publishes the database and the strand goes
1807
- * `'active'` — the one legitimate way a joiner launch becomes writable without a peer.
1808
- *
1809
- * @throws when the strand is not tracked, or is still quiesced (no live
1810
- * database) — both mean the bootstrap did NOT run, which a founder request
1811
- * must never swallow.
1812
- */
1813
- async ensureFounderBootstrap(strandId: string): Promise<void> {
1814
- const instance = this.instances.get(strandId);
1815
- if (!instance) {
1816
- throw new Error(`Cannot run the founder bootstrap for strand ${strandId}: not tracked`);
1817
- }
1818
- const gate = this.firstSyncGates.get(strandId);
1819
- const database = instance.database ?? gate?.database;
1820
- if (!database) {
1821
- throw new Error(
1822
- `Cannot run the founder bootstrap for strand ${strandId}: it is quiesced, so there ` +
1823
- 'is no live database to write to — resume it first.'
1824
- );
1825
- }
1826
- // Forward the RETAINED config's party key: a foundExistingStrand that flipped a
1827
- // joiner launch to founder may have resolved a key the live database's captured
1828
- // config (built at the original launch) never saw.
1829
- await database.ensureFounderBootstrap(this.launchConfigs.get(strandId)?.partyMemberPrivateKey);
1830
- if (!instance.database) {
1831
- this.publishDatabase(instance, database);
1832
- }
1833
- }
1834
-
1835
- /**
1836
- * Stop a strand instance
1837
- */
1838
- async stopStrand(strandId: string): Promise<void> {
1839
- const instance = this.instances.get(strandId);
1840
- if (!instance) {
1841
- log('Strand %s not found', strandId);
1842
- return;
1843
- }
1844
-
1845
- log('Stopping strand instance: %s', strandId);
1846
- instance.status = 'stopping';
1847
- this.rejectWritableWaiters(strandId, 'was stopped');
1848
-
1849
- try {
1850
- await this.releaseRuntime(instance);
1851
- instance.status = 'stopped';
1852
- this.instances.delete(strandId);
1853
- this.launchConfigs.delete(strandId);
1854
- // Storage is released only here — NOT in releaseRuntime, which a quiesce shares.
1855
- await this.disposeStrandStorage(strandId);
1856
- log('Strand %s stopped successfully', strandId);
1857
- } catch (error) {
1858
- instance.status = 'error';
1859
- instance.error = error instanceof Error ? error.message : String(error);
1860
- log('Error stopping strand %s: %s', strandId, instance.error);
1861
- throw error;
1862
- }
1863
- }
1864
-
1865
- /**
1866
- * Stop all strand instances
1867
- */
1868
- async stopAll(): Promise<void> {
1869
- this.stopping = true;
1870
- log('Stopping all strand instances (%d)', this.instances.size);
1871
-
1872
- const stopPromises = Array.from(this.instances.keys()).map(id =>
1873
- this.stopStrand(id).catch(err => {
1874
- log('Error stopping strand %s during shutdown: %s', id, err);
1875
- })
1876
- );
1877
-
1878
- await Promise.all(stopPromises);
1879
- this.stopping = false;
1880
- log('All strand instances stopped');
1881
- }
1882
- }
1883
-
1
+ import debug from 'debug';
2
+ import type { Libp2p, PrivateKey } from '@libp2p/interface';
3
+ import { createLibp2pNode, type IRawStorage } from '@optimystic/db-p2p';
4
+ import { wrapStorageWithCache, disposeStorageCache } from '@serfab/quereus-plugin-sereus';
5
+ import { StrandDatabase } from './strand-database.js';
6
+ import type { StrandCommitDurability, StrandCommitHeld } from './strand-commit-durability.js';
7
+ import { PeerJoinBackfill, type PeerJoinBackfillConfig } from './peer-join-backfill.js';
8
+ import { strandNetworkStatePersistence, type StrandNetworkStateStore } from './strand-network-state.js';
9
+ import {
10
+ StrandRevocationEnforcer,
11
+ createRevocationConnectionGater,
12
+ readStrandRevocationRows,
13
+ type StrandRevocationEnforcementConfig
14
+ } from './strand-revocation-enforcer.js';
15
+ import {
16
+ StrandMembershipReconciler,
17
+ type PendingMembershipInviteSource,
18
+ type StrandMembershipReconciliationConfig
19
+ } from './strand-membership-reconciler.js';
20
+ import { removeMemberPeer } from './strand-membership-writer.js';
21
+ import { strandMemberKeyPair } from './strand-member-key.js';
22
+ import { assertSchemaSignature } from './schema-verification.js';
23
+ import { assertStrandScopeKey } from './storage-scope.js';
24
+ import {
25
+ StrandFirstSyncGate,
26
+ StrandAwaitingFirstSyncError,
27
+ strandFirstSyncComplete,
28
+ DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS,
29
+ type StrandFirstSyncConfig
30
+ } from './strand-first-sync-gate.js';
31
+ import type {
32
+ StrandInstance,
33
+ StrandRow,
34
+ StorageConfig,
35
+ NetworkConfig,
36
+ LatencyHint,
37
+ NodeProfile,
38
+ SAppConfig,
39
+ SAppInfo,
40
+ RawStorageProvider,
41
+ Libp2pNodeWithRepo
42
+ } from './types.js';
43
+ import { DEFAULT_CONNECTION_MONITOR, resolveStrandClusterSize, strandClusterPolicy } from './types.js';
44
+ import { strandNodeAddrs } from './strand-network-config.js';
45
+ import { nodeTransportsOption } from './node-transports.js';
46
+ import { resolveRelayServer } from './relay-server.js';
47
+ import { strandCohortTopicOption, type StrandReactivityConfig } from './strand-reactivity.js';
48
+ import { superviseRelayReservation, type RelayReservationSupervisor } from './relay-reservation.js';
49
+ import { strandRedialTimings, superviseStrandPeerRedial, type StrandPeerRedial } from './strand-peer-redial.js';
50
+ import { groupAddrsByPeerId } from './peer-addr-book.js';
51
+ import { isCohortUnreachableRead } from './control-read-retry.js';
52
+ import { declaredCohortReadDeadlineMs, optimysticDialLimits, peerJoinPushBudget, relayReservationBudgetMs, resolveLinkRoundTripMs } from './link-budget.js';
53
+
54
+ const log = debug('sereus:cadre:strand-manager');
55
+
56
+ /**
57
+ * How often a joining launch that could not build its database, because no seed peer had
58
+ * answered, retries the build on its running libp2p node
59
+ * (`StrandInstanceManager.deferUnreachableJoin`). Each attempt composes a fresh database and
60
+ * re-reads the schema catalog over the network, so it is spaced well above the first-sync
61
+ * gate's probe cadence.
62
+ *
63
+ * NOTE: the 5 s dates from when each attempt also rebuilt the libp2p node. A joiner whose seed
64
+ * peer answered just after a failed attempt waits up to this long to become writable; if that
65
+ * wait shows up in a measured join, try a shorter first retry.
66
+ */
67
+ export const UNREACHABLE_JOIN_RETRY_MS = 5_000;
68
+
69
+ /**
70
+ * How one database build of a runtime ended ({@link StrandInstanceManager.buildStrandDatabase}):
71
+ * published or held by the first-sync gate; failed only because no seed peer has answered yet;
72
+ * or overtaken by a release of the runtime it was building on.
73
+ */
74
+ type StrandDatabaseBuild = 'built' | 'awaiting-seed' | 'released';
75
+
76
+ const timing = debug('sereus:cadre:timing');
77
+
78
+ /** One caller blocked in {@link StrandInstanceManager.whenWritable}. */
79
+ interface WritableWaiter {
80
+ resolve: () => void;
81
+ reject: (error: Error) => void;
82
+ }
83
+
84
+ /**
85
+ * Whether a tracked instance is launched but waiting for its first sync: the runtime is
86
+ * up (`libp2pNode` set) while the database is still withheld (`database` unset). That
87
+ * is the first-sync gate's state regardless of what `status` says — the hibernation
88
+ * manager's idle timer can flip a long-gated joiner to `'idle'` without changing it.
89
+ *
90
+ * NOTE: `status` is therefore not the source of truth for "gated": a joiner that reaches
91
+ * nobody for `idleTimeout` (5 min at the interactive hint) reads `'idle'`, then
92
+ * `'hibernating'`, while still holding no database. Harmless today — every decision the
93
+ * runtime makes goes through this predicate, {@link StrandInstanceManager.publishDatabase}
94
+ * announces on the idle-flipped instance exactly as on a `'syncing'` one, and an app that
95
+ * shows "waiting for the other member" on `'syncing'` merely sees "idle" instead after
96
+ * five minutes. If an app ever needs the gated LABEL to survive the idle flip, make the
97
+ * hibernation manager's idle transition preserve `'syncing'` rather than adding a flag.
98
+ */
99
+ export function isAwaitingFirstSync(instance: StrandInstance): boolean {
100
+ return instance.libp2pNode !== undefined && instance.database === undefined;
101
+ }
102
+
103
+ /**
104
+ * The status a LIVE instance (runtime rebuilt or woken) should report: `'active'` once its
105
+ * database is published, `'syncing'` while the first-sync gate still withholds it. Every
106
+ * site that would otherwise write `'active'` after a build or a wake goes through this,
107
+ * so a gated joiner never reads as writable.
108
+ */
109
+ export function liveStrandStatus(instance: StrandInstance): 'active' | 'syncing' {
110
+ return instance.database ? 'active' : 'syncing';
111
+ }
112
+
113
+ /**
114
+ * Configuration for starting a strand instance
115
+ */
116
+ export interface StartStrandConfig {
117
+ strandRow: StrandRow;
118
+ /**
119
+ * sApp configuration provided by the hosting application. Absent for a **storage
120
+ * replica** — a strand this node stores and serves without the app installed
121
+ * (`CadreNodeConfig.hostUnclaimedStrands`): no schema signature check, no `App`
122
+ * schema, no `sAppInfo` on the instance, and the default latency hint. A replica is
123
+ * always a joiner; `StrandDatabase` refuses to found one. An app that later claims the
124
+ * strand upgrades the running replica in place ({@link StrandInstanceManager.attachSApp}).
125
+ */
126
+ sAppConfig?: SAppConfig;
127
+ storage?: StorageConfig;
128
+ network?: NetworkConfig;
129
+ profile: NodeProfile;
130
+ defaultLatencyHint: LatencyHint;
131
+ privateKey?: PrivateKey;
132
+ /** Cohort-derived discovery seed (multiaddr strings). Defaults to [] when omitted. */
133
+ bootstrapNodes?: string[];
134
+ /**
135
+ * Require a valid author signature on the sApp schema before bring-up.
136
+ * Defaults to true (fail closed) when omitted; set false only for dev/test
137
+ * with unsigned demo schemas. Mirrors {@link CadreNodeConfig.requireSignedSchemas}.
138
+ */
139
+ requireSignedSchemas?: boolean;
140
+ /**
141
+ * Whether this node founds the strand (vs. joins it). Forwarded to the
142
+ * StrandDatabase so the founder bootstrap (Header, founding Member/Manager)
143
+ * runs once at bring-up. Joiners leave this unset and write nothing. Callers
144
+ * resolve it BEFORE calling `startStrand` (`CadreNode.launchStrand` derives it
145
+ * from the row's `FounderOwnerKey` when no explicit flag is given — see
146
+ * {@link StrandConfig.founder}); a founder request that arrives while the
147
+ * instance is already tracked goes through {@link StrandInstanceManager.foundExistingStrand},
148
+ * never through a repeat `startStrand`.
149
+ */
150
+ founder?: boolean;
151
+ /**
152
+ * THIS party's own strand membership private key (base64 protobuf) for a closed
153
+ * strand — the identity the founder bootstrap derives `Member.Key` /
154
+ * `Manager.MemberKey` from. Resolved by the caller (`CadreNode.launchStrand`: an
155
+ * explicit attach-time key, else the control-layer `StrandPartyKey` row, healed by
156
+ * mint-on-launch for the founding machine) and retained with the launch config, so a
157
+ * hibernation wake rebuilds under the same identity. Deliberately NOT the strand
158
+ * row's shared `MemberPrivateKey` (see `StrandDatabaseConfig.partyMemberPrivateKey`).
159
+ * Absent for open strands, and for joiners with no persisted party key.
160
+ */
161
+ partyMemberPrivateKey?: string;
162
+ /**
163
+ * Number of nodes Optimystic is told this strand's replication cluster should
164
+ * have. Same rule as {@link CadreNodeConfig.strandClusterSize}, which CadreNode
165
+ * forwards here: every node on the strand should use the same value, and it is
166
+ * frozen when the strand's libp2p node is created. Defaults to
167
+ * `DEFAULT_STRAND_CLUSTER_SIZE` (4); values below `MIN_CLUSTER_SIZE` (2) are
168
+ * rejected by `resolveStrandClusterSize`. Strand-only — the
169
+ * control network's breadth is the fixed `CONTROL_REPLICATION_BREADTH`.
170
+ */
171
+ clusterSize?: number;
172
+ /**
173
+ * Machines that SERVE THIS STRAND (this node included), for the strand node's
174
+ * block-repair corroboration yardstick — see `resolveRepairYardstick`. It must be
175
+ * an authenticated per-strand count: the machines that actually run a node for this
176
+ * strand, not the machines that exist.
177
+ *
178
+ * **The party's enrolled-machine count is NOT this number and must never be passed
179
+ * here.** A strand launches only on machines whose embedding app registered its sApp
180
+ * config (`CadreNode.addStrand`), so a closed strand shared by two machines of a
181
+ * three-machine party is served by two. Passing three over-declares, and
182
+ * over-declaring is the unsafe direction: at a declaration of 3 or more Optimystic
183
+ * pins the repair corroboration floor at two corroborating peers, which a cohort
184
+ * that can only ever field one peer can never reach — so the strand can never repair
185
+ * a block (`cluster-fetch:no-quorum`, surfacing as reads failing with `Missing
186
+ * block`). That regression is why this field was renamed off "enrolledMachines":
187
+ * `bug-strand-yardstick-counts-party-machines`.
188
+ *
189
+ * **Nothing feeds it in production today.** No authenticated per-strand serving count
190
+ * exists yet, so `CadreNode` passes nothing and the strand node runs the frozen
191
+ * `STRAND_CLUSTER_POLICY` — declaring no yardstick, which leaves the known,
192
+ * upstream-tracked single-voter exposure
193
+ * (`backlog/debt-read-repair-single-voter-corroboration`). Building the count is
194
+ * `backlog/feat-strand-yardstick-from-serving-machines`; this field and its
195
+ * threading are the seam it plugs into.
196
+ *
197
+ * Volatile when a source does exist: re-resolve it on every resume beside the cohort
198
+ * seed, since machines join and leave a strand while it hibernates. Omitting it means
199
+ * "this node does not know", which declares nothing.
200
+ */
201
+ servingMachines?: number;
202
+ /**
203
+ * Tuning for the strand peer-join block catch-up ({@link PeerJoinBackfill}),
204
+ * forwarded from {@link CadreNodeConfig.strandBackfill}. When the strand's
205
+ * libp2p node connects to a peer this runtime has not yet caught up, every
206
+ * block in the strand's own raw store is pushed to it. Runs only on strands
207
+ * with per-strand storage; `{ enabled: false }` restores the pre-existing
208
+ * no-backfill behaviour.
209
+ */
210
+ backfill?: PeerJoinBackfillConfig;
211
+ /**
212
+ * Whether this strand's libp2p node is built with Optimystic's change notifications,
213
+ * forwarded from {@link CadreNodeConfig.strandReactivity} and resolved per strand by
214
+ * `strandCohortTopicOption`. Retained with the launch config, so a hibernation wake
215
+ * rebuilds the node with the same setting.
216
+ */
217
+ reactivity?: StrandReactivityConfig;
218
+ /**
219
+ * Tuning for the CLOSED-strand revoked-peer gate
220
+ * ({@link StrandRevocationEnforcer}), forwarded from
221
+ * {@link CadreNodeConfig.strandRevocationEnforcement}. Armed only for
222
+ * `strandRow.Type === 'c'` (an open strand has no membership rows to derive a
223
+ * deny set from); `{ enabled: false }` restores the pre-existing behaviour
224
+ * (a removed party's peers keep being served).
225
+ */
226
+ revocationEnforcement?: StrandRevocationEnforcementConfig;
227
+
228
+ /**
229
+ * The staged formation membership invitation for THIS strand — the seam the
230
+ * bring-up membership reconciler (`strand-membership-reconciler.ts`) reads to
231
+ * redeem the party's `Strand.Member` seat, and clears once the invitation is
232
+ * spent, burned, or dead. `CadreNode.launchStrand` wires it over its in-memory
233
+ * `pendingMembershipInvites` map; read lazily per pass, so a re-formation that
234
+ * replaces the entry between passes is picked up. Only consulted for closed
235
+ * strands launched with a {@link partyMemberPrivateKey}; harmless otherwise.
236
+ */
237
+ pendingMembershipInvite?: PendingMembershipInviteSource;
238
+
239
+ /**
240
+ * Tuning for the CLOSED-strand membership reconciler, forwarded from
241
+ * {@link CadreNodeConfig.strandMembershipReconciliation}. Armed only for
242
+ * closed strands launched with a {@link partyMemberPrivateKey};
243
+ * `{ enabled: false }` disarms the loop (test fixtures that hand-drive the
244
+ * membership writers). When it names no `pollIntervalMs` the reconciler
245
+ * mirrors {@link revocationEnforcement}'s cadence — as its IDLE cadence and
246
+ * the cap of its unfinished-join retry ladder, not as a flat retry interval.
247
+ */
248
+ membershipReconciliation?: StrandMembershipReconciliationConfig;
249
+
250
+ /**
251
+ * Called when THIS node's own peer id turns up in the strand's revoked set —
252
+ * this node's party was removed from the closed strand, or left it. Fires once
253
+ * per removal (re-armed if the party is re-admitted; a resume also rebuilds the
254
+ * enforcer and may legitimately re-fire), and only for closed strands with the
255
+ * gate armed. `CadreNode`
256
+ * wires it to its `strand:revoked` event; nothing is stopped or torn down on
257
+ * this node's behalf — what to do about it is the app's call.
258
+ */
259
+ onSelfRevoked?: (strandId: string) => void;
260
+
261
+ /**
262
+ * Called when the membership reconciler reports a blocked re-join — this node holds a
263
+ * staged membership invitation for the strand that its writes cannot redeem, which is
264
+ * what a REMOVED party handed a fresh invitation hits (see "Reporting a blocked
265
+ * re-join" in `strand-membership-reconciler.ts` for the two triggers, one of them a
266
+ * suspicion rather than a verdict). At most once per re-arm of the loop — a further
267
+ * invitation staged while the loop is still running does not reset the report — and
268
+ * only for closed strands with a party key. `CadreNode` wires it to its `strand:rejoin-blocked`
269
+ * event; nothing is stopped or torn down — a remaining manager admitting this party's
270
+ * key directly is the remedy, and the loop finishes the join by itself once that lands.
271
+ */
272
+ onRejoinBlocked?: (strandId: string) => void;
273
+
274
+ /**
275
+ * Tuning for the JOINING machine's first-sync write gate (`strand-first-sync-gate.ts`),
276
+ * forwarded from {@link CadreNodeConfig.strandFirstSync}: the Header probe cadence while
277
+ * a non-founder launch is `'syncing'`, and the default budget {@link whenWritable} waits
278
+ * before rejecting. Founders and machines that already hold the Header are never gated.
279
+ */
280
+ firstSync?: StrandFirstSyncConfig;
281
+
282
+ /**
283
+ * Called when a launch that came up `'syncing'` (see {@link firstSync}) becomes
284
+ * writable: the strand's `Strand.Header` arrived from a peer — or a founder request
285
+ * ran the bootstrap against the gated database — and `instance.database` is now set.
286
+ * Never called for a launch that was writable when `startStrand`/`resumeStrand`
287
+ * resolved. `CadreNode` wires it to its `strand:writable` event. Retained with the
288
+ * launch config, so a hibernation resume that comes up gated announces too.
289
+ */
290
+ onWritable?: (strandId: string) => void;
291
+
292
+ /**
293
+ * Called synchronously inside every commit on the strand's database that wrote something,
294
+ * with who holds it — the app's commits and cadre-core's own membership writes alike.
295
+ * `CadreNode` wires it to its `strand:commit-durability` event. Retained with the launch
296
+ * config and passed to every database built for the launch, so a hibernation wake's rebuilt
297
+ * database reports too. A throw is logged and does not affect the commit.
298
+ */
299
+ onCommitDurability?: (commit: StrandCommitDurability) => void;
300
+
301
+ /**
302
+ * Called when a commit reported `followed` below full replication becomes held by every member
303
+ * of its cohort, while the database that made it is still open. `CadreNode` wires it to its
304
+ * `strand:commit-held` event. Retained and isolated like {@link onCommitDurability}.
305
+ */
306
+ onCommitHeld?: (event: StrandCommitHeld) => void;
307
+
308
+ /**
309
+ * Re-announce this strand's delegate peer id (`delegatePeerId` — the strand
310
+ * node's own transport peer id) to ONE relay (`relayAddr`, a direct dial addr
311
+ * with a trailing `/p2p/<relayPeerId>`), unthrottled. Awaited before every
312
+ * relay-reservation RE-drive of that relay — never before the first attempt,
313
+ * which the launch/resume seed pass has already announced for.
314
+ *
315
+ * Why: a party control node running the relay server admits the strand node on
316
+ * an in-memory delegate grant that a relay restart drops, so a re-drive that did
317
+ * not re-announce first would be denied at the relay's gate. `CadreNode` wires
318
+ * its own control-mesh announce here; a throw or rejection is logged by the
319
+ * supervisor and the re-drive still runs. Retained with the launch config, so a
320
+ * hibernation wake's rebuilt supervisors carry it too.
321
+ */
322
+ announceDelegateToRelay?: (strandId: string, relayAddr: string, delegatePeerId: string) => Promise<void>;
323
+
324
+ /**
325
+ * The node-local strand network state (`strand-network-state.ts`): this strand's
326
+ * slice of it is handed to db-p2p as `persistence`, so the strand node saves its
327
+ * FRET routing table (with each peer's signed address record) on every connection
328
+ * and re-imports it when it is next built. Absent ⇒ nothing is saved and the node
329
+ * starts with an empty table. `CadreNode` passes its store. Retained with the launch
330
+ * config, so a hibernation wake rebuilds the node over the same state.
331
+ */
332
+ networkState?: StrandNetworkStateStore;
333
+ }
334
+
335
+ /**
336
+ * Volatile inputs re-resolved when resuming a quiesced strand — the ones that can
337
+ * have moved since it last ran, and that the rebuilt libp2p node freezes again. Each
338
+ * one omitted keeps the value the retained launch config already holds, so a resume
339
+ * that passes nothing rebuilds the strand exactly as it last ran.
340
+ */
341
+ export interface ResumeStrandOverrides {
342
+ /**
343
+ * Freshly-resolved cohort discovery seed (multiaddr strings). Grows as peers are
344
+ * learned since the strand first launched.
345
+ */
346
+ bootstrapNodes?: string[];
347
+ /**
348
+ * Freshly-read count of the machines serving this strand, for the repair yardstick
349
+ * (see {@link StartStrandConfig.servingMachines} — including why the party's
350
+ * enrolled-machine count is not it). Moves whenever a machine starts or stops
351
+ * serving the strand, which a hibernating strand does not otherwise notice. Nothing
352
+ * passes it today. Omitting it here does NOT mean "unknown" the way omitting it from
353
+ * {@link StartStrandConfig} does — it retains the last value; see `resumeStrand`.
354
+ */
355
+ servingMachines?: number;
356
+ }
357
+
358
+ /** A {@link StrandInstanceManager.resumeStrand} or {@link StrandInstanceManager.quiesceStrand} of one strand. */
359
+ type RuntimeTransition =
360
+ | { kind: 'resume'; operation: Promise<StrandInstance> }
361
+ | { kind: 'quiesce'; operation: Promise<void> };
362
+
363
+ /**
364
+ * Get the isolated storage path for a specific strand.
365
+ *
366
+ * @deprecated This helper is Node-only and throws in React Native (it assumes a
367
+ * filesystem layout). Use a storage provider factory function instead, which
368
+ * receives the strandId and can create strand-specific storage paths using
369
+ * platform-appropriate methods.
370
+ *
371
+ * @example
372
+ * // Instead of using getStrandStoragePath, use a storage provider factory:
373
+ * const storage = {
374
+ * provider: (strandId: string) => new FileRawStorage(`./data/strands/${strandId}`)
375
+ * };
376
+ */
377
+ export function getStrandStoragePath(basePath: string, strandId: string): string {
378
+ // Check if we're in a Node.js environment
379
+ if (typeof process === 'undefined' || !process.versions?.node) {
380
+ throw new Error(
381
+ 'getStrandStoragePath is not available in React Native. ' +
382
+ 'Use a storage provider factory function instead.'
383
+ );
384
+ }
385
+
386
+ // Sanitize strandId for filesystem safety (UUIDs should be safe, but just in case)
387
+ const safeId = strandId.replace(/[^a-zA-Z0-9-]/g, '_');
388
+
389
+ // Build the path with plain string joins rather than the Node `path` module.
390
+ // A static `require('path')` forces RN bundlers (e.g. Metro) to *resolve* the
391
+ // module at bundle time even though this Node-only helper throws above before
392
+ // ever reaching here — joining by hand keeps the module free of any Node
393
+ // built-in reference, so RN bundles need no `path` shim.
394
+ const trimmedBase = basePath.replace(/[\\/]+$/, '');
395
+ return `${trimmedBase}/strands/${safeId}`;
396
+ }
397
+
398
+ /**
399
+ * Resolve a storage provider for a specific strand.
400
+ * If the provider is a factory function, call it with the strandId.
401
+ *
402
+ * Called only from {@link StrandInstanceManager.startStrand}, which owns the result
403
+ * for the instance's lifetime — see `strandStorages`, and which has already asserted
404
+ * the id is usable as a scope key. Do not move that assertion here: this function
405
+ * returns early when no provider is configured, and the id becomes a libp2p protocol
406
+ * prefix on that path too.
407
+ *
408
+ * @param provider - Storage provider (instance or factory)
409
+ * @param strandId - The strand ID to create storage for
410
+ * @returns The resolved IRawStorage instance, or undefined if no provider
411
+ */
412
+ function resolveStrandStorage(
413
+ provider: RawStorageProvider | undefined,
414
+ strandId: string
415
+ ): IRawStorage | undefined {
416
+ if (!provider) {
417
+ return undefined;
418
+ }
419
+ const storage = typeof provider === 'function' ? provider(strandId) : provider;
420
+ // Wrapped in the write-through raw-storage cache (quereus-plugin-sereus's cached-storage.ts).
421
+ // Called ONCE per strand launch — `startStrand` keeps the result for the instance's
422
+ // lifetime — so the wrap survives every runtime rebuild the instance goes through.
423
+ return wrapStorageWithCache(storage, strandId);
424
+ }
425
+
426
+ /**
427
+ * Verify an sApp's schema signature (fail-closed unless `requireSignedSchemas` is
428
+ * false) and project the config onto the instance's `sAppInfo`.
429
+ */
430
+ function verifiedSAppInfo(strandId: string, sAppConfig: SAppConfig, requireSignedSchemas: boolean | undefined): SAppInfo {
431
+ assertSchemaSignature(sAppConfig, { requireSignature: requireSignedSchemas ?? true });
432
+ log('Strand %s sApp schema signature verified (author: %s)', strandId, sAppConfig.id);
433
+ return {
434
+ id: sAppConfig.id,
435
+ version: sAppConfig.version,
436
+ schema: sAppConfig.schema,
437
+ signature: sAppConfig.signature
438
+ };
439
+ }
440
+
441
+ /** Log wording for what a launch runs: the sApp and its version, or a storage replica. */
442
+ function describeSApp(sAppConfig: SAppConfig | undefined): string {
443
+ return sAppConfig ? `sApp: ${sAppConfig.id} v${sAppConfig.version}` : 'storage replica';
444
+ }
445
+
446
+ /**
447
+ * Manages individual strand instances - creates and destroys isolated libp2p nodes
448
+ * for each strand the cadre participates in.
449
+ */
450
+ export class StrandInstanceManager {
451
+ private instances: Map<string, StrandInstance> = new Map();
452
+ /**
453
+ * Retained launch config per strand, captured in `startStrand` and cleared in
454
+ * `stopStrand`. `resumeStrand` reuses it to rebuild a quiesced strand's runtime
455
+ * without the caller re-threading storage/network/profile/key/sApp config.
456
+ */
457
+ private launchConfigs: Map<string, StartStrandConfig> = new Map();
458
+ /**
459
+ * The per-strand peer-join block catch-up, keyed by strand id. Private (not on
460
+ * the public {@link StrandInstance}) because it is runtime plumbing with the
461
+ * same lifetime as the strand's libp2p node: created in `buildStrandRuntime`,
462
+ * stopped and dropped in `releaseRuntime` — so quiesce → resume rebuilds it
463
+ * with a fresh caught-up-peer memo, which is intended (a resumed node may have
464
+ * missed writes).
465
+ */
466
+ private backfills: Map<string, PeerJoinBackfill> = new Map();
467
+ /**
468
+ * The per-strand revoked-peer enforcer (closed strands only), keyed by strand
469
+ * id. Same lifecycle rationale as {@link backfills}: created in
470
+ * `buildStrandRuntime`, stopped and dropped in `releaseRuntime`, so quiesce →
471
+ * resume rebuilds it with a fresh (initially empty, fail-open) snapshot.
472
+ */
473
+ private revocationEnforcers: Map<string, StrandRevocationEnforcer> = new Map();
474
+ /**
475
+ * The per-strand membership reconciler (closed strands launched with a party
476
+ * key only), keyed by strand id. Same lifecycle rationale as {@link backfills}:
477
+ * created in `buildStrandRuntime`, stopped and dropped in `releaseRuntime`, so
478
+ * quiesce → resume rebuilds it and re-runs the idempotent join ladder (redeem a
479
+ * staged invitation, write this machine's own `MemberPeer` binding) from scratch.
480
+ */
481
+ private membershipReconcilers: Map<string, StrandMembershipReconciler> = new Map();
482
+ /**
483
+ * The per-strand first-sync gate (`strand-first-sync-gate.ts`), keyed by strand id:
484
+ * holds a launch's `StrandDatabase` while it is NOT yet published on the instance.
485
+ * Present from the moment the database object exists in `buildStrandRuntime` until
486
+ * {@link publishDatabase} hands it to the app — so it doubles as the rollback handle
487
+ * for a failed `initialize()` — and, for a joiner that holds no `Strand.Header` yet,
488
+ * for as long as the launch stays `'syncing'`. Same lifecycle as {@link backfills}:
489
+ * stopped (its database closed) and dropped in `releaseRuntime`, so a quiesce →
490
+ * resume rebuild re-probes over the same store. An entry and `instance.database`
491
+ * are mutually exclusive.
492
+ */
493
+ private firstSyncGates: Map<string, StrandFirstSyncGate> = new Map();
494
+ /**
495
+ * Callers blocked in {@link whenWritable}, keyed by strand id. Resolved by
496
+ * {@link publishDatabase}, rejected by {@link stopStrand}; each waiter also carries
497
+ * its own timeout. Deliberately NOT cleared by `releaseRuntime`: a waiter outlives a
498
+ * quiesce → resume cycle, since the rebuild is what may finally publish the database.
499
+ */
500
+ private writableWaiters: Map<string, Set<WritableWaiter>> = new Map();
501
+ /**
502
+ * The per-strand relay-reservation supervisors — ONE PER CONFIGURED RELAY, each
503
+ * over the node's own bare `/p2p-circuit` listener for that relay
504
+ * (`strand-network-config.ts`) — keyed by strand id. Same lifecycle rationale as
505
+ * {@link backfills}: started in `buildStrandRuntime` right after the libp2p node
506
+ * exists, stopped FIRST and dropped in `releaseRuntime` (before the database
507
+ * closes and the node stops, so no re-drive dials a node being torn down), so
508
+ * quiesce → resume rebuilds them over the new node. What makes a strand node's
509
+ * lost relay slot come back on its own — the control node has the same loop in
510
+ * `CadreNode.reserveRelays`.
511
+ */
512
+ private relaySupervisors: Map<string, RelayReservationSupervisor[]> = new Map();
513
+ /**
514
+ * The per-strand redial of the strand's other members (`strand-peer-redial.ts`), keyed by
515
+ * strand id. Same lifecycle as {@link relaySupervisors}: started in `buildStrandRuntime` once
516
+ * the libp2p node exists, stopped first in `releaseRuntime`, so a hibernating strand dials
517
+ * nobody and a resume redials over the new node.
518
+ */
519
+ private peerRedials: Map<string, StrandPeerRedial> = new Map();
520
+ /**
521
+ * The resolved (cache-wrapped) raw storage per strand id — the instance's OWN
522
+ * store, resolved once in `startStrand` and held until `stopStrand` disposes it.
523
+ * Private for the same reason `backfills` is: runtime plumbing, not part of the
524
+ * public {@link StrandInstance}.
525
+ *
526
+ * Deliberately NOT touched by `releaseRuntime`: that is what lets a quiesce →
527
+ * resume cycle rebuild the libp2p node over the SAME store, keeping its
528
+ * write-through cache warm (and, on an in-memory backend, keeping the strand's
529
+ * blocks at all). An entry exists iff `instances` does AND the launch config
530
+ * supplied a storage provider.
531
+ *
532
+ * NOTE: a hibernating strand therefore keeps its store — and its share of the
533
+ * process-wide cache pool — resident for as long as the instance is tracked. That
534
+ * is the point (a warm wake), and the pool evicts under pressure, so the cost is
535
+ * one map entry per hibernating strand today. If a device ever hibernates strands
536
+ * by the hundred, revisit: dropping the store at quiesce and paying for a cold
537
+ * wake becomes the better trade.
538
+ */
539
+ private strandStorages: Map<string, IRawStorage> = new Map();
540
+ /**
541
+ * The runtime build in flight per strand id (`buildStrandRuntime`, from `startStrand` or
542
+ * `resumeStrand`, or a deferred join's database retry), present until it settles. The
543
+ * instance is tracked for the whole build, with its database not yet constructed or not yet
544
+ * initialized, so a caller that must act on the FINISHED runtime ({@link attachSApp},
545
+ * {@link whenRuntimeBuilt}) waits on this instead. A failed build's rejection belongs to the
546
+ * call that started it.
547
+ */
548
+ private runtimeBuilds: Map<string, Promise<unknown>> = new Map();
549
+ /**
550
+ * The latest resume or quiesce requested per strand id, present until it settles. Each one
551
+ * starts only once the one requested before it has settled, so a wake that lands during a
552
+ * quiesce rebuilds after it, and a quiesce requested during a rebuild releases what that
553
+ * rebuild finished. The WHOLE operation, not its entry in {@link runtimeBuilds}: that settles
554
+ * before a resume's own catch records `'error'`, so a joiner awaiting it could read a stale
555
+ * status.
556
+ */
557
+ private transitions: Map<string, RuntimeTransition> = new Map();
558
+ /**
559
+ * The pending database retry per strand id of a launch whose database could not be built
560
+ * because no seed peer had answered yet ({@link deferUnreachableJoin}). Cleared by
561
+ * {@link releaseRuntime}, so a stop or a quiesce cancels it.
562
+ */
563
+ private unreachableJoinRetries: Map<string, unknown> = new Map();
564
+ private stopping = false;
565
+
566
+ constructor() {
567
+ log('StrandInstanceManager created');
568
+ }
569
+
570
+ /**
571
+ * Get all current strand instances
572
+ */
573
+ getInstances(): Map<string, StrandInstance> {
574
+ return new Map(this.instances);
575
+ }
576
+
577
+ /**
578
+ * Get a specific strand instance
579
+ */
580
+ getInstance(strandId: string): StrandInstance | undefined {
581
+ return this.instances.get(strandId);
582
+ }
583
+
584
+ /**
585
+ * Check if a strand is currently running
586
+ */
587
+ hasStrand(strandId: string): boolean {
588
+ return this.instances.has(strandId);
589
+ }
590
+
591
+ /**
592
+ * Start a new strand instance.
593
+ *
594
+ * A failed launch leaves NOTHING tracked: the instance and its retained launch
595
+ * config are both dropped before the error is rethrown, so the strand id is
596
+ * free for a genuine retry. This matches the pre-registration failure path
597
+ * (a rejected schema signature, which throws before anything is recorded) —
598
+ * both failure modes of this call leave the same residue: none. Callers learn
599
+ * of the failure from the rejected promise (and, on the control-discovered
600
+ * path, from CadreNode's `strand:error` event), not from an error record left
601
+ * behind in `instances`.
602
+ *
603
+ * The strand's raw storage is resolved HERE, once, and held for the instance's
604
+ * lifetime (see `strandStorages`) — `buildStrandRuntime` only reads it, so a
605
+ * hibernation wake never re-enters the embedder's provider.
606
+ */
607
+ async startStrand(config: StartStrandConfig): Promise<StrandInstance> {
608
+ const { strandRow, sAppConfig } = config;
609
+ const strandId = strandRow.Id;
610
+
611
+ if (this.stopping) {
612
+ throw new Error('StrandInstanceManager is stopping');
613
+ }
614
+
615
+ if (this.instances.has(strandId)) {
616
+ // Callers resolve founder-ness BEFORE reaching here (CadreNode.launchStrand) and
617
+ // honor a founder request on a tracked instance via foundExistingStrand — so a
618
+ // founder flag arriving at this early return against a non-founder retained
619
+ // config is a dropped bootstrap, and must never again be silent.
620
+ if (config.founder === true && this.launchConfigs.get(strandId)?.founder !== true) {
621
+ log('startStrand: strand %s is already running but was NOT launched as founder — ' +
622
+ 'this early return DROPS the founder request; use foundExistingStrand', strandId);
623
+ }
624
+ log('Strand %s already running', strandId);
625
+ return this.instances.get(strandId)!;
626
+ }
627
+
628
+ log('Starting strand instance: %s (%s)', strandId, describeSApp(sAppConfig));
629
+ const tTotal = performance.now();
630
+
631
+ // The id becomes two names below: the storage scope key the embedder's provider
632
+ // turns into a directory or database name, and `networkName` in buildStrandRuntime,
633
+ // from which the libp2p protocol prefix `/optimystic/strand-<id>` is built. A
634
+ // replicated strand row carries whatever id the founding node wrote, so neither is
635
+ // safe unchecked. Asserted HERE rather than in `resolveStrandStorage` because that
636
+ // function returns early when no provider is configured — a node with no storage
637
+ // still reaches buildStrandRuntime and still mints the protocol prefix.
638
+ assertStrandScopeKey(strandId);
639
+
640
+ const sAppInfo = sAppConfig ? verifiedSAppInfo(strandId, sAppConfig, config.requireSignedSchemas) : undefined;
641
+
642
+ // Resolve this strand's storage ONCE, before anything is recorded. If a factory
643
+ // function is provided, it is called with the strandId to create strand-specific
644
+ // storage (e.g. strand-isolated directories). A provider that throws therefore
645
+ // fails the launch alongside the schema-signature check, leaving nothing tracked.
646
+ const strandStorage = resolveStrandStorage(config.storage?.provider, strandId);
647
+ if (strandStorage) {
648
+ log('Strand %s using provided storage provider', strandId);
649
+ }
650
+
651
+ // Determine latency hint: sApp config > default
652
+ const latencyHint = sAppConfig?.latencyHint ?? config.defaultLatencyHint;
653
+
654
+ const instance: StrandInstance = {
655
+ strandId,
656
+ status: 'starting',
657
+ sAppInfo,
658
+ memberPrivateKey: strandRow.MemberPrivateKey ?? undefined,
659
+ connectedPeers: 0,
660
+ lastActivity: new Date(),
661
+ latencyHint
662
+ };
663
+
664
+ this.instances.set(strandId, instance);
665
+ this.launchConfigs.set(strandId, config);
666
+ if (strandStorage) {
667
+ this.strandStorages.set(strandId, strandStorage);
668
+ }
669
+
670
+ try {
671
+ await this.trackRuntimeBuild(strandId, this.buildStrandRuntime(instance, config));
672
+ timing('[startStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
673
+ log('Strand %s started successfully (%s)', strandId, describeSApp(sAppConfig));
674
+ return instance;
675
+ } catch (error) {
676
+ // Status/error first — the (now discarded) record is still what `log` reports on.
677
+ instance.status = 'error';
678
+ instance.error = error instanceof Error ? error.message : String(error);
679
+ log('Failed to start strand %s: %s', strandId, instance.error);
680
+ // Drop the dead record so this strand id can be launched again. Keep the
681
+ // `launchConfigs` has an entry iff `instances` does invariant — resumeStrand
682
+ // reads both, and a config without an instance would strand the config.
683
+ this.instances.delete(strandId);
684
+ this.launchConfigs.delete(strandId);
685
+ // The store this launch resolved goes with it: nothing owns it any more, and a
686
+ // retained cache wrapper would be handed back (already retired) on a retry.
687
+ await this.disposeStrandStorage(strandId);
688
+ throw error;
689
+ }
690
+ }
691
+
692
+ /** Hold `build` in {@link runtimeBuilds} until it settles, and settle as it does. */
693
+ private async trackRuntimeBuild<T>(strandId: string, build: Promise<T>): Promise<T> {
694
+ this.runtimeBuilds.set(strandId, build);
695
+ try {
696
+ return await build;
697
+ } finally {
698
+ if (this.runtimeBuilds.get(strandId) === build) {
699
+ this.runtimeBuilds.delete(strandId);
700
+ }
701
+ }
702
+ }
703
+
704
+ /**
705
+ * Wait until no runtime build of `strandId` is in flight. Never rejects: a failed build
706
+ * is reported by the call that started it, and the caller re-reads the instance after.
707
+ *
708
+ * NOTE: after a failed launch the re-read sees the instance gone only because
709
+ * `startStrand`'s catch deletes it synchronously, and its continuation is queued before
710
+ * this waiter's. If that cleanup ever awaits before `instances.delete`, a waiter can act
711
+ * on the dying record; move the cleanup inside the tracked promise then.
712
+ */
713
+ private async settleRuntimeBuilds(strandId: string): Promise<void> {
714
+ for (let build = this.runtimeBuilds.get(strandId); build; build = this.runtimeBuilds.get(strandId)) {
715
+ await build.catch((error: unknown) => {
716
+ log('Strand %s: the runtime build waited on failed (reported by its launcher): %o', strandId, error);
717
+ });
718
+ }
719
+ }
720
+
721
+ /**
722
+ * Build (or rebuild) the libp2p node + StrandDatabase for an instance and
723
+ * attach them, transitioning it to `active`. Shared by `startStrand` (fresh
724
+ * launch) and `resumeStrand` (rehydrating a quiesced instance). Reads all
725
+ * volatile inputs (bootstrapNodes, servingMachines, network, profile,
726
+ * privateKey, sApp config) from `config`, so the caller controls the
727
+ * cohort-derived values. Storage is the
728
+ * one input it does NOT re-read from `config`: that belongs to the instance and
729
+ * comes from `strandStorages`.
730
+ *
731
+ * A database that cannot be built because no seed peer has answered yet does not fail the
732
+ * build: the runtime comes up `'syncing'` without it and the database phase alone is
733
+ * retried on the same node ({@link deferUnreachableJoin}).
734
+ */
735
+ private async buildStrandRuntime(instance: StrandInstance, config: StartStrandConfig): Promise<void> {
736
+ const strandId = instance.strandId;
737
+
738
+ // Refuse a bad `linkRoundTripMs` before any strand bring-up, for the reason
739
+ // `CadreNode.start()` does: every budget derived from it here is behind a condition
740
+ // (backfill disabled, no relay addrs), so a zero or NaN declaration would otherwise
741
+ // surface later inside a path that logs and carries on. `link-budget.ts`.
742
+ resolveLinkRoundTripMs(config.network?.linkRoundTripMs);
743
+
744
+ // The store the instance OWNS (resolved once in `startStrand`), not a fresh
745
+ // resolution: a rebuild must reach the same backend through the same warm cache.
746
+ const strandStorage = this.strandStorages.get(strandId);
747
+
748
+ // db-p2p namespaces every one of the node's protocol ids by network name
749
+ // (`/optimystic/<networkName>/...`), so anything dialing this node's own
750
+ // services must derive its prefix from the SAME string the node was built
751
+ // with — hence one binding for both, not two literals that can drift.
752
+ const networkName = `strand-${strandId}`;
753
+ const protocolPrefix = `/optimystic/${networkName}`;
754
+
755
+ // Whether this node runs the circuit-relay server, and its init — the same
756
+ // resolution the control node takes from the same config (`relay-server.ts`).
757
+ const relayServer = resolveRelayServer(config.network, config.profile);
758
+ // The strand-node VIEW of the machine's one `NetworkConfig`, not the control
759
+ // node's resolution: fixed direct listen ports become ephemeral (two nodes cannot
760
+ // bind one port), the announce config is dropped (it names the control node's
761
+ // address), and every configured relay becomes one bare `/p2p-circuit` SEARCH
762
+ // listener plus a dial addr in `relayAddrs` for the per-relay supervisor started
763
+ // below — the same route the control node takes, because the configured
764
+ // `<relay>/p2p-circuit` shape loses its address on a relay restart, a hangup, or
765
+ // libp2p's own reservation refresh and recovers from none of them. See
766
+ // `strand-network-config.ts` for all three, and `relay-reservation.ts`.
767
+ //
768
+ // `relayAddrs` is destructured OFF: it is not a `createLibp2pNode` option, and
769
+ // spreading it would hand db-p2p a key it does not know.
770
+ const { relayAddrs: relayDialAddrs = [], ...addrOptions } = strandNodeAddrs(config.network);
771
+
772
+ // The CLOSED-strand revoked-peer gate (see strand-revocation-enforcer.ts).
773
+ // Constructed BEFORE the libp2p node because the node's options embed its
774
+ // predicates; its deny set starts empty (admit everything — fail-open, same
775
+ // posture as bring-up everywhere here) and is first populated after the
776
+ // strand database initializes below. Registered in the map immediately so
777
+ // the failure rollback (releaseRuntime) tears it down like every other
778
+ // runtime component. Open strands skip it entirely: their Member/MemberPeer
779
+ // tables are empty by schema (`OnlyClosed`), so there is nothing to derive
780
+ // a deny set from — arming would be pointless polling.
781
+ const revocationEnforcer =
782
+ config.strandRow.Type === 'c' && config.revocationEnforcement?.enabled !== false
783
+ ? new StrandRevocationEnforcer({
784
+ label: strandId,
785
+ readRows: () => {
786
+ const database = instance.database;
787
+ if (!database) {
788
+ throw new Error(`strand ${strandId} has no live database`);
789
+ }
790
+ return readStrandRevocationRows(database.getDatabase());
791
+ },
792
+ // Read per sweep, never captured: this closure is built BEFORE the
793
+ // libp2p node exists (its options embed the enforcer's predicates),
794
+ // and `releaseRuntime` clears the field again on quiesce. Undefined
795
+ // therefore means "no transport right now", which the enforcer
796
+ // treats as "nothing to tear down".
797
+ getNetwork: () => instance.libp2pNode,
798
+ onSelfRevoked: () => config.onSelfRevoked?.(strandId)
799
+ }, config.revocationEnforcement)
800
+ : undefined;
801
+ if (revocationEnforcer) {
802
+ this.revocationEnforcers.set(strandId, revocationEnforcer);
803
+ }
804
+
805
+ // Closed strands compose revoked-peer denial onto the caller's gater and arm
806
+ // the fail-closed per-stream gate; open strands keep the raw configured gater
807
+ // (their peers are legitimately cross-party and nothing is ever revoked).
808
+ const revocationGateOptions = revocationEnforcer
809
+ ? {
810
+ connectionGater: createRevocationConnectionGater(revocationEnforcer, config.network?.connectionGater),
811
+ authorizeInboundStream: (remotePeerId: string, protocol: string) =>
812
+ revocationEnforcer.authorizeStream(remotePeerId, protocol)
813
+ }
814
+ : config.network?.connectionGater
815
+ ? { connectionGater: config.network.connectionGater }
816
+ : {};
817
+
818
+ const reactivityOption = strandCohortTopicOption(config.reactivity, strandId);
819
+ if (reactivityOption.cohortTopic) {
820
+ log('strand %s: change notifications on', strandId);
821
+ }
822
+
823
+ try {
824
+ // Bound once: the breadth is also the ceiling on the repair yardstick below, and the
825
+ // two must be derived from the same resolution. Inside the `try` deliberately — a
826
+ // rejected clusterSize is a build failure that runs the same cleanup as any other.
827
+ const strandClusterSize = resolveStrandClusterSize(config.clusterSize);
828
+
829
+ let t0 = performance.now();
830
+ const node = await createLibp2pNode({
831
+ port: 0, // Random port
832
+ bootstrapNodes: config.bootstrapNodes ?? [],
833
+ networkName,
834
+ storage: strandStorage,
835
+ fretProfile: config.profile === 'storage' ? 'core' : 'edge',
836
+ relay: relayServer.enabled,
837
+ // NOTE: unlike the control node, a strand node has no unauthorized-reservation budget,
838
+ // so with the per-connection cap off any peer that reaches this node can hold one of
839
+ // `maxReservations` slots and forward uncapped through it. If strand relays are ever
840
+ // abused for bandwidth, give strand nodes a budget or a capped init of their own.
841
+ ...(relayServer.enabled && { relayServerInit: relayServer.init }),
842
+ clusterSize: strandClusterSize,
843
+ // Deliberately NOT CONTROL_CLUSTER_POLICY: a strand is application data with its own
844
+ // breadth reasoning, and the shape match with the control policy is a coincidence.
845
+ //
846
+ // The builder declares this node's block-repair corroboration yardstick from the
847
+ // count of machines SERVING this strand, capped at the breadth above (a block
848
+ // never lives on more machines than the cohort is wide). Given no count — the
849
+ // production path today, since no per-strand serving count exists yet — it
850
+ // returns the frozen STRAND_CLUSTER_POLICY itself, declaring nothing. Resolved
851
+ // HERE rather than at `startStrand`, so a wake from hibernation would pick up a
852
+ // serving set that changed while the strand slept.
853
+ // The read deadline is settled by the same helper the control node uses, because the
854
+ // two networks ride one link: the host's own, else derived from its declared
855
+ // `linkRoundTripMs`, else nothing, and the base policy's COHORT_READ_DEADLINE_MS stands.
856
+ clusterPolicy: strandClusterPolicy(strandClusterSize, {
857
+ servingMachines: config.servingMachines,
858
+ cohortQueryTimeoutMs: declaredCohortReadDeadlineMs(config.network)
859
+ }),
860
+ arachnode: {
861
+ enableRingZulu: config.profile === 'storage'
862
+ },
863
+ ...(config.privateKey && { privateKey: config.privateKey }),
864
+ // Built per runtime, not per launch: the adapter stops saving once the strand's
865
+ // state is forgotten, and a rebuilt runtime is what starts it saving again.
866
+ //
867
+ // NOTE: the saved state also restores which peers db-p2p saw serving the strand,
868
+ // and it counts them in the cohort until FRET finds them unreachable. A node built
869
+ // while every other member is offline therefore fails its first writes ("Failed to
870
+ // get super-majority") — for 4-6 s on loopback, the window a running node already
871
+ // sees when a member drops. If apps report failed sends after relaunching alone on
872
+ // a slow relayed link, retry the write in the app or raise it upstream (db-p2p's
873
+ // remembered-serving fallback); dropping `persistence` brings back the split
874
+ // restart.
875
+ ...(config.networkState && { persistence: strandNetworkStatePersistence(config.networkState, strandId) }),
876
+ // With relays configured, built with libp2p's relay discovery off (given a transport
877
+ // list to wrap — `node-transports.ts`), so the supervisors below are the only thing
878
+ // that fills the bare `/p2p-circuit` slots: otherwise a cohort seed running the relay
879
+ // server takes one as soon as it connects (`relay-reservation.ts`, "WHY LIBP2P'S
880
+ // RELAY DISCOVERY IS SWITCHED OFF").
881
+ ...nodeTransportsOption(config.network, addrOptions, relayDialAddrs.length > 0),
882
+ ...(config.network?.noiseCrypto && { noiseCrypto: config.network.noiseCrypto }),
883
+ // Unconditional, and the same default the control node takes: every node of
884
+ // every party runs the monitor over its connection to a slow phone, so the
885
+ // widened ping deadline has to reach the strand nodes too (see
886
+ // DEFAULT_CONNECTION_MONITOR).
887
+ connectionMonitor: config.network?.connectionMonitor ?? DEFAULT_CONNECTION_MONITOR,
888
+ // The same declared link the control node states, and for the same reason: a strand
889
+ // node is also the listener for every other member's strand node, and Optimystic
890
+ // derives that listener's limit from this (`link-budget.ts`).
891
+ linkRoundTripMs: resolveLinkRoundTripMs(config.network?.linkRoundTripMs),
892
+ // The same dial limits as the control node: a strand node dials the same machines,
893
+ // through the same relays and gates.
894
+ ...optimysticDialLimits(config.network?.linkRoundTripMs),
895
+ // Listen entries plus the WebSocket transport switch they imply — a strand node
896
+ // announces nothing the operator configured (`strand-network-config.ts`), and
897
+ // spreads AFTER `transports` above because the switch is a no-op whenever a
898
+ // transport list was passed. The bare `/p2p-circuit` entries (one per relay) open
899
+ // no connection here; each registers a pending reservation that the matching
900
+ // supervisor below fills. That is what gives a NAT'd strand node a reachable relay
901
+ // slot — and works against a party-run relay because the launch path announced
902
+ // this strand's derived peerId to it first (delegate admission; see cadre-node.ts).
903
+ ...addrOptions,
904
+ // The raw configured gater (open strands), or the revocation-composed
905
+ // gater plus the fail-closed per-stream revoked-peer gate (closed
906
+ // strands) — resolved above, before the try.
907
+ ...revocationGateOptions,
908
+ // `{}` unless the operator enabled change notifications for this strand (`strand-reactivity.ts`).
909
+ ...reactivityOption
910
+ }) as Libp2pNodeWithRepo;
911
+ timing('[buildStrandRuntime:%s] createLibp2pNode: %dms', strandId, Math.round(performance.now() - t0));
912
+
913
+ instance.libp2pNode = node;
914
+
915
+ // One reservation supervisor PER RELAY, started now so the first attempts
916
+ // overlap the database bring-up below (the relay is never in a strand's
917
+ // Optimystic cohort — its protocol ids are namespaced `/optimystic/strand-<id>/…`
918
+ // — so an open relay connection cannot disturb that bring-up). Their first
919
+ // attempts are awaited before the strand goes `active`, below. Registered in the
920
+ // map immediately so the failure rollback (releaseRuntime) stops them like every
921
+ // other runtime component.
922
+ this.relaySupervisors.set(strandId, this.startRelaySupervisors(strandId, node, relayDialAddrs, config));
923
+ // Redials the strand's other members whenever none is connected, on the budget the
924
+ // declared link gives a relayed dial — what reconnects two restarted phones on a slow
925
+ // link, where FRET's own redial cannot (`strand-peer-redial.ts`). The relays are
926
+ // excluded by peer id: the node is connected to them throughout, and they are no member.
927
+ this.peerRedials.set(strandId, superviseStrandPeerRedial({
928
+ label: strandId,
929
+ node,
930
+ seed: config.bootstrapNodes ?? [],
931
+ excluded: new Set(groupAddrsByPeerId([...relayDialAddrs]).keys()),
932
+ ...(revocationEnforcer && { isRevoked: (peerId: string) => revocationEnforcer.isRevoked(peerId) })
933
+ }, strandRedialTimings(config.network?.linkRoundTripMs)));
934
+
935
+ const databaseBuild = await this.buildStrandDatabase(instance, config, node);
936
+ if (!this.isCurrentRuntime(instance, node)) {
937
+ // A stop released this runtime during the database phase (`stopStrand` does not
938
+ // wait for builds); arming the loops below would restart them on a stopped node.
939
+ log('Strand %s was stopped while its runtime was being built', strandId);
940
+ return;
941
+ }
942
+
943
+ // The membership reconciler: finish this party's join on every machine —
944
+ // redeem a staged formation invitation if one is pending, then write the
945
+ // durable machine→party binding (Strand.MemberPeer). Armed here, the one
946
+ // seam where the strand's transport peer id exists and its database has been
947
+ // attempted, for launch AND hibernation resume, for closed strands that carry the
948
+ // party's own membership key. start() kicks an immediate pass WITHOUT
949
+ // awaiting it — a joiner at this instant has not synced the founder's rows
950
+ // and may lack write quorum, so bring-up is never blocked; an unfinished join
951
+ // then retries on a short doubling ladder capped at the configured
952
+ // pollIntervalMs (which is also the flat cadence while nobody has admitted this
953
+ // party yet), and the loop stops once the member row and this machine's own
954
+ // binding are both in place. Armed AFTER the database phase above, so a gated or
955
+ // deferred launch always has a reconciler registered by the time it can publish.
956
+ if (config.strandRow.Type === 'c' && config.partyMemberPrivateKey
957
+ && config.membershipReconciliation?.enabled !== false) {
958
+ const reconciler = new StrandMembershipReconciler({
959
+ label: strandId,
960
+ partyMemberPrivateKey: config.partyMemberPrivateKey,
961
+ // Read per pass, never captured — same lifecycle argument as the
962
+ // enforcer's getNetwork: quiesce drops both handles.
963
+ getDatabase: () => instance.database?.getDatabase(),
964
+ getOwnPeerId: () => instance.libp2pNode?.peerId.toString(),
965
+ pendingInvite: config.pendingMembershipInvite,
966
+ // The enforcer's CURRENT snapshot view of this node's own peer id — the
967
+ // reconciler stops rather than fight a self-revocation. Absent when the
968
+ // gate is disarmed (fail-open: the loop just runs).
969
+ isSelfRevoked: revocationEnforcer
970
+ ? () => {
971
+ const ownPeerId = instance.libp2pNode?.peerId.toString();
972
+ return ownPeerId !== undefined && revocationEnforcer.isRevoked(ownPeerId);
973
+ }
974
+ : undefined,
975
+ onRejoinBlocked: () => config.onRejoinBlocked?.(strandId)
976
+ }, {
977
+ pollIntervalMs: config.membershipReconciliation?.pollIntervalMs
978
+ ?? config.revocationEnforcement?.pollIntervalMs
979
+ });
980
+ this.membershipReconcilers.set(strandId, reconciler);
981
+ reconciler.start();
982
+ }
983
+
984
+ // Arm the revoked-peer deny-set poll now that the database it reads
985
+ // exists. start() kicks an immediate refresh WITHOUT awaiting it —
986
+ // bring-up and resume are never blocked on a membership read; until the
987
+ // first read lands the empty snapshot admits everyone (fail-open).
988
+ revocationEnforcer?.start();
989
+
990
+ // Peer-join block catch-up: push this strand's own blocks to each newly
991
+ // connected peer, so a machine that joined after blocks were committed
992
+ // still ends up physically holding them (without per-strand storage there
993
+ // is nothing to copy). Armed for EVERY stored strand: `PeerJoinBackfill`
994
+ // only does work when the strand's libp2p node reports a peer connection,
995
+ // so on a device that is genuinely alone it is inert, and arming it at
996
+ // launch is what closes the "founded alone, never replicates" hole — a
997
+ // peer that joins later gets the founder's blocks without any relaunch.
998
+ // No `authorizePeer` gate, deliberately — see the module comment in
999
+ // peer-join-backfill.ts for the strand-side argument (and why the control
1000
+ // network, which DOES gate, is different).
1001
+ //
1002
+ // NOTE: cost is one PeerJoinBackfill object + one `peer:identify` listener
1003
+ // per running strand — linear in strand count, negligible at the handful a
1004
+ // device or host runs today. If a node ever hosts strands by the hundred,
1005
+ // move to one shared listener that dispatches by strand id.
1006
+ if (strandStorage && config.backfill?.enabled !== false) {
1007
+ if (node.keyNetwork) {
1008
+ const backfill = new PeerJoinBackfill({
1009
+ label: strandId,
1010
+ libp2p: node,
1011
+ peerNetwork: node.keyNetwork,
1012
+ storage: strandStorage,
1013
+ // The same prefix the receiver registered its block-transfer handler
1014
+ // under — derived from networkName above, never re-spelled here.
1015
+ protocolPrefix
1016
+ }, {
1017
+ // Dial and response deadlines counted in link round trips, not fixed milliseconds:
1018
+ // a relayed dial costs a fixed number of exchanges, so a fixed budget has a link
1019
+ // speed above which this catch-up can never reach the peer at all. See
1020
+ // `link-budget.ts`. Spread BEFORE the host's own config so an explicit
1021
+ // `strandBackfill.dialTimeoutMs` still wins.
1022
+ ...peerJoinPushBudget(config.network?.linkRoundTripMs),
1023
+ ...config.backfill
1024
+ });
1025
+ backfill.start();
1026
+ this.backfills.set(strandId, backfill);
1027
+ } else {
1028
+ log('Strand %s: libp2p node exposes no keyNetwork; peer-join block catch-up is inert', strandId);
1029
+ }
1030
+ }
1031
+
1032
+ // The relay supervisors' FIRST attempts, all of them, before `active`: the happy
1033
+ // path still publishes its circuit addr before `addStrand` resolves (the
1034
+ // strand-addr RPC answers read it, and the same-party circuit scenario asserts
1035
+ // it). Fail-SOFT — a first attempt that lands nothing does not fail the launch.
1036
+ // The strand's database is up, and the supervisor keeps trying on its backoff;
1037
+ // failing here would only trade that for `StrandWatcher`'s full-rebuild retry.
1038
+ //
1039
+ // NOTE: a relay that is down costs this launch one full drive — the reservation budget
1040
+ // counted from the declared link round trip, 18 s at its default (`link-budget.ts`) — and
1041
+ // `StrandWatcher` launches strands one at a time, so N strands cost N of those in
1042
+ // bring-up during a relay outage, and MORE on a host that declared a slower link. If that
1043
+ // ever matters, stop awaiting here (the circuit addr then lands after `active`) rather
1044
+ // than shortening the drive.
1045
+ t0 = performance.now();
1046
+ await this.awaitFirstRelayAttempts(strandId);
1047
+ timing('[buildStrandRuntime:%s] relay first attempts: %dms', strandId, Math.round(performance.now() - t0));
1048
+
1049
+ // No `lastActivity` stamp: bringing a runtime up is not activity. A check-in marks
1050
+ // activity before its resume and must see only what landed while the strand was up.
1051
+ instance.status = liveStrandStatus(instance);
1052
+ if (databaseBuild === 'awaiting-seed') {
1053
+ // Armed only now that the build is over: a retry firing mid-build would find the
1054
+ // build in flight.
1055
+ this.deferUnreachableJoin(instance);
1056
+ } else if (instance.status === 'syncing') {
1057
+ log('Strand %s launched as a joiner with no Strand.Header held yet — writes are withheld until ' +
1058
+ 'a member of the strand is reached', strandId);
1059
+ }
1060
+ } catch (error) {
1061
+ // Roll back any partially-attached runtime so the instance is left with
1062
+ // NEITHER handle. Otherwise the `libp2pNode || database` "already live"
1063
+ // guard in resumeStrand/handleStrandWake would treat a half-built strand
1064
+ // as healthy — leaking the libp2p node and never retrying the rebuild.
1065
+ await this.releaseRuntime(instance).catch((cleanupErr) => {
1066
+ log('buildStrandRuntime cleanup for strand %s also failed: %o', strandId, cleanupErr);
1067
+ });
1068
+ throw error;
1069
+ }
1070
+ }
1071
+
1072
+ /**
1073
+ * The database phase of a runtime build, on the libp2p node already attached: create the
1074
+ * StrandDatabase, initialize it, then publish it or arm its first-sync gate. Run by
1075
+ * {@link buildStrandRuntime} and again by each {@link retryUnreachableJoin}, with a new
1076
+ * StrandDatabase per attempt.
1077
+ *
1078
+ * Returns `'awaiting-seed'` when initialize failed only because no seed peer has answered
1079
+ * (`cohort-unreachable`): that attempt's database is closed and the node keeps running. Any
1080
+ * other failure throws, with the attempt's database left with its gate for
1081
+ * {@link releaseRuntime} to close.
1082
+ */
1083
+ private async buildStrandDatabase(
1084
+ instance: StrandInstance,
1085
+ config: StartStrandConfig,
1086
+ node: Libp2pNodeWithRepo
1087
+ ): Promise<StrandDatabaseBuild> {
1088
+ const strandId = instance.strandId;
1089
+ // Held by the first-sync gate (registered before initialize) rather than attached
1090
+ // to the instance: a failed init is then cleaned up through the gate (close() is safe on
1091
+ // a partially-initialized db), and the app only ever sees `instance.database` once this
1092
+ // machine is allowed to write to the strand.
1093
+ let t0 = performance.now();
1094
+ const strandDb = new StrandDatabase({
1095
+ strandId,
1096
+ sAppConfig: config.sAppConfig,
1097
+ libp2pNode: node,
1098
+ coordinatedRepo: node.coordinatedRepo,
1099
+ // Founder bootstrap inputs: the strand's type drives which membership rows
1100
+ // are written, and the PARTY's own key (partyMemberPrivateKey, resolved by the
1101
+ // caller from the control-layer StrandPartyKey row) derives the founding
1102
+ // Member/Manager key. The row's shared MemberPrivateKey rides along as the
1103
+ // read-gating secret only — it derives nobody's identity.
1104
+ strandType: config.strandRow.Type,
1105
+ memberPrivateKey: config.strandRow.MemberPrivateKey ?? undefined,
1106
+ partyMemberPrivateKey: config.partyMemberPrivateKey,
1107
+ founder: config.founder,
1108
+ onCommitDurability: config.onCommitDurability,
1109
+ onCommitHeld: config.onCommitHeld
1110
+ });
1111
+ const gate = new StrandFirstSyncGate({
1112
+ label: strandId,
1113
+ database: strandDb,
1114
+ onHeaderHeld: () => this.publishDatabase(instance, strandDb)
1115
+ }, config.firstSync);
1116
+ this.firstSyncGates.set(strandId, gate);
1117
+ try {
1118
+ await strandDb.initialize();
1119
+ } catch (error) {
1120
+ if (!isCohortUnreachableRead(error)) {
1121
+ throw error;
1122
+ }
1123
+ await this.discardDatabaseAttempt(strandId, gate);
1124
+ log('Strand %s: no seed peer has answered yet, so this joiner cannot build its database (%s); ' +
1125
+ 'its runtime stays up and the build is retried every %dms',
1126
+ strandId, error instanceof Error ? error.message : String(error), UNREACHABLE_JOIN_RETRY_MS);
1127
+ return 'awaiting-seed';
1128
+ }
1129
+ timing('[buildStrandRuntime:%s] strandDatabase.initialize: %dms', strandId, Math.round(performance.now() - t0));
1130
+ if (this.firstSyncGates.get(strandId) !== gate) {
1131
+ // A stop released the runtime while initialize ran, closing this database through its
1132
+ // gate part-way; close what initialize finished after that.
1133
+ await strandDb.close();
1134
+ return 'released';
1135
+ }
1136
+
1137
+ // The first-sync write gate. A founder just wrote the Header in its bootstrap; any
1138
+ // other machine may commit only once it holds the Header — which it can only have
1139
+ // received from a peer (now, or on an earlier run over the same store) — and has read
1140
+ // each App table once, so their collections are fetched too. Publishing the database
1141
+ // is what makes the strand writable to the app; until then the instance stays
1142
+ // `'syncing'` and the gate re-probes on its cadence. Everything armed after the database
1143
+ // phase reads `instance.database` lazily, so the reconciler and enforcer wait with it —
1144
+ // and `publishDatabase` kicks the reconciler when the wait ends, so a joiner's membership
1145
+ // rows land with the strand rather than one retry later.
1146
+ t0 = performance.now();
1147
+ const synced = config.founder === true || await strandFirstSyncComplete(strandDb.getDatabase(), strandId);
1148
+ timing('[buildStrandRuntime:%s] first-sync probe: %dms', strandId, Math.round(performance.now() - t0));
1149
+ if (this.firstSyncGates.get(strandId) !== gate) {
1150
+ // A stop released the runtime during the probe and closed this database through its gate.
1151
+ return 'released';
1152
+ }
1153
+ if (synced) {
1154
+ this.publishDatabase(instance, strandDb);
1155
+ } else {
1156
+ gate.start();
1157
+ }
1158
+ return 'built';
1159
+ }
1160
+
1161
+ /** Close a database attempt that failed to initialize, and drop its gate if it is still the registered one. */
1162
+ private async discardDatabaseAttempt(strandId: string, gate: StrandFirstSyncGate): Promise<void> {
1163
+ gate.stop();
1164
+ if (this.firstSyncGates.get(strandId) === gate) {
1165
+ this.firstSyncGates.delete(strandId);
1166
+ }
1167
+ await gate.database.close();
1168
+ }
1169
+
1170
+ /**
1171
+ * Keep a launch `'syncing'` when its database could not be built because no seed peer has
1172
+ * answered yet, and retry the database build every {@link UNREACHABLE_JOIN_RETRY_MS} on the
1173
+ * runtime already up.
1174
+ *
1175
+ * Optimystic (since 1.11.0) will not rule a block never-created while any of a node's
1176
+ * `bootstrapNodes` is unheard, so a joiner alone with an unreachable seed cannot build even
1177
+ * the schema catalog: `strandDb.initialize()` fails with `cohort-unreachable`. A founder
1178
+ * given a seed is refused the same way (normally it has none: no sibling runs the strand yet). Refusing is
1179
+ * right (building it alone would fork the catalog), but failing the launch would drop the
1180
+ * strand until the watcher relaunched it, and `addStrand` would reject with a raw Optimystic
1181
+ * error. Deferring gives a joiner the same contract the first-sync gate gives one that did
1182
+ * build: the strand stays tracked, {@link whenWritable} waits and rejects with the retryable
1183
+ * `StrandAwaitingFirstSyncError`, and the launch proceeds once a seed peer answers.
1184
+ *
1185
+ * The libp2p node, its connections and the background loops stay up meanwhile. A seed peer
1186
+ * can answer just after the schema read gave up on it — on a slow link it connects and its
1187
+ * peer-join backfill delivers the whole store — and the retry then builds the database, and
1188
+ * runs the first-sync probe, while that peer is still connected.
1189
+ */
1190
+ private deferUnreachableJoin(instance: StrandInstance): void {
1191
+ const strandId = instance.strandId;
1192
+ const timer = setTimeout(() => {
1193
+ this.unreachableJoinRetries.delete(strandId);
1194
+ void this.retryUnreachableJoin(instance);
1195
+ }, UNREACHABLE_JOIN_RETRY_MS);
1196
+ (timer as { unref?: () => void }).unref?.();
1197
+ this.unreachableJoinRetries.set(strandId, timer);
1198
+ }
1199
+
1200
+ /**
1201
+ * One retry scheduled by {@link deferUnreachableJoin}: the database phase again, on the
1202
+ * runtime still attached. Skipped when the strand was stopped or released since — a quiesce
1203
+ * releases it and the resume after rebuilds the whole runtime — or already has a database.
1204
+ * A failure other than an unanswered seed releases the runtime and marks the strand
1205
+ * `'error'`, as a failed resume does.
1206
+ */
1207
+ private async retryUnreachableJoin(instance: StrandInstance): Promise<void> {
1208
+ const strandId = instance.strandId;
1209
+ const config = this.launchConfigs.get(strandId);
1210
+ // Every strand node is built by `buildStrandRuntime`, as a node with its coordinated repo.
1211
+ const node = instance.libp2pNode as Libp2pNodeWithRepo | undefined;
1212
+ if (!config || !node || !this.isCurrentRuntime(instance, node) || instance.database
1213
+ || this.firstSyncGates.has(strandId) || this.isQuiescing(strandId)) {
1214
+ return;
1215
+ }
1216
+ let build: StrandDatabaseBuild;
1217
+ try {
1218
+ // Tracked like any runtime build, so a wake, a quiesce or an sApp attach waits for it
1219
+ // rather than acting on a database that is still initializing.
1220
+ build = await this.trackRuntimeBuild(strandId, this.buildStrandDatabase(instance, config, node));
1221
+ } catch (error) {
1222
+ if (!this.isCurrentRuntime(instance, node)) {
1223
+ log('Strand %s: a database retry failed after its runtime was released: %o', strandId, error);
1224
+ return;
1225
+ }
1226
+ await this.releaseRuntime(instance).catch((cleanupErr) => {
1227
+ log('Strand %s: releasing the runtime after a failed database retry also failed: %o', strandId, cleanupErr);
1228
+ });
1229
+ instance.status = 'error';
1230
+ instance.error = error instanceof Error ? error.message : String(error);
1231
+ log('Strand %s: building the database of a joiner that was waiting for a seed peer failed: %s', strandId, instance.error);
1232
+ return;
1233
+ }
1234
+ if (build === 'awaiting-seed' && this.isCurrentRuntime(instance, node) && !this.isQuiescing(strandId)) {
1235
+ this.deferUnreachableJoin(instance);
1236
+ }
1237
+ }
1238
+
1239
+ /** Whether `instance` is still tracked, with `node` still its runtime's libp2p node. */
1240
+ private isCurrentRuntime(instance: StrandInstance, node: Libp2p): boolean {
1241
+ return !this.stopping && this.instances.get(instance.strandId) === instance && instance.libp2pNode === node;
1242
+ }
1243
+
1244
+ /**
1245
+ * Release an instance's strand-network runtime: stop the relay supervisors and
1246
+ * the other background loops, close the StrandDatabase, then stop the libp2p
1247
+ * node (construction order in reverse), clearing both fields and zeroing
1248
+ * connectedPeers. Tolerant of partially-built state — either handle may be
1249
+ * absent — so it doubles as rollback for a failed `buildStrandRuntime`. Shared
1250
+ * by `quiesceStrand`, `stopStrand`, and that rollback path.
1251
+ *
1252
+ * Leaves `strandStorages` untouched by design — the store outlives the runtime it
1253
+ * was built into, which is what makes a resume warm. Only `stopStrand` disposes it.
1254
+ */
1255
+ private async releaseRuntime(instance: StrandInstance): Promise<void> {
1256
+ // Relay supervisors FIRST of all — before anything below is torn down — so no
1257
+ // re-drive is scheduled against a node being stopped. `stop()` is synchronous
1258
+ // and never awaits a drive, so a relay that is down cannot delay this teardown.
1259
+ // `stop()` also cancels the drive already in flight, so an attempt started
1260
+ // moments before this does not keep dialing and polling the node the lines
1261
+ // below are stopping; its result is discarded either way.
1262
+ const unreachableJoinRetry = this.unreachableJoinRetries.get(instance.strandId);
1263
+ if (unreachableJoinRetry !== undefined) {
1264
+ clearTimeout(unreachableJoinRetry as ReturnType<typeof setTimeout>);
1265
+ this.unreachableJoinRetries.delete(instance.strandId);
1266
+ }
1267
+ const relaySupervisors = this.relaySupervisors.get(instance.strandId);
1268
+ if (relaySupervisors) {
1269
+ relaySupervisors.forEach((supervisor) => supervisor.stop());
1270
+ this.relaySupervisors.delete(instance.strandId);
1271
+ }
1272
+ this.peerRedials.get(instance.strandId)?.stop();
1273
+ this.peerRedials.delete(instance.strandId);
1274
+ // Backfill next — before the database closes and the libp2p node stops — so
1275
+ // no NEW catch-up push is issued against a torn-down transport. A push already
1276
+ // in flight is not awaited; it fails into the module's own per-chunk catch.
1277
+ const backfill = this.backfills.get(instance.strandId);
1278
+ if (backfill) {
1279
+ backfill.stop();
1280
+ this.backfills.delete(instance.strandId);
1281
+ }
1282
+ // The revoked-peer enforcer goes with the runtime it gated: a resume
1283
+ // rebuilds it with a fresh (initially empty, fail-open) snapshot.
1284
+ const revocationEnforcer = this.revocationEnforcers.get(instance.strandId);
1285
+ if (revocationEnforcer) {
1286
+ revocationEnforcer.stop();
1287
+ this.revocationEnforcers.delete(instance.strandId);
1288
+ }
1289
+ // The membership reconciler likewise: a resume rebuilds it and re-runs the
1290
+ // idempotent ladder, which is what makes resume-after-partial-join heal.
1291
+ const membershipReconciler = this.membershipReconcilers.get(instance.strandId);
1292
+ if (membershipReconciler) {
1293
+ membershipReconciler.stop();
1294
+ this.membershipReconcilers.delete(instance.strandId);
1295
+ }
1296
+ // A still-gated database (a joiner that never received the Header, or a launch whose
1297
+ // initialize() failed) is closed through its gate; a published one through the
1298
+ // instance. Never both — publishing moves the handle from the gate to the instance.
1299
+ const gate = this.firstSyncGates.get(instance.strandId);
1300
+ if (gate) {
1301
+ gate.stop();
1302
+ this.firstSyncGates.delete(instance.strandId);
1303
+ await gate.database.close();
1304
+ }
1305
+ if (instance.database) {
1306
+ await instance.database.close();
1307
+ instance.database = undefined;
1308
+ }
1309
+ if (instance.libp2pNode) {
1310
+ await instance.libp2pNode.stop();
1311
+ instance.libp2pNode = undefined;
1312
+ }
1313
+ instance.connectedPeers = 0;
1314
+ }
1315
+
1316
+ /**
1317
+ * One {@link superviseRelayReservation} per relay dial addr, each over exactly
1318
+ * that relay so "held" is judged per relay (`circuitMultiaddrsVia`) and losing
1319
+ * one relay re-drives only that one. They are the only thing that fills the node's
1320
+ * search slots once the node is built with libp2p's relay discovery off
1321
+ * (`nodeTransportsOption`). Default retry timings — the control node's (2 s
1322
+ * doubling to 60 s between failed attempts, a 5 s liveness check while held). Each DRIVE's
1323
+ * own deadline is counted in link round trips at this host's declared
1324
+ * `network.linkRoundTripMs` (`link-budget.ts`), so the same declaration that lengthens the
1325
+ * control node's drive lengthens these.
1326
+ *
1327
+ * Each supervisor's `beforeRedrive` is the caller's
1328
+ * {@link StartStrandConfig.announceDelegateToRelay} for THIS relay and THIS
1329
+ * node's peer id, so a re-drive after a relay restart is preceded by a fresh
1330
+ * delegate grant on the relay about to be dialed. Returns `[]` when no relay is
1331
+ * configured — the strand then simply has no circuit listener to fill.
1332
+ */
1333
+ private startRelaySupervisors(
1334
+ strandId: string,
1335
+ node: Libp2pNodeWithRepo,
1336
+ relayDialAddrs: readonly string[],
1337
+ config: StartStrandConfig
1338
+ ): RelayReservationSupervisor[] {
1339
+ if (relayDialAddrs.length === 0) {
1340
+ return [];
1341
+ }
1342
+ const announce = config.announceDelegateToRelay;
1343
+ const delegatePeerId = node.peerId.toString();
1344
+ const timeoutMs = relayReservationBudgetMs(config.network?.linkRoundTripMs);
1345
+ return relayDialAddrs.map((relayAddr) => superviseRelayReservation(node, [relayAddr], {
1346
+ timeoutMs,
1347
+ ...(announce && { beforeRedrive: () => announce(strandId, relayAddr, delegatePeerId) })
1348
+ }));
1349
+ }
1350
+
1351
+ /**
1352
+ * Wait for every relay supervisor's first attempt to settle, concurrently, and log
1353
+ * the ones that landed nothing. Never throws — a strand whose relay is unreachable
1354
+ * at launch still comes up, with its supervisors retrying in the background.
1355
+ */
1356
+ private async awaitFirstRelayAttempts(strandId: string): Promise<void> {
1357
+ const supervisors = this.relaySupervisors.get(strandId) ?? [];
1358
+ if (supervisors.length === 0) {
1359
+ return;
1360
+ }
1361
+ await Promise.all(supervisors.map((supervisor) => supervisor.firstAttempt));
1362
+ supervisors.forEach((supervisor) => {
1363
+ if (supervisor.lastError !== null) {
1364
+ log('Strand %s: relay reservation not held after the first attempt (retrying in the background): %s',
1365
+ strandId, supervisor.lastError);
1366
+ }
1367
+ });
1368
+ }
1369
+
1370
+ /**
1371
+ * Drop the strand's owned store and release this strand's claim on its cache. The
1372
+ * wrapper counts holders, so the cache is emptied and unregistered from the shared
1373
+ * pool only if no other scope still holds it. Called only where the strand's whole
1374
+ * lifetime ends (`stopStrand`, and the failed-launch rollback) — never on a quiesce.
1375
+ *
1376
+ * A dispose failure is logged, not thrown: the store is already unreferenced here,
1377
+ * and failing the stop over a cache-bookkeeping error would leave the caller unable
1378
+ * to tear the strand down. `disposeStorageCache` no-ops for an unwrapped store
1379
+ * (e.g. `MemoryRawStorage`), so no instanceof test is needed.
1380
+ */
1381
+ private async disposeStrandStorage(strandId: string): Promise<void> {
1382
+ const storage = this.strandStorages.get(strandId);
1383
+ if (!storage) {
1384
+ return;
1385
+ }
1386
+ this.strandStorages.delete(strandId);
1387
+ try {
1388
+ await disposeStorageCache(storage);
1389
+ } catch (error) {
1390
+ log('Failed to dispose storage cache for strand %s: %o', strandId, error);
1391
+ }
1392
+ }
1393
+
1394
+ /**
1395
+ * Refresh a strand's revoked-peer deny set NOW — and, with it, run the
1396
+ * teardown sweep that hangs up every connected revoked peer.
1397
+ *
1398
+ * The gate is otherwise poll-driven (default
1399
+ * `DEFAULT_REVOCATION_POLL_INTERVAL_MS`), because neither a replicated
1400
+ * revocation nor a local `revokeMember`/`leaveStrand` raises anything this
1401
+ * runtime can hook. A caller that just wrote a revocation against the
1402
+ * strand's database should follow it with this call, which makes the cut
1403
+ * immediate instead of waiting out the interval.
1404
+ *
1405
+ * Quiet no-op — matching `quiesceStrand`'s posture — when the strand is not
1406
+ * tracked, is quiesced, is open, or has the gate disabled: in every one of
1407
+ * those cases there is no enforcer to refresh. Never rejects (the enforcer's
1408
+ * refresh contains its own failures), and resolves only once the sweep has
1409
+ * finished.
1410
+ */
1411
+ async refreshRevocationEnforcement(strandId: string): Promise<void> {
1412
+ const enforcer = this.revocationEnforcers.get(strandId);
1413
+ if (!enforcer) {
1414
+ log('refreshRevocationEnforcement: strand %s has no armed revocation enforcer', strandId);
1415
+ return;
1416
+ }
1417
+ await enforcer.refresh();
1418
+ }
1419
+
1420
+ /**
1421
+ * A fresh membership invitation was staged for `strandId` (`CadreNode`'s
1422
+ * `adoptFormationMembershipInvite`): re-arm the strand's membership reconciler so the
1423
+ * invitation is attempted now rather than never — the loop finished during the first
1424
+ * join and would otherwise stay stopped until a relaunch. Quiet no-op when no reconciler
1425
+ * is armed: a first formation stages before the strand is added, and bring-up then arms
1426
+ * a loop that finds the invitation by itself. Returns at once; the pass runs on the
1427
+ * loop's own serialized chain and never rejects.
1428
+ */
1429
+ notifyMembershipInviteStaged(strandId: string): void {
1430
+ const reconciler = this.membershipReconcilers.get(strandId);
1431
+ if (!reconciler) {
1432
+ log('notifyMembershipInviteStaged: strand %s has no armed membership reconciler — bring-up will find the invitation', strandId);
1433
+ return;
1434
+ }
1435
+ void reconciler.rearm();
1436
+ }
1437
+
1438
+ /**
1439
+ * Best-effort removal of THIS machine's own `Strand.MemberPeer` binding — the
1440
+ * self arm of `removeMemberPeer`, signed with the retained launch config's party
1441
+ * key. Called by `CadreNode.unpublishStrand` BEFORE the local stop, while the
1442
+ * strand database and transport are still live: after the unpublish commits, the
1443
+ * party's `StrandPartyKey` control row is gone, so no restart could ever sign
1444
+ * this removal again — the in-memory retained key is the last chance.
1445
+ *
1446
+ * Never throws. Quiet no-op for a strand that is untracked, open, or launched
1447
+ * without a party key; a quiesced (hibernating) strand, or a strand whose write
1448
+ * quorum is already unreachable, leaves the stale binding behind with a log —
1449
+ * it grants nothing today (admission is not allowlist-gated) and only
1450
+ * mis-credits diversity. The strand's own membership reconciler is stopped —
1451
+ * and its in-flight pass awaited — FIRST, so a pass that was already past its
1452
+ * own stopped check cannot re-register the binding this is about to clear.
1453
+ *
1454
+ * NOTE: deliberately NOT handled here (or anywhere yet): clearing the bindings
1455
+ * of a machine removed from the CADRE at the control layer, or of a party's
1456
+ * OTHER machines when the party unpublishes — the party still holds the key on
1457
+ * every surviving machine and can clear from any of them, and the stale rows
1458
+ * grant nothing while admission is deny-list only. Revisit when
1459
+ * `feat-strand-member-allowlist-admission` lands and a stale binding starts
1460
+ * granting admission rather than merely mis-crediting diversity.
1461
+ */
1462
+ async clearOwnMemberPeerBinding(strandId: string): Promise<void> {
1463
+ const instance = this.instances.get(strandId);
1464
+ const config = this.launchConfigs.get(strandId);
1465
+ if (!instance || !config || config.strandRow.Type !== 'c' || !config.partyMemberPrivateKey) {
1466
+ return;
1467
+ }
1468
+ const reconciler = this.membershipReconcilers.get(strandId);
1469
+ if (reconciler) {
1470
+ reconciler.stop();
1471
+ await reconciler.settle();
1472
+ }
1473
+ const db = instance.database?.getDatabase();
1474
+ const peerId = instance.libp2pNode?.peerId.toString();
1475
+ if (!db || !peerId) {
1476
+ log('clearOwnMemberPeerBinding: strand %s has no live runtime — own MemberPeer binding left in place', strandId);
1477
+ return;
1478
+ }
1479
+ try {
1480
+ // Background write on the app's database: never join a transaction the app has open.
1481
+ await removeMemberPeer(db, {
1482
+ memberKeyPair: strandMemberKeyPair(config.partyMemberPrivateKey),
1483
+ peerId
1484
+ }, { joinOpenTransaction: false });
1485
+ log('clearOwnMemberPeerBinding: strand %s — own binding for peer %s cleared', strandId, peerId);
1486
+ } catch (error) {
1487
+ log('clearOwnMemberPeerBinding: strand %s — best-effort clear failed (strand may already be unreachable): %o',
1488
+ strandId, error);
1489
+ }
1490
+ }
1491
+
1492
+ /**
1493
+ * Quiesce a strand: release its strand-network resources (stop the libp2p node,
1494
+ * close the StrandDatabase) while RETAINING the instance record — identity,
1495
+ * sAppInfo, keys, latency hint, metadata — and its launch config so it can be
1496
+ * resumed later, then mark it `hibernating`. Mechanically this is `stopStrand` minus
1497
+ * the instance/config deletion. A tracked strand with no runtime left (a failed
1498
+ * rebuild already released it) is only marked; an untracked one is left alone.
1499
+ *
1500
+ * Ordered with {@link resumeStrand} (see {@link transitions}): it starts once the resume
1501
+ * or launch build before it has settled, so it releases a finished runtime, and the
1502
+ * status write is its last step, so a resume requested meanwhile writes after it. A call
1503
+ * made while another quiesce is the latest request joins it. A failed release leaves the
1504
+ * status as it was and rejects.
1505
+ */
1506
+ async quiesceStrand(strandId: string): Promise<void> {
1507
+ const previous = this.transitions.get(strandId);
1508
+ if (previous?.kind === 'quiesce') {
1509
+ log('quiesceStrand: strand %s — joining the quiesce already requested', strandId);
1510
+ return previous.operation;
1511
+ }
1512
+ const operation = this.runQuiesce(strandId, previous);
1513
+ this.holdTransition(strandId, { kind: 'quiesce', operation });
1514
+ return operation;
1515
+ }
1516
+
1517
+ /** Body of {@link quiesceStrand}. */
1518
+ private async runQuiesce(strandId: string, previous: RuntimeTransition | undefined): Promise<void> {
1519
+ await this.settleTransition(strandId, previous);
1520
+ await this.settleRuntimeBuilds(strandId);
1521
+ const instance = this.instances.get(strandId);
1522
+ if (!instance) {
1523
+ log('quiesceStrand: strand %s not found', strandId);
1524
+ return;
1525
+ }
1526
+ if (instance.libp2pNode || instance.database) {
1527
+ log('Quiescing strand instance: %s', strandId);
1528
+ await this.releaseRuntime(instance);
1529
+ log('Strand %s quiesced (resources released, instance retained)', strandId);
1530
+ } else {
1531
+ log('quiesceStrand: strand %s already quiesced', strandId);
1532
+ }
1533
+ instance.status = 'hibernating';
1534
+ }
1535
+
1536
+ /**
1537
+ * Whether the latest runtime transition requested for `strandId` is a quiesce that has
1538
+ * not finished. Its handles may still be attached and its status still live, but it is on
1539
+ * its way to `hibernating`, so a caller that needs it up must {@link resumeStrand} it — the
1540
+ * resume runs after the quiesce — rather than treat it as live.
1541
+ */
1542
+ isQuiescing(strandId: string): boolean {
1543
+ return this.transitions.get(strandId)?.kind === 'quiesce';
1544
+ }
1545
+
1546
+ /**
1547
+ * Resume a previously-quiesced strand: rebuild its libp2p node + StrandDatabase
1548
+ * from the retained launch config and re-attach them, transitioning it back to
1549
+ * `active`. `overrides` re-applies volatile inputs that may have changed since
1550
+ * launch (the cohort `bootstrapNodes` seed and the strand's `servingMachines`
1551
+ * count) and updates the retained config so a later resume reuses the latest
1552
+ * values. Returns the live instance unchanged if it is already running.
1553
+ *
1554
+ * Overlapping calls share one rebuild: a call made while a resume is the latest request
1555
+ * for the strand — a wake landing during a check-in — joins it and settles exactly as it
1556
+ * does, `'error'` status included. The joiner's own `overrides` are ignored; the first
1557
+ * resume's seed wins, and both callers resolved the cohort seed moments apart. A call made
1558
+ * while a quiesce is the latest request runs after that quiesce and rebuilds (see
1559
+ * {@link transitions}), and one made while `startStrand` is still building waits for that
1560
+ * build rather than starting a second.
1561
+ */
1562
+ async resumeStrand(strandId: string, overrides?: ResumeStrandOverrides): Promise<StrandInstance> {
1563
+ if (this.stopping) {
1564
+ throw new Error('StrandInstanceManager is stopping');
1565
+ }
1566
+ // No `await` between this read and `holdTransition`, or a second caller slips through
1567
+ // and builds.
1568
+ const previous = this.transitions.get(strandId);
1569
+ if (previous?.kind === 'resume') {
1570
+ log('resumeStrand: strand %s — joining the resume already in flight', strandId);
1571
+ return previous.operation;
1572
+ }
1573
+ const operation = this.runResume(strandId, previous, overrides);
1574
+ this.holdTransition(strandId, { kind: 'resume', operation });
1575
+ return operation;
1576
+ }
1577
+
1578
+ /** Record `transition` as the latest for `strandId` until it settles. */
1579
+ private holdTransition(strandId: string, transition: RuntimeTransition): void {
1580
+ this.transitions.set(strandId, transition);
1581
+ const release = (): void => {
1582
+ if (this.transitions.get(strandId) === transition) {
1583
+ this.transitions.delete(strandId);
1584
+ }
1585
+ };
1586
+ // The rejection itself reaches the caller through the operation returned to it.
1587
+ void transition.operation.then(release, release);
1588
+ }
1589
+
1590
+ /** Wait for the transition requested before this one. Never rejects: its failure belongs to its caller. */
1591
+ private async settleTransition(strandId: string, previous: RuntimeTransition | undefined): Promise<void> {
1592
+ if (!previous) {
1593
+ return;
1594
+ }
1595
+ await (previous.operation as Promise<unknown>).catch((error: unknown) => {
1596
+ log('Strand %s: the %s queued ahead failed (reported by its caller): %o', strandId, previous.kind, error);
1597
+ });
1598
+ }
1599
+
1600
+ /** Body of {@link resumeStrand}; at most one runs per strand at a time. */
1601
+ private async runResume(
1602
+ strandId: string,
1603
+ previous: RuntimeTransition | undefined,
1604
+ overrides?: ResumeStrandOverrides
1605
+ ): Promise<StrandInstance> {
1606
+ // Before any "already live" test: a quiesce ahead still has the handles attached, and
1607
+ // mid-build (a launch still building) the libp2p node is attached while the database is
1608
+ // not. A failed launch has already dropped the instance, and the check below reports it
1609
+ // untracked.
1610
+ await this.settleTransition(strandId, previous);
1611
+ await this.settleRuntimeBuilds(strandId);
1612
+ const instance = this.instances.get(strandId);
1613
+ if (!instance) {
1614
+ throw new Error(`Cannot resume strand ${strandId}: not tracked`);
1615
+ }
1616
+ const launchConfig = this.launchConfigs.get(strandId);
1617
+ if (!launchConfig) {
1618
+ throw new Error(`Cannot resume strand ${strandId}: no retained launch config`);
1619
+ }
1620
+ if (instance.libp2pNode || instance.database) {
1621
+ log('resumeStrand: strand %s already live', strandId);
1622
+ return instance;
1623
+ }
1624
+
1625
+ log('Resuming strand instance: %s', strandId);
1626
+ const tTotal = performance.now();
1627
+
1628
+ // Re-apply volatile inputs and persist them so a subsequent resume reuses them.
1629
+ // Each `??` matters: a resume that passes no override must keep the retained value,
1630
+ // and a resume that passes one must leave it retained for the next resume — otherwise
1631
+ // a later no-override wake silently reverts to whatever launch time saw.
1632
+ const resumeConfig: StartStrandConfig = {
1633
+ ...launchConfig,
1634
+ bootstrapNodes: overrides?.bootstrapNodes ?? launchConfig.bootstrapNodes,
1635
+ // NOTE: `??` retains, so an override can raise or lower the count but cannot CLEAR it
1636
+ // back to "this node no longer knows" — the direction that would declare nothing. Moot
1637
+ // while nothing feeds `servingMachines` at all; if a source lands
1638
+ // (`backlog/feat-strand-yardstick-from-serving-machines`) that can legitimately lose the
1639
+ // count — a strand whose member rows became unreadable — this merge must gain an explicit
1640
+ // clear rather than silently declaring a stale number over a serving set it can no longer
1641
+ // see. Same applies to `bootstrapNodes` above, where a stale seed is harmless.
1642
+ servingMachines: overrides?.servingMachines ?? launchConfig.servingMachines
1643
+ };
1644
+ this.launchConfigs.set(strandId, resumeConfig);
1645
+
1646
+ instance.status = 'starting';
1647
+ try {
1648
+ await this.trackRuntimeBuild(strandId, this.buildStrandRuntime(instance, resumeConfig));
1649
+ timing('[resumeStrand:%s] total: %dms', strandId, Math.round(performance.now() - tTotal));
1650
+ log('Strand %s resumed successfully', strandId);
1651
+ return instance;
1652
+ } catch (error) {
1653
+ instance.status = 'error';
1654
+ instance.error = error instanceof Error ? error.message : String(error);
1655
+ log('Failed to resume strand %s: %s', strandId, instance.error);
1656
+ throw error;
1657
+ }
1658
+ }
1659
+
1660
+ /**
1661
+ * Honor a founder request against an ALREADY-TRACKED strand — the seam that
1662
+ * closes the "whoever launches first decides whether the bootstrap runs" gap:
1663
+ * an instance first launched as a joiner (an app's own attach, or a watcher
1664
+ * poll winning the launch race) used to swallow a later founder request
1665
+ * silently, leaving the strand active with no `Strand.Header`.
1666
+ *
1667
+ * Flips the RETAINED launch config's `founder` to true, so every later
1668
+ * quiesce → resume rebuild founds as well (the bootstrap is insert-if-absent —
1669
+ * {@link StrandDatabase.ensureFounderBootstrap} — so re-running it per rebuild
1670
+ * writes nothing twice), and runs the bootstrap against the live database now.
1671
+ *
1672
+ * @returns how the request resolved:
1673
+ * - `'already-founder'` — the retained config already founds; nothing to do.
1674
+ * - `'bootstrapped'` — config flipped and the live database ran the bootstrap.
1675
+ * - `'needs-resume'` — config flipped, but the instance is quiesced (no live
1676
+ * database) or being quiesced (its database is closing), so the bootstrap could
1677
+ * not run here: the CALLER must wake the
1678
+ * strand (`CadreNode.wakeStrand`, which owns the hibernation bookkeeping this
1679
+ * manager does not) so the rebuild — which now founds — runs it.
1680
+ * @param resolvePartyKey - Asked for the party's own membership key when (and only
1681
+ * when) a CLOSED strand's retained config carries none — the instance was launched
1682
+ * as a joiner before its `StrandPartyKey` row existed or replicated. The resolved
1683
+ * key is retained alongside the founder flip so the bootstrap (now, or on the
1684
+ * caller's wake for `'needs-resume'`) can seat the founding Member/Manager.
1685
+ * @throws when the strand is not tracked — this seam exists only for the
1686
+ * tracked-instance launch path; an untracked id is a caller bug.
1687
+ * @throws whatever the live bootstrap throws (e.g. `PreSplitStrandIdentityError`),
1688
+ * after {@link withdrawFounderRequest} — so a retry re-attempts the founding rather
1689
+ * than resolving `'already-founder'` over an instance that never founded. A caller
1690
+ * whose `'needs-resume'` wake fails owes the same withdrawal.
1691
+ */
1692
+ async foundExistingStrand(
1693
+ strandId: string,
1694
+ resolvePartyKey?: () => Promise<string | undefined>
1695
+ ): Promise<'already-founder' | 'bootstrapped' | 'needs-resume'> {
1696
+ const instance = this.instances.get(strandId);
1697
+ const config = this.launchConfigs.get(strandId);
1698
+ if (!instance || !config) {
1699
+ throw new Error(`Cannot found strand ${strandId}: not tracked`);
1700
+ }
1701
+ if (config.founder === true) {
1702
+ return 'already-founder';
1703
+ }
1704
+ const partyMemberPrivateKey =
1705
+ config.partyMemberPrivateKey
1706
+ ?? (config.strandRow.Type === 'c' ? await resolvePartyKey?.() : undefined);
1707
+ // A fresh object rather than mutating in place: startStrand retains the CALLER'S
1708
+ // config object, which is not ours to rewrite.
1709
+ this.launchConfigs.set(strandId, { ...config, founder: true, partyMemberPrivateKey });
1710
+ if (this.isQuiescing(strandId) || (!instance.database && !this.firstSyncGates.has(strandId))) {
1711
+ return 'needs-resume';
1712
+ }
1713
+ try {
1714
+ await this.ensureFounderBootstrap(strandId);
1715
+ } catch (error) {
1716
+ this.withdrawFounderRequest(strandId);
1717
+ throw error;
1718
+ }
1719
+ return 'bootstrapped';
1720
+ }
1721
+
1722
+ /**
1723
+ * Give a tracked storage replica ({@link StartStrandConfig.sAppConfig} absent) the app's
1724
+ * schema in place — the seam for an app on this machine claiming a strand this node was
1725
+ * already hosting. No runtime rebuild: the libp2p node, its peer id and connections, the
1726
+ * store and its warm cache all stay, and the new `App` tables read the blocks the replica
1727
+ * already holds. Callers attach BEFORE {@link foundExistingStrand}: the founder bootstrap
1728
+ * writes the sApp into `Strand.Header` and refuses a database that has none.
1729
+ *
1730
+ * A runtime build in flight (the replica's launch, or a hibernation wake) is waited out
1731
+ * first, so the attach acts on the database that build produced. Then, in order: the
1732
+ * schema signature is checked before anything changes; the retained launch config takes
1733
+ * the sApp, so every later rebuild applies it through `composeStrand`; the live database —
1734
+ * published, or still held by the first-sync gate — gets the schema; and only then does
1735
+ * the instance record `sAppInfo` and the sApp's latency hint. An instance with no live
1736
+ * database gets the config alone: a quiesced one applies the schema at its next resume, a
1737
+ * launch waiting for a seed peer at its next database retry.
1738
+ *
1739
+ * @returns `'already-attached'` when the instance already runs an sApp — a DIFFERENT one
1740
+ * is logged and left as it is, as a second claim of a claimed strand always has been —
1741
+ * else `'attached'`.
1742
+ * @throws when the strand is not tracked (a caller bug, or a launch that failed while
1743
+ * this waited on it); when the schema signature is refused, having changed nothing; and
1744
+ * whatever the live apply throws (e.g. a quiesce closed the database mid-apply) — the
1745
+ * retained config then still carries the sApp and `sAppInfo` stays unset, so the next
1746
+ * claim retries the apply.
1747
+ *
1748
+ * NOTE: two claims of one replica racing each other both pass the `sAppInfo` check and
1749
+ * apply concurrently; the loser of the declarative diff can reject, and its `addStrand`
1750
+ * retry then resolves `'already-attached'`. Needs an app calling `addStrand` twice at once
1751
+ * (or beside a watcher retry); if it is ever seen, chain attaches per strand id.
1752
+ */
1753
+ async attachSApp(
1754
+ strandId: string,
1755
+ sAppConfig: SAppConfig,
1756
+ options: { requireSignedSchemas?: boolean } = {}
1757
+ ): Promise<'attached' | 'already-attached'> {
1758
+ await this.settleRuntimeBuilds(strandId);
1759
+ const instance = this.instances.get(strandId);
1760
+ const config = this.launchConfigs.get(strandId);
1761
+ if (!instance || !config) {
1762
+ throw new Error(`Cannot attach an sApp to strand ${strandId}: not tracked`);
1763
+ }
1764
+ if (instance.sAppInfo) {
1765
+ if (instance.sAppInfo.id !== sAppConfig.id) {
1766
+ log('attachSApp: strand %s already runs sApp %s — the claim for sApp %s is ignored',
1767
+ strandId, instance.sAppInfo.id, sAppConfig.id);
1768
+ }
1769
+ return 'already-attached';
1770
+ }
1771
+ const sAppInfo = verifiedSAppInfo(strandId, sAppConfig, options.requireSignedSchemas);
1772
+ // A fresh object rather than mutating in place: startStrand retains the CALLER'S
1773
+ // config object, which is not ours to rewrite.
1774
+ this.launchConfigs.set(strandId, { ...config, sAppConfig });
1775
+ const database = instance.database ?? this.firstSyncGates.get(strandId)?.database;
1776
+ if (database) {
1777
+ await database.attachAppSchema(sAppConfig);
1778
+ } else {
1779
+ log('attachSApp: strand %s has no live database — its next build applies the sApp schema', strandId);
1780
+ }
1781
+ instance.sAppInfo = sAppInfo;
1782
+ if (sAppConfig.latencyHint) {
1783
+ // HibernationManager reads the hint whenever it arms a timer, so the app's hint governs
1784
+ // from the next one: a timer already armed runs once at the old duration, and a replica
1785
+ // launched under a realtime default was never tracked, so it stays up until relaunched.
1786
+ instance.latencyHint = sAppConfig.latencyHint;
1787
+ }
1788
+ log('Strand %s upgraded from storage replica to %s', strandId, describeSApp(sAppConfig));
1789
+ return 'attached';
1790
+ }
1791
+
1792
+ /**
1793
+ * Whether `strandId` is launched but still waiting for its first sync — a joiner whose
1794
+ * runtime is up while its database is withheld (status `'syncing'`, or `'idle'` after
1795
+ * the hibernation manager's idle timer fired on it), including one whose database build
1796
+ * waits for a seed peer to answer ({@link deferUnreachableJoin}). `false` for a writable,
1797
+ * quiesced, or untracked strand. The predicate {@link whenWritable}'s callers gate on.
1798
+ */
1799
+ isAwaitingFirstSync(strandId: string): boolean {
1800
+ const instance = this.instances.get(strandId);
1801
+ return instance !== undefined && isAwaitingFirstSync(instance);
1802
+ }
1803
+
1804
+ /**
1805
+ * Resolve once the strand's database is published to the app — immediately for a
1806
+ * writable strand — or reject with {@link StrandAwaitingFirstSyncError} after
1807
+ * `timeoutMs` (default: the retained launch config's `firstSync.timeoutMs`, else
1808
+ * {@link DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS}). The rejection is RETRYABLE: nothing is
1809
+ * torn down, the gate keeps probing, and a later call waits afresh. A quiesced
1810
+ * (hibernating) strand is not woken here — the wait spans a resume, so a caller that
1811
+ * wants one wakes it (`CadreNode.wakeStrand`) and waits. Rejects immediately for an
1812
+ * untracked strand, and whenever the strand is stopped while a wait is pending.
1813
+ */
1814
+ whenWritable(strandId: string, options?: { timeoutMs?: number }): Promise<StrandInstance> {
1815
+ const instance = this.instances.get(strandId);
1816
+ if (!instance) {
1817
+ return Promise.reject(new Error(`Cannot wait for strand ${strandId} to become writable: not tracked`));
1818
+ }
1819
+ if (instance.database) {
1820
+ return Promise.resolve(instance);
1821
+ }
1822
+ const timeoutMs = options?.timeoutMs
1823
+ ?? this.launchConfigs.get(strandId)?.firstSync?.timeoutMs
1824
+ ?? DEFAULT_STRAND_FIRST_SYNC_TIMEOUT_MS;
1825
+ const startedAt = Date.now();
1826
+ return new Promise<StrandInstance>((resolve, reject) => {
1827
+ const waiters = this.writableWaiters.get(strandId) ?? new Set<WritableWaiter>();
1828
+ this.writableWaiters.set(strandId, waiters);
1829
+ const settle = (): void => {
1830
+ clearTimeout(timer);
1831
+ waiters.delete(waiter);
1832
+ if (waiters.size === 0) {
1833
+ this.writableWaiters.delete(strandId);
1834
+ }
1835
+ };
1836
+ const waiter: WritableWaiter = {
1837
+ resolve: () => { settle(); resolve(instance); },
1838
+ reject: (error) => { settle(); reject(error); }
1839
+ };
1840
+ const timer = setTimeout(
1841
+ () => waiter.reject(new StrandAwaitingFirstSyncError(strandId, Date.now() - startedAt)),
1842
+ timeoutMs);
1843
+ (timer as { unref?: () => void }).unref?.();
1844
+ waiters.add(waiter);
1845
+ });
1846
+ }
1847
+
1848
+ /**
1849
+ * The tracked instance once no runtime build of it is in flight, or `undefined` when none
1850
+ * is tracked by then — never launched, or the launch waited on failed and dropped its
1851
+ * record. For a caller about to hand a tracked instance to an app: until its build settles
1852
+ * the instance is `'starting'` with no database, and a failed launch leaves no instance.
1853
+ * Never rejects; a failed build is reported by the call that started it.
1854
+ */
1855
+ async whenRuntimeBuilt(strandId: string): Promise<StrandInstance | undefined> {
1856
+ await this.settleRuntimeBuilds(strandId);
1857
+ return this.instances.get(strandId);
1858
+ }
1859
+
1860
+ /**
1861
+ * Hand a launch's database to the app: set `instance.database`, retire the gate that
1862
+ * held it, release every {@link whenWritable} waiter, and — when the launch had already
1863
+ * been reported gated — flip it `'active'` and announce it through the retained config's
1864
+ * `onWritable`. "Reported gated" is any status but `'starting'`: `'syncing'`, or the
1865
+ * `'idle'` the hibernation manager's idle timer flips a long-gated joiner to (see
1866
+ * {@link isAwaitingFirstSync}) — the Header arriving after that flip must announce too,
1867
+ * or an app hanging on `strand:writable` never learns the strand opened. A publish that
1868
+ * lands while the instance is still `'starting'` (the Header arrived during the rest of
1869
+ * bring-up) announces nothing: `startStrand` / `resumeStrand` are about to report the
1870
+ * strand `'active'`, and `strand:writable` is defined as the follow-up to a gated
1871
+ * launch, never a duplicate of `strand:started`.
1872
+ *
1873
+ * It is also the one seam where a WITHHELD database becomes available, so it kicks the
1874
+ * membership reconciler: on a gated launch that loop's own immediate pass ran while
1875
+ * `instance.database` was still unset, found no database, and would otherwise not try
1876
+ * again until its retry timer fired. A launch that was never gated publishes here BEFORE
1877
+ * the reconciler is constructed, so there is nothing registered to kick and the loop's own
1878
+ * immediate pass already sees the database — which is why the kick needs no `wasGated`
1879
+ * test of its own.
1880
+ */
1881
+ private publishDatabase(instance: StrandInstance, database: StrandDatabase): void {
1882
+ const strandId = instance.strandId;
1883
+ const gate = this.firstSyncGates.get(strandId);
1884
+ if (gate) {
1885
+ gate.open();
1886
+ this.firstSyncGates.delete(strandId);
1887
+ }
1888
+ instance.database = database;
1889
+ const wasGated = instance.status !== 'starting';
1890
+ if (wasGated) {
1891
+ // A Header delivered by a peer is strand activity; a publish during bring-up is not
1892
+ // (see the build's end in `buildStrandRuntime`).
1893
+ instance.lastActivity = new Date();
1894
+ instance.status = 'active';
1895
+ log('Strand %s is now writable: Strand.Header held', strandId);
1896
+ }
1897
+ const waiters = this.writableWaiters.get(strandId);
1898
+ if (waiters) {
1899
+ this.writableWaiters.delete(strandId);
1900
+ waiters.forEach((waiter) => waiter.resolve());
1901
+ }
1902
+ if (wasGated) {
1903
+ this.launchConfigs.get(strandId)?.onWritable?.(strandId);
1904
+ }
1905
+ // Not awaited: publishing must stay synchronous, and the pass chains on the loop's own
1906
+ // tail, so it cannot overlap a pass already in flight.
1907
+ void this.membershipReconcilers.get(strandId)?.reconcile();
1908
+ }
1909
+
1910
+ /** Reject every {@link whenWritable} waiter for a strand that is going away. */
1911
+ private rejectWritableWaiters(strandId: string, reason: string): void {
1912
+ const waiters = this.writableWaiters.get(strandId);
1913
+ if (!waiters) {
1914
+ return;
1915
+ }
1916
+ this.writableWaiters.delete(strandId);
1917
+ waiters.forEach((waiter) => waiter.reject(new Error(`Strand ${strandId} ${reason} before becoming writable`)));
1918
+ }
1919
+
1920
+ /**
1921
+ * Undo {@link foundExistingStrand}'s founder flip after the founding it promised
1922
+ * failed, so the retained config again says what this instance actually runs as (a
1923
+ * joiner) and the next founder request re-attempts the bootstrap. The resolved party
1924
+ * key stays retained — it is this party's identity for the strand either way. No-op
1925
+ * when the strand is untracked or its config does not found.
1926
+ */
1927
+ withdrawFounderRequest(strandId: string): void {
1928
+ const config = this.launchConfigs.get(strandId);
1929
+ if (config?.founder === true) {
1930
+ this.launchConfigs.set(strandId, { ...config, founder: false });
1931
+ }
1932
+ }
1933
+
1934
+ /**
1935
+ * Run the (idempotent) founder bootstrap against a tracked strand's LIVE
1936
+ * database, independently of what the retained launch config says.
1937
+ *
1938
+ * Separate from {@link foundExistingStrand} because a caller that resolved
1939
+ * `'needs-resume'` and woke the strand must not assume the wake's own rebuild
1940
+ * founded it: `HibernationManager` COALESCES wakes, so a wake already in flight
1941
+ * when the config flipped had already read the PRE-flip config and rebuilt as a
1942
+ * joiner. Re-running the bootstrap costs one insert-if-absent probe per table
1943
+ * and is the only thing that makes "founding resolves once the Header is
1944
+ * written" true on that path.
1945
+ *
1946
+ * A strand still `'syncing'` (its database withheld behind the first-sync gate) is
1947
+ * founded through the gate: the bootstrap writes the Header this machine was waiting
1948
+ * to receive, so a successful run publishes the database and the strand goes
1949
+ * `'active'` — the one legitimate way a joiner launch becomes writable without a peer.
1950
+ *
1951
+ * @throws when the strand is not tracked, or is still quiesced (no live
1952
+ * database) — both mean the bootstrap did NOT run, which a founder request
1953
+ * must never swallow.
1954
+ */
1955
+ async ensureFounderBootstrap(strandId: string): Promise<void> {
1956
+ const instance = this.instances.get(strandId);
1957
+ if (!instance) {
1958
+ throw new Error(`Cannot run the founder bootstrap for strand ${strandId}: not tracked`);
1959
+ }
1960
+ const gate = this.firstSyncGates.get(strandId);
1961
+ const database = instance.database ?? gate?.database;
1962
+ if (!database) {
1963
+ throw new Error(
1964
+ `Cannot run the founder bootstrap for strand ${strandId}: it has no live database to ` +
1965
+ 'write to — it is quiesced (resume it first), or its database build is waiting for a ' +
1966
+ 'seed peer to answer.'
1967
+ );
1968
+ }
1969
+ // Forward the RETAINED config's party key: a foundExistingStrand that flipped a
1970
+ // joiner launch to founder may have resolved a key the live database's captured
1971
+ // config (built at the original launch) never saw.
1972
+ await database.ensureFounderBootstrap(this.launchConfigs.get(strandId)?.partyMemberPrivateKey);
1973
+ if (!instance.database) {
1974
+ this.publishDatabase(instance, database);
1975
+ }
1976
+ }
1977
+
1978
+ /**
1979
+ * Stop a strand instance
1980
+ */
1981
+ async stopStrand(strandId: string): Promise<void> {
1982
+ const instance = this.instances.get(strandId);
1983
+ if (!instance) {
1984
+ log('Strand %s not found', strandId);
1985
+ return;
1986
+ }
1987
+
1988
+ log('Stopping strand instance: %s', strandId);
1989
+ instance.status = 'stopping';
1990
+ this.rejectWritableWaiters(strandId, 'was stopped');
1991
+
1992
+ try {
1993
+ await this.releaseRuntime(instance);
1994
+ instance.status = 'stopped';
1995
+ this.instances.delete(strandId);
1996
+ this.launchConfigs.delete(strandId);
1997
+ // Storage is released only here — NOT in releaseRuntime, which a quiesce shares.
1998
+ await this.disposeStrandStorage(strandId);
1999
+ log('Strand %s stopped successfully', strandId);
2000
+ } catch (error) {
2001
+ instance.status = 'error';
2002
+ instance.error = error instanceof Error ? error.message : String(error);
2003
+ log('Error stopping strand %s: %s', strandId, instance.error);
2004
+ throw error;
2005
+ }
2006
+ }
2007
+
2008
+ /**
2009
+ * Stop all strand instances
2010
+ */
2011
+ async stopAll(): Promise<void> {
2012
+ this.stopping = true;
2013
+ log('Stopping all strand instances (%d)', this.instances.size);
2014
+
2015
+ const stopPromises = Array.from(this.instances.keys()).map(id =>
2016
+ this.stopStrand(id).catch(err => {
2017
+ log('Error stopping strand %s during shutdown: %s', id, err);
2018
+ })
2019
+ );
2020
+
2021
+ await Promise.all(stopPromises);
2022
+ this.stopping = false;
2023
+ log('All strand instances stopped');
2024
+ }
2025
+ }
2026
+