@serfab/cadre-core 1.23.0 → 1.24.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 (313) hide show
  1. package/README.md +216 -294
  2. package/dist/arachnode-stub.d.ts +12 -4
  3. package/dist/arachnode-stub.js +15 -8
  4. package/dist/arachnode-stub.js.map +1 -1
  5. package/dist/cadre-invite-protocol.js +5 -4
  6. package/dist/cadre-invite-protocol.js.map +1 -1
  7. package/dist/cadre-node.d.ts +145 -44
  8. package/dist/cadre-node.js +239 -79
  9. package/dist/cadre-node.js.map +1 -1
  10. package/dist/control-authorization.d.ts +14 -2
  11. package/dist/control-authorization.js +8 -3
  12. package/dist/control-authorization.js.map +1 -1
  13. package/dist/control-cohort.d.ts +27 -13
  14. package/dist/control-cohort.js +21 -14
  15. package/dist/control-cohort.js.map +1 -1
  16. package/dist/control-database.d.ts +18 -16
  17. package/dist/control-database.js +57 -22
  18. package/dist/control-database.js.map +1 -1
  19. package/dist/control-protocol-guard.d.ts +1 -1
  20. package/dist/control-protocol-guard.js +7 -3
  21. package/dist/control-protocol-guard.js.map +1 -1
  22. package/dist/control-read-retry.d.ts +49 -11
  23. package/dist/control-read-retry.js +56 -15
  24. package/dist/control-read-retry.js.map +1 -1
  25. package/dist/control-retry.d.ts +32 -3
  26. package/dist/control-retry.js +35 -4
  27. package/dist/control-retry.js.map +1 -1
  28. package/dist/control-schema-version.d.ts +5 -5
  29. package/dist/control-schema-version.js +5 -5
  30. package/dist/control-schema-version.js.map +1 -1
  31. package/dist/control-schema.d.ts +5 -5
  32. package/dist/control-schema.js +1032 -1011
  33. package/dist/control-schema.js.map +1 -1
  34. package/dist/control-write-retry.d.ts +54 -65
  35. package/dist/control-write-retry.js +134 -158
  36. package/dist/control-write-retry.js.map +1 -1
  37. package/dist/delegate-admission.d.ts +1 -1
  38. package/dist/delegate-admission.js +1 -1
  39. package/dist/edge-node/config.d.ts +4 -3
  40. package/dist/edge-node/config.js +11 -9
  41. package/dist/edge-node/config.js.map +1 -1
  42. package/dist/edge-node/dissolve.d.ts +4 -4
  43. package/dist/edge-node/dissolve.js +4 -4
  44. package/dist/edge-node/edge-join.d.ts +1 -1
  45. package/dist/edge-node/edge-join.js +1 -1
  46. package/dist/edge-node/edge-node.js +2 -2
  47. package/dist/edge-node/edge-node.js.map +1 -1
  48. package/dist/edge-node/index.d.ts +1 -0
  49. package/dist/edge-node/index.js +1 -0
  50. package/dist/edge-node/index.js.map +1 -1
  51. package/dist/edge-node/join-credential.d.ts +1 -1
  52. package/dist/edge-node/join-credential.js +1 -1
  53. package/dist/edge-node/lazy-raw-storage.js +12 -0
  54. package/dist/edge-node/lazy-raw-storage.js.map +1 -1
  55. package/dist/edge-node/listen-addrs.d.ts +21 -0
  56. package/dist/edge-node/listen-addrs.js +25 -0
  57. package/dist/edge-node/listen-addrs.js.map +1 -0
  58. package/dist/edge-node/owner-grant.d.ts +1 -1
  59. package/dist/edge-node/owner-grant.js +1 -1
  60. package/dist/edge-node/platform.d.ts +5 -4
  61. package/dist/edge-node/platform.js.map +1 -1
  62. package/dist/edge-node/strand-move.d.ts +1 -1
  63. package/dist/edge-node/strand-move.js +1 -1
  64. package/dist/edge-node/strands.js +27 -11
  65. package/dist/edge-node/strands.js.map +1 -1
  66. package/dist/index.d.ts +7 -5
  67. package/dist/index.js +18 -7
  68. package/dist/index.js.map +1 -1
  69. package/dist/invitation-bootstrap.d.ts +28 -5
  70. package/dist/invitation-bootstrap.js +41 -8
  71. package/dist/invitation-bootstrap.js.map +1 -1
  72. package/dist/link-budget.d.ts +53 -4
  73. package/dist/link-budget.js +58 -5
  74. package/dist/link-budget.js.map +1 -1
  75. package/dist/machine-removal.d.ts +2 -2
  76. package/dist/machine-removal.js +4 -3
  77. package/dist/machine-removal.js.map +1 -1
  78. package/dist/membership-connection-gater.d.ts +2 -2
  79. package/dist/membership-connection-gater.js +2 -2
  80. package/dist/membership-view.d.ts +2 -2
  81. package/dist/membership-view.js +2 -2
  82. package/dist/node-claim-payload.d.ts +15 -7
  83. package/dist/node-claim-payload.js +25 -9
  84. package/dist/node-claim-payload.js.map +1 -1
  85. package/dist/node-class.d.ts +36 -0
  86. package/dist/node-class.js +26 -0
  87. package/dist/node-class.js.map +1 -0
  88. package/dist/node-default-transports.d.ts +50 -3
  89. package/dist/node-default-transports.js +48 -3
  90. package/dist/node-default-transports.js.map +1 -1
  91. package/dist/node-roles.d.ts +118 -0
  92. package/dist/node-roles.js +142 -0
  93. package/dist/node-roles.js.map +1 -0
  94. package/dist/node-transports.d.ts +6 -2
  95. package/dist/node-transports.js +39 -7
  96. package/dist/node-transports.js.map +1 -1
  97. package/dist/owner-anchor-sync.js +1 -1
  98. package/dist/owner-key-export.js +1 -1
  99. package/dist/owner-key-flows.d.ts +1 -1
  100. package/dist/owner-key-store.js +1 -1
  101. package/dist/owner-signer.js +1 -1
  102. package/dist/peer-authorization.d.ts +3 -1
  103. package/dist/peer-authorization.js +3 -1
  104. package/dist/peer-authorization.js.map +1 -1
  105. package/dist/peer-dial.d.ts +74 -10
  106. package/dist/peer-dial.js +89 -17
  107. package/dist/peer-dial.js.map +1 -1
  108. package/dist/peer-join-backfill.js +4 -4
  109. package/dist/peer-join-backfill.js.map +1 -1
  110. package/dist/peer-record.d.ts +34 -9
  111. package/dist/peer-record.js +66 -13
  112. package/dist/peer-record.js.map +1 -1
  113. package/dist/pending-join-runner.d.ts +1 -1
  114. package/dist/pending-join-runner.js +1 -1
  115. package/dist/provider/client.d.ts +6 -5
  116. package/dist/provider/client.js +3 -3
  117. package/dist/provider/client.js.map +1 -1
  118. package/dist/provider/descriptor.d.ts +1 -1
  119. package/dist/provider/descriptor.js +1 -1
  120. package/dist/provider/oauth.d.ts +1 -1
  121. package/dist/provider/oauth.js +1 -1
  122. package/dist/provider/rent-node.d.ts +4 -3
  123. package/dist/provider/rent-node.js +3 -3
  124. package/dist/provider/rent-node.js.map +1 -1
  125. package/dist/relay-addrs.d.ts +62 -7
  126. package/dist/relay-addrs.js +74 -11
  127. package/dist/relay-addrs.js.map +1 -1
  128. package/dist/relay-reservation.d.ts +1 -1
  129. package/dist/relay-reservation.js +1 -1
  130. package/dist/relay-server.d.ts +6 -5
  131. package/dist/relay-server.js +5 -5
  132. package/dist/relay-server.js.map +1 -1
  133. package/dist/schema-verification.d.ts +13 -10
  134. package/dist/schema-verification.js +32 -24
  135. package/dist/schema-verification.js.map +1 -1
  136. package/dist/sealed-party-key.js +1 -1
  137. package/dist/seed-bootstrap.d.ts +4 -3
  138. package/dist/seed-bootstrap.js +6 -7
  139. package/dist/seed-bootstrap.js.map +1 -1
  140. package/dist/strand-addr-protocol.d.ts +8 -6
  141. package/dist/strand-addr-protocol.js +12 -10
  142. package/dist/strand-addr-protocol.js.map +1 -1
  143. package/dist/strand-app-schema-report.d.ts +16 -2
  144. package/dist/strand-app-schema-report.js +15 -0
  145. package/dist/strand-app-schema-report.js.map +1 -1
  146. package/dist/strand-cohort.d.ts +1 -4
  147. package/dist/strand-cohort.js.map +1 -1
  148. package/dist/strand-commit-durability.d.ts +1 -1
  149. package/dist/strand-database.d.ts +13 -6
  150. package/dist/strand-database.js +17 -9
  151. package/dist/strand-database.js.map +1 -1
  152. package/dist/strand-first-sync-gate.d.ts +3 -2
  153. package/dist/strand-first-sync-gate.js +3 -2
  154. package/dist/strand-first-sync-gate.js.map +1 -1
  155. package/dist/strand-formation-deadlines.d.ts +2 -2
  156. package/dist/strand-formation-deadlines.js +2 -2
  157. package/dist/strand-formation-protocol.d.ts +1 -1
  158. package/dist/strand-formation-protocol.js +51 -16
  159. package/dist/strand-formation-protocol.js.map +1 -1
  160. package/dist/strand-instance-manager.d.ts +67 -33
  161. package/dist/strand-instance-manager.js +164 -55
  162. package/dist/strand-instance-manager.js.map +1 -1
  163. package/dist/strand-membership-reconciler.d.ts +8 -3
  164. package/dist/strand-membership-reconciler.js +8 -3
  165. package/dist/strand-membership-reconciler.js.map +1 -1
  166. package/dist/strand-membership-writer.d.ts +2 -2
  167. package/dist/strand-membership-writer.js +41 -39
  168. package/dist/strand-membership-writer.js.map +1 -1
  169. package/dist/strand-move.js +1 -1
  170. package/dist/strand-network-config.d.ts +15 -5
  171. package/dist/strand-network-config.js +7 -6
  172. package/dist/strand-network-config.js.map +1 -1
  173. package/dist/strand-party-key-rotation.d.ts +7 -3
  174. package/dist/strand-party-key-rotation.js +7 -3
  175. package/dist/strand-party-key-rotation.js.map +1 -1
  176. package/dist/strand-party-machines.d.ts +19 -8
  177. package/dist/strand-party-machines.js +26 -11
  178. package/dist/strand-party-machines.js.map +1 -1
  179. package/dist/strand-party-peers.d.ts +36 -14
  180. package/dist/strand-party-peers.js +24 -15
  181. package/dist/strand-party-peers.js.map +1 -1
  182. package/dist/strand-peer-redial.d.ts +1 -1
  183. package/dist/strand-peer-redial.js +1 -1
  184. package/dist/strand-reactivity.d.ts +20 -17
  185. package/dist/strand-reactivity.js +31 -18
  186. package/dist/strand-reactivity.js.map +1 -1
  187. package/dist/strand-revocation-enforcer.d.ts +3 -3
  188. package/dist/strand-revocation-enforcer.js +3 -3
  189. package/dist/strand-wake-protocol.d.ts +19 -7
  190. package/dist/strand-wake-protocol.js +22 -10
  191. package/dist/strand-wake-protocol.js.map +1 -1
  192. package/dist/strand-watcher.d.ts +1 -1
  193. package/dist/strand-watcher.js +1 -1
  194. package/dist/table-change-watch.js +1 -1
  195. package/dist/types.d.ts +116 -55
  196. package/dist/types.js.map +1 -1
  197. package/dist/webrtc-upgrade.d.ts +254 -0
  198. package/dist/webrtc-upgrade.js +355 -0
  199. package/dist/webrtc-upgrade.js.map +1 -0
  200. package/package.json +9 -9
  201. package/src/announce-addrs.ts +93 -93
  202. package/src/arachnode-stub.ts +18 -10
  203. package/src/bootstrap-peer-store-file.ts +44 -44
  204. package/src/bootstrap-peer-store.ts +214 -214
  205. package/src/cadre-invite-protocol.ts +741 -740
  206. package/src/cadre-node.ts +12462 -12280
  207. package/src/claim-proof.ts +147 -147
  208. package/src/control-authorization.ts +290 -276
  209. package/src/control-cohort.ts +223 -204
  210. package/src/control-database.ts +72 -28
  211. package/src/control-formation-recorder.ts +359 -359
  212. package/src/control-protocol-guard.ts +370 -366
  213. package/src/control-read-retry.ts +222 -180
  214. package/src/control-retry.ts +36 -4
  215. package/src/control-schema-version.ts +301 -301
  216. package/src/control-schema.ts +1108 -1087
  217. package/src/control-write-retry.ts +639 -669
  218. package/src/delegate-admission.ts +351 -351
  219. package/src/describe-thrown.ts +60 -60
  220. package/src/ed25519-key.ts +185 -185
  221. package/src/edge-node/config.ts +13 -10
  222. package/src/edge-node/dissolve.ts +252 -252
  223. package/src/edge-node/edge-join.ts +320 -320
  224. package/src/edge-node/edge-node.ts +1095 -1095
  225. package/src/edge-node/index.ts +60 -59
  226. package/src/edge-node/join-credential.ts +16 -16
  227. package/src/edge-node/lazy-raw-storage.ts +194 -178
  228. package/src/edge-node/listen-addrs.ts +26 -0
  229. package/src/edge-node/node-local.ts +84 -84
  230. package/src/edge-node/options.ts +195 -195
  231. package/src/edge-node/owner-grant.ts +63 -63
  232. package/src/edge-node/platform.ts +5 -4
  233. package/src/edge-node/strand-move.ts +266 -266
  234. package/src/edge-node/strands.ts +27 -12
  235. package/src/enrolled-machine-store-file.ts +43 -43
  236. package/src/enrolled-machine-store.ts +280 -280
  237. package/src/fetch-impl.ts +23 -23
  238. package/src/file-durable-slot.ts +64 -64
  239. package/src/file-safe-name.ts +32 -32
  240. package/src/formation-approval.ts +604 -604
  241. package/src/formation-token.ts +63 -63
  242. package/src/fs-atomic.ts +92 -92
  243. package/src/index.ts +987 -957
  244. package/src/invitation-bootstrap.ts +152 -118
  245. package/src/joined-strand-store.ts +553 -553
  246. package/src/key-store-file.ts +142 -142
  247. package/src/link-budget.ts +61 -5
  248. package/src/machine-removal.ts +211 -210
  249. package/src/member-redemption.ts +643 -643
  250. package/src/membership-connection-gater.ts +650 -650
  251. package/src/membership-view.ts +147 -147
  252. package/src/node-claim-payload.ts +34 -12
  253. package/src/node-class.ts +47 -0
  254. package/src/node-default-transports.ts +65 -3
  255. package/src/node-roles.ts +220 -0
  256. package/src/node-transports.ts +86 -49
  257. package/src/owner-anchor-sync.ts +172 -172
  258. package/src/owner-grant-protocol.ts +547 -547
  259. package/src/owner-key-export.ts +348 -348
  260. package/src/owner-key-flows.ts +109 -109
  261. package/src/owner-key-store.ts +1 -1
  262. package/src/owner-keys.ts +179 -179
  263. package/src/owner-signer.ts +92 -92
  264. package/src/peer-addr-book.ts +252 -252
  265. package/src/peer-authorization.ts +584 -582
  266. package/src/peer-dial.ts +698 -605
  267. package/src/peer-join-backfill.ts +961 -961
  268. package/src/peer-record.ts +71 -16
  269. package/src/pending-join-runner.ts +798 -798
  270. package/src/primary-lan-address.ts +47 -47
  271. package/src/provider/client.ts +327 -326
  272. package/src/provider/descriptor.ts +129 -129
  273. package/src/provider/index.ts +59 -59
  274. package/src/provider/oauth.ts +285 -285
  275. package/src/provider/rent-node.ts +276 -275
  276. package/src/relay-addrs.ts +90 -12
  277. package/src/relay-reservation.ts +1 -1
  278. package/src/relay-server.ts +99 -98
  279. package/src/schema-verification.ts +38 -23
  280. package/src/sealed-party-key.ts +190 -190
  281. package/src/seed-bootstrap.ts +8 -11
  282. package/src/seed-trust-policy.ts +353 -353
  283. package/src/self-address-update.ts +19 -19
  284. package/src/strand-addr-protocol.ts +17 -14
  285. package/src/strand-app-schema-report.ts +147 -122
  286. package/src/strand-cohort.ts +1 -5
  287. package/src/strand-commit-durability.ts +165 -165
  288. package/src/strand-database.ts +522 -510
  289. package/src/strand-first-sync-gate.ts +3 -2
  290. package/src/strand-formation-deadlines.ts +227 -227
  291. package/src/strand-formation-manager.ts +731 -731
  292. package/src/strand-formation-protocol.ts +1174 -1138
  293. package/src/strand-fret-addrs.ts +179 -179
  294. package/src/strand-instance-manager.ts +188 -63
  295. package/src/strand-membership-reconciler.ts +1315 -1310
  296. package/src/strand-membership-writer.ts +2152 -2150
  297. package/src/strand-move.ts +1 -1
  298. package/src/strand-network-config.ts +16 -6
  299. package/src/strand-offline.ts +178 -178
  300. package/src/strand-party-key-rotation.ts +440 -436
  301. package/src/strand-party-machines.ts +308 -293
  302. package/src/strand-party-peers.ts +151 -129
  303. package/src/strand-peer-redial.ts +1 -1
  304. package/src/strand-reactivity.ts +36 -19
  305. package/src/strand-revocation-enforcer.ts +758 -758
  306. package/src/strand-wake-protocol.ts +406 -394
  307. package/src/strand-watcher.ts +1 -1
  308. package/src/table-change-watch.ts +285 -285
  309. package/src/timed-step.ts +28 -28
  310. package/src/timeout-scheduler.ts +29 -29
  311. package/src/trusted-owner-store.ts +242 -242
  312. package/src/types.ts +3182 -3121
  313. package/src/webrtc-upgrade.ts +439 -0
@@ -1,1310 +1,1315 @@
1
- /**
2
- * Strand membership reconciliation: the per-instance background loop that finishes a
3
- * party's join at strand bring-up and keeps the party's machine bindings whole. Every
4
- * machine of a party that runs a closed strand ends up with (1) the party's `Strand.Member`
5
- * row seated — redeeming the formation-staged invitation if one is pending — (2) its own
6
- * durable machine→party binding (`Strand.MemberPeer`) written, which is what revocation
7
- * enforcement and future admission control key on, and (3) every live sibling machine's
8
- * binding written under the party's current key, with a removed machine's binding cleared —
9
- * see "Binding the party's other machines" below.
10
- *
11
- * ## Contract
12
- *
13
- * - **Never blocks or fails bring-up.** Armed by `StrandInstanceManager.buildStrandRuntime`
14
- * right after the strand database initializes (launch AND hibernation resume — the one
15
- * seam where a transport peer id and a live `Database` both exist), and every pass is
16
- * fully contained: a joiner at that instant has typically not synced the founder's rows
17
- * and may lack write quorum, so failure means "retry next tick", never a throw.
18
- * - **Kicked the moment its database appears.** A joining machine's first pass runs while
19
- * the first-sync write gate still withholds `instance.database`, so it finds no database
20
- * and returns at once. `StrandInstanceManager.publishDatabase` calls `reconcile()` as it
21
- * hands the database to the app, which is what makes the join finish about a second after
22
- * the strand becomes writable rather than on the next timer.
23
- * - **Retries fast while the join is unfinished, slowly while it is only waiting.** A pass
24
- * that leaves the join unfinished re-arms on a ladder starting at
25
- * {@link INITIAL_JOIN_RETRY_INTERVAL_MS} and doubling, capped at the configured poll
26
- * interval (default {@link DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS}). A pass
27
- * that finds no member row AND no staged invitation is not an unfinished join but a wait
28
- * for someone to admit this party — nothing this machine can do faster — so it re-arms on
29
- * the flat poll interval and resets the ladder. The loop stops on the done state.
30
- * - **Done state**: the party's member row is visible locally, this machine's own binding
31
- * is in place, every live sibling with a `StrandPeer` row is bound under the party's key
32
- * (a pass that wrote a binding is not done; the next pass has to find nothing left), AND no
33
- * invitation is still staged — the loop stops. A LATER revocation is the enforcer's
34
- * business, not this loop's; a resume rebuilds the reconciler and re-verifies from scratch
35
- * (every write is idempotent, so re-running is free), and a fresh invitation staged on a
36
- * done loop, or a change to the party's machines, re-arms it in place ({@link rearm}).
37
- *
38
- * ## One pass
39
- *
40
- * 1. **Self-revocation check.** If the enforcer flags this node's own party as revoked and
41
- * no invitation is staged, stop rather than fight — re-admission arrives (if ever) via
42
- * a fresh formation, which re-arms the loop. With an invitation staged the loop reports
43
- * the dead end (below) and carries on: the redemption is attempted like any other, and a
44
- * manager's re-admission lets a later pass finish it.
45
- * 2. **Ensure membership.** Read first whether the party is moving to another key in this
46
- * strand ({@link PartyStrandPeerSource.pendingKey}, one control read per pass); while it
47
- * is, the step runs under that key instead — see "Redeeming under the pending key". Otherwise:
48
- * member row visible → done with this step; if a staged invitation is still unspent, BURN it
49
- * ({@link burnInvite} — the `ConsumedInvite` row alone) so the bearer credential cannot be
50
- * spent by anyone else. A burn refused by the cohort keeps the invitation staged for the next
51
- * pass (it is the same write gate a redemption faces, and the local member row may be stale —
52
- * see "Re-arming"); a dead invitation is dropped. Member row absent + staged invitation →
53
- * {@link consumeInvite} under the party's own key, retried across passes until the `Invite`
54
- * row has replicated here and the write commits. Absent with no invitation (founder rows not
55
- * yet synced, or a machine whose party never joined) → keep waiting, escalating to one
56
- * visible warning after {@link IDLE_PASSES_BEFORE_ESCALATION} passes, never throwing.
57
- * 3. **Ensure the binding.** {@link registerMemberPeer} (insert-if-absent, restart-safe)
58
- * with this node's own strand transport peer id — only after step 2 sees the member
59
- * row locally (its deferred `MemberExists` reads the live local table). A binding
60
- * written while a burn keeps being refused leaves the loop live to settle the
61
- * invitation later.
62
- * 4. **Bind live siblings.** Every strand peer id the control database records for a live
63
- * machine of this party ({@link PartyStrandPeerSource.read}) that has no binding under the
64
- * party's key gets one, written here with the party key. See "Binding the party's other
65
- * machines".
66
- * 5. **Clear removed machines.** A binding under the party's key for a machine removed from
67
- * the cadre is cleared through the self branch of {@link removeMemberPeer} — unless the
68
- * pending-key read at step 2 found a party key rotation pending for the strand, or failed.
69
- * 6. **Re-attempt this machine's own `StrandPeer` row** ({@link PartyStrandPeerSource.publishOwn}),
70
- * the control-side statement step 4 on the siblings reads: a background write at bring-up
71
- * that is deferred while alone or refused until this machine's own `CadrePeer` row arrives.
72
- *
73
- * ## Binding the party's other machines
74
- *
75
- * A `MemberPeer` binding is signed by the member key, which every machine of the party holds,
76
- * so any machine can bind any peer id under the party's key: the party vouching for its own
77
- * machine. Which peer ids are the party's machines comes from `CadreControl.StrandPeer`, each
78
- * machine's own signed statement of its peer id in the strand, joined to the party's live
79
- * machines and its `CadrePeer` tombstones (`strand-party-peers.ts`). The point is a party
80
- * member key that changes (a machine removal rotates it: `strand-party-key-rotation.ts`):
81
- * a sibling offline through the change returns to find itself bound under the new key by the
82
- * machines that were there, and a machine bound by a sibling that had not yet heard of its
83
- * removal is cleared once the tombstone arrives.
84
- *
85
- * Step 5 is gated on no rotation pending (the pending-key state step 2 read). While one is, the
86
- * removed machine's binding under the current key is exactly the orphan the rotation is about to
87
- * leave behind, and clearing it would hand the removed machine a clean slate the deny-list gate
88
- * admits. A failed pending read clears nothing for the same reason. After the swap the pending row is gone, and the step
89
- * clears a binding a lagging sibling wrote under the new key. The gate holds only because a
90
- * removal writes the machine's tombstone and the pending row in ONE transaction
91
- * (`ControlDatabase.removeMachine`): a tombstone that reaches this node without
92
- * its pending row reads as "no rotation", and this step clears the binding the rotation
93
- * meant to orphan, which leaves the removed machine admitted as a stranger rather than denied.
94
- *
95
- * The step reads the party's bindings once per pass (`listMemberPeers`) and compares in
96
- * JavaScript, the scan-not-seek idiom. Two machines binding one sibling at once collide on the
97
- * `MemberPeer` primary key; the loser's write is refused and its next pass finds the row. A
98
- * sibling's row that cannot be read keeps the loop live on the flat poll interval, and a write
99
- * that fails is retried on the ladder.
100
- *
101
- * ## Redeeming under the pending key
102
- *
103
- * A machine removal replaces the party's member key K in each closed strand with a fresh key K'
104
- * (`strand-party-key-rotation.ts`), and in a strand the party does not manage K cannot seat K'
105
- * itself: the strand's host has to re-invite the party, or its manager admit K' by hand
106
- * (docs/strands.md → Replacing the party's key). The host's fresh invitation is staged here like
107
- * any other and lands in step 2, which is why one rule governs that step: **while a
108
- * `PendingStrandPartyKey` row exists for the strand, this loop never writes a `Strand.Member`
109
- * row under K.** The removed machine holds K, and a seat written under K is a seat it keeps.
110
- * Three cases, decided by what {@link PartyStrandPeerSource.pendingKey} answers at the head of
111
- * the pass (a rejected read counts as pending with the key unreadable):
112
- *
113
- * - **No rotation pending**: the ordinary step 2 above.
114
- * - **Pending, the key not readable here** (the row is sealed to other machines: this machine
115
- * was admitted after the removal, or runs on an ephemeral identity; or the read failed): the
116
- * step neither consumes nor burns. A staged invitation stays staged, with one debug line, for
117
- * a machine that can read the key to redeem; the pass is idle, and it does not count toward
118
- * the probable blocked re-join report below — it left the invitation staged on purpose.
119
- * - **Pending, the key opened**: with K' already a member (admitted by hand, or seated by a
120
- * sibling's redemption), a staged invitation is burned against K' and the rotation driver is
121
- * kicked ({@link StrandMembershipReconcilerDeps.onPendingKeySeated}); with K' not yet a member
122
- * and an invitation staged, it is redeemed under K' and the driver kicked; a refused
123
- * redemption is classified as under K, except that a sealed strand is not terminal here (the
124
- * party may still be a member under K) and only drops the dead invitation. With nothing staged
125
- * the pass is idle: the driver has reported `needs-another-party`, and nothing happens until
126
- * the host acts.
127
- *
128
- * Step 2 still answers whether K's member row is visible, which the binding steps that follow
129
- * are under: K is the party's current key until the control swap, and a binding written under K
130
- * after K has left (step 5 of the rotation, before the swap replicates here) is refused by
131
- * `MemberPeer.MemberExists` and polled, until the swap re-keys this loop. The loop does not
132
- * latch done while a rotation is pending, whatever else is in place, so a by-hand admission or a
133
- * sibling's redemption is noticed on the next pass and the driver kicked; a pass that wrote
134
- * nothing is idle, so the cadence is the flat poll interval. The pending state ends with the
135
- * swap: `StrandInstanceManager.rekeyParty` rebuilds this loop under K', whose next pass finds no
136
- * pending row, clears the removed machine's stale binding (step 5) and latches done as before.
137
- * Whoever redeems the host's invitation seats a key of its choosing, so the invitation must reach
138
- * the party's owner and not the removed machine, as with every invitation today.
139
- *
140
- * ## Stops, and re-arming
141
- *
142
- * Two kinds of stop. A RE-ARMABLE stop is one a fresh invitation, or a change to the
143
- * party's machines, should reopen:
144
- *
145
- * - **Done** (above).
146
- * - **Self-revoked with nothing staged** (step 1 above). A machine whose only binding is
147
- * orphaned — its sibling rotated the key before this machine's `StrandPeer` row reached it —
148
- * is denied by every other machine, so its own loop cannot write and stops here. The heal is
149
- * a sibling binding it (step 4 there); its enforcer then drops its peer id from the deny set
150
- * and reports `onSelfRestored`, which re-arms this loop.
151
- *
152
- * A PERMANENT stop is one a fresh invitation changes nothing about — {@link rearm} is a
153
- * no-op after it:
154
- *
155
- * - **Sealed strand**: `consumeInvite` rejected by `ConsumedInvite.NotSealed` — nobody
156
- * can ever be admitted, so retrying forever is noise. Terminal-with-log.
157
- * - **Undecodable party key**: nothing can be signed; loud log, stop.
158
- * - **The public {@link stop}**: `StrandInstanceManager.releaseRuntime` and
159
- * `clearOwnMemberPeerBinding` both call it and mean it — the latter stops the loop and
160
- * awaits {@link settle} precisely so no pass can re-register the binding it is about to
161
- * delete, and a re-arm that restarted the loop would undo that.
162
- *
163
- * `CadreNode.adoptFormationMembershipInvite` stages every fresh invitation and notifies
164
- * the instance manager, which calls {@link rearm}: a done loop reopens and runs one pass
165
- * at once; a running loop is merely kicked. This is what lets a party that was REMOVED
166
- * from the strand, and then handed a new invitation, actually attempt it — the loop
167
- * finished during its first join, long before the removal. `CadreNode` also re-arms every
168
- * strand's loop when `CadreControl.StrandPeer`, `CadrePeer` or `Revocation` changes
169
- * (`StrandInstanceManager.notifyPartyPeersChanged`), so a sibling's row arriving binds it
170
- * within the watch's coalescing window rather than at the next resume.
171
- *
172
- * On a removed party the local replica is usually stale: the cohort cut this machine off
173
- * at about the moment the removal was written, so `isStrandMember` still answers true and
174
- * a re-armed pass lands in the already-member arm. That is why the burn arm keeps a
175
- * refused invitation staged and why the done state requires nothing staged — otherwise
176
- * the fresh credential would be dropped on the first refused burn and the loop would latch
177
- * done again, with the only trace a debug line.
178
- *
179
- * A DEAD invitation that is not terminal for the loop — expired, cancelled, or already
180
- * consumed by someone else (`ConsumedInvite`'s primary key) — is dropped with a log and
181
- * the loop keeps idling: a fresh formation stages a new invitation, and a manager-side
182
- * admission (`addMemberByManager`) seats the member row without one.
183
- *
184
- * ## Reporting a blocked re-join
185
- *
186
- * Redeeming (or burning) writes into the strand, and the machines that would carry that
187
- * write are exactly the ones the remaining members refuse once this party is removed. So
188
- * the attempt is expected to fail, and the failure is REPORTED rather than left to the
189
- * ladder: one `console.warn` plus the {@link StrandMembershipReconcilerDeps.onRejoinBlocked}
190
- * callback (`CadreNode`'s `strand:rejoin-blocked` event), at most once per re-arm cycle.
191
- * Two triggers:
192
- *
193
- * - **Confirmed** — a pass finds this party self-revoked AND an invitation staged. The node
194
- * knows it was removed and is holding a credential it cannot spend.
195
- * - **Probable** — {@link UNFINISHED_PASSES_BEFORE_ESCALATION} consecutive attempted passes
196
- * left the invitation staged. The case that matters most in the field: a removed party
197
- * that never learned it was removed (the removal did not replicate here before the cut).
198
- * It is a suspicion, not a verdict — the invitation's `Invite` row may simply not have
199
- * replicated here yet — and the warning names both causes.
200
- *
201
- * The remedy in either case is a remaining manager admitting this party's member key
202
- * directly (`addMemberByManager`): that lifts the refusal, replication resumes, and the
203
- * still-running loop sees the member row, burns the leftover credential and finishes by
204
- * itself.
205
- *
206
- * ## Sharing the database with the app
207
- *
208
- * The strand `Database` this loop writes to is the one the app holds. Every write here
209
- * passes `joinOpenTransaction: false`, so it runs as a transaction of its own and never
210
- * joins one the app has open: the writer refuses with `StrandTransactionBusyError`, having
211
- * written nothing, and the pass retries on the ladder. A busy refusal is never read as a
212
- * dead invitation, and a busy burn leaves the invitation staged for the next pass.
213
- *
214
- * A write refused because the strand's offline queue holds transactions
215
- * (`StrandOfflineQueueBusyError`, docs/strands.md → "Offline mode") is a busy refusal too: it
216
- * wrote nothing, and the ladder retries it until the queue drains. A membership commit queued
217
- * behind an app commit anyway (the race that refusal leaves open) can fail with Optimystic's
218
- * `OfflineCommitTimeoutError`, which is an unclassified failure here: a redemption keeps the
219
- * invitation and retries, and a binding is retried by the next pass. Each pass reads the state
220
- * before it writes (the member row, then the binding, which is insert-if-absent), so a write that
221
- * landed after all (`sent: true`) is found by that pass rather than written twice.
222
- *
223
- * ## Half-committed join
224
- *
225
- * On a networked strand optimystic commits `Member` and `ConsumedInvite` as separate
226
- * collections and can report that only some of them were saved (`CoordinatorPartialCommitError`,
227
- * or the plugin's legacy `PartialCommitError`). When `ConsumedInvite` is saved and `Member` is
228
- * not, the invitation is spent and the schema seats a `Member` through an invitation only in the
229
- * same transaction as a fresh consumption, so this loop can never seat the party from it. Such a
230
- * failure is recognised by TYPE before any message text is read (its message names the
231
- * `ConsumedInvite` collection, which a text match once mistook for a dead invitation), reported
232
- * with ONE `console.warn`, and the invitation is dropped. The loop keeps running like it does
233
- * after a dead invitation: a manager admission, or a `Member` row that did land, is picked up by
234
- * the next pass, which then writes the binding. Whether sereus should repair such a join itself
235
- * is `blocked/strand-half-committed-join-recovery`.
236
- */
237
-
238
- import debug from 'debug';
239
- import type { Database } from '@quereus/quereus';
240
- import { CoordinatorPartialCommitError } from '@optimystic/db-core';
241
- import { PartialCommitError } from '@optimystic/quereus-plugin-optimystic';
242
- import { causeChain } from './control-retry.js';
243
- import type { Ed25519KeyPair } from './ed25519-key.js';
244
- import type { StrandMembershipInvite } from './types.js';
245
- import { strandMemberKeyPair } from './strand-member-key.js';
246
- import {
247
- StrandOfflineQueueBusyError,
248
- StrandTransactionBusyError,
249
- burnInvite,
250
- consumeInvite,
251
- isStrandMember,
252
- listMemberPeers,
253
- registerMemberPeer,
254
- removeMemberPeer,
255
- type StrandWriteOptions,
256
- } from './strand-membership-writer.js';
257
- import type { OpenedPendingPartyKey } from './strand-party-key-rotation.js';
258
- import type { PartyStrandPeerSource, PartyStrandPeers, PendingPartyKeyState } from './strand-party-peers.js';
259
- import { defaultTimeoutScheduler, type TimeoutScheduler } from './timeout-scheduler.js';
260
- import { describeThrown } from './describe-thrown.js';
261
-
262
- const log = debug('sereus:cadre:strand-membership-reconciler');
263
-
264
- /**
265
- * Default poll interval, ms: the loop's idle cadence while nobody has admitted this party, and
266
- * the cap of its unfinished-join retry ladder. The loop stops once joined, so this matters only
267
- * while a machine is joining.
268
- */
269
- export const DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS = 30_000;
270
-
271
- /**
272
- * Idle passes (no member row, no staged invitation) before ONE `console.warn`
273
- * escalation — at the default 30 s cadence, about five minutes of waiting. The loop
274
- * keeps retrying quietly after it; the warning exists so a joiner stuck waiting on
275
- * founder-row replication is visible without the debug namespace enabled.
276
- */
277
- export const IDLE_PASSES_BEFORE_ESCALATION = 10;
278
-
279
- /**
280
- * Consecutive passes that ran against a live database and ended with the staged
281
- * invitation still unsettled — whatever refused it — before the loop reports a probable
282
- * blocked re-join (see "Reporting a blocked re-join" in the module doc). The same order
283
- * as {@link IDLE_PASSES_BEFORE_ESCALATION}: about three minutes at the default cadence
284
- * (the ladder's five doubling rungs, then five passes at the 30 s cap). Counted by outcome
285
- * rather than by classified failure because a cut-off machine can fail before any write is
286
- * classified: its membership READ may already throw.
287
- */
288
- export const UNFINISHED_PASSES_BEFORE_ESCALATION = 10;
289
-
290
- /**
291
- * First retry delay, ms, for a pass that left the join UNFINISHED — a `consumeInvite`
292
- * whose `Strand.Invite` row has not replicated to this machine yet, a cohort briefly
293
- * unwritable, a database not yet published. Doubles per such pass up to the configured
294
- * poll interval. Sized for what it retries: invite-row replication resolves in about a
295
- * second over a direct connection and a few over a relay. The poll interval is NOT sized
296
- * for that — it is sized for the idle case (waiting to be admitted at all), which is why
297
- * this ladder exists instead of a shorter interval.
298
- */
299
- export const INITIAL_JOIN_RETRY_INTERVAL_MS = 1_000;
300
-
301
- /** Every write this loop makes runs in a transaction of its own — see "Sharing the database with the app". */
302
- const OWN_TRANSACTION: StrandWriteOptions = { joinOpenTransaction: false };
303
-
304
- /**
305
- * The `consumeInvite` rejection that means the strand is SEALED — `ConsumedInvite.NotSealed`
306
- * fired, which Quereus renders `CHECK constraint failed: NotSealed (<its expression>)`.
307
- * Terminal for a non-member: nobody can ever be admitted again.
308
- */
309
- const SEALED_REJECTION = /CHECK constraint failed: NotSealed\b/;
310
-
311
- /**
312
- * `consumeInvite` rejections that mean the INVITATION is dead but the loop should keep
313
- * waiting for membership to arrive another way: expired (`CHECK constraint failed: NotExpired`),
314
- * cancelled (`CHECK constraint failed: NotCancelled`), or already consumed by someone else
315
- * (`UNIQUE constraint failed: ConsumedInvite.InviteKey`, the primary key).
316
- *
317
- * Anchored to the engine's full constraint-failure texts, not the bare names: other failures
318
- * embed those names — a half-committed join's message names the `default/strand/ConsumedInvite`
319
- * collection, which the bare `ConsumedInvite` this used to match read as a dead invitation. The
320
- * texts are pinned against the real engine in `strand-membership-reconciler.spec.ts`, so a
321
- * rewording in Quereus fails a spec instead of silently turning a dead invitation into an
322
- * endless retry.
323
- */
324
- const DEAD_INVITE_REJECTION =
325
- /CHECK constraint failed: (?:NotExpired|NotCancelled)\b|UNIQUE constraint failed: ConsumedInvite\.InviteKey\b/;
326
-
327
- /**
328
- * A redemption only part of which was saved: the collections (or, on the plugin's legacy
329
- * path, tree labels) that were saved and those that were not, as the error reports them.
330
- */
331
- export interface HalfCommittedJoin {
332
- kind: 'half-committed';
333
- saved: readonly string[];
334
- unsaved: readonly string[];
335
- }
336
-
337
- /** Where {@link classifyConsumeFailure} routes a failed `consumeInvite` or `burnInvite`. */
338
- export type ConsumeFailure =
339
- | HalfCommittedJoin
340
- /**
341
- * The app had a transaction open, or the strand's offline queue held transactions, so nothing
342
- * was tried — keep the invitation, retry.
343
- */
344
- | { kind: 'busy' }
345
- /** The strand is sealed — terminal for a non-member; a member's leftover invitation is merely dead. */
346
- | { kind: 'sealed' }
347
- /** Expired, cancelled, or consumed by someone else — drop the invitation, keep waiting. */
348
- | { kind: 'dead-invite' }
349
- /**
350
- * Anything else — the `Invite` row has not replicated here yet, or the cohort refused the
351
- * write (a removed party's machines are denied) — keep the invitation, retry.
352
- */
353
- | { kind: 'retry' };
354
-
355
- /**
356
- * Route a `consumeInvite` or `burnInvite` rejection. Both write the `Strand.ConsumedInvite`
357
- * row under the same `NotExpired` / `NotCancelled` / `NotSealed` / primary-key constraints
358
- * (a burn writes that row alone), so one classifier serves both. Typed checks run before any
359
- * text check: a busy refusal (another transaction was open, so nothing ran) and a
360
- * half-committed join are recognised by their error's type anywhere in the `cause` chain.
361
- * The busy refusal carries Quereus's own refusal as its cause, and a half-committed join's
362
- * message embeds collection names and the underlying failure's text, either of which a text
363
- * matcher can misread. The sealed and dead-invitation checks then read the top-level message.
364
- *
365
- * A second loaded copy of `@optimystic/db-core` (or of the plugin) would fail `instanceof`; the
366
- * half-commit then falls through the anchored texts to `retry`, and once the saved `ConsumedInvite`
367
- * row is visible here a later attempt fails on its primary key and drops the invitation quietly —
368
- * the old silent outcome, a few passes later, never a wrong write.
369
- */
370
- export function classifyConsumeFailure(error: unknown): ConsumeFailure {
371
- if (isTransactionBusy(error)) return { kind: 'busy' };
372
- const halfCommitted = halfCommittedJoin(error);
373
- if (halfCommitted) return halfCommitted;
374
- const message = describeThrown(error);
375
- if (SEALED_REJECTION.test(message)) return { kind: 'sealed' };
376
- if (DEAD_INVITE_REJECTION.test(message)) return { kind: 'dead-invite' };
377
- return { kind: 'retry' };
378
- }
379
-
380
- /**
381
- * The first partial-commit error in the `cause` chain, as the lists it reports.
382
- *
383
- * NOTE: `PartialCommitError` is imported from the plugin's root entry while strands register the
384
- * plugin through its `/plugin` entry (`quereus-plugin-sereus`'s `compose-strand.ts`); the two are
385
- * one class only because the plugin's build emits both entries over one shared chunk — the same
386
- * dependency, and the same remedy if upstream ever bundles them apart, as the NOTE on
387
- * `reportsPossiblyStoredWrite` in `control-write-retry.ts`.
388
- */
389
- function halfCommittedJoin(error: unknown): HalfCommittedJoin | undefined {
390
- for (const link of causeChain(error)) {
391
- if (link instanceof CoordinatorPartialCommitError) {
392
- return { kind: 'half-committed', saved: link.committedCollections, unsaved: link.failedCollections };
393
- }
394
- if (link instanceof PartialCommitError) {
395
- return { kind: 'half-committed', saved: link.persisted, unsaved: link.unpersisted };
396
- }
397
- }
398
- return undefined;
399
- }
400
-
401
- /**
402
- * Whether a writer refused having written nothing, because another transaction was open or the
403
- * offline queue held transactions (see "Sharing the database with the app").
404
- */
405
- function isTransactionBusy(error: unknown): boolean {
406
- return causeChain(error).some((link) =>
407
- link instanceof StrandTransactionBusyError || link instanceof StrandOfflineQueueBusyError);
408
- }
409
-
410
- /**
411
- * The staged formation invitation seam — `CadreNode`'s in-memory
412
- * `pendingMembershipInvites` cache, scoped to one strand. Read lazily per pass (a
413
- * re-formation may replace the entry between passes) and cleared by the reconciler once
414
- * the invitation is spent, burned, or dead — the invalidation half the cache itself
415
- * deliberately does not own.
416
- */
417
- export interface PendingMembershipInviteSource {
418
- /** The staged invitation, or `undefined` when none is pending for this strand. */
419
- get(): StrandMembershipInvite | undefined;
420
- /**
421
- * Drop `settled` (spent, burned, or dead) — only if it is still the staged one. A
422
- * re-formation can replace the entry between a pass's {@link get} and this call, and
423
- * the fresh invitation it staged must survive the older one being settled.
424
- */
425
- clear(settled: StrandMembershipInvite): void;
426
- }
427
-
428
- export interface StrandMembershipReconcilerDeps {
429
- /** Log tag naming which strand this reconciler serves (the strand id). */
430
- label: string;
431
- /**
432
- * THIS party's own strand membership private key (base64 protobuf, the control-layer
433
- * `StrandPartyKey` row's content). Decoded LAZILY on the first pass, so a malformed
434
- * key stops the loop with a log instead of failing bring-up.
435
- */
436
- partyMemberPrivateKey: string;
437
- /**
438
- * The live strand `Database`, read per pass, never captured — the instance's handle
439
- * is dropped on quiesce, and `undefined` means "no live database this instant" (the
440
- * pass simply waits for the next tick).
441
- */
442
- getDatabase: () => Database | undefined;
443
- /**
444
- * This node's own strand transport peer id — the `MemberPeer.PeerId` to bind. Read
445
- * per pass for the same lifecycle reason as {@link getDatabase}.
446
- */
447
- getOwnPeerId: () => string | undefined;
448
- /** The staged invitation seam. Absent for flows with no invitation (e.g. tests). */
449
- pendingInvite?: PendingMembershipInviteSource;
450
- /**
451
- * The control-database seam for steps 2 and 4 to 6 of the pass (see "Binding the party's other
452
- * machines" and "Redeeming under the pending key" in the module doc): the party's pending key
453
- * in this strand as this machine can read it, the party's machines' strand peer ids, and this
454
- * machine's own `StrandPeer` row. Absent (tests, an embedder with no control database) means
455
- * no rotation is ever pending and the loop binds only this machine.
456
- */
457
- partyPeers?: PartyStrandPeerSource;
458
- /**
459
- * Called when a pass finds the party's PENDING key seated as a member of the strand (see
460
- * "Redeeming under the pending key"): it redeemed the staged invitation under that key, or found
461
- * it seated already. On every such pass until the control swap re-keys the loop. `CadreNode`
462
- * wires it to its party key rotation driver, which finishes the move on an owner machine.
463
- */
464
- onPendingKeySeated?: () => void;
465
- /**
466
- * Whether the revocation enforcer currently flags THIS node's own party as revoked.
467
- * When it does and nothing is staged, the loop stops rather than fight the enforcer;
468
- * with an invitation staged it reports the blocked re-join and keeps trying — see the
469
- * module doc. Absent (enforcement disarmed) means "not known revoked".
470
- */
471
- isSelfRevoked?: () => boolean;
472
- /**
473
- * Called when the loop reports a blocked re-join (see "Reporting a blocked re-join" in
474
- * the module doc) — at most once per re-arm cycle, after the `console.warn`. `CadreNode`
475
- * wires it to its `strand:rejoin-blocked` event.
476
- */
477
- onRejoinBlocked?: () => void;
478
- /**
479
- * Timer seam for the retry ladder; omit for real (unref'd) timeouts. Timeouts rather
480
- * than the enforcer's repeating interval because the delay changes per pass and the next
481
- * pass is armed only once the previous one settles, so a slow pass never stacks ticks
482
- * behind it — the same seam the first-sync gate's probe loop uses.
483
- */
484
- scheduler?: TimeoutScheduler;
485
- }
486
-
487
- /** Embedder-facing tuning, threaded by `StrandInstanceManager`. */
488
- export interface StrandMembershipReconciliationConfig {
489
- /**
490
- * Default true. False disarms the loop entirely — meant for test fixtures that
491
- * hand-drive the membership writers and assert exact row sets; a production
492
- * node that disarms it never seats a joiner's member row or binds its machines.
493
- */
494
- enabled?: boolean;
495
- /**
496
- * Idle cadence, ms — how often the loop re-checks while nobody has admitted this party
497
- * yet — and the CAP of the unfinished-join retry ladder. Default
498
- * {@link DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS}.
499
- */
500
- pollIntervalMs?: number;
501
- }
502
-
503
- /**
504
- * The per-strand membership reconciliation loop. Created in
505
- * `StrandInstanceManager.buildStrandRuntime` (closed strands with a party key only),
506
- * started right after the strand database initializes, stopped and dropped in
507
- * `releaseRuntime` — so quiesce → resume rebuilds it and re-runs the (idempotent) ladder
508
- * from scratch.
509
- */
510
- export class StrandMembershipReconciler {
511
- private readonly scheduler: TimeoutScheduler;
512
- private readonly pollIntervalMs: number;
513
- /** Tail of the pass chain — serializes passes (no two in flight). */
514
- private tail: Promise<void> = Promise.resolve();
515
- private timer: unknown;
516
- private started = false;
517
- private stoppedFlag = false;
518
- /**
519
- * Whether the last stop was one {@link rearm} may not undo — see "Stops, and re-arming"
520
- * in the module doc. Latched by the public {@link stop} and the permanent terminal
521
- * states, never cleared.
522
- */
523
- private permanentlyStopped = false;
524
- private doneFlag = false;
525
- /** Lazily decoded party keypair — see {@link StrandMembershipReconcilerDeps.partyMemberPrivateKey}. */
526
- private keyPair: Ed25519KeyPair | undefined;
527
- private idlePasses = 0;
528
- private idleEscalated = false;
529
- /** Consecutive attempted passes that left the invitation staged — see {@link UNFINISHED_PASSES_BEFORE_ESCALATION}. */
530
- private unfinishedPasses = 0;
531
- /** Whether the blocked re-join was already reported this re-arm cycle (one report, either trigger). */
532
- private rejoinBlockedReported = false;
533
- /**
534
- * Whether the pass in flight left the staged invitation alone ON PURPOSE (a rotation is pending
535
- * and this machine cannot read the key), which is not an attempt that failed and so does not
536
- * count toward the probable blocked re-join report. Reset at the head of every pass.
537
- */
538
- private inviteLeftStagedDeliberately = false;
539
- /** Whether this cycle has logged that the loop stays live for a pending rotation (one line per re-arm cycle). */
540
- private pendingRotationLogged = false;
541
- /**
542
- * Whether the pass that just ran is waiting on something no faster retry can shorten — no
543
- * member row and no staged invitation (a wait to be admitted, {@link noteIdlePass}), or the
544
- * party's machines unreadable ({@link waitForPoll}). Such a pass re-arms on the flat poll
545
- * interval; every other unfinished outcome climbs the ladder.
546
- *
547
- * NOTE: the ladder is therefore the DEFAULT for any outcome nobody classified — a new
548
- * early return added to {@link doPass} inherits the fast retry unless it calls
549
- * {@link noteIdlePass} or {@link waitForPoll}. Right for every outcome that exists today
550
- * (each is an unfinished join this machine can make progress on). If an early return is
551
- * ever added for a condition retrying cannot resolve, classify it so.
552
- */
553
- private lastPassIdle = false;
554
- /** Current rung of the unfinished-join retry ladder, ms; unset before the first retry. */
555
- private retryDelayMs: number | undefined;
556
-
557
- constructor(
558
- private readonly deps: StrandMembershipReconcilerDeps,
559
- config?: StrandMembershipReconciliationConfig
560
- ) {
561
- this.scheduler = deps.scheduler ?? defaultTimeoutScheduler;
562
- this.pollIntervalMs = config?.pollIntervalMs ?? DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS;
563
- }
564
-
565
- /**
566
- * True once member row + own binding were both confirmed with nothing staged and the
567
- * loop stopped. Cleared again by {@link rearm}.
568
- */
569
- get done(): boolean {
570
- return this.doneFlag;
571
- }
572
-
573
- /** True while the loop is stopped — done, terminal, or externally stopped. */
574
- get stopped(): boolean {
575
- return this.stoppedFlag;
576
- }
577
-
578
- /**
579
- * Kick an immediate pass (not awaited — bring-up never blocks on it). Every later pass
580
- * is armed only once the previous one settles — see the retry ladder in the module doc —
581
- * so there is no repeating interval to arm here.
582
- */
583
- start(): void {
584
- if (this.started || this.stoppedFlag) return;
585
- this.started = true;
586
- void this.reconcile();
587
- log('[%s] membership reconciler started (retry from %dms, idle poll %dms)',
588
- this.deps.label, Math.min(INITIAL_JOIN_RETRY_INTERVAL_MS, this.pollIntervalMs), this.pollIntervalMs);
589
- }
590
-
591
- /**
592
- * Resolve once no pass is in flight. {@link stop} only disarms the retry TIMER — a pass
593
- * already past its stopped check runs to completion, so a caller that must know the
594
- * loop can no longer write (`StrandInstanceManager.clearOwnMemberPeerBinding`, which
595
- * would otherwise have its removal undone by a racing `registerMemberPeer`) awaits
596
- * this after stopping. Never rejects: the pass chain contains every failure.
597
- */
598
- async settle(): Promise<void> {
599
- await this.tail;
600
- }
601
-
602
- /**
603
- * Disarm the retry timer, for good: a later {@link rearm} is refused. A pass already in
604
- * flight completes but writes idempotently — {@link settle} is what waits it out.
605
- */
606
- stop(): void {
607
- this.halt('stopped by the runtime', true);
608
- }
609
-
610
- /**
611
- * Something changed that a stopped loop should look at — `cause` names it for the log: a
612
- * fresh invitation was staged, the party's machines changed, or this machine is no longer
613
- * revoked. Reopen a loop that stopped on a re-armable state (done, or self-revoked with
614
- * nothing staged) and run one pass at once; merely kick a loop that is still running; do
615
- * nothing after a permanent stop. Never rejects, and serialized like {@link reconcile}: the
616
- * reopen happens when the queued pass STARTS, after any pass in flight has settled, so a
617
- * `done` that pass latches cannot swallow the re-arm — and a public {@link stop} that lands
618
- * first still wins, because the queued pass re-checks it.
619
- */
620
- rearm(cause = 'a fresh invitation'): Promise<void> {
621
- return this.enqueue(() => this.reopen(cause) ? this.doPass() : Promise.resolve());
622
- }
623
-
624
- /**
625
- * Run one pass now. Never rejects. Serialized: concurrent calls chain, so no two
626
- * passes overlap and each explicit call gets a pass that STARTS after the call. On a
627
- * started loop the pass re-arms the retry timer where it settles, so an explicit call —
628
- * `StrandInstanceManager.publishDatabase`'s kick when a joiner's database is finally
629
- * published — REPLACES the pending timer rather than running alongside it.
630
- */
631
- reconcile(): Promise<void> {
632
- return this.enqueue(() => this.doPass());
633
- }
634
-
635
- /** Chain `pass` after every pass already queued; the tail never rejects. */
636
- private enqueue(pass: () => Promise<void>): Promise<void> {
637
- // The catch is what keeps the chain alive. `doPass` contains its own failures, but its
638
- // `finally` calls into the injected scheduler, and a throw from there would leave `tail`
639
- // REJECTED — after which every later `reconcile()` short-circuits on it and the join
640
- // stalls for good, silently. Swallowing it here makes the "never rejects" contract
641
- // {@link reconcile}, {@link rearm}, {@link settle} and the `void`-ed call sites all rely
642
- // on structural rather than incidental.
643
- const run = this.tail.then(pass).catch((error) => {
644
- log('[%s] reconcile pass threw outside its own handler — the chain continues: %o',
645
- this.deps.label, error);
646
- });
647
- this.tail = run;
648
- return run;
649
- }
650
-
651
- /**
652
- * The re-arm itself, run at the head of the queued pass: `false` refuses the pass (a
653
- * permanent stop), a running loop is left as it is, and a re-armable stop is reopened
654
- * with the idle and unfinished counters, both escalation latches and the retry ladder
655
- * reset — a fresh invitation is a fresh cycle.
656
- */
657
- private reopen(cause: string): boolean {
658
- if (this.permanentlyStopped) {
659
- log('[%s] re-arm (%s) refused — the loop is stopped for good', this.deps.label, cause);
660
- return false;
661
- }
662
- if (!this.stoppedFlag) {
663
- // NOTE: a running loop keeps its counters and its once-per-cycle report latch, so a
664
- // party whose loop already reported and is then re-formed AGAIN gets no second report
665
- // for the replacement invitation. If that second report is ever wanted, key the latch
666
- // on the staged invitation's key rather than on the re-arm.
667
- log('[%s] %s on a running loop — kicking a pass', this.deps.label, cause);
668
- return true;
669
- }
670
- this.stoppedFlag = false;
671
- this.doneFlag = false;
672
- this.idlePasses = 0;
673
- this.idleEscalated = false;
674
- this.unfinishedPasses = 0;
675
- this.rejoinBlockedReported = false;
676
- this.pendingRotationLogged = false;
677
- this.retryDelayMs = undefined;
678
- log('[%s] membership reconciler re-armed by %s', this.deps.label, cause);
679
- return true;
680
- }
681
-
682
- /** One serialized pass; contains every failure (contract: never rejects). */
683
- private async doPass(): Promise<void> {
684
- if (this.stoppedFlag || this.doneFlag) return;
685
- this.lastPassIdle = false;
686
- try {
687
- if (this.deps.isSelfRevoked?.() === true && !this.stagedInviteBlockedBySelfRevocation()) {
688
- // NOTE: the enforcer's flag lags a re-admission by up to one of its polls. If the
689
- // pass that settled the last staged invitation then failed to write the binding, this
690
- // stop lands with the binding missing until the next resume rebuilds the loop. A
691
- // missing binding only mis-credits diversity today; if it ever gates admission, make
692
- // this stop also require the binding to be in place.
693
- this.finish('this party is revoked from the strand — re-admission arrives (if ever) via a fresh formation, '
694
- + 'or a sibling binds this machine under the party\'s current key', false);
695
- return;
696
- }
697
- const keyPair = this.resolveKeyPair();
698
- if (!keyPair) return; // undecodable key already stopped the loop
699
- const db = this.deps.getDatabase();
700
- if (!db) return; // no live database this instant (quiesce race) — next tick decides
701
- await this.attempt(db, keyPair);
702
- } catch (error) {
703
- log('[%s] reconcile pass failed — retrying next tick: %o', this.deps.label, error);
704
- } finally {
705
- this.scheduleNext();
706
- }
707
- }
708
-
709
- /**
710
- * Steps 2 to 6 against a live database, with the outcome counted toward the probable
711
- * blocked re-join report whether the attempt returned or threw.
712
- *
713
- * NOTE: steps 4 to 6 cost one `StrandPeer` read, one fresh membership read and one
714
- * `MemberPeer` scan per pass, per closed strand, and `CadreNode` re-arms every strand's loop
715
- * on each change to the party's machines, their records included. Fine at party scale; if a
716
- * party ever runs many strands on many machines, read `StrandPeer` once per control change
717
- * rather than per pass.
718
- */
719
- private async attempt(db: Database, keyPair: Ed25519KeyPair): Promise<void> {
720
- this.inviteLeftStagedDeliberately = false;
721
- try {
722
- const pending = await this.readPendingKeyState();
723
- if (!(await this.ensureMembership(db, keyPair, pending))) return;
724
- // NOTE: accepted tradeoff — the redemption (`Member` + `ConsumedInvite`) and the binding
725
- // below stay two SEPARATE commits on purpose. Merging them would save one commit: its
726
- // serial latency and, since Optimystic 1.19.0 pends and commits a transaction's collections
727
- // together, its `/cluster` requests (the two commits cost 6 on a two-member strand in
728
- // `message-cost-accounting` on 2026-10-25, 20 before). It would also let a torn commit
729
- // (Optimystic can report a multi-collection commit partly saved) or the cohort applying
730
- // the collections out of order show this machine's `MemberPeer` without its `Member`,
731
- // which the revocation enforcer reads as a removed member and hangs up on — fail closed,
732
- // undone only by a manager clearing the binding (module doc of
733
- // `strand-revocation-enforcer.ts`). And it would add a half-committed shape (`MemberPeer`
734
- // saved, the invitation still live) that {@link reportHalfCommittedJoin}'s dropping of the
735
- // invitation gets wrong. Revisit when Optimystic offers an all-or-nothing multi-collection
736
- // commit, or when the enforcer can tell a not-yet-seated binding from a removed member's.
737
- if (!(await this.ensureBinding(db, keyPair))) return;
738
- const siblingsSettled = await this.reconcileSiblings(db, keyPair, pending.pending);
739
- await this.publishOwnStrandPeer();
740
- this.latchDone(siblingsSettled, pending.pending);
741
- } finally {
742
- this.noteAttemptOutcome();
743
- }
744
- }
745
-
746
- /**
747
- * The party's pending key in this strand, read once per pass. No seam means no rotation is
748
- * ever pending; a rejected read is "pending, key unreadable", the posture under which nothing
749
- * is seated under the current key and no removed machine's binding is cleared (module doc).
750
- */
751
- private async readPendingKeyState(): Promise<PendingPartyKeyState> {
752
- const source = this.deps.partyPeers;
753
- if (!source) return { pending: false };
754
- try {
755
- return await source.pendingKey();
756
- } catch (error) {
757
- log('[%s] whether a party key rotation is pending could not be read — treated as pending with the key unreadable: %s',
758
- this.deps.label, describeThrown(error));
759
- return { pending: true, key: null };
760
- }
761
- }
762
-
763
- /**
764
- * Arm the next pass, now that this one has settled — so a slow pass never stacks ticks
765
- * behind it. Only a STARTED loop schedules: a caller driving {@link reconcile} by hand
766
- * (the unit tests, and the publish kick on a launch whose `start()` has not run yet) gets
767
- * exactly the passes it asks for and no background timer.
768
- */
769
- private scheduleNext(): void {
770
- if (!this.started || this.stoppedFlag || this.doneFlag) return;
771
- this.clearTimer();
772
- const delayMs = this.nextDelayMs();
773
- this.timer = this.scheduler.setTimeout(() => {
774
- this.timer = undefined;
775
- void this.reconcile();
776
- }, delayMs);
777
- }
778
-
779
- /**
780
- * The delay before the next pass: the flat poll interval while the loop is merely waiting
781
- * ({@link lastPassIdle}), otherwise the next rung
782
- * of the doubling ladder from {@link INITIAL_JOIN_RETRY_INTERVAL_MS}, capped at the poll
783
- * interval. A pass that lands idle resets the ladder, so a later unfinished join starts
784
- * over at the bottom rung.
785
- */
786
- private nextDelayMs(): number {
787
- if (this.lastPassIdle) {
788
- this.retryDelayMs = undefined;
789
- return this.pollIntervalMs;
790
- }
791
- this.retryDelayMs = Math.min(
792
- this.retryDelayMs === undefined ? INITIAL_JOIN_RETRY_INTERVAL_MS : this.retryDelayMs * 2,
793
- this.pollIntervalMs
794
- );
795
- return this.retryDelayMs;
796
- }
797
-
798
- private clearTimer(): void {
799
- if (this.timer !== undefined) {
800
- this.scheduler.clearTimeout(this.timer);
801
- this.timer = undefined;
802
- }
803
- }
804
-
805
- /**
806
- * Step 2 of the pass: `true` iff the party's member row under its CURRENT key is visible
807
- * locally by the time this returns (already present, or seated by redeeming the staged
808
- * invitation). While a rotation is pending the staged invitation is spent under the pending
809
- * key instead, or left alone ("Redeeming under the pending key" in the module doc), and the
810
- * answer is only whether the current key is still a member.
811
- */
812
- private async ensureMembership(db: Database, keyPair: Ed25519KeyPair, pending: PendingPartyKeyState): Promise<boolean> {
813
- if (!pending.pending) {
814
- return this.ensureMembershipUnderOwnKey(db, keyPair);
815
- }
816
- const isMember = await isStrandMember(db, keyPair.publicKeyB64);
817
- if (pending.key === null) {
818
- this.leaveInviteStaged();
819
- } else {
820
- await this.seatPendingKey(db, pending.key);
821
- }
822
- return isMember;
823
- }
824
-
825
- /** Step 2 with no rotation pending: the member row under the party's own key, seated from the staged invitation if need be. */
826
- private async ensureMembershipUnderOwnKey(db: Database, keyPair: Ed25519KeyPair): Promise<boolean> {
827
- if (await isStrandMember(db, keyPair.publicKeyB64)) {
828
- await this.burnLeftoverInvite(db, keyPair);
829
- return true;
830
- }
831
- const invite = this.deps.pendingInvite?.get();
832
- if (!invite) {
833
- this.noteIdlePass();
834
- return false;
835
- }
836
- try {
837
- await consumeInvite(db, {
838
- inviteKey: invite.inviteKey,
839
- invitePrivateKey: invite.invitePrivateKey,
840
- memberKey: keyPair.publicKeyB64,
841
- }, OWN_TRANSACTION);
842
- } catch (error) {
843
- this.handleConsumeFailure(error, invite, 'own-key');
844
- return false;
845
- }
846
- this.deps.pendingInvite?.clear(invite);
847
- log('[%s] redeemed the staged membership invitation — Member row seated under this party\'s key', this.deps.label);
848
- return true;
849
- }
850
-
851
- /**
852
- * Step 2 while a rotation is pending whose key this machine cannot read: nothing is seated or
853
- * burned, since the only key this machine could sign with is the one being retired. A staged
854
- * invitation is left for a machine that can read the key, and the pass is idle.
855
- */
856
- private leaveInviteStaged(): void {
857
- this.waitForPoll();
858
- if (this.deps.pendingInvite?.get()) {
859
- this.inviteLeftStagedDeliberately = true;
860
- log('[%s] the staged invitation is left staged: the party is moving to a key this machine cannot read', this.deps.label);
861
- }
862
- }
863
-
864
- /**
865
- * Step 2 while a rotation is pending and this machine can read the pending key: see the
866
- * pending-and-opened case of "Redeeming under the pending key" in the module doc. A pending
867
- * key that does not decode throws to the pass's catch, which retries it.
868
- */
869
- private async seatPendingKey(db: Database, opened: OpenedPendingPartyKey): Promise<void> {
870
- const newKey = strandMemberKeyPair(opened.privateKey);
871
- const invite = this.deps.pendingInvite?.get();
872
- if (await isStrandMember(db, newKey.publicKeyB64)) {
873
- if (invite) {
874
- await this.burnLeftoverInvite(db, newKey);
875
- } else {
876
- this.waitForPoll();
877
- }
878
- this.kickRotationDriver('the pending key is a member');
879
- return;
880
- }
881
- if (!invite) {
882
- this.waitForPoll();
883
- return;
884
- }
885
- try {
886
- await consumeInvite(db, {
887
- inviteKey: invite.inviteKey,
888
- invitePrivateKey: invite.invitePrivateKey,
889
- memberKey: newKey.publicKeyB64,
890
- }, OWN_TRANSACTION);
891
- } catch (error) {
892
- this.handleConsumeFailure(error, invite, 'pending-key');
893
- return;
894
- }
895
- this.deps.pendingInvite?.clear(invite);
896
- log('[%s] redeemed the staged membership invitation under the party\'s PENDING key — the rotation can finish', this.deps.label);
897
- this.kickRotationDriver('the pending key was just seated');
898
- }
899
-
900
- /**
901
- * Tell the rotation driver the pending key is seated. Once per pass that sees the seat, so a
902
- * machine that cannot drive (no owner key here, or the swap deferred) hears it again on its
903
- * next pass rather than never.
904
- *
905
- * NOTE: a non-owner machine that reads the key kicks on every pass between the seat and the
906
- * swap, and `CadreNode.driveRotationIfPending` logs its refusal each time; bounded by the
907
- * seconds the swap takes on the owner machine. The owner machine alone does the same while
908
- * its swap is deferred (the only sibling offline): every pass kicks, the driver runs its
909
- * reads and ends "swap deferred", for as long as that sibling stays away. If either log
910
- * ever matters, kick once per seat (remember the pending stamp kicked for).
911
- */
912
- private kickRotationDriver(cause: string): void {
913
- try {
914
- this.deps.onPendingKeySeated?.();
915
- log('[%s] rotation driver kicked: %s', this.deps.label, cause);
916
- } catch (error) {
917
- log('[%s] the pending-key-seated callback threw: %s', this.deps.label, describeThrown(error));
918
- }
919
- }
920
-
921
- /**
922
- * The already-member arm: spend a still-staged invitation so nobody else can. The stage
923
- * is cleared once the burn lands or the invitation is known dead (already spent,
924
- * cancelled, expired, or the strand sealed around a party that is still a member) — with
925
- * the member row present a dead credential has no further local use, and keeping it
926
- * staged would leave `getPendingMembershipInvite` lying. A refused burn keeps it staged:
927
- * a busy refusal tried nothing, and a write the cohort refused is the removed-party shape
928
- * ("Stops, and re-arming" in the module doc), where the local member row is stale and the
929
- * credential is the one thing a later manager admission lets this loop settle.
930
- *
931
- * NOTE: this REPLACES an earlier accepted tradeoff that never retried a burn which failed
932
- * for a transient reason and dropped the invitation instead. That decision was made when
933
- * this arm could only ever see an invitation staged before the first join finished, so a
934
- * dropped credential cost nothing but a spendable bearer token. {@link rearm} makes the
935
- * arm reachable with a freshly issued invitation the app wants redeemed, and dropping
936
- * that one on the first refused write is the silent failure this loop exists to avoid.
937
- */
938
- private async burnLeftoverInvite(db: Database, keyPair: Ed25519KeyPair): Promise<void> {
939
- const invite = this.deps.pendingInvite?.get();
940
- if (!invite) return;
941
- try {
942
- await burnInvite(db, {
943
- inviteKey: invite.inviteKey,
944
- invitePrivateKey: invite.invitePrivateKey,
945
- memberKey: keyPair.publicKeyB64,
946
- }, OWN_TRANSACTION);
947
- } catch (error) {
948
- this.handleBurnFailure(error, invite);
949
- return;
950
- }
951
- this.deps.pendingInvite?.clear(invite);
952
- log('[%s] burned the leftover invitation (member row already present)', this.deps.label);
953
- }
954
-
955
- /**
956
- * Act on a `burnInvite` rejection as {@link classifyConsumeFailure} routes it. Unlike a
957
- * redemption, a sealed strand is not terminal here — the member row is present, so this
958
- * party is a member of the sealed strand and only its leftover credential is dead — and a
959
- * half-committed burn (one collection, so a report of it means the commit's durability
960
- * was in doubt) is retried: the next pass either lands it or fails on the row's primary
961
- * key, which drops it as dead.
962
- */
963
- private handleBurnFailure(error: unknown, invite: StrandMembershipInvite): void {
964
- const failure = classifyConsumeFailure(error);
965
- switch (failure.kind) {
966
- case 'busy':
967
- log('[%s] burning the leftover invitation deferred — nothing was tried; it stays staged for the next '
968
- + 'pass: %s', this.deps.label, describeThrown(error));
969
- return;
970
- case 'sealed':
971
- case 'dead-invite':
972
- log('[%s] the leftover invitation is dead (already spent, cancelled, expired, or the strand sealed) — '
973
- + 'dropping it: %s', this.deps.label, describeThrown(error));
974
- this.deps.pendingInvite?.clear(invite);
975
- return;
976
- case 'half-committed':
977
- case 'retry':
978
- log('[%s] burning the leftover invitation was refused — it stays staged and is retried next tick '
979
- + '(the cohort refusing this machine, or a transient write failure): %s', this.deps.label, describeThrown(error));
980
- return;
981
- }
982
- }
983
-
984
- /**
985
- * Step 3 of the pass: write this machine's own `MemberPeer` binding (insert-if-absent);
986
- * `true` once it is in place. A missing transport peer id (a quiesce racing the pass)
987
- * defers to the next tick; a write failure — a busy refusal included — is contained by the
988
- * pass's outer catch and retried.
989
- */
990
- private async ensureBinding(db: Database, keyPair: Ed25519KeyPair): Promise<boolean> {
991
- const peerId = this.deps.getOwnPeerId();
992
- if (!peerId) {
993
- log('[%s] no live transport peer id this pass — binding deferred', this.deps.label);
994
- return false;
995
- }
996
- await registerMemberPeer(db, { memberKeyPair: keyPair, peerId }, OWN_TRANSACTION);
997
- return true;
998
- }
999
-
1000
- /**
1001
- * Steps 4 and 5 of the pass, against the party's machines as the control database records
1002
- * them: `true` when nothing was left to write — every live sibling was already bound and no
1003
- * removed machine's binding had to be cleared — so the pass may latch done. A pass that
1004
- * wrote is not settled: the next one re-reads and confirms. Rows that cannot be read settle
1005
- * nothing and move the next pass to the flat poll interval; nothing this machine can do
1006
- * sooner. No seam means no siblings to bind: settled.
1007
- */
1008
- private async reconcileSiblings(db: Database, keyPair: Ed25519KeyPair, rotationPending: boolean): Promise<boolean> {
1009
- const source = this.deps.partyPeers;
1010
- if (!source) return true;
1011
- let peers: PartyStrandPeers;
1012
- try {
1013
- peers = await source.read();
1014
- } catch (error) {
1015
- log('[%s] the party\'s strand peers could not be read — sibling bindings wait for the next poll: %s',
1016
- this.deps.label, describeThrown(error));
1017
- this.waitForPoll();
1018
- return false;
1019
- }
1020
- const bound = new Set(await listMemberPeers(db, keyPair.publicKeyB64));
1021
- const unbound = peers.live.map((peer) => peer.strandPeerId).filter((peerId) => !bound.has(peerId));
1022
- const stale = peers.removed.filter((peerId) => bound.has(peerId));
1023
- const siblingsBound = await this.bindSiblings(db, keyPair, unbound);
1024
- const removedCleared = await this.clearRemovedMachines(db, keyPair, rotationPending, stale);
1025
- return siblingsBound && removedCleared;
1026
- }
1027
-
1028
- /**
1029
- * Step 4: bind each of `unbound` under the party's key. Each write is contained on its own,
1030
- * so one sibling's refusal (busy, or a collision with a sibling binding the same id) does
1031
- * not keep the others waiting. `true` iff there was nothing to bind.
1032
- */
1033
- private async bindSiblings(db: Database, keyPair: Ed25519KeyPair, unbound: readonly string[]): Promise<boolean> {
1034
- for (const peerId of unbound) {
1035
- try {
1036
- await registerMemberPeer(db, { memberKeyPair: keyPair, peerId }, OWN_TRANSACTION);
1037
- log('[%s] bound sibling machine %s under the party\'s key', this.deps.label, peerId);
1038
- } catch (error) {
1039
- log('[%s] binding sibling machine %s failed — retried next tick: %s', this.deps.label, peerId, describeThrown(error));
1040
- }
1041
- }
1042
- return unbound.length === 0;
1043
- }
1044
-
1045
- /**
1046
- * Step 5: clear the binding of each of `stale` (removed machines bound under the party's
1047
- * key), through the self branch of {@link removeMemberPeer} — signed by the party key, which
1048
- * is the row's own member key, so any peer id of the party's is reachable this way. Clears
1049
- * nothing while a key rotation is pending for the strand, or while whether one is could not be
1050
- * read, both of which `rotationPending` carries (see the module doc); that is settled, since
1051
- * the loop stays live until the swap re-keys it. `true` iff nothing was left to clear.
1052
- */
1053
- private async clearRemovedMachines(
1054
- db: Database,
1055
- keyPair: Ed25519KeyPair,
1056
- rotationPending: boolean,
1057
- stale: readonly string[],
1058
- ): Promise<boolean> {
1059
- if (stale.length === 0) return true;
1060
- if (rotationPending) {
1061
- log('[%s] %d removed machine(s) stay bound: a party key rotation is pending, or whether one is could not be read',
1062
- this.deps.label, stale.length);
1063
- return true;
1064
- }
1065
- for (const peerId of stale) {
1066
- try {
1067
- await removeMemberPeer(db, { memberKeyPair: keyPair, peerId }, OWN_TRANSACTION);
1068
- log('[%s] cleared the binding of removed machine %s', this.deps.label, peerId);
1069
- } catch (error) {
1070
- log('[%s] clearing the binding of removed machine %s failed — retried next tick: %s',
1071
- this.deps.label, peerId, describeThrown(error));
1072
- }
1073
- }
1074
- return false;
1075
- }
1076
-
1077
- /** Step 6: re-attempt this machine's own `StrandPeer` row; the seam contains its failures and remembers success. */
1078
- private async publishOwnStrandPeer(): Promise<void> {
1079
- const peerId = this.deps.getOwnPeerId();
1080
- if (!this.deps.partyPeers || !peerId) return;
1081
- try {
1082
- await this.deps.partyPeers.publishOwn(peerId);
1083
- } catch (error) {
1084
- log('[%s] publishing this machine\'s StrandPeer row threw — retried next pass: %s', this.deps.label, describeThrown(error));
1085
- }
1086
- }
1087
-
1088
- /**
1089
- * The done decision, once the member row and the own binding are in place: not while a party
1090
- * key rotation is pending (the loop stays live to notice the pending key seated, and is
1091
- * rebuilt under that key by the swap; logged once per cycle), not while an invitation is still
1092
- * staged (its burn keeps being refused; the loop stays live so a later pass can settle the
1093
- * credential), and not while a sibling step wrote or could not read this pass. Otherwise latch
1094
- * done and stop.
1095
- */
1096
- private latchDone(siblingsSettled: boolean, rotationPending: boolean): void {
1097
- if (rotationPending) {
1098
- // NOTE: a rotation the host never finishes (no re-invitation, no by-hand admission) keeps
1099
- // this loop polling flat for good: one control read plus the strand reads of steps 2 to 5
1100
- // per poll interval, per such strand. Fine at party scale; if a party ever carries many
1101
- // strands with rotations pending indefinitely, re-arm on the strand's `Member` table
1102
- // changing instead of polling for the seat.
1103
- if (!this.pendingRotationLogged) {
1104
- this.pendingRotationLogged = true;
1105
- log('[%s] a party key rotation is pending — the loop stays live until the party\'s key is swapped', this.deps.label);
1106
- }
1107
- return;
1108
- }
1109
- if (this.deps.pendingInvite?.get()) {
1110
- log('[%s] own MemberPeer binding is in place but an invitation is still staged — not done yet', this.deps.label);
1111
- return;
1112
- }
1113
- if (!siblingsSettled) {
1114
- log('[%s] sibling bindings changed or could not be read this pass — confirming next pass', this.deps.label);
1115
- return;
1116
- }
1117
- this.doneFlag = true;
1118
- this.finish('member row, own MemberPeer binding and every known sibling binding are in place', false);
1119
- }
1120
-
1121
- /** Re-arm the next pass on the flat poll interval, for a wait no faster retry can shorten. */
1122
- private waitForPoll(): void {
1123
- this.lastPassIdle = true;
1124
- }
1125
-
1126
- /**
1127
- * Act on a `consumeInvite` rejection as {@link classifyConsumeFailure} routes it: busy → keep
1128
- * the invitation and retry; half-committed → warn and drop; sealed → terminal under the party's
1129
- * own key, but under the pending key only a dead invitation (the party may still be a member
1130
- * under its current key, whose bindings this loop keeps whole, and the rotation stays pending
1131
- * for the life of the row); dead invitation → drop; anything else → retry.
1132
- */
1133
- private handleConsumeFailure(error: unknown, invite: StrandMembershipInvite, under: 'own-key' | 'pending-key'): void {
1134
- const failure = classifyConsumeFailure(error);
1135
- switch (failure.kind) {
1136
- case 'busy':
1137
- log('[%s] redeeming the staged invitation deferred — nothing was tried; retrying next tick: %s',
1138
- this.deps.label, describeThrown(error));
1139
- return;
1140
- case 'half-committed':
1141
- this.reportHalfCommittedJoin(failure, error, invite);
1142
- return;
1143
- case 'sealed':
1144
- // The staged credential is dead with the seal; drop it so the cache stays honest.
1145
- this.deps.pendingInvite?.clear(invite);
1146
- if (under === 'pending-key') {
1147
- log('[%s] the strand is sealed, so the party\'s pending key can never be admitted there — the staged '
1148
- + 'invitation is dead and dropped; the rotation stays pending', this.deps.label);
1149
- this.waitForPoll();
1150
- return;
1151
- }
1152
- this.finish('the strand is sealed — nobody can ever be admitted, so the staged invitation is dead', true);
1153
- return;
1154
- case 'dead-invite':
1155
- // NOTE: accepted tradeoff — dropping a dead invitation does not mark the pass idle,
1156
- // so the next attempt is one ladder rung away rather than a full poll interval. Kept:
1157
- // the pass AFTER it finds no member row and no invitation, marks itself idle, and
1158
- // re-arms flat, so the cost is one extra read per dead credential. Revisit if a
1159
- // source of dead invitations ever repeats per pass.
1160
- log('[%s] the staged invitation is dead (expired, cancelled, or consumed elsewhere) — dropping it; '
1161
- + 'a fresh formation stages a new one: %s', this.deps.label, describeThrown(error));
1162
- this.deps.pendingInvite?.clear(invite);
1163
- return;
1164
- case 'retry':
1165
- log('[%s] consumeInvite failed — retrying next tick (Invite row not yet replicated here, the cohort '
1166
- + 'refusing this machine, or a transient write failure): %s', this.deps.label, describeThrown(error));
1167
- return;
1168
- }
1169
- }
1170
-
1171
- /**
1172
- * Count an attempted pass that left the invitation staged (whatever stopped it — a
1173
- * refused or busy write, or a read that threw on a cut-off machine); one that settled
1174
- * it, or finished, ends the streak. A pass that left it staged on purpose (a rotation
1175
- * pending whose key this machine cannot read) is no attempt: it neither counts nor ends
1176
- * the streak. At {@link UNFINISHED_PASSES_BEFORE_ESCALATION} report the PROBABLE blocked
1177
- * re-join.
1178
- */
1179
- private noteAttemptOutcome(): void {
1180
- if (this.inviteLeftStagedDeliberately) return;
1181
- if (this.doneFlag || !this.deps.pendingInvite?.get()) {
1182
- this.unfinishedPasses = 0;
1183
- return;
1184
- }
1185
- this.unfinishedPasses += 1;
1186
- if (this.unfinishedPasses >= UNFINISHED_PASSES_BEFORE_ESCALATION) {
1187
- this.reportRejoinBlocked(
1188
- `${this.unfinishedPasses} membership reconcile passes have left the staged membership invitation `
1189
- + 'unsettled. Either this party was removed from the strand and the remaining members are refusing its '
1190
- + 'machines, or the invitation\'s Strand.Invite row has not replicated here yet.'
1191
- );
1192
- }
1193
- }
1194
-
1195
- /**
1196
- * Step 1's CONFIRMED trigger: self-revoked with an invitation staged. Reports (once per
1197
- * re-arm cycle) and answers `true` so the pass carries on — the redemption is attempted
1198
- * and refused like any other write, and a manager's re-admission lets a later pass finish.
1199
- * `false` (nothing staged) means step 1 stops the loop as before.
1200
- */
1201
- private stagedInviteBlockedBySelfRevocation(): boolean {
1202
- if (!this.deps.pendingInvite?.get()) return false;
1203
- this.reportRejoinBlocked(
1204
- 'this party is revoked from the strand and holds a staged membership invitation it cannot spend: the '
1205
- + 'remaining members refuse this machine\'s strand writes, so the redemption cannot land.'
1206
- );
1207
- return true;
1208
- }
1209
-
1210
- /**
1211
- * ONE `console.warn` and one callback per re-arm cycle, whichever trigger fires first —
1212
- * see "Reporting a blocked re-join" in the module doc. `cause` is the trigger's own
1213
- * sentence; the remedy and the loop's posture are the same for both.
1214
- */
1215
- private reportRejoinBlocked(cause: string): void {
1216
- if (this.rejoinBlockedReported) return;
1217
- this.rejoinBlockedReported = true;
1218
- console.warn(
1219
- `[sereus] strand ${this.deps.label}: ${cause} A fresh invitation cannot re-admit a removed party by itself — `
1220
- + 'a remaining manager must admit this party\'s member key directly (addMemberByManager). The membership '
1221
- + 'loop keeps retrying quietly and completes the join once a Member row for this party appears.'
1222
- );
1223
- this.deps.onRejoinBlocked?.();
1224
- }
1225
-
1226
- /**
1227
- * A redemption only part of which was saved (see "Half-committed join" in the module doc):
1228
- * ONE visible warning naming both halves, and the staged invitation dropped. The pass is not
1229
- * marked idle, so the next one runs a ladder rung later and either finds a `Member` row (a
1230
- * saved one, or a manager's admission) and writes the binding, or idles flat.
1231
- *
1232
- * NOTE: the invitation is dropped whichever half was saved. In the observed shape
1233
- * (`ConsumedInvite` saved, `Member` not) it is spent and a retry could only fail on
1234
- * `ConsumedInvite`'s primary key. In the opposite shape (`Member` saved, `ConsumedInvite` not)
1235
- * keeping it would let the already-member arm burn it; dropping it leaves that bearer
1236
- * credential spendable until it expires — the state the burn arm's accepted tradeoff already
1237
- * lands in. Not branched on, because telling the shapes apart means parsing the lists, which
1238
- * are collection ids on the coordinator path but free-form tree labels on the plugin's legacy
1239
- * path. Revisit if a `Member`-saved half-commit is ever observed, or when
1240
- * `blocked/strand-half-committed-join-recovery` is decided.
1241
- */
1242
- private reportHalfCommittedJoin(failure: HalfCommittedJoin, error: unknown, invite: StrandMembershipInvite): void {
1243
- console.warn(
1244
- `[sereus] strand ${this.deps.label}: redeeming the staged membership invitation was only partly saved. `
1245
- + `Saved: [${failure.saved.join(', ')}]. Not saved: [${failure.unsaved.join(', ')}]. `
1246
- + 'The invitation is dropped: a saved ConsumedInvite row spends it, so it cannot be redeemed again. '
1247
- + 'If this party\'s Member row is not among the saved, the party is not a member of the strand and '
1248
- + 'cannot become one from this invitation — a manager must admit it directly (addMemberByManager). '
1249
- + 'The membership loop keeps checking and completes the join once a Member row for this party appears.'
1250
- );
1251
- log('[%s] half-committed redemption, full error: %o', this.deps.label, error);
1252
- this.deps.pendingInvite?.clear(invite);
1253
- // The idle passes that follow are the wait this warning already explained; the escalation's
1254
- // "waiting on the founder rows to replicate" would be a second, misleading warning.
1255
- this.idleEscalated = true;
1256
- }
1257
-
1258
- /** Decode the party key once; an undecodable key is terminal (nothing can be signed). */
1259
- private resolveKeyPair(): Ed25519KeyPair | undefined {
1260
- if (this.keyPair) return this.keyPair;
1261
- try {
1262
- this.keyPair = strandMemberKeyPair(this.deps.partyMemberPrivateKey);
1263
- } catch (error) {
1264
- this.finish(`the party membership key does not decode — nothing can be signed (${describeThrown(error)})`, true);
1265
- return undefined;
1266
- }
1267
- return this.keyPair;
1268
- }
1269
-
1270
- /**
1271
- * Count a no-member/no-invitation pass; escalate to ONE visible warning at the bound.
1272
- *
1273
- * NOTE: an idling loop never gives up — a machine whose party is never admitted keeps
1274
- * polling for the life of the process, one `Strand.Member` scan per strand per
1275
- * interval (30 s by default). Negligible at the handful of strands a device runs and
1276
- * the handful of members a strand has; if a node ever runs strands by the hundred, or
1277
- * a strand's member set grows large, bound the idle phase (give up after N passes and
1278
- * surface it) rather than shortening the interval.
1279
- */
1280
- private noteIdlePass(): void {
1281
- this.lastPassIdle = true;
1282
- this.idlePasses += 1;
1283
- if (this.idlePasses >= IDLE_PASSES_BEFORE_ESCALATION && !this.idleEscalated) {
1284
- this.idleEscalated = true;
1285
- console.warn(
1286
- `[sereus] strand ${this.deps.label}: ${this.idlePasses} membership reconcile passes and still no `
1287
- + 'Member row for this party and no staged invitation — a joiner is waiting on the founder rows to '
1288
- + 'replicate (or on a manager admission). The loop keeps retrying quietly.'
1289
- );
1290
- }
1291
- }
1292
-
1293
- /**
1294
- * Stop with a reason — the terminal and done paths' shared exit. `permanent` says whether
1295
- * a fresh invitation may reopen the loop ("Stops, and re-arming" in the module doc).
1296
- */
1297
- private finish(reason: string, permanent: boolean): void {
1298
- this.halt(`membership reconciliation stopping: ${reason}`, permanent);
1299
- }
1300
-
1301
- /** Latch the stop and disarm the timer; a permanent latch sticks even on an already-stopped loop. */
1302
- private halt(reason: string, permanent: boolean): void {
1303
- if (permanent) this.permanentlyStopped = true;
1304
- if (this.stoppedFlag) return;
1305
- this.stoppedFlag = true;
1306
- this.clearTimer();
1307
- log('[%s] membership reconciler stopped%s: %s%s', this.deps.label, this.doneFlag ? ' (done)' : '', reason,
1308
- permanent ? '' : ' — a fresh invitation or a change to the party\'s machines re-arms it');
1309
- }
1310
- }
1
+ /**
2
+ * Strand membership reconciliation: the per-instance background loop that finishes a
3
+ * party's join at strand bring-up and keeps the party's machine bindings whole. Every
4
+ * machine of a party that runs a closed strand ends up with (1) the party's `Strand.Member`
5
+ * row seated — redeeming the formation-staged invitation if one is pending — (2) its own
6
+ * durable machine→party binding (`Strand.MemberPeer`) written, which is what revocation
7
+ * enforcement and future admission control key on, and (3) every live sibling machine's
8
+ * binding written under the party's current key, with a removed machine's binding cleared —
9
+ * see "Binding the party's other machines" below.
10
+ *
11
+ * ## Contract
12
+ *
13
+ * - **Never blocks or fails bring-up.** Armed by `StrandInstanceManager.buildStrandRuntime`
14
+ * right after the strand database initializes (launch AND hibernation resume — the one
15
+ * seam where a transport peer id and a live `Database` both exist), and every pass is
16
+ * fully contained: a joiner at that instant has typically not synced the founder's rows
17
+ * and may lack write quorum, so failure means "retry next tick", never a throw.
18
+ * - **Kicked the moment its database appears.** A joining machine's first pass runs while
19
+ * the first-sync write gate still withholds `instance.database`, so it finds no database
20
+ * and returns at once. `StrandInstanceManager.publishDatabase` calls `reconcile()` as it
21
+ * hands the database to the app, which is what makes the join finish about a second after
22
+ * the strand becomes writable rather than on the next timer.
23
+ * - **Retries fast while the join is unfinished, slowly while it is only waiting.** A pass
24
+ * that leaves the join unfinished re-arms on a ladder starting at
25
+ * {@link INITIAL_JOIN_RETRY_INTERVAL_MS} and doubling, capped at the configured poll
26
+ * interval (default {@link DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS}). A pass
27
+ * that finds no member row AND no staged invitation is not an unfinished join but a wait
28
+ * for someone to admit this party — nothing this machine can do faster — so it re-arms on
29
+ * the flat poll interval and resets the ladder. The loop stops on the done state.
30
+ * - **Done state**: the party's member row is visible locally, this machine's own binding
31
+ * is in place, every live sibling with a `StrandPeer` row is bound under the party's key
32
+ * (a pass that wrote a binding is not done; the next pass has to find nothing left), AND no
33
+ * invitation is still staged — the loop stops. A LATER revocation is the enforcer's
34
+ * business, not this loop's; a resume rebuilds the reconciler and re-verifies from scratch
35
+ * (every write is idempotent, so re-running is free), and a fresh invitation staged on a
36
+ * done loop, or a change to the party's machines, re-arms it in place ({@link rearm}).
37
+ *
38
+ * ## One pass
39
+ *
40
+ * 1. **Self-revocation check.** If the enforcer flags this node's own party as revoked and
41
+ * no invitation is staged, stop rather than fight — re-admission arrives (if ever) via
42
+ * a fresh formation, which re-arms the loop. With an invitation staged the loop reports
43
+ * the dead end (below) and carries on: the redemption is attempted like any other, and a
44
+ * manager's re-admission lets a later pass finish it.
45
+ * 2. **Ensure membership.** Read first whether the party is moving to another key in this
46
+ * strand ({@link PartyStrandPeerSource.pendingKey}, one control read per pass); while it
47
+ * is, the step runs under that key instead — see "Redeeming under the pending key". Otherwise:
48
+ * member row visible → done with this step; if a staged invitation is still unspent, BURN it
49
+ * ({@link burnInvite} — the `ConsumedInvite` row alone) so the bearer credential cannot be
50
+ * spent by anyone else. A burn refused by the cohort keeps the invitation staged for the next
51
+ * pass (it is the same write gate a redemption faces, and the local member row may be stale —
52
+ * see "Re-arming"); a dead invitation is dropped. Member row absent + staged invitation →
53
+ * {@link consumeInvite} under the party's own key, retried across passes until the `Invite`
54
+ * row has replicated here and the write commits. Absent with no invitation (founder rows not
55
+ * yet synced, or a machine whose party never joined) → keep waiting, escalating to one
56
+ * visible warning after {@link IDLE_PASSES_BEFORE_ESCALATION} passes, never throwing.
57
+ * 3. **Ensure the binding.** {@link registerMemberPeer} (insert-if-absent, restart-safe)
58
+ * with this node's own strand transport peer id — only after step 2 sees the member
59
+ * row locally (its deferred `MemberExists` reads the live local table). A binding
60
+ * written while a burn keeps being refused leaves the loop live to settle the
61
+ * invitation later.
62
+ * 4. **Bind live siblings.** Every strand peer id the control database records for a live
63
+ * machine of this party ({@link PartyStrandPeerSource.read}) that has no binding under the
64
+ * party's key gets one, written here with the party key. See "Binding the party's other
65
+ * machines".
66
+ * 5. **Clear removed machines.** A binding under the party's key for a machine removed from
67
+ * the cadre is cleared through the self branch of {@link removeMemberPeer} — unless the
68
+ * pending-key read at step 2 found a party key rotation pending for the strand, or failed.
69
+ * 6. **Re-attempt this machine's own `StrandPeer` row** ({@link PartyStrandPeerSource.publishOwn}),
70
+ * the control-side statement step 4 on the siblings reads: a background write at bring-up
71
+ * that is deferred while alone or refused until this machine's own `CadrePeer` row arrives.
72
+ *
73
+ * ## Binding the party's other machines
74
+ *
75
+ * A `MemberPeer` binding is signed by the member key, which every machine of the party holds,
76
+ * so any machine can bind any peer id under the party's key: the party vouching for its own
77
+ * machine. Which peer ids are the party's machines comes from `CadreControl.StrandPeer`, each
78
+ * machine's own signed statement of its peer id in the strand, joined to the party's live
79
+ * machines and its `CadrePeer` tombstones (`strand-party-peers.ts`). The point is a party
80
+ * member key that changes (a machine removal rotates it: `strand-party-key-rotation.ts`):
81
+ * a sibling offline through the change returns to find itself bound under the new key by the
82
+ * machines that were there, and a machine bound by a sibling that had not yet heard of its
83
+ * removal is cleared once the tombstone arrives.
84
+ *
85
+ * Step 5 is gated on no rotation pending (the pending-key state step 2 read). While one is, the
86
+ * removed machine's binding under the current key is exactly the orphan the rotation is about to
87
+ * leave behind, and clearing it would hand the removed machine a clean slate the deny-list gate
88
+ * admits. A failed pending read clears nothing for the same reason. After the swap the pending row is gone, and the step
89
+ * clears a binding a lagging sibling wrote under the new key. The gate holds only because a
90
+ * removal writes the machine's tombstone and the pending row in ONE transaction
91
+ * (`ControlDatabase.removeMachine`): a tombstone that reaches this node without
92
+ * its pending row reads as "no rotation", and this step clears the binding the rotation
93
+ * meant to orphan, which leaves the removed machine admitted as a stranger rather than denied.
94
+ *
95
+ * The step reads the party's bindings once per pass (`listMemberPeers`) and compares in
96
+ * JavaScript, the scan-not-seek idiom. Two machines binding one sibling at once collide on the
97
+ * `MemberPeer` primary key; the loser's write is refused and its next pass finds the row. A
98
+ * sibling's row that cannot be read keeps the loop live on the flat poll interval, and a write
99
+ * that fails is retried on the ladder.
100
+ *
101
+ * ## Redeeming under the pending key
102
+ *
103
+ * A machine removal replaces the party's member key K in each closed strand with a fresh key K'
104
+ * (`strand-party-key-rotation.ts`), and in a strand the party does not manage K cannot seat K'
105
+ * itself: the strand's host has to re-invite the party, or its manager admit K' by hand
106
+ * (docs/strands/keys.md → Replacing the party's key). The host's fresh invitation is staged here like
107
+ * any other and lands in step 2, which is why one rule governs that step: **while a
108
+ * `PendingStrandPartyKey` row exists for the strand, this loop never writes a `Strand.Member`
109
+ * row under K.** The removed machine holds K, and a seat written under K is a seat it keeps.
110
+ * Three cases, decided by what {@link PartyStrandPeerSource.pendingKey} answers at the head of
111
+ * the pass (a rejected read counts as pending with the key unreadable):
112
+ *
113
+ * - **No rotation pending**: the ordinary step 2 above.
114
+ * - **Pending, the key not readable here** (the row is sealed to other machines: this machine
115
+ * was admitted after the removal, or runs on an ephemeral identity; or the read failed): the
116
+ * step neither consumes nor burns. A staged invitation stays staged, with one debug line, for
117
+ * a machine that can read the key to redeem; the pass is idle, and it does not count toward
118
+ * the probable blocked re-join report below — it left the invitation staged on purpose.
119
+ * - **Pending, the key opened**: with K' already a member (admitted by hand, or seated by a
120
+ * sibling's redemption), a staged invitation is burned against K' and the rotation driver is
121
+ * kicked ({@link StrandMembershipReconcilerDeps.onPendingKeySeated}); with K' not yet a member
122
+ * and an invitation staged, it is redeemed under K' and the driver kicked; a refused
123
+ * redemption is classified as under K, except that a sealed strand is not terminal here (the
124
+ * party may still be a member under K) and only drops the dead invitation. With nothing staged
125
+ * the pass is idle: the driver has reported `needs-another-party`, and nothing happens until
126
+ * the host acts.
127
+ *
128
+ * Step 2 still answers whether K's member row is visible, which the binding steps that follow
129
+ * are under: K is the party's current key until the control swap, and a binding written under K
130
+ * after K has left (step 5 of the rotation, before the swap replicates here) is refused by
131
+ * `MemberPeer.MemberExists` and polled, until the swap re-keys this loop. The loop does not
132
+ * latch done while a rotation is pending, whatever else is in place, so a by-hand admission or a
133
+ * sibling's redemption is noticed on the next pass and the driver kicked; a pass that wrote
134
+ * nothing is idle, so the cadence is the flat poll interval. The pending state ends with the
135
+ * swap: `StrandInstanceManager.rekeyParty` rebuilds this loop under K', whose next pass finds no
136
+ * pending row, clears the removed machine's stale binding (step 5) and latches done as before.
137
+ * Whoever redeems the host's invitation seats a key of its choosing, so the invitation must reach
138
+ * the party's owner and not the removed machine, as with every invitation today.
139
+ *
140
+ * ## Stops, and re-arming
141
+ *
142
+ * Two kinds of stop. A RE-ARMABLE stop is one a fresh invitation, or a change to the
143
+ * party's machines, should reopen:
144
+ *
145
+ * - **Done** (above).
146
+ * - **Self-revoked with nothing staged** (step 1 above). A machine whose only binding is
147
+ * orphaned — its sibling rotated the key before this machine's `StrandPeer` row reached it —
148
+ * is denied by every other machine, so its own loop cannot write and stops here. The heal is
149
+ * a sibling binding it (step 4 there); its enforcer then drops its peer id from the deny set
150
+ * and reports `onSelfRestored`, which re-arms this loop.
151
+ *
152
+ * A PERMANENT stop is one a fresh invitation changes nothing about — {@link rearm} is a
153
+ * no-op after it:
154
+ *
155
+ * - **Sealed strand**: `consumeInvite` rejected by `ConsumedInvite.NotSealed` — nobody
156
+ * can ever be admitted, so retrying forever is noise. Terminal-with-log.
157
+ * - **Undecodable party key**: nothing can be signed; loud log, stop.
158
+ * - **The public {@link stop}**: `StrandInstanceManager.releaseRuntime` and
159
+ * `clearOwnMemberPeerBinding` both call it and mean it — the latter stops the loop and
160
+ * awaits {@link settle} precisely so no pass can re-register the binding it is about to
161
+ * delete, and a re-arm that restarted the loop would undo that.
162
+ *
163
+ * `CadreNode.adoptFormationMembershipInvite` stages every fresh invitation and notifies
164
+ * the instance manager, which calls {@link rearm}: a done loop reopens and runs one pass
165
+ * at once; a running loop is merely kicked. This is what lets a party that was REMOVED
166
+ * from the strand, and then handed a new invitation, actually attempt it — the loop
167
+ * finished during its first join, long before the removal. `CadreNode` also re-arms every
168
+ * strand's loop when `CadreControl.StrandPeer`, `CadrePeer` or `Revocation` changes
169
+ * (`StrandInstanceManager.notifyPartyPeersChanged`), so a sibling's row arriving binds it
170
+ * within the watch's coalescing window rather than at the next resume.
171
+ *
172
+ * On a removed party the local replica is usually stale: the cohort cut this machine off
173
+ * at about the moment the removal was written, so `isStrandMember` still answers true and
174
+ * a re-armed pass lands in the already-member arm. That is why the burn arm keeps a
175
+ * refused invitation staged and why the done state requires nothing staged — otherwise
176
+ * the fresh credential would be dropped on the first refused burn and the loop would latch
177
+ * done again, with the only trace a debug line.
178
+ *
179
+ * A DEAD invitation that is not terminal for the loop — expired, cancelled, or already
180
+ * consumed by someone else (`ConsumedInvite`'s primary key) — is dropped with a log and
181
+ * the loop keeps idling: a fresh formation stages a new invitation, and a manager-side
182
+ * admission (`addMemberByManager`) seats the member row without one.
183
+ *
184
+ * ## Reporting a blocked re-join
185
+ *
186
+ * Redeeming (or burning) writes into the strand, and the machines that would carry that
187
+ * write are exactly the ones the remaining members refuse once this party is removed. So
188
+ * the attempt is expected to fail, and the failure is REPORTED rather than left to the
189
+ * ladder: one `console.warn` plus the {@link StrandMembershipReconcilerDeps.onRejoinBlocked}
190
+ * callback (`CadreNode`'s `strand:rejoin-blocked` event), at most once per re-arm cycle.
191
+ * Two triggers:
192
+ *
193
+ * - **Confirmed** — a pass finds this party self-revoked AND an invitation staged. The node
194
+ * knows it was removed and is holding a credential it cannot spend.
195
+ * - **Probable** — {@link UNFINISHED_PASSES_BEFORE_ESCALATION} consecutive attempted passes
196
+ * left the invitation staged. The case that matters most in the field: a removed party
197
+ * that never learned it was removed (the removal did not replicate here before the cut).
198
+ * It is a suspicion, not a verdict — the invitation's `Invite` row may simply not have
199
+ * replicated here yet — and the warning names both causes.
200
+ *
201
+ * The remedy in either case is a remaining manager admitting this party's member key
202
+ * directly (`addMemberByManager`): that lifts the refusal, replication resumes, and the
203
+ * still-running loop sees the member row, burns the leftover credential and finishes by
204
+ * itself.
205
+ *
206
+ * ## Sharing the database with the app
207
+ *
208
+ * The strand `Database` this loop writes to is the one the app holds. Every write here
209
+ * passes `joinOpenTransaction: false`, so it runs as a transaction of its own and never
210
+ * joins one the app has open: the writer refuses with `StrandTransactionBusyError`, having
211
+ * written nothing, and the pass retries on the ladder. A busy refusal is never read as a
212
+ * dead invitation, and a busy burn leaves the invitation staged for the next pass.
213
+ *
214
+ * A write refused because the strand's offline queue holds transactions
215
+ * (`StrandOfflineQueueBusyError`, docs/strands/writes.md → "Offline mode") is a busy refusal too: it
216
+ * wrote nothing, and the ladder retries it until the queue drains. A membership commit queued
217
+ * behind an app commit anyway (the race that refusal leaves open) can fail with Optimystic's
218
+ * `OfflineCommitTimeoutError`, which is an unclassified failure here: a redemption keeps the
219
+ * invitation and retries, and a binding is retried by the next pass. Each pass reads the state
220
+ * before it writes (the member row, then the binding, which is insert-if-absent), so a write that
221
+ * landed after all (`sent: true`) is found by that pass rather than written twice.
222
+ *
223
+ * ## Half-committed join
224
+ *
225
+ * On a networked strand optimystic commits `Member` and `ConsumedInvite` as separate
226
+ * collections and can report that only some of them were saved (`CoordinatorPartialCommitError`,
227
+ * or the plugin's legacy `PartialCommitError`). When `ConsumedInvite` is saved and `Member` is
228
+ * not, the invitation is spent and the schema seats a `Member` through an invitation only in the
229
+ * same transaction as a fresh consumption, so this loop can never seat the party from it. Such a
230
+ * failure is recognised by TYPE before any message text is read (its message names the
231
+ * `ConsumedInvite` collection, which a text match once mistook for a dead invitation), reported
232
+ * with ONE `console.warn`, and the invitation is dropped. The loop keeps running like it does
233
+ * after a dead invitation: a manager admission, or a `Member` row that did land, is picked up by
234
+ * the next pass, which then writes the binding. Whether sereus should repair such a join itself
235
+ * is `blocked/strand-half-committed-join-recovery`.
236
+ */
237
+
238
+ import debug from 'debug';
239
+ import type { Database } from '@quereus/quereus';
240
+ import { CoordinatorPartialCommitError } from '@optimystic/db-core';
241
+ import { PartialCommitError } from '@optimystic/quereus-plugin-optimystic';
242
+ import { causeChain } from './control-retry.js';
243
+ import type { Ed25519KeyPair } from './ed25519-key.js';
244
+ import type { StrandMembershipInvite } from './types.js';
245
+ import { strandMemberKeyPair } from './strand-member-key.js';
246
+ import {
247
+ StrandOfflineQueueBusyError,
248
+ StrandTransactionBusyError,
249
+ burnInvite,
250
+ consumeInvite,
251
+ isStrandMember,
252
+ listMemberPeers,
253
+ registerMemberPeer,
254
+ removeMemberPeer,
255
+ type StrandWriteOptions,
256
+ } from './strand-membership-writer.js';
257
+ import type { OpenedPendingPartyKey } from './strand-party-key-rotation.js';
258
+ import type { PartyStrandPeerSource, PartyStrandPeers, PendingPartyKeyState } from './strand-party-peers.js';
259
+ import { defaultTimeoutScheduler, type TimeoutScheduler } from './timeout-scheduler.js';
260
+ import { describeThrown } from './describe-thrown.js';
261
+
262
+ const log = debug('sereus:cadre:strand-membership-reconciler');
263
+
264
+ /**
265
+ * Default poll interval, ms: the loop's idle cadence while nobody has admitted this party, and
266
+ * the cap of its unfinished-join retry ladder. The loop stops once joined, so this matters only
267
+ * while a machine is joining.
268
+ */
269
+ export const DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS = 30_000;
270
+
271
+ /**
272
+ * Idle passes (no member row, no staged invitation) before ONE `console.warn`
273
+ * escalation — at the default 30 s cadence, about five minutes of waiting. The loop
274
+ * keeps retrying quietly after it; the warning exists so a joiner stuck waiting on
275
+ * founder-row replication is visible without the debug namespace enabled.
276
+ */
277
+ export const IDLE_PASSES_BEFORE_ESCALATION = 10;
278
+
279
+ /**
280
+ * Consecutive passes that ran against a live database and ended with the staged
281
+ * invitation still unsettled — whatever refused it — before the loop reports a probable
282
+ * blocked re-join (see "Reporting a blocked re-join" in the module doc). The same order
283
+ * as {@link IDLE_PASSES_BEFORE_ESCALATION}: about three minutes at the default cadence
284
+ * (the ladder's five doubling rungs, then five passes at the 30 s cap). Counted by outcome
285
+ * rather than by classified failure because a cut-off machine can fail before any write is
286
+ * classified: its membership READ may already throw.
287
+ */
288
+ export const UNFINISHED_PASSES_BEFORE_ESCALATION = 10;
289
+
290
+ /**
291
+ * First retry delay, ms, for a pass that left the join UNFINISHED — a `consumeInvite`
292
+ * whose `Strand.Invite` row has not replicated to this machine yet, a cohort briefly
293
+ * unwritable, a database not yet published. Doubles per such pass up to the configured
294
+ * poll interval. Sized for what it retries: invite-row replication resolves in about a
295
+ * second over a direct connection and a few over a relay. The poll interval is NOT sized
296
+ * for that — it is sized for the idle case (waiting to be admitted at all), which is why
297
+ * this ladder exists instead of a shorter interval.
298
+ */
299
+ export const INITIAL_JOIN_RETRY_INTERVAL_MS = 1_000;
300
+
301
+ /** Every write this loop makes runs in a transaction of its own — see "Sharing the database with the app". */
302
+ const OWN_TRANSACTION: StrandWriteOptions = { joinOpenTransaction: false };
303
+
304
+ /**
305
+ * The `consumeInvite` rejection that means the strand is SEALED — `ConsumedInvite.NotSealed`
306
+ * fired, which Quereus renders `CHECK constraint failed: NotSealed (<its expression>)`.
307
+ * Terminal for a non-member: nobody can ever be admitted again.
308
+ */
309
+ const SEALED_REJECTION = /CHECK constraint failed: NotSealed\b/;
310
+
311
+ /**
312
+ * `consumeInvite` rejections that mean the INVITATION is dead but the loop should keep
313
+ * waiting for membership to arrive another way: expired (`CHECK constraint failed: NotExpired`),
314
+ * cancelled (`CHECK constraint failed: NotCancelled`), or already consumed by someone else
315
+ * (`UNIQUE constraint failed: ConsumedInvite.InviteKey`, the primary key).
316
+ *
317
+ * Anchored to the engine's full constraint-failure texts, not the bare names: other failures
318
+ * embed those names — a half-committed join's message names the `default/strand/ConsumedInvite`
319
+ * collection, which the bare `ConsumedInvite` this used to match read as a dead invitation. The
320
+ * texts are pinned against the real engine in `strand-membership-reconciler.spec.ts`, so a
321
+ * rewording in Quereus fails a spec instead of silently turning a dead invitation into an
322
+ * endless retry.
323
+ */
324
+ const DEAD_INVITE_REJECTION =
325
+ /CHECK constraint failed: (?:NotExpired|NotCancelled)\b|UNIQUE constraint failed: ConsumedInvite\.InviteKey\b/;
326
+
327
+ /**
328
+ * A redemption only part of which was saved: the collections (or, on the plugin's legacy
329
+ * path, tree labels) that were saved and those that were not, as the error reports them.
330
+ */
331
+ export interface HalfCommittedJoin {
332
+ kind: 'half-committed';
333
+ saved: readonly string[];
334
+ unsaved: readonly string[];
335
+ }
336
+
337
+ /** Where {@link classifyConsumeFailure} routes a failed `consumeInvite` or `burnInvite`. */
338
+ export type ConsumeFailure =
339
+ | HalfCommittedJoin
340
+ /**
341
+ * The app had a transaction open, or the strand's offline queue held transactions, so nothing
342
+ * was tried — keep the invitation, retry.
343
+ */
344
+ | { kind: 'busy' }
345
+ /** The strand is sealed — terminal for a non-member; a member's leftover invitation is merely dead. */
346
+ | { kind: 'sealed' }
347
+ /** Expired, cancelled, or consumed by someone else — drop the invitation, keep waiting. */
348
+ | { kind: 'dead-invite' }
349
+ /**
350
+ * Anything else — the `Invite` row has not replicated here yet, or the cohort refused the
351
+ * write (a removed party's machines are denied) — keep the invitation, retry.
352
+ */
353
+ | { kind: 'retry' };
354
+
355
+ /**
356
+ * Route a `consumeInvite` or `burnInvite` rejection. Both write the `Strand.ConsumedInvite`
357
+ * row under the same `NotExpired` / `NotCancelled` / `NotSealed` / primary-key constraints
358
+ * (a burn writes that row alone), so one classifier serves both. Typed checks run before any
359
+ * text check: a busy refusal (another transaction was open, so nothing ran) and a
360
+ * half-committed join are recognised by their error's type anywhere in the `cause` chain.
361
+ * The busy refusal carries Quereus's own refusal as its cause, and a half-committed join's
362
+ * message embeds collection names and the underlying failure's text, either of which a text
363
+ * matcher can misread. The sealed and dead-invitation checks then read the top-level message.
364
+ *
365
+ * A second loaded copy of `@optimystic/db-core` (or of the plugin) would fail `instanceof`; the
366
+ * half-commit then falls through the anchored texts to `retry`, and once the saved `ConsumedInvite`
367
+ * row is visible here a later attempt fails on its primary key and drops the invitation quietly —
368
+ * the old silent outcome, a few passes later, never a wrong write.
369
+ */
370
+ export function classifyConsumeFailure(error: unknown): ConsumeFailure {
371
+ if (isTransactionBusy(error)) return { kind: 'busy' };
372
+ const halfCommitted = halfCommittedJoin(error);
373
+ if (halfCommitted) return halfCommitted;
374
+ const message = describeThrown(error);
375
+ if (SEALED_REJECTION.test(message)) return { kind: 'sealed' };
376
+ if (DEAD_INVITE_REJECTION.test(message)) return { kind: 'dead-invite' };
377
+ return { kind: 'retry' };
378
+ }
379
+
380
+ /**
381
+ * The first partial-commit error in the `cause` chain, as the lists it reports.
382
+ *
383
+ * NOTE: `PartialCommitError` is imported from the plugin's root entry while strands register the
384
+ * plugin through its `/plugin` entry (`quereus-plugin-sereus`'s `compose-strand.ts`); the two are
385
+ * one class only because the plugin's build emits both entries over one shared chunk — the same
386
+ * dependency, and the same remedy if upstream ever bundles them apart, as the NOTE on
387
+ * `reportsPossiblyStoredWrite` in `control-write-retry.ts`.
388
+ */
389
+ function halfCommittedJoin(error: unknown): HalfCommittedJoin | undefined {
390
+ for (const link of causeChain(error)) {
391
+ if (link instanceof CoordinatorPartialCommitError) {
392
+ return { kind: 'half-committed', saved: link.committedCollections, unsaved: link.failedCollections };
393
+ }
394
+ if (link instanceof PartialCommitError) {
395
+ return { kind: 'half-committed', saved: link.persisted, unsaved: link.unpersisted };
396
+ }
397
+ }
398
+ return undefined;
399
+ }
400
+
401
+ /**
402
+ * Whether a writer refused having written nothing, because another transaction was open or the
403
+ * offline queue held transactions (see "Sharing the database with the app").
404
+ */
405
+ function isTransactionBusy(error: unknown): boolean {
406
+ return causeChain(error).some((link) =>
407
+ link instanceof StrandTransactionBusyError || link instanceof StrandOfflineQueueBusyError);
408
+ }
409
+
410
+ /**
411
+ * The staged formation invitation seam — `CadreNode`'s in-memory
412
+ * `pendingMembershipInvites` cache, scoped to one strand. Read lazily per pass (a
413
+ * re-formation may replace the entry between passes) and cleared by the reconciler once
414
+ * the invitation is spent, burned, or dead — the invalidation half the cache itself
415
+ * deliberately does not own.
416
+ */
417
+ export interface PendingMembershipInviteSource {
418
+ /** The staged invitation, or `undefined` when none is pending for this strand. */
419
+ get(): StrandMembershipInvite | undefined;
420
+ /**
421
+ * Drop `settled` (spent, burned, or dead) — only if it is still the staged one. A
422
+ * re-formation can replace the entry between a pass's {@link get} and this call, and
423
+ * the fresh invitation it staged must survive the older one being settled.
424
+ */
425
+ clear(settled: StrandMembershipInvite): void;
426
+ }
427
+
428
+ export interface StrandMembershipReconcilerDeps {
429
+ /** Log tag naming which strand this reconciler serves (the strand id). */
430
+ label: string;
431
+ /**
432
+ * THIS party's own strand membership private key (base64 protobuf, the control-layer
433
+ * `StrandPartyKey` row's content). Decoded LAZILY on the first pass, so a malformed
434
+ * key stops the loop with a log instead of failing bring-up.
435
+ */
436
+ partyMemberPrivateKey: string;
437
+ /**
438
+ * The live strand `Database`, read per pass, never captured — the instance's handle
439
+ * is dropped on quiesce, and `undefined` means "no live database this instant" (the
440
+ * pass simply waits for the next tick).
441
+ */
442
+ getDatabase: () => Database | undefined;
443
+ /**
444
+ * This node's own strand transport peer id — the `MemberPeer.PeerId` to bind. Read
445
+ * per pass for the same lifecycle reason as {@link getDatabase}.
446
+ */
447
+ getOwnPeerId: () => string | undefined;
448
+ /** The staged invitation seam. Absent for flows with no invitation (e.g. tests). */
449
+ pendingInvite?: PendingMembershipInviteSource;
450
+ /**
451
+ * The control-database seam for steps 2 and 4 to 6 of the pass (see "Binding the party's other
452
+ * machines" and "Redeeming under the pending key" in the module doc): the party's pending key
453
+ * in this strand as this machine can read it, the party's machines' strand peer ids, and this
454
+ * machine's own `StrandPeer` row. Absent (tests, an embedder with no control database) means
455
+ * no rotation is ever pending and the loop binds only this machine.
456
+ */
457
+ partyPeers?: PartyStrandPeerSource;
458
+ /**
459
+ * Called when a pass finds the party's PENDING key seated as a member of the strand (see
460
+ * "Redeeming under the pending key"): it redeemed the staged invitation under that key, or found
461
+ * it seated already. On every such pass until the control swap re-keys the loop. `CadreNode`
462
+ * wires it to its party key rotation driver, which finishes the move on an owner machine.
463
+ */
464
+ onPendingKeySeated?: () => void;
465
+ /**
466
+ * Whether the revocation enforcer currently flags THIS node's own party as revoked.
467
+ * When it does and nothing is staged, the loop stops rather than fight the enforcer;
468
+ * with an invitation staged it reports the blocked re-join and keeps trying — see the
469
+ * module doc. Absent (enforcement disarmed) means "not known revoked".
470
+ */
471
+ isSelfRevoked?: () => boolean;
472
+ /**
473
+ * Called when the loop reports a blocked re-join (see "Reporting a blocked re-join" in
474
+ * the module doc) — at most once per re-arm cycle, after the `console.warn`. `CadreNode`
475
+ * wires it to its `strand:rejoin-blocked` event.
476
+ */
477
+ onRejoinBlocked?: () => void;
478
+ /**
479
+ * Timer seam for the retry ladder; omit for real (unref'd) timeouts. Timeouts rather
480
+ * than the enforcer's repeating interval because the delay changes per pass and the next
481
+ * pass is armed only once the previous one settles, so a slow pass never stacks ticks
482
+ * behind it — the same seam the first-sync gate's probe loop uses.
483
+ */
484
+ scheduler?: TimeoutScheduler;
485
+ }
486
+
487
+ /** Embedder-facing tuning, threaded by `StrandInstanceManager`. */
488
+ export interface StrandMembershipReconciliationConfig {
489
+ /**
490
+ * Default true. False disarms the loop entirely — meant for test fixtures that
491
+ * hand-drive the membership writers and assert exact row sets; a production
492
+ * node that disarms it never seats a joiner's member row or binds its machines.
493
+ */
494
+ enabled?: boolean;
495
+ /**
496
+ * Idle cadence, ms — how often the loop re-checks while nobody has admitted this party
497
+ * yet — and the CAP of the unfinished-join retry ladder. Default
498
+ * {@link DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS}.
499
+ */
500
+ pollIntervalMs?: number;
501
+ }
502
+
503
+ /**
504
+ * The per-strand membership reconciliation loop. Created in
505
+ * `StrandInstanceManager.buildStrandRuntime` (closed strands with a party key only),
506
+ * started right after the strand database initializes, stopped and dropped in
507
+ * `releaseRuntime` — so quiesce → resume rebuilds it and re-runs the (idempotent) ladder
508
+ * from scratch.
509
+ */
510
+ export class StrandMembershipReconciler {
511
+ private readonly scheduler: TimeoutScheduler;
512
+ private readonly pollIntervalMs: number;
513
+ /** Tail of the pass chain — serializes passes (no two in flight). */
514
+ private tail: Promise<void> = Promise.resolve();
515
+ private timer: unknown;
516
+ private started = false;
517
+ private stoppedFlag = false;
518
+ /**
519
+ * Whether the last stop was one {@link rearm} may not undo — see "Stops, and re-arming"
520
+ * in the module doc. Latched by the public {@link stop} and the permanent terminal
521
+ * states, never cleared.
522
+ */
523
+ private permanentlyStopped = false;
524
+ private doneFlag = false;
525
+ /** Lazily decoded party keypair — see {@link StrandMembershipReconcilerDeps.partyMemberPrivateKey}. */
526
+ private keyPair: Ed25519KeyPair | undefined;
527
+ private idlePasses = 0;
528
+ private idleEscalated = false;
529
+ /** Consecutive attempted passes that left the invitation staged — see {@link UNFINISHED_PASSES_BEFORE_ESCALATION}. */
530
+ private unfinishedPasses = 0;
531
+ /** Whether the blocked re-join was already reported this re-arm cycle (one report, either trigger). */
532
+ private rejoinBlockedReported = false;
533
+ /**
534
+ * Whether the pass in flight left the staged invitation alone ON PURPOSE (a rotation is pending
535
+ * and this machine cannot read the key), which is not an attempt that failed and so does not
536
+ * count toward the probable blocked re-join report. Reset at the head of every pass.
537
+ */
538
+ private inviteLeftStagedDeliberately = false;
539
+ /** Whether this cycle has logged that the loop stays live for a pending rotation (one line per re-arm cycle). */
540
+ private pendingRotationLogged = false;
541
+ /**
542
+ * Whether the pass that just ran is waiting on something no faster retry can shorten — no
543
+ * member row and no staged invitation (a wait to be admitted, {@link noteIdlePass}), or the
544
+ * party's machines unreadable ({@link waitForPoll}). Such a pass re-arms on the flat poll
545
+ * interval; every other unfinished outcome climbs the ladder.
546
+ *
547
+ * NOTE: the ladder is therefore the DEFAULT for any outcome nobody classified — a new
548
+ * early return added to {@link doPass} inherits the fast retry unless it calls
549
+ * {@link noteIdlePass} or {@link waitForPoll}. Right for every outcome that exists today
550
+ * (each is an unfinished join this machine can make progress on). If an early return is
551
+ * ever added for a condition retrying cannot resolve, classify it so.
552
+ */
553
+ private lastPassIdle = false;
554
+ /** Current rung of the unfinished-join retry ladder, ms; unset before the first retry. */
555
+ private retryDelayMs: number | undefined;
556
+
557
+ constructor(
558
+ private readonly deps: StrandMembershipReconcilerDeps,
559
+ config?: StrandMembershipReconciliationConfig
560
+ ) {
561
+ this.scheduler = deps.scheduler ?? defaultTimeoutScheduler;
562
+ this.pollIntervalMs = config?.pollIntervalMs ?? DEFAULT_MEMBERSHIP_RECONCILE_INTERVAL_MS;
563
+ }
564
+
565
+ /**
566
+ * True once member row + own binding were both confirmed with nothing staged and the
567
+ * loop stopped. Cleared again by {@link rearm}.
568
+ */
569
+ get done(): boolean {
570
+ return this.doneFlag;
571
+ }
572
+
573
+ /** True while the loop is stopped — done, terminal, or externally stopped. */
574
+ get stopped(): boolean {
575
+ return this.stoppedFlag;
576
+ }
577
+
578
+ /**
579
+ * Kick an immediate pass (not awaited — bring-up never blocks on it). Every later pass
580
+ * is armed only once the previous one settles — see the retry ladder in the module doc —
581
+ * so there is no repeating interval to arm here.
582
+ */
583
+ start(): void {
584
+ if (this.started || this.stoppedFlag) return;
585
+ this.started = true;
586
+ void this.reconcile();
587
+ log('[%s] membership reconciler started (retry from %dms, idle poll %dms)',
588
+ this.deps.label, Math.min(INITIAL_JOIN_RETRY_INTERVAL_MS, this.pollIntervalMs), this.pollIntervalMs);
589
+ }
590
+
591
+ /**
592
+ * Resolve once no pass is in flight. {@link stop} only disarms the retry TIMER — a pass
593
+ * already past its stopped check runs to completion, so a caller that must know the
594
+ * loop can no longer write (`StrandInstanceManager.clearOwnMemberPeerBinding`, which
595
+ * would otherwise have its removal undone by a racing `registerMemberPeer`) awaits
596
+ * this after stopping. Never rejects: the pass chain contains every failure.
597
+ */
598
+ async settle(): Promise<void> {
599
+ await this.tail;
600
+ }
601
+
602
+ /**
603
+ * Disarm the retry timer, for good: a later {@link rearm} is refused. A pass already in
604
+ * flight completes but writes idempotently — {@link settle} is what waits it out.
605
+ */
606
+ stop(): void {
607
+ this.halt('stopped by the runtime', true);
608
+ }
609
+
610
+ /**
611
+ * Something changed that a stopped loop should look at — `cause` names it for the log: a
612
+ * fresh invitation was staged, the party's machines changed, or this machine is no longer
613
+ * revoked. Reopen a loop that stopped on a re-armable state (done, or self-revoked with
614
+ * nothing staged) and run one pass at once; merely kick a loop that is still running; do
615
+ * nothing after a permanent stop. Never rejects, and serialized like {@link reconcile}: the
616
+ * reopen happens when the queued pass STARTS, after any pass in flight has settled, so a
617
+ * `done` that pass latches cannot swallow the re-arm — and a public {@link stop} that lands
618
+ * first still wins, because the queued pass re-checks it.
619
+ */
620
+ rearm(cause = 'a fresh invitation'): Promise<void> {
621
+ return this.enqueue(() => this.reopen(cause) ? this.doPass() : Promise.resolve());
622
+ }
623
+
624
+ /**
625
+ * Run one pass now. Never rejects. Serialized: concurrent calls chain, so no two
626
+ * passes overlap and each explicit call gets a pass that STARTS after the call. On a
627
+ * started loop the pass re-arms the retry timer where it settles, so an explicit call —
628
+ * `StrandInstanceManager.publishDatabase`'s kick when a joiner's database is finally
629
+ * published — REPLACES the pending timer rather than running alongside it.
630
+ */
631
+ reconcile(): Promise<void> {
632
+ return this.enqueue(() => this.doPass());
633
+ }
634
+
635
+ /** Chain `pass` after every pass already queued; the tail never rejects. */
636
+ private enqueue(pass: () => Promise<void>): Promise<void> {
637
+ // The catch is what keeps the chain alive. `doPass` contains its own failures, but its
638
+ // `finally` calls into the injected scheduler, and a throw from there would leave `tail`
639
+ // REJECTED — after which every later `reconcile()` short-circuits on it and the join
640
+ // stalls for good, silently. Swallowing it here makes the "never rejects" contract
641
+ // {@link reconcile}, {@link rearm}, {@link settle} and the `void`-ed call sites all rely
642
+ // on structural rather than incidental.
643
+ const run = this.tail.then(pass).catch((error) => {
644
+ log('[%s] reconcile pass threw outside its own handler — the chain continues: %o',
645
+ this.deps.label, error);
646
+ });
647
+ this.tail = run;
648
+ return run;
649
+ }
650
+
651
+ /**
652
+ * The re-arm itself, run at the head of the queued pass: `false` refuses the pass (a
653
+ * permanent stop), a running loop is left as it is, and a re-armable stop is reopened
654
+ * with the idle and unfinished counters, both escalation latches and the retry ladder
655
+ * reset — a fresh invitation is a fresh cycle.
656
+ */
657
+ private reopen(cause: string): boolean {
658
+ if (this.permanentlyStopped) {
659
+ log('[%s] re-arm (%s) refused — the loop is stopped for good', this.deps.label, cause);
660
+ return false;
661
+ }
662
+ if (!this.stoppedFlag) {
663
+ // NOTE: a running loop keeps its counters and its once-per-cycle report latch, so a
664
+ // party whose loop already reported and is then re-formed AGAIN gets no second report
665
+ // for the replacement invitation. If that second report is ever wanted, key the latch
666
+ // on the staged invitation's key rather than on the re-arm.
667
+ log('[%s] %s on a running loop — kicking a pass', this.deps.label, cause);
668
+ return true;
669
+ }
670
+ this.stoppedFlag = false;
671
+ this.doneFlag = false;
672
+ this.idlePasses = 0;
673
+ this.idleEscalated = false;
674
+ this.unfinishedPasses = 0;
675
+ this.rejoinBlockedReported = false;
676
+ this.pendingRotationLogged = false;
677
+ this.retryDelayMs = undefined;
678
+ log('[%s] membership reconciler re-armed by %s', this.deps.label, cause);
679
+ return true;
680
+ }
681
+
682
+ /** One serialized pass; contains every failure (contract: never rejects). */
683
+ private async doPass(): Promise<void> {
684
+ if (this.stoppedFlag || this.doneFlag) return;
685
+ this.lastPassIdle = false;
686
+ try {
687
+ if (this.deps.isSelfRevoked?.() === true && !this.stagedInviteBlockedBySelfRevocation()) {
688
+ // NOTE: the enforcer's flag lags a re-admission by up to one of its polls. If the
689
+ // pass that settled the last staged invitation then failed to write the binding, this
690
+ // stop lands with the binding missing until the next resume rebuilds the loop. A
691
+ // missing binding only mis-credits diversity today; if it ever gates admission, make
692
+ // this stop also require the binding to be in place.
693
+ this.finish('this party is revoked from the strand — re-admission arrives (if ever) via a fresh formation, '
694
+ + 'or a sibling binds this machine under the party\'s current key', false);
695
+ return;
696
+ }
697
+ const keyPair = this.resolveKeyPair();
698
+ if (!keyPair) return; // undecodable key already stopped the loop
699
+ const db = this.deps.getDatabase();
700
+ if (!db) return; // no live database this instant (quiesce race) — next tick decides
701
+ await this.attempt(db, keyPair);
702
+ } catch (error) {
703
+ log('[%s] reconcile pass failed — retrying next tick: %o', this.deps.label, error);
704
+ } finally {
705
+ this.scheduleNext();
706
+ }
707
+ }
708
+
709
+ /**
710
+ * Steps 2 to 6 against a live database, with the outcome counted toward the probable
711
+ * blocked re-join report whether the attempt returned or threw.
712
+ *
713
+ * NOTE: steps 4 to 6 cost one `StrandPeer` read, one fresh membership read and one
714
+ * `MemberPeer` scan per pass, per closed strand, and `CadreNode` re-arms every strand's loop
715
+ * on each change to the party's machines, their records included. Fine at party scale; if a
716
+ * party ever runs many strands on many machines, read `StrandPeer` once per control change
717
+ * rather than per pass.
718
+ */
719
+ private async attempt(db: Database, keyPair: Ed25519KeyPair): Promise<void> {
720
+ this.inviteLeftStagedDeliberately = false;
721
+ try {
722
+ const pending = await this.readPendingKeyState();
723
+ if (!(await this.ensureMembership(db, keyPair, pending))) return;
724
+ // NOTE: accepted tradeoff — the redemption (`Member` + `ConsumedInvite`) and the binding
725
+ // below stay two SEPARATE commits on purpose. Merging them would save one commit: its
726
+ // serial latency and, since Optimystic 1.19.0 pends and commits a transaction's collections
727
+ // together, its `/cluster` requests (the two commits cost 6 on a two-member strand in
728
+ // `message-cost-accounting` on 2026-10-25, 20 before). It would also let a torn commit
729
+ // (Optimystic can report a multi-collection commit partly saved) or the cohort applying
730
+ // the collections out of order show this machine's `MemberPeer` without its `Member`,
731
+ // which the revocation enforcer reads as a removed member and hangs up on — fail closed,
732
+ // undone only by a manager clearing the binding (module doc of
733
+ // `strand-revocation-enforcer.ts`). And it would add a half-committed shape (`MemberPeer`
734
+ // saved, the invitation still live) that {@link reportHalfCommittedJoin}'s dropping of the
735
+ // invitation gets wrong. Revisit when Optimystic offers an all-or-nothing multi-collection
736
+ // commit, or when the enforcer can tell a not-yet-seated binding from a removed member's.
737
+ if (!(await this.ensureBinding(db, keyPair))) return;
738
+ const siblingsSettled = await this.reconcileSiblings(db, keyPair, pending.pending);
739
+ await this.publishOwnStrandPeer();
740
+ this.latchDone(siblingsSettled, pending.pending);
741
+ } finally {
742
+ this.noteAttemptOutcome();
743
+ }
744
+ }
745
+
746
+ /**
747
+ * The party's pending key in this strand, read once per pass. No seam means no rotation is
748
+ * ever pending; a rejected read is "pending, key unreadable", the posture under which nothing
749
+ * is seated under the current key and no removed machine's binding is cleared (module doc).
750
+ */
751
+ private async readPendingKeyState(): Promise<PendingPartyKeyState> {
752
+ const source = this.deps.partyPeers;
753
+ if (!source) return { pending: false };
754
+ try {
755
+ return await source.pendingKey();
756
+ } catch (error) {
757
+ log('[%s] whether a party key rotation is pending could not be read — treated as pending with the key unreadable: %s',
758
+ this.deps.label, describeThrown(error));
759
+ return { pending: true, key: null };
760
+ }
761
+ }
762
+
763
+ /**
764
+ * Arm the next pass, now that this one has settled — so a slow pass never stacks ticks
765
+ * behind it. Only a STARTED loop schedules: a caller driving {@link reconcile} by hand
766
+ * (the unit tests, and the publish kick on a launch whose `start()` has not run yet) gets
767
+ * exactly the passes it asks for and no background timer.
768
+ */
769
+ private scheduleNext(): void {
770
+ if (!this.started || this.stoppedFlag || this.doneFlag) return;
771
+ this.clearTimer();
772
+ const delayMs = this.nextDelayMs();
773
+ this.timer = this.scheduler.setTimeout(() => {
774
+ this.timer = undefined;
775
+ void this.reconcile();
776
+ }, delayMs);
777
+ }
778
+
779
+ /**
780
+ * The delay before the next pass: the flat poll interval while the loop is merely waiting
781
+ * ({@link lastPassIdle}), otherwise the next rung
782
+ * of the doubling ladder from {@link INITIAL_JOIN_RETRY_INTERVAL_MS}, capped at the poll
783
+ * interval. A pass that lands idle resets the ladder, so a later unfinished join starts
784
+ * over at the bottom rung.
785
+ */
786
+ private nextDelayMs(): number {
787
+ if (this.lastPassIdle) {
788
+ this.retryDelayMs = undefined;
789
+ return this.pollIntervalMs;
790
+ }
791
+ this.retryDelayMs = Math.min(
792
+ this.retryDelayMs === undefined ? INITIAL_JOIN_RETRY_INTERVAL_MS : this.retryDelayMs * 2,
793
+ this.pollIntervalMs
794
+ );
795
+ return this.retryDelayMs;
796
+ }
797
+
798
+ private clearTimer(): void {
799
+ if (this.timer !== undefined) {
800
+ this.scheduler.clearTimeout(this.timer);
801
+ this.timer = undefined;
802
+ }
803
+ }
804
+
805
+ /**
806
+ * Step 2 of the pass: `true` iff the party's member row under its CURRENT key is visible
807
+ * locally by the time this returns (already present, or seated by redeeming the staged
808
+ * invitation). While a rotation is pending the staged invitation is spent under the pending
809
+ * key instead, or left alone ("Redeeming under the pending key" in the module doc), and the
810
+ * answer is only whether the current key is still a member.
811
+ */
812
+ private async ensureMembership(db: Database, keyPair: Ed25519KeyPair, pending: PendingPartyKeyState): Promise<boolean> {
813
+ if (!pending.pending) {
814
+ return this.ensureMembershipUnderOwnKey(db, keyPair);
815
+ }
816
+ const isMember = await isStrandMember(db, keyPair.publicKeyB64);
817
+ if (pending.key === null) {
818
+ this.leaveInviteStaged();
819
+ } else {
820
+ await this.seatPendingKey(db, pending.key);
821
+ }
822
+ return isMember;
823
+ }
824
+
825
+ /** Step 2 with no rotation pending: the member row under the party's own key, seated from the staged invitation if need be. */
826
+ private async ensureMembershipUnderOwnKey(db: Database, keyPair: Ed25519KeyPair): Promise<boolean> {
827
+ if (await isStrandMember(db, keyPair.publicKeyB64)) {
828
+ await this.burnLeftoverInvite(db, keyPair);
829
+ return true;
830
+ }
831
+ const invite = this.deps.pendingInvite?.get();
832
+ if (!invite) {
833
+ this.noteIdlePass();
834
+ return false;
835
+ }
836
+ try {
837
+ await consumeInvite(db, {
838
+ inviteKey: invite.inviteKey,
839
+ invitePrivateKey: invite.invitePrivateKey,
840
+ memberKey: keyPair.publicKeyB64,
841
+ }, OWN_TRANSACTION);
842
+ } catch (error) {
843
+ this.handleConsumeFailure(error, invite, 'own-key');
844
+ return false;
845
+ }
846
+ this.deps.pendingInvite?.clear(invite);
847
+ log('[%s] redeemed the staged membership invitation — Member row seated under this party\'s key', this.deps.label);
848
+ return true;
849
+ }
850
+
851
+ /**
852
+ * Step 2 while a rotation is pending whose key this machine cannot read: nothing is seated or
853
+ * burned, since the only key this machine could sign with is the one being retired. A staged
854
+ * invitation is left for a machine that can read the key, and the pass is idle.
855
+ */
856
+ private leaveInviteStaged(): void {
857
+ this.waitForPoll();
858
+ if (this.deps.pendingInvite?.get()) {
859
+ this.inviteLeftStagedDeliberately = true;
860
+ log('[%s] the staged invitation is left staged: the party is moving to a key this machine cannot read', this.deps.label);
861
+ }
862
+ }
863
+
864
+ /**
865
+ * Step 2 while a rotation is pending and this machine can read the pending key: see the
866
+ * pending-and-opened case of "Redeeming under the pending key" in the module doc. A pending
867
+ * key that does not decode throws to the pass's catch, which retries it.
868
+ */
869
+ private async seatPendingKey(db: Database, opened: OpenedPendingPartyKey): Promise<void> {
870
+ const newKey = strandMemberKeyPair(opened.privateKey);
871
+ const invite = this.deps.pendingInvite?.get();
872
+ if (await isStrandMember(db, newKey.publicKeyB64)) {
873
+ if (invite) {
874
+ await this.burnLeftoverInvite(db, newKey);
875
+ } else {
876
+ this.waitForPoll();
877
+ }
878
+ this.kickRotationDriver('the pending key is a member');
879
+ return;
880
+ }
881
+ if (!invite) {
882
+ this.waitForPoll();
883
+ return;
884
+ }
885
+ try {
886
+ await consumeInvite(db, {
887
+ inviteKey: invite.inviteKey,
888
+ invitePrivateKey: invite.invitePrivateKey,
889
+ memberKey: newKey.publicKeyB64,
890
+ }, OWN_TRANSACTION);
891
+ } catch (error) {
892
+ this.handleConsumeFailure(error, invite, 'pending-key');
893
+ return;
894
+ }
895
+ this.deps.pendingInvite?.clear(invite);
896
+ log('[%s] redeemed the staged membership invitation under the party\'s PENDING key — the rotation can finish', this.deps.label);
897
+ this.kickRotationDriver('the pending key was just seated');
898
+ }
899
+
900
+ /**
901
+ * Tell the rotation driver the pending key is seated. Once per pass that sees the seat, so a
902
+ * machine that cannot drive (no owner key here, or the swap deferred) hears it again on its
903
+ * next pass rather than never.
904
+ *
905
+ * NOTE: a non-owner machine that reads the key kicks on every pass between the seat and the
906
+ * swap, and `CadreNode.driveRotationIfPending` logs its refusal each time; bounded by the
907
+ * seconds the swap takes on the owner machine. The owner machine alone does the same while
908
+ * its swap is deferred (the only sibling offline): every pass kicks, the driver runs its
909
+ * reads and ends "swap deferred", for as long as that sibling stays away. If either log
910
+ * ever matters, kick once per seat (remember the pending stamp kicked for).
911
+ */
912
+ private kickRotationDriver(cause: string): void {
913
+ try {
914
+ this.deps.onPendingKeySeated?.();
915
+ log('[%s] rotation driver kicked: %s', this.deps.label, cause);
916
+ } catch (error) {
917
+ log('[%s] the pending-key-seated callback threw: %s', this.deps.label, describeThrown(error));
918
+ }
919
+ }
920
+
921
+ /**
922
+ * The already-member arm: spend a still-staged invitation so nobody else can. The stage
923
+ * is cleared once the burn lands or the invitation is known dead (already spent,
924
+ * cancelled, expired, or the strand sealed around a party that is still a member) — with
925
+ * the member row present a dead credential has no further local use, and keeping it
926
+ * staged would leave `getPendingMembershipInvite` lying. A refused burn keeps it staged:
927
+ * a busy refusal tried nothing, and a write the cohort refused is the removed-party shape
928
+ * ("Stops, and re-arming" in the module doc), where the local member row is stale and the
929
+ * credential is the one thing a later manager admission lets this loop settle.
930
+ *
931
+ * NOTE: this REPLACES an earlier accepted tradeoff that never retried a burn which failed
932
+ * for a transient reason and dropped the invitation instead. That decision was made when
933
+ * this arm could only ever see an invitation staged before the first join finished, so a
934
+ * dropped credential cost nothing but a spendable bearer token. {@link rearm} makes the
935
+ * arm reachable with a freshly issued invitation the app wants redeemed, and dropping
936
+ * that one on the first refused write is the silent failure this loop exists to avoid.
937
+ */
938
+ private async burnLeftoverInvite(db: Database, keyPair: Ed25519KeyPair): Promise<void> {
939
+ const invite = this.deps.pendingInvite?.get();
940
+ if (!invite) return;
941
+ try {
942
+ await burnInvite(db, {
943
+ inviteKey: invite.inviteKey,
944
+ invitePrivateKey: invite.invitePrivateKey,
945
+ memberKey: keyPair.publicKeyB64,
946
+ }, OWN_TRANSACTION);
947
+ } catch (error) {
948
+ this.handleBurnFailure(error, invite);
949
+ return;
950
+ }
951
+ this.deps.pendingInvite?.clear(invite);
952
+ log('[%s] burned the leftover invitation (member row already present)', this.deps.label);
953
+ }
954
+
955
+ /**
956
+ * Act on a `burnInvite` rejection as {@link classifyConsumeFailure} routes it. Unlike a
957
+ * redemption, a sealed strand is not terminal here — the member row is present, so this
958
+ * party is a member of the sealed strand and only its leftover credential is dead — and a
959
+ * half-committed burn (one collection, so a report of it means the commit's durability
960
+ * was in doubt) is retried: the next pass either lands it or fails on the row's primary
961
+ * key, which drops it as dead.
962
+ */
963
+ private handleBurnFailure(error: unknown, invite: StrandMembershipInvite): void {
964
+ const failure = classifyConsumeFailure(error);
965
+ switch (failure.kind) {
966
+ case 'busy':
967
+ log('[%s] burning the leftover invitation deferred — nothing was tried; it stays staged for the next '
968
+ + 'pass: %s', this.deps.label, describeThrown(error));
969
+ return;
970
+ case 'sealed':
971
+ case 'dead-invite':
972
+ log('[%s] the leftover invitation is dead (already spent, cancelled, expired, or the strand sealed) — '
973
+ + 'dropping it: %s', this.deps.label, describeThrown(error));
974
+ this.deps.pendingInvite?.clear(invite);
975
+ return;
976
+ case 'half-committed':
977
+ case 'retry':
978
+ log('[%s] burning the leftover invitation was refused — it stays staged and is retried next tick '
979
+ + '(the cohort refusing this machine, or a transient write failure): %s', this.deps.label, describeThrown(error));
980
+ return;
981
+ }
982
+ }
983
+
984
+ /**
985
+ * Step 3 of the pass: write this machine's own `MemberPeer` binding (insert-if-absent);
986
+ * `true` once it is in place. A missing transport peer id (a quiesce racing the pass)
987
+ * defers to the next tick; a write failure — a busy refusal included — is contained by the
988
+ * pass's outer catch and retried.
989
+ */
990
+ private async ensureBinding(db: Database, keyPair: Ed25519KeyPair): Promise<boolean> {
991
+ const peerId = this.deps.getOwnPeerId();
992
+ if (!peerId) {
993
+ log('[%s] no live transport peer id this pass — binding deferred', this.deps.label);
994
+ return false;
995
+ }
996
+ await registerMemberPeer(db, { memberKeyPair: keyPair, peerId }, OWN_TRANSACTION);
997
+ return true;
998
+ }
999
+
1000
+ /**
1001
+ * Steps 4 and 5 of the pass, against the party's machines as the control database records
1002
+ * them: `true` when nothing was left to write — every live sibling was already bound and no
1003
+ * removed machine's binding had to be cleared — so the pass may latch done. A pass that
1004
+ * wrote is not settled: the next one re-reads and confirms. Rows that cannot be read settle
1005
+ * nothing and move the next pass to the flat poll interval; nothing this machine can do
1006
+ * sooner. No seam means no siblings to bind: settled.
1007
+ */
1008
+ private async reconcileSiblings(db: Database, keyPair: Ed25519KeyPair, rotationPending: boolean): Promise<boolean> {
1009
+ const source = this.deps.partyPeers;
1010
+ if (!source) return true;
1011
+ let peers: PartyStrandPeers;
1012
+ try {
1013
+ peers = await source.read();
1014
+ } catch (error) {
1015
+ log('[%s] the party\'s strand peers could not be read — sibling bindings wait for the next poll: %s',
1016
+ this.deps.label, describeThrown(error));
1017
+ this.waitForPoll();
1018
+ return false;
1019
+ }
1020
+ const bound = new Set(await listMemberPeers(db, keyPair.publicKeyB64));
1021
+ const unbound = peers.live.map((peer) => peer.strandPeerId).filter((peerId) => !bound.has(peerId));
1022
+ const stale = peers.removed.filter((peerId) => bound.has(peerId));
1023
+ const siblingsBound = await this.bindSiblings(db, keyPair, unbound);
1024
+ const removedCleared = await this.clearRemovedMachines(db, keyPair, rotationPending, stale);
1025
+ return siblingsBound && removedCleared;
1026
+ }
1027
+
1028
+ /**
1029
+ * Step 4: bind each of `unbound` under the party's key. Each write is contained on its own,
1030
+ * so one sibling's refusal (busy, or a collision with a sibling binding the same id) does
1031
+ * not keep the others waiting. `true` iff there was nothing to bind.
1032
+ */
1033
+ private async bindSiblings(db: Database, keyPair: Ed25519KeyPair, unbound: readonly string[]): Promise<boolean> {
1034
+ for (const peerId of unbound) {
1035
+ try {
1036
+ await registerMemberPeer(db, { memberKeyPair: keyPair, peerId }, OWN_TRANSACTION);
1037
+ log('[%s] bound sibling machine %s under the party\'s key', this.deps.label, peerId);
1038
+ } catch (error) {
1039
+ log('[%s] binding sibling machine %s failed — retried next tick: %s', this.deps.label, peerId, describeThrown(error));
1040
+ }
1041
+ }
1042
+ return unbound.length === 0;
1043
+ }
1044
+
1045
+ /**
1046
+ * Step 5: clear the binding of each of `stale` (removed machines bound under the party's
1047
+ * key), through the self branch of {@link removeMemberPeer} — signed by the party key, which
1048
+ * is the row's own member key, so any peer id of the party's is reachable this way. Clears
1049
+ * nothing while a key rotation is pending for the strand, or while whether one is could not be
1050
+ * read, both of which `rotationPending` carries (see the module doc); that is settled, since
1051
+ * the loop stays live until the swap re-keys it. `true` iff nothing was left to clear.
1052
+ */
1053
+ private async clearRemovedMachines(
1054
+ db: Database,
1055
+ keyPair: Ed25519KeyPair,
1056
+ rotationPending: boolean,
1057
+ stale: readonly string[],
1058
+ ): Promise<boolean> {
1059
+ if (stale.length === 0) return true;
1060
+ if (rotationPending) {
1061
+ log('[%s] %d removed machine(s) stay bound: a party key rotation is pending, or whether one is could not be read',
1062
+ this.deps.label, stale.length);
1063
+ return true;
1064
+ }
1065
+ for (const peerId of stale) {
1066
+ try {
1067
+ await removeMemberPeer(db, { memberKeyPair: keyPair, peerId }, OWN_TRANSACTION);
1068
+ log('[%s] cleared the binding of removed machine %s', this.deps.label, peerId);
1069
+ } catch (error) {
1070
+ log('[%s] clearing the binding of removed machine %s failed — retried next tick: %s',
1071
+ this.deps.label, peerId, describeThrown(error));
1072
+ }
1073
+ }
1074
+ return false;
1075
+ }
1076
+
1077
+ /**
1078
+ * Step 6: re-attempt this machine's own `StrandPeer` row; the seam contains its failures and
1079
+ * remembers success. Bring-up writes the row for every machine, client or serving, so this is
1080
+ * the retry of a write deferred or refused there, never a first attempt a role could have
1081
+ * skipped.
1082
+ */
1083
+ private async publishOwnStrandPeer(): Promise<void> {
1084
+ const peerId = this.deps.getOwnPeerId();
1085
+ if (!this.deps.partyPeers || !peerId) return;
1086
+ try {
1087
+ await this.deps.partyPeers.publishOwn(peerId);
1088
+ } catch (error) {
1089
+ log('[%s] publishing this machine\'s StrandPeer row threw — retried next pass: %s', this.deps.label, describeThrown(error));
1090
+ }
1091
+ }
1092
+
1093
+ /**
1094
+ * The done decision, once the member row and the own binding are in place: not while a party
1095
+ * key rotation is pending (the loop stays live to notice the pending key seated, and is
1096
+ * rebuilt under that key by the swap; logged once per cycle), not while an invitation is still
1097
+ * staged (its burn keeps being refused; the loop stays live so a later pass can settle the
1098
+ * credential), and not while a sibling step wrote or could not read this pass. Otherwise latch
1099
+ * done and stop.
1100
+ */
1101
+ private latchDone(siblingsSettled: boolean, rotationPending: boolean): void {
1102
+ if (rotationPending) {
1103
+ // NOTE: a rotation the host never finishes (no re-invitation, no by-hand admission) keeps
1104
+ // this loop polling flat for good: one control read plus the strand reads of steps 2 to 5
1105
+ // per poll interval, per such strand. Fine at party scale; if a party ever carries many
1106
+ // strands with rotations pending indefinitely, re-arm on the strand's `Member` table
1107
+ // changing instead of polling for the seat.
1108
+ if (!this.pendingRotationLogged) {
1109
+ this.pendingRotationLogged = true;
1110
+ log('[%s] a party key rotation is pending — the loop stays live until the party\'s key is swapped', this.deps.label);
1111
+ }
1112
+ return;
1113
+ }
1114
+ if (this.deps.pendingInvite?.get()) {
1115
+ log('[%s] own MemberPeer binding is in place but an invitation is still staged — not done yet', this.deps.label);
1116
+ return;
1117
+ }
1118
+ if (!siblingsSettled) {
1119
+ log('[%s] sibling bindings changed or could not be read this pass — confirming next pass', this.deps.label);
1120
+ return;
1121
+ }
1122
+ this.doneFlag = true;
1123
+ this.finish('member row, own MemberPeer binding and every known sibling binding are in place', false);
1124
+ }
1125
+
1126
+ /** Re-arm the next pass on the flat poll interval, for a wait no faster retry can shorten. */
1127
+ private waitForPoll(): void {
1128
+ this.lastPassIdle = true;
1129
+ }
1130
+
1131
+ /**
1132
+ * Act on a `consumeInvite` rejection as {@link classifyConsumeFailure} routes it: busy → keep
1133
+ * the invitation and retry; half-committed → warn and drop; sealed → terminal under the party's
1134
+ * own key, but under the pending key only a dead invitation (the party may still be a member
1135
+ * under its current key, whose bindings this loop keeps whole, and the rotation stays pending
1136
+ * for the life of the row); dead invitation → drop; anything else → retry.
1137
+ */
1138
+ private handleConsumeFailure(error: unknown, invite: StrandMembershipInvite, under: 'own-key' | 'pending-key'): void {
1139
+ const failure = classifyConsumeFailure(error);
1140
+ switch (failure.kind) {
1141
+ case 'busy':
1142
+ log('[%s] redeeming the staged invitation deferred — nothing was tried; retrying next tick: %s',
1143
+ this.deps.label, describeThrown(error));
1144
+ return;
1145
+ case 'half-committed':
1146
+ this.reportHalfCommittedJoin(failure, error, invite);
1147
+ return;
1148
+ case 'sealed':
1149
+ // The staged credential is dead with the seal; drop it so the cache stays honest.
1150
+ this.deps.pendingInvite?.clear(invite);
1151
+ if (under === 'pending-key') {
1152
+ log('[%s] the strand is sealed, so the party\'s pending key can never be admitted there — the staged '
1153
+ + 'invitation is dead and dropped; the rotation stays pending', this.deps.label);
1154
+ this.waitForPoll();
1155
+ return;
1156
+ }
1157
+ this.finish('the strand is sealed — nobody can ever be admitted, so the staged invitation is dead', true);
1158
+ return;
1159
+ case 'dead-invite':
1160
+ // NOTE: accepted tradeoff — dropping a dead invitation does not mark the pass idle,
1161
+ // so the next attempt is one ladder rung away rather than a full poll interval. Kept:
1162
+ // the pass AFTER it finds no member row and no invitation, marks itself idle, and
1163
+ // re-arms flat, so the cost is one extra read per dead credential. Revisit if a
1164
+ // source of dead invitations ever repeats per pass.
1165
+ log('[%s] the staged invitation is dead (expired, cancelled, or consumed elsewhere) — dropping it; '
1166
+ + 'a fresh formation stages a new one: %s', this.deps.label, describeThrown(error));
1167
+ this.deps.pendingInvite?.clear(invite);
1168
+ return;
1169
+ case 'retry':
1170
+ log('[%s] consumeInvite failed — retrying next tick (Invite row not yet replicated here, the cohort '
1171
+ + 'refusing this machine, or a transient write failure): %s', this.deps.label, describeThrown(error));
1172
+ return;
1173
+ }
1174
+ }
1175
+
1176
+ /**
1177
+ * Count an attempted pass that left the invitation staged (whatever stopped it — a
1178
+ * refused or busy write, or a read that threw on a cut-off machine); one that settled
1179
+ * it, or finished, ends the streak. A pass that left it staged on purpose (a rotation
1180
+ * pending whose key this machine cannot read) is no attempt: it neither counts nor ends
1181
+ * the streak. At {@link UNFINISHED_PASSES_BEFORE_ESCALATION} report the PROBABLE blocked
1182
+ * re-join.
1183
+ */
1184
+ private noteAttemptOutcome(): void {
1185
+ if (this.inviteLeftStagedDeliberately) return;
1186
+ if (this.doneFlag || !this.deps.pendingInvite?.get()) {
1187
+ this.unfinishedPasses = 0;
1188
+ return;
1189
+ }
1190
+ this.unfinishedPasses += 1;
1191
+ if (this.unfinishedPasses >= UNFINISHED_PASSES_BEFORE_ESCALATION) {
1192
+ this.reportRejoinBlocked(
1193
+ `${this.unfinishedPasses} membership reconcile passes have left the staged membership invitation `
1194
+ + 'unsettled. Either this party was removed from the strand and the remaining members are refusing its '
1195
+ + 'machines, or the invitation\'s Strand.Invite row has not replicated here yet.'
1196
+ );
1197
+ }
1198
+ }
1199
+
1200
+ /**
1201
+ * Step 1's CONFIRMED trigger: self-revoked with an invitation staged. Reports (once per
1202
+ * re-arm cycle) and answers `true` so the pass carries on — the redemption is attempted
1203
+ * and refused like any other write, and a manager's re-admission lets a later pass finish.
1204
+ * `false` (nothing staged) means step 1 stops the loop as before.
1205
+ */
1206
+ private stagedInviteBlockedBySelfRevocation(): boolean {
1207
+ if (!this.deps.pendingInvite?.get()) return false;
1208
+ this.reportRejoinBlocked(
1209
+ 'this party is revoked from the strand and holds a staged membership invitation it cannot spend: the '
1210
+ + 'remaining members refuse this machine\'s strand writes, so the redemption cannot land.'
1211
+ );
1212
+ return true;
1213
+ }
1214
+
1215
+ /**
1216
+ * ONE `console.warn` and one callback per re-arm cycle, whichever trigger fires first —
1217
+ * see "Reporting a blocked re-join" in the module doc. `cause` is the trigger's own
1218
+ * sentence; the remedy and the loop's posture are the same for both.
1219
+ */
1220
+ private reportRejoinBlocked(cause: string): void {
1221
+ if (this.rejoinBlockedReported) return;
1222
+ this.rejoinBlockedReported = true;
1223
+ console.warn(
1224
+ `[sereus] strand ${this.deps.label}: ${cause} A fresh invitation cannot re-admit a removed party by itself — `
1225
+ + 'a remaining manager must admit this party\'s member key directly (addMemberByManager). The membership '
1226
+ + 'loop keeps retrying quietly and completes the join once a Member row for this party appears.'
1227
+ );
1228
+ this.deps.onRejoinBlocked?.();
1229
+ }
1230
+
1231
+ /**
1232
+ * A redemption only part of which was saved (see "Half-committed join" in the module doc):
1233
+ * ONE visible warning naming both halves, and the staged invitation dropped. The pass is not
1234
+ * marked idle, so the next one runs a ladder rung later and either finds a `Member` row (a
1235
+ * saved one, or a manager's admission) and writes the binding, or idles flat.
1236
+ *
1237
+ * NOTE: the invitation is dropped whichever half was saved. In the observed shape
1238
+ * (`ConsumedInvite` saved, `Member` not) it is spent and a retry could only fail on
1239
+ * `ConsumedInvite`'s primary key. In the opposite shape (`Member` saved, `ConsumedInvite` not)
1240
+ * keeping it would let the already-member arm burn it; dropping it leaves that bearer
1241
+ * credential spendable until it expires — the state the burn arm's accepted tradeoff already
1242
+ * lands in. Not branched on, because telling the shapes apart means parsing the lists, which
1243
+ * are collection ids on the coordinator path but free-form tree labels on the plugin's legacy
1244
+ * path. Revisit if a `Member`-saved half-commit is ever observed, or when
1245
+ * `blocked/strand-half-committed-join-recovery` is decided.
1246
+ */
1247
+ private reportHalfCommittedJoin(failure: HalfCommittedJoin, error: unknown, invite: StrandMembershipInvite): void {
1248
+ console.warn(
1249
+ `[sereus] strand ${this.deps.label}: redeeming the staged membership invitation was only partly saved. `
1250
+ + `Saved: [${failure.saved.join(', ')}]. Not saved: [${failure.unsaved.join(', ')}]. `
1251
+ + 'The invitation is dropped: a saved ConsumedInvite row spends it, so it cannot be redeemed again. '
1252
+ + 'If this party\'s Member row is not among the saved, the party is not a member of the strand and '
1253
+ + 'cannot become one from this invitation — a manager must admit it directly (addMemberByManager). '
1254
+ + 'The membership loop keeps checking and completes the join once a Member row for this party appears.'
1255
+ );
1256
+ log('[%s] half-committed redemption, full error: %o', this.deps.label, error);
1257
+ this.deps.pendingInvite?.clear(invite);
1258
+ // The idle passes that follow are the wait this warning already explained; the escalation's
1259
+ // "waiting on the founder rows to replicate" would be a second, misleading warning.
1260
+ this.idleEscalated = true;
1261
+ }
1262
+
1263
+ /** Decode the party key once; an undecodable key is terminal (nothing can be signed). */
1264
+ private resolveKeyPair(): Ed25519KeyPair | undefined {
1265
+ if (this.keyPair) return this.keyPair;
1266
+ try {
1267
+ this.keyPair = strandMemberKeyPair(this.deps.partyMemberPrivateKey);
1268
+ } catch (error) {
1269
+ this.finish(`the party membership key does not decode — nothing can be signed (${describeThrown(error)})`, true);
1270
+ return undefined;
1271
+ }
1272
+ return this.keyPair;
1273
+ }
1274
+
1275
+ /**
1276
+ * Count a no-member/no-invitation pass; escalate to ONE visible warning at the bound.
1277
+ *
1278
+ * NOTE: an idling loop never gives up — a machine whose party is never admitted keeps
1279
+ * polling for the life of the process, one `Strand.Member` scan per strand per
1280
+ * interval (30 s by default). Negligible at the handful of strands a device runs and
1281
+ * the handful of members a strand has; if a node ever runs strands by the hundred, or
1282
+ * a strand's member set grows large, bound the idle phase (give up after N passes and
1283
+ * surface it) rather than shortening the interval.
1284
+ */
1285
+ private noteIdlePass(): void {
1286
+ this.lastPassIdle = true;
1287
+ this.idlePasses += 1;
1288
+ if (this.idlePasses >= IDLE_PASSES_BEFORE_ESCALATION && !this.idleEscalated) {
1289
+ this.idleEscalated = true;
1290
+ console.warn(
1291
+ `[sereus] strand ${this.deps.label}: ${this.idlePasses} membership reconcile passes and still no `
1292
+ + 'Member row for this party and no staged invitation — a joiner is waiting on the founder rows to '
1293
+ + 'replicate (or on a manager admission). The loop keeps retrying quietly.'
1294
+ );
1295
+ }
1296
+ }
1297
+
1298
+ /**
1299
+ * Stop with a reason — the terminal and done paths' shared exit. `permanent` says whether
1300
+ * a fresh invitation may reopen the loop ("Stops, and re-arming" in the module doc).
1301
+ */
1302
+ private finish(reason: string, permanent: boolean): void {
1303
+ this.halt(`membership reconciliation stopping: ${reason}`, permanent);
1304
+ }
1305
+
1306
+ /** Latch the stop and disarm the timer; a permanent latch sticks even on an already-stopped loop. */
1307
+ private halt(reason: string, permanent: boolean): void {
1308
+ if (permanent) this.permanentlyStopped = true;
1309
+ if (this.stoppedFlag) return;
1310
+ this.stoppedFlag = true;
1311
+ this.clearTimer();
1312
+ log('[%s] membership reconciler stopped%s: %s%s', this.deps.label, this.doneFlag ? ' (done)' : '', reason,
1313
+ permanent ? '' : ' — a fresh invitation or a change to the party\'s machines re-arms it');
1314
+ }
1315
+ }