@serfab/cadre-core 1.20.0 → 1.22.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 (113) hide show
  1. package/README.md +294 -294
  2. package/dist/cadre-node.d.ts +329 -53
  3. package/dist/cadre-node.js +767 -85
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-authorization.d.ts +32 -2
  6. package/dist/control-authorization.js +19 -0
  7. package/dist/control-authorization.js.map +1 -1
  8. package/dist/control-database.d.ts +236 -23
  9. package/dist/control-database.js +601 -178
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-schema.d.ts +3 -3
  12. package/dist/control-schema.js +71 -7
  13. package/dist/control-schema.js.map +1 -1
  14. package/dist/ed25519-key.d.ts +8 -0
  15. package/dist/ed25519-key.js +11 -1
  16. package/dist/ed25519-key.js.map +1 -1
  17. package/dist/index.d.ts +5 -1
  18. package/dist/index.js +13 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/machine-removal.d.ts +51 -1
  21. package/dist/machine-removal.js +42 -1
  22. package/dist/machine-removal.js.map +1 -1
  23. package/dist/membership-connection-gater.d.ts +8 -0
  24. package/dist/membership-connection-gater.js +13 -1
  25. package/dist/membership-connection-gater.js.map +1 -1
  26. package/dist/owner-keys.js +2 -1
  27. package/dist/owner-keys.js.map +1 -1
  28. package/dist/owner-signer.js +3 -4
  29. package/dist/owner-signer.js.map +1 -1
  30. package/dist/peer-authorization.d.ts +14 -2
  31. package/dist/peer-authorization.js +24 -1
  32. package/dist/peer-authorization.js.map +1 -1
  33. package/dist/relay-reservation.js +20 -1
  34. package/dist/relay-reservation.js.map +1 -1
  35. package/dist/sealed-party-key.d.ts +32 -0
  36. package/dist/sealed-party-key.js +162 -0
  37. package/dist/sealed-party-key.js.map +1 -0
  38. package/dist/seed-bootstrap.d.ts +10 -3
  39. package/dist/seed-bootstrap.js +12 -0
  40. package/dist/seed-bootstrap.js.map +1 -1
  41. package/dist/strand-addr-protocol.d.ts +56 -6
  42. package/dist/strand-addr-protocol.js +57 -5
  43. package/dist/strand-addr-protocol.js.map +1 -1
  44. package/dist/strand-app-schema-report.d.ts +6 -3
  45. package/dist/strand-app-schema-report.js +13 -7
  46. package/dist/strand-app-schema-report.js.map +1 -1
  47. package/dist/strand-commit-durability.d.ts +33 -2
  48. package/dist/strand-commit-durability.js +44 -4
  49. package/dist/strand-commit-durability.js.map +1 -1
  50. package/dist/strand-database.d.ts +36 -6
  51. package/dist/strand-database.js +35 -11
  52. package/dist/strand-database.js.map +1 -1
  53. package/dist/strand-instance-manager.d.ts +133 -9
  54. package/dist/strand-instance-manager.js +266 -42
  55. package/dist/strand-instance-manager.js.map +1 -1
  56. package/dist/strand-membership-reconciler.d.ts +250 -51
  57. package/dist/strand-membership-reconciler.js +410 -66
  58. package/dist/strand-membership-reconciler.js.map +1 -1
  59. package/dist/strand-membership-writer.d.ts +7 -0
  60. package/dist/strand-membership-writer.js +9 -0
  61. package/dist/strand-membership-writer.js.map +1 -1
  62. package/dist/strand-party-key-rotation.d.ts +177 -0
  63. package/dist/strand-party-key-rotation.js +340 -0
  64. package/dist/strand-party-key-rotation.js.map +1 -0
  65. package/dist/strand-party-machines.d.ts +111 -0
  66. package/dist/strand-party-machines.js +258 -0
  67. package/dist/strand-party-machines.js.map +1 -0
  68. package/dist/strand-party-peers.d.ts +101 -0
  69. package/dist/strand-party-peers.js +49 -0
  70. package/dist/strand-party-peers.js.map +1 -0
  71. package/dist/strand-peer-redial.d.ts +34 -7
  72. package/dist/strand-peer-redial.js +46 -13
  73. package/dist/strand-peer-redial.js.map +1 -1
  74. package/dist/strand-revocation-enforcer.d.ts +15 -1
  75. package/dist/strand-revocation-enforcer.js +16 -9
  76. package/dist/strand-revocation-enforcer.js.map +1 -1
  77. package/dist/strand-transport-key.js +3 -0
  78. package/dist/strand-transport-key.js.map +1 -1
  79. package/dist/strand-watcher.d.ts +7 -4
  80. package/dist/strand-watcher.js +12 -7
  81. package/dist/strand-watcher.js.map +1 -1
  82. package/dist/types.d.ts +165 -17
  83. package/dist/types.js.map +1 -1
  84. package/package.json +9 -8
  85. package/src/cadre-node.ts +12252 -11528
  86. package/src/control-authorization.ts +41 -1
  87. package/src/control-database.ts +6123 -5594
  88. package/src/control-schema.ts +71 -7
  89. package/src/ed25519-key.ts +12 -1
  90. package/src/index.ts +957 -924
  91. package/src/machine-removal.ts +80 -1
  92. package/src/membership-connection-gater.ts +13 -1
  93. package/src/owner-keys.ts +2 -1
  94. package/src/owner-signer.ts +92 -94
  95. package/src/peer-authorization.ts +27 -3
  96. package/src/relay-reservation.ts +28 -1
  97. package/src/sealed-party-key.ts +190 -0
  98. package/src/seed-bootstrap.ts +17 -3
  99. package/src/strand-addr-protocol.ts +67 -6
  100. package/src/strand-app-schema-report.ts +17 -10
  101. package/src/strand-commit-durability.ts +54 -5
  102. package/src/strand-database.ts +48 -12
  103. package/src/strand-instance-manager.ts +330 -42
  104. package/src/strand-membership-reconciler.ts +1310 -942
  105. package/src/strand-membership-writer.ts +10 -0
  106. package/src/strand-party-key-rotation.ts +436 -0
  107. package/src/strand-party-machines.ts +293 -0
  108. package/src/strand-party-peers.ts +129 -0
  109. package/src/strand-peer-redial.ts +61 -14
  110. package/src/strand-revocation-enforcer.ts +27 -9
  111. package/src/strand-transport-key.ts +3 -0
  112. package/src/strand-watcher.ts +12 -7
  113. package/src/types.ts +3112 -2962
@@ -1,5 +1,6 @@
1
1
  import debug from 'debug';
2
2
  import type { Libp2p, PrivateKey } from '@libp2p/interface';
3
+ import type { ICohortReachability } from '@optimystic/db-core';
3
4
  import { createLibp2pNode, type IRawStorage } from '@optimystic/db-p2p';
4
5
  import { wrapStorageWithCache, disposeStorageCache } from '@serfab/quereus-plugin-sereus';
5
6
  import { StrandDatabase, type StrandDatabaseOffline } from './strand-database.js';
@@ -20,6 +21,8 @@ import {
20
21
  type StrandMembershipReconciliationConfig
21
22
  } from './strand-membership-reconciler.js';
22
23
  import { removeMemberPeer } from './strand-membership-writer.js';
24
+ import type { PartyStrandPeer, PartyStrandPeerSource } from './strand-party-peers.js';
25
+ import { StrandPartyMachines, cohortGateWaitingForMachines, watchRemovedMachinesInSeed } from './strand-party-machines.js';
23
26
  import { strandMemberKeyPair } from './strand-member-key.js';
24
27
  import { assertSchemaSignature } from './schema-verification.js';
25
28
  import { assertStrandScopeKey } from './storage-scope.js';
@@ -249,6 +252,42 @@ export interface StartStrandConfig {
249
252
  */
250
253
  membershipReconciliation?: StrandMembershipReconciliationConfig;
251
254
 
255
+ /**
256
+ * The party's machines in THIS strand, as the control database records them
257
+ * (`strand-party-peers.ts`): `CadreNode.launchStrand` wires it for every strand, open or
258
+ * closed, party key or not. Bring-up publishes this machine's own `StrandPeer` row through it
259
+ * in the background, once the strand's libp2p node exists (launch and hibernation resume
260
+ * alike, since the row is this machine's statement of a peer id that is the same across
261
+ * both). On a closed strand the membership reconciler reads the party's other machines
262
+ * through it to bind them (`strand-membership-reconciler.ts` → "Binding the party's other
263
+ * machines"); on a node offering offline mode ({@link offline}) the queue's gate reads them
264
+ * as the machines a queued transaction waits for (`strand-party-machines.ts`). An open
265
+ * strand's row serves only that wait. Retained with the launch config.
266
+ */
267
+ partyPeers?: PartyStrandPeerSource;
268
+
269
+ /**
270
+ * Called when the membership reconciler finds the party's PENDING membership key seated as a
271
+ * `Strand.Member` in this strand (`strand-membership-reconciler.ts` → "Redeeming under the
272
+ * pending key"): it redeemed the host's fresh invitation under that key, or another party's
273
+ * manager admitted the key by hand. `CadreNode` wires it to its party key rotation driver,
274
+ * which then finishes the move on an owner machine the key is sealed to
275
+ * (`strand-party-key-rotation.ts`). Called on every pass that sees the seat until the control
276
+ * record is swapped, so the receiver refuses cheaply when it cannot drive. Retained with the
277
+ * launch config.
278
+ */
279
+ onPartyKeySeated?: (strandId: string) => void;
280
+
281
+ /**
282
+ * Called when a read of the party's machines finds one removed from the cadre in
283
+ * {@link bootstrapNodes}, on a node tracking them ({@link offline} with {@link partyPeers}), and
284
+ * once per such machine ({@link watchRemovedMachinesInSeed}). The node refuses that peer but
285
+ * cannot drop it from its frozen seed, so its queue stays held until a new node is built from a
286
+ * fresh seed: `CadreNode` quiesces and resumes the runtime. May be called during a build or a
287
+ * rebuild, so the receiver serializes. Retained with the launch config.
288
+ */
289
+ onRemovedMachineInSeed?: (strandId: string) => void;
290
+
252
291
  /**
253
292
  * Called when THIS node's own peer id turns up in the strand's revoked set —
254
293
  * this node's party was removed from the closed strand, or left it. Fires once
@@ -369,6 +408,12 @@ export interface ResumeStrandOverrides {
369
408
  * {@link StartStrandConfig} does — it retains the last value; see `resumeStrand`.
370
409
  */
371
410
  servingMachines?: number;
411
+ /**
412
+ * The party's membership key for a closed strand as the control record names it now
413
+ * (`StrandPartyKey.PrivateKey`), re-read by `CadreNode.resumeStrandRuntime` because a party
414
+ * key rotation can finish while the strand hibernates. Omitted, the retained key stands.
415
+ */
416
+ partyMemberPrivateKey?: string;
372
417
  }
373
418
 
374
419
  /** A {@link StrandInstanceManager.resumeStrand} or {@link StrandInstanceManager.quiesceStrand} of one strand. */
@@ -534,6 +579,21 @@ export class StrandInstanceManager {
534
579
  * nobody and a resume redials over the new node.
535
580
  */
536
581
  private peerRedials: Map<string, StrandPeerRedial> = new Map();
582
+ /**
583
+ * The party's other machines known to hold each strand (`strand-party-machines.ts`), keyed
584
+ * by strand id, on a node offering offline mode for a launch with a party-machine seam. Same
585
+ * lifecycle as {@link peerRedials}: built in `buildStrandRuntime` before the libp2p node (the
586
+ * node's redial loop, the database's offline gate and its commit record read it), stopped and dropped in
587
+ * `releaseRuntime`, so a resume reads the control database afresh. Refreshed by
588
+ * {@link notifyPartyPeersChanged}.
589
+ */
590
+ private partyMachines: Map<string, StrandPartyMachines> = new Map();
591
+ /**
592
+ * Per strand, the removed machines' peer ids a rebuild was asked for
593
+ * ({@link watchRemovedMachinesInSeed}). Outlives a runtime, which is its point: it is what stops
594
+ * a rebuilt node whose seed still names one from asking again. Dropped with the launch config.
595
+ */
596
+ private seedRemovalsAnnounced: Map<string, Set<string>> = new Map();
537
597
  /**
538
598
  * The resolved (cache-wrapped) raw storage per strand id — the instance's OWN
539
599
  * store, resolved once in `startStrand` and held until `stopStrand` disposes it.
@@ -713,6 +773,7 @@ export class StrandInstanceManager {
713
773
  // reads both, and a config without an instance would strand the config.
714
774
  this.instances.delete(strandId);
715
775
  this.launchConfigs.delete(strandId);
776
+ this.seedRemovalsAnnounced.delete(strandId);
716
777
  // The cleanup above remembered the half-built database's queue; an untracked strand keeps none.
717
778
  this.closedQueues.delete(strandId);
718
779
  // The store this launch resolved goes with it: nothing owns it any more, and a
@@ -842,7 +903,11 @@ export class StrandInstanceManager {
842
903
  // therefore means "no transport right now", which the enforcer
843
904
  // treats as "nothing to tear down".
844
905
  getNetwork: () => instance.libp2pNode,
845
- onSelfRevoked: () => config.onSelfRevoked?.(strandId)
906
+ onSelfRevoked: () => config.onSelfRevoked?.(strandId),
907
+ // The membership reconciler below stops on a self-revocation ("stop rather than
908
+ // fight"); a sibling binding this machine back in is what restarts it. Looked up
909
+ // at call time: the reconciler is built after the enforcer, and dropped with it.
910
+ onSelfRestored: () => this.rearmMembershipReconciler(strandId, 'this machine is no longer revoked')
846
911
  }, config.revocationEnforcement)
847
912
  : undefined;
848
913
  if (revocationEnforcer) {
@@ -867,12 +932,37 @@ export class StrandInstanceManager {
867
932
  log('strand %s: change notifications on', strandId);
868
933
  }
869
934
 
935
+ // The party's other machines holding this strand, for the offline queue's gate, each commit's
936
+ // durability record and the redial loop below (`strand-party-machines.ts`). Only a node offering offline mode pays
937
+ // for the control reads, which leaves out the always-on programs. Built BEFORE the libp2p
938
+ // node, and its first read started now, so a queue restored at launch waits on rows that
939
+ // were asked for before the node existed. Registered in the map at once, so the failure
940
+ // rollback (releaseRuntime) stops it like every other runtime component.
941
+ const partyMachines = config.offline && config.partyPeers
942
+ ? new StrandPartyMachines({ label: strandId, source: config.partyPeers })
943
+ : undefined;
944
+ if (partyMachines) {
945
+ this.partyMachines.set(strandId, partyMachines);
946
+ this.watchSeedForRemovedMachines(strandId, config, partyMachines);
947
+ partyMachines.refresh();
948
+ }
949
+
870
950
  try {
871
951
  let t0 = performance.now();
872
952
  const node = await createLibp2pNode({
873
953
  port: 0, // Random port
874
954
  bootstrapNodes: config.bootstrapNodes ?? [],
875
955
  networkName,
956
+ // A machine removed from the party stops counting as a member, ahead of whatever this node
957
+ // remembers of it, so a queue stops waiting for it. Read live, and everyone else takes the
958
+ // path they would with no predicate.
959
+ //
960
+ // NOTE: a machine can state any id in its own `StrandPeer` row before its removal, and that
961
+ // id is then refused here, leaving that peer out of this node's cohorts. One id per
962
+ // (strand, machine), in a row a machine the party trusted then signed, and an id a live
963
+ // sibling recorded is never read as removed. If a peer is ever seen left out of cohorts
964
+ // this way, the row needs a proof that the id it states is the machine's own.
965
+ ...(partyMachines && { isNetworkMember: (peerId: string) => !partyMachines.removed().has(peerId) }),
876
966
  storage: strandStorage,
877
967
  fretProfile: config.profile === 'storage' ? 'core' : 'edge',
878
968
  relay: relayServer.enabled,
@@ -969,6 +1059,17 @@ export class StrandInstanceManager {
969
1059
 
970
1060
  instance.libp2pNode = node;
971
1061
 
1062
+ // This machine's statement of its peer id in the strand, for the party's control
1063
+ // database (`StrandPeer`): a background write that never fails or delays the launch.
1064
+ // The seam defers it while a write could fork the party and retries it on cohort
1065
+ // growth and from every membership reconciler pass, so a refusal here is not final.
1066
+ // Written for open strands too: their row is what a sibling's offline queue waits for.
1067
+ if (config.partyPeers) {
1068
+ void config.partyPeers.publishOwn(node.peerId.toString()).catch((error) => {
1069
+ log('Strand %s: publishing this machine\'s StrandPeer row threw (retried later): %o', strandId, error);
1070
+ });
1071
+ }
1072
+
972
1073
  // One reservation supervisor PER RELAY, started now so the first attempts
973
1074
  // overlap the database bring-up below (the relay is never in a strand's
974
1075
  // Optimystic cohort — its protocol ids are namespaced `/optimystic/strand-<id>/…`
@@ -981,12 +1082,20 @@ export class StrandInstanceManager {
981
1082
  // declared link gives a relayed dial — what reconnects two restarted phones on a slow
982
1083
  // link, where FRET's own redial cannot (`strand-peer-redial.ts`). The relays are
983
1084
  // excluded by peer id: the node is connected to them throughout, and they are no member.
1085
+ // The party's machines holding the strand are dialed too, at the addresses the
1086
+ // strand-addr RPC put in the address book, so a sibling's blocked port that opens is
1087
+ // reached without a connection ever having been made to it.
1088
+ // A machine removed from the party is revoked to this loop on an open strand too: neither a
1089
+ // peer to dial nor a connection that stands in for reaching the party's other machines.
984
1090
  this.peerRedials.set(strandId, superviseStrandPeerRedial({
985
1091
  label: strandId,
986
1092
  node,
987
1093
  seed: config.bootstrapNodes ?? [],
988
1094
  excluded: new Set(groupAddrsByPeerId([...relayDialAddrs]).keys()),
989
- ...(revocationEnforcer && { isRevoked: (peerId: string) => revocationEnforcer.isRevoked(peerId) })
1095
+ ...((revocationEnforcer || partyMachines) && {
1096
+ isRevoked: (peerId: string) => revocationEnforcer?.isRevoked(peerId) === true || partyMachines?.removed().has(peerId) === true
1097
+ }),
1098
+ ...(partyMachines && { partyMachines: () => partyMachines.machines().map((machine) => machine.strandPeerId) })
990
1099
  }, strandRedialTimings(config.network?.linkRoundTripMs)));
991
1100
 
992
1101
  const databaseBuild = await this.buildStrandDatabase(instance, config, node);
@@ -1012,30 +1121,7 @@ export class StrandInstanceManager {
1012
1121
  // (`bindFounderPeer`), so the first pass finds them and stops. Armed AFTER the database
1013
1122
  // phase above, so a gated or deferred launch always has a reconciler registered by the
1014
1123
  // time it can publish.
1015
- if (config.strandRow.Type === 'c' && config.partyMemberPrivateKey
1016
- && config.membershipReconciliation?.enabled !== false) {
1017
- const reconciler = new StrandMembershipReconciler({
1018
- label: strandId,
1019
- partyMemberPrivateKey: config.partyMemberPrivateKey,
1020
- // Read per pass, never captured — same lifecycle argument as the
1021
- // enforcer's getNetwork: quiesce drops both handles.
1022
- getDatabase: () => instance.database?.getDatabase(),
1023
- getOwnPeerId: () => instance.libp2pNode?.peerId.toString(),
1024
- pendingInvite: config.pendingMembershipInvite,
1025
- // The enforcer's CURRENT snapshot view of this node's own peer id — the
1026
- // reconciler stops rather than fight a self-revocation. Absent when the
1027
- // gate is disarmed (fail-open: the loop just runs).
1028
- isSelfRevoked: revocationEnforcer
1029
- ? () => {
1030
- const ownPeerId = instance.libp2pNode?.peerId.toString();
1031
- return ownPeerId !== undefined && revocationEnforcer.isRevoked(ownPeerId);
1032
- }
1033
- : undefined,
1034
- onRejoinBlocked: () => config.onRejoinBlocked?.(strandId)
1035
- }, config.membershipReconciliation);
1036
- this.membershipReconcilers.set(strandId, reconciler);
1037
- reconciler.start();
1038
- }
1124
+ this.armMembershipReconciler(instance, config, revocationEnforcer);
1039
1125
 
1040
1126
  // Peer-join block catch-up: push this strand's own blocks to each newly
1041
1127
  // connected peer, so a machine that joined after blocks were committed
@@ -1142,6 +1228,7 @@ export class StrandInstanceManager {
1142
1228
  // a partially-initialized db), and the app only ever sees `instance.database` once this
1143
1229
  // machine is allowed to write to the strand.
1144
1230
  let t0 = performance.now();
1231
+ const partyMachines = this.partyMachines.get(strandId);
1145
1232
  const strandDb = new StrandDatabase({
1146
1233
  strandId,
1147
1234
  sAppConfig: config.sAppConfig,
@@ -1161,8 +1248,9 @@ export class StrandInstanceManager {
1161
1248
  bindFounderPeer: config.membershipReconciliation?.enabled !== false,
1162
1249
  onCommitDurability: config.onCommitDurability,
1163
1250
  onCommitHeld: config.onCommitHeld,
1164
- offline: this.offlineDatabaseConfig(strandId, config.offline),
1165
- appSchema: config.appSchema
1251
+ offline: this.offlineDatabaseConfig(strandId, config.offline, this.offlineCohortGate(strandId, node)),
1252
+ appSchema: config.appSchema,
1253
+ ...(partyMachines && { partyMachines: () => partyMachines.machines() })
1166
1254
  });
1167
1255
  const storageRepo = node.storageRepo;
1168
1256
  const gate = new StrandFirstSyncGate({
@@ -1238,10 +1326,14 @@ export class StrandInstanceManager {
1238
1326
 
1239
1327
  /**
1240
1328
  * One build's {@link StrandDatabaseOffline}: the strand's journal, which the database resolves as
1241
- * it initializes (a throw or rejection fails the build), and the strand's mode, which it reads each
1242
- * time it applies it.
1329
+ * it initializes (a throw or rejection fails the build), the strand's mode, which it reads each
1330
+ * time it applies it, and the gate its queue asks, when one could be built.
1243
1331
  */
1244
- private offlineDatabaseConfig(strandId: string, offline: StartStrandConfig['offline']): StrandDatabaseOffline | undefined {
1332
+ private offlineDatabaseConfig(
1333
+ strandId: string,
1334
+ offline: StartStrandConfig['offline'],
1335
+ cohortReachability: ICohortReachability | undefined
1336
+ ): StrandDatabaseOffline | undefined {
1245
1337
  if (!offline) {
1246
1338
  return undefined;
1247
1339
  }
@@ -1249,10 +1341,64 @@ export class StrandInstanceManager {
1249
1341
  return {
1250
1342
  ...listeners,
1251
1343
  journal: () => journal(strandId),
1252
- mode: () => this.currentOfflineMode(strandId, offline)
1344
+ mode: () => this.currentOfflineMode(strandId, offline),
1345
+ ...(cohortReachability && { cohortReachability })
1253
1346
  };
1254
1347
  }
1255
1348
 
1349
+ /**
1350
+ * The gate a build's offline queue asks: the node's own, closed also while the party has
1351
+ * machines holding the strand that this node is alone in a cohort without
1352
+ * (`cohortGateWaitingForMachines`). None when the launch tracks no party machines (no offline
1353
+ * mode, or no party-machine seam), or when the node carries no gate or key network to compose
1354
+ * over; the queue then asks the node's own gate, as before.
1355
+ */
1356
+ private offlineCohortGate(strandId: string, node: Libp2pNodeWithRepo): ICohortReachability | undefined {
1357
+ const partyMachines = this.partyMachines.get(strandId);
1358
+ if (!partyMachines) {
1359
+ return undefined;
1360
+ }
1361
+ if (!node.cohortReachability || !node.keyNetwork) {
1362
+ log('Strand %s: its node carries no %s, so its offline queue does not wait for the party\'s machines',
1363
+ strandId, node.cohortReachability ? 'key network' : 'reachability gate');
1364
+ return undefined;
1365
+ }
1366
+ return cohortGateWaitingForMachines(node.cohortReachability, node.keyNetwork, node.peerId.toString(), partyMachines);
1367
+ }
1368
+
1369
+ /** Ask the launcher for a rebuild when a machine removed from the party is in this runtime's seed. */
1370
+ private watchSeedForRemovedMachines(strandId: string, config: StartStrandConfig, machines: StrandPartyMachines): void {
1371
+ const { onRemovedMachineInSeed } = config;
1372
+ if (!onRemovedMachineInSeed) {
1373
+ return;
1374
+ }
1375
+ let announced = this.seedRemovalsAnnounced.get(strandId);
1376
+ if (!announced) {
1377
+ announced = new Set();
1378
+ this.seedRemovalsAnnounced.set(strandId, announced);
1379
+ }
1380
+ const seedPeers = new Set(groupAddrsByPeerId(config.bootstrapNodes ?? []).keys());
1381
+ watchRemovedMachinesInSeed(machines, seedPeers, announced, () => onRemovedMachineInSeed(strandId), strandId);
1382
+ }
1383
+
1384
+ /**
1385
+ * The party's other machines known to hold `strandId` with no open connection from its strand
1386
+ * node: what an offline queue reporting `waitingFor: 'cohort'` may be waiting for
1387
+ * (`docs/strands.md` → "Waiting for the party's own machines"). Empty for a strand not tracked
1388
+ * or not running here, and on a launch that tracks no party machines.
1389
+ */
1390
+ unreachedPartyMachines(strandId: string): readonly PartyStrandPeer[] {
1391
+ const partyMachines = this.partyMachines.get(strandId);
1392
+ const node = this.instances.get(strandId)?.libp2pNode;
1393
+ if (!partyMachines || !node) {
1394
+ return [];
1395
+ }
1396
+ const connected = new Set(node.getConnections()
1397
+ .filter((connection) => connection.status === 'open')
1398
+ .map((connection) => connection.remotePeer.toString()));
1399
+ return partyMachines.machines().filter((machine) => !connected.has(machine.strandPeerId));
1400
+ }
1401
+
1256
1402
  /**
1257
1403
  * Whether this strand's raw store holds no block. False for a store that cannot list its
1258
1404
  * blocks, or whose listing fails, so such a launch probes at once.
@@ -1384,6 +1530,9 @@ export class StrandInstanceManager {
1384
1530
  }
1385
1531
  this.peerRedials.get(instance.strandId)?.stop();
1386
1532
  this.peerRedials.delete(instance.strandId);
1533
+ // The party-machine tracker with the loop and gate that read it; a resume reads afresh.
1534
+ this.partyMachines.get(instance.strandId)?.stop();
1535
+ this.partyMachines.delete(instance.strandId);
1387
1536
  // Backfill next — before the database closes and the libp2p node stops — so
1388
1537
  // no NEW catch-up push is issued against a torn-down transport. A push already
1389
1538
  // in flight is not awaited; it fails into the module's own per-chunk catch.
@@ -1541,12 +1690,146 @@ export class StrandInstanceManager {
1541
1690
  * loop's own serialized chain and never rejects.
1542
1691
  */
1543
1692
  notifyMembershipInviteStaged(strandId: string): void {
1693
+ if (!this.rearmMembershipReconciler(strandId, 'a fresh invitation')) {
1694
+ log('notifyMembershipInviteStaged: strand %s has no armed membership reconciler — bring-up will find the invitation', strandId);
1695
+ }
1696
+ }
1697
+
1698
+ /**
1699
+ * The party's machines changed in the control database — a `StrandPeer` row, a `CadrePeer`
1700
+ * row or a tombstone arrived or was written here (`CadreNode`'s watch on those tables,
1701
+ * coalesced). Re-arm every armed membership reconciler, so a sibling's row is bound, or a
1702
+ * removed machine's binding cleared, within the watch's window rather than at the next
1703
+ * resume, and read every strand's party machines again, so an offline queue waits for a
1704
+ * machine as soon as its row arrives and stops waiting for one as soon as it is removed.
1705
+ * Table events carry no row keys, so every strand's loop and tracker is woken; a loop with
1706
+ * nothing to do confirms and stops again. Returns at once; each pass runs on its loop's own
1707
+ * serialized chain and never rejects.
1708
+ */
1709
+ notifyPartyPeersChanged(): void {
1710
+ for (const strandId of this.membershipReconcilers.keys()) {
1711
+ this.rearmMembershipReconciler(strandId, 'a change to the party\'s machines');
1712
+ }
1713
+ for (const partyMachines of this.partyMachines.values()) {
1714
+ partyMachines.refresh();
1715
+ }
1716
+ }
1717
+
1718
+ /** Re-arm `strandId`'s membership reconciler for `cause`; `false` when none is armed. */
1719
+ private rearmMembershipReconciler(strandId: string, cause: string): boolean {
1544
1720
  const reconciler = this.membershipReconcilers.get(strandId);
1545
1721
  if (!reconciler) {
1546
- log('notifyMembershipInviteStaged: strand %s has no armed membership reconciler — bring-up will find the invitation', strandId);
1722
+ return false;
1723
+ }
1724
+ void reconciler.rearm(cause);
1725
+ return true;
1726
+ }
1727
+
1728
+ /**
1729
+ * Build and start `instance`'s membership reconciler from `config`, for a closed strand that
1730
+ * carries the party's own membership key with the loop enabled; nothing otherwise. Called by
1731
+ * {@link buildStrandRuntime} after the database phase, and by {@link rekeyParty} over a
1732
+ * running instance with the re-keyed config. Every dependency is read per pass, never
1733
+ * captured, so the loop follows the instance through quiesce and resume.
1734
+ */
1735
+ private armMembershipReconciler(
1736
+ instance: StrandInstance,
1737
+ config: StartStrandConfig,
1738
+ revocationEnforcer: StrandRevocationEnforcer | undefined
1739
+ ): void {
1740
+ if (config.strandRow.Type !== 'c' || !config.partyMemberPrivateKey || config.membershipReconciliation?.enabled === false) {
1547
1741
  return;
1548
1742
  }
1549
- void reconciler.rearm();
1743
+ const strandId = instance.strandId;
1744
+ const reconciler = new StrandMembershipReconciler({
1745
+ label: strandId,
1746
+ partyMemberPrivateKey: config.partyMemberPrivateKey,
1747
+ // Read per pass, never captured — same lifecycle argument as the
1748
+ // enforcer's getNetwork: quiesce drops both handles.
1749
+ getDatabase: () => instance.database?.getDatabase(),
1750
+ getOwnPeerId: () => instance.libp2pNode?.peerId.toString(),
1751
+ pendingInvite: config.pendingMembershipInvite,
1752
+ partyPeers: config.partyPeers,
1753
+ // The enforcer's CURRENT snapshot view of this node's own peer id — the
1754
+ // reconciler stops rather than fight a self-revocation. Absent when the
1755
+ // gate is disarmed (fail-open: the loop just runs).
1756
+ isSelfRevoked: revocationEnforcer
1757
+ ? () => {
1758
+ const ownPeerId = instance.libp2pNode?.peerId.toString();
1759
+ return ownPeerId !== undefined && revocationEnforcer.isRevoked(ownPeerId);
1760
+ }
1761
+ : undefined,
1762
+ onRejoinBlocked: () => config.onRejoinBlocked?.(strandId),
1763
+ onPendingKeySeated: () => config.onPartyKeySeated?.(strandId)
1764
+ }, config.membershipReconciliation);
1765
+ this.membershipReconcilers.set(strandId, reconciler);
1766
+ reconciler.start();
1767
+ }
1768
+
1769
+ /**
1770
+ * Move a tracked closed strand onto `partyMemberPrivateKey`, the party's membership key the
1771
+ * control record now names (a party key rotation finished here or replicated from the machine
1772
+ * that finished it: `strand-party-key-rotation.ts`). The retained launch config is replaced
1773
+ * with a fresh object carrying the key ({@link foundExistingStrand}'s idiom: the caller's
1774
+ * config object is not ours to rewrite), so every later resume rebuilds under it, and the
1775
+ * founder bootstrap a resume re-runs derives from it (insert-if-absent; the strand's rows
1776
+ * already hold the new key as member and manager, so it writes nothing). The running
1777
+ * instance's membership reconciler, which signs with the key, is stopped and awaited, then
1778
+ * rebuilt and started over the re-keyed config, so its next pass binds under the new key.
1779
+ *
1780
+ * A tracked instance with no party key before (a storage replica launched before the party's
1781
+ * row reached this node) is keyed the same way and gains its reconciler now rather than at its
1782
+ * next resume. A build in flight is waited out first, so the reconciler it arms is the one
1783
+ * replaced here rather than a second one beside it; a key the retained config already names
1784
+ * is answered before that wait, since the party key watch asks this for every tracked closed
1785
+ * strand on every change to the key tables.
1786
+ *
1787
+ * @returns `rekeyed` when a running instance's reconciler was rebuilt; `retained` when only the
1788
+ * config changed (a hibernating instance, or one with the loop disabled); `unchanged` when
1789
+ * the key already matched or the strand is open; `untracked` when the strand is not here.
1790
+ */
1791
+ async rekeyParty(strandId: string, partyMemberPrivateKey: string): Promise<'rekeyed' | 'retained' | 'unchanged' | 'untracked'> {
1792
+ const before = this.rekeyNeeded(strandId, partyMemberPrivateKey);
1793
+ if (before !== 'needed') {
1794
+ return before;
1795
+ }
1796
+ await this.settleRuntimeBuilds(strandId);
1797
+ const after = this.rekeyNeeded(strandId, partyMemberPrivateKey);
1798
+ if (after !== 'needed') {
1799
+ return after;
1800
+ }
1801
+ const instance = this.instances.get(strandId)!;
1802
+ const config = this.launchConfigs.get(strandId)!;
1803
+ const rekeyed: StartStrandConfig = { ...config, partyMemberPrivateKey };
1804
+ this.launchConfigs.set(strandId, rekeyed);
1805
+ const reconciler = this.membershipReconcilers.get(strandId);
1806
+ if (reconciler) {
1807
+ reconciler.stop();
1808
+ await reconciler.settle();
1809
+ this.membershipReconcilers.delete(strandId);
1810
+ }
1811
+ if (!instance.libp2pNode || this.isQuiescing(strandId)) {
1812
+ log('rekeyParty: strand %s has no live runtime; the re-keyed config waits for its resume', strandId);
1813
+ return 'retained';
1814
+ }
1815
+ this.armMembershipReconciler(instance, rekeyed, this.revocationEnforcers.get(strandId));
1816
+ const armed = this.membershipReconcilers.has(strandId);
1817
+ log('rekeyParty: strand %s re-keyed (%s)', strandId, armed ? 'membership reconciler rebuilt' : 'membership reconciliation disabled');
1818
+ return armed ? 'rekeyed' : 'retained';
1819
+ }
1820
+
1821
+ /** Whether {@link rekeyParty} has anything to do for `strandId`: the retained config is a closed strand's and names another key. */
1822
+ private rekeyNeeded(strandId: string, partyMemberPrivateKey: string): 'needed' | 'unchanged' | 'untracked' {
1823
+ const config = this.launchConfigs.get(strandId);
1824
+ if (!config || !this.instances.has(strandId)) {
1825
+ return 'untracked';
1826
+ }
1827
+ return config.strandRow.Type !== 'c' || config.partyMemberPrivateKey === partyMemberPrivateKey ? 'unchanged' : 'needed';
1828
+ }
1829
+
1830
+ /** The ids of every tracked closed strand, running or hibernating. */
1831
+ trackedClosedStrandIds(): string[] {
1832
+ return [...this.launchConfigs].filter(([, config]) => config.strandRow.Type === 'c').map(([strandId]) => strandId);
1550
1833
  }
1551
1834
 
1552
1835
  /**
@@ -1566,13 +1849,16 @@ export class StrandInstanceManager {
1566
1849
  * and its in-flight pass awaited — FIRST, so a pass that was already past its
1567
1850
  * own stopped check cannot re-register the binding this is about to clear.
1568
1851
  *
1569
- * NOTE: deliberately NOT handled here (or anywhere yet): clearing the bindings
1570
- * of a machine removed from the CADRE at the control layer, or of a party's
1571
- * OTHER machines when the party unpublishes — the party still holds the key on
1572
- * every surviving machine and can clear from any of them, and the stale rows
1573
- * grant nothing while admission is deny-list only. Revisit when
1574
- * `feat-strand-member-allowlist-admission` lands and a stale binding starts
1575
- * granting admission rather than merely mis-crediting diversity.
1852
+ * A machine removed from the CADRE at the control layer is not cleared here either: the
1853
+ * party replaces its key in the strand instead (`strand-party-key-rotation.ts`), which
1854
+ * leaves that machine's binding an orphan the revoked-peer gate denies, and the membership
1855
+ * reconciler clears what a lagging sibling wrote under the new key.
1856
+ *
1857
+ * NOTE: deliberately NOT handled here (or anywhere yet): clearing the bindings of a party's
1858
+ * OTHER machines when the party unpublishes — the party still holds the key on every
1859
+ * surviving machine and can clear from any of them, and the stale rows grant nothing while
1860
+ * admission is deny-list only. Revisit when `feat-strand-member-allowlist-admission` lands
1861
+ * and a stale binding starts granting admission rather than merely mis-crediting diversity.
1576
1862
  */
1577
1863
  async clearOwnMemberPeerBinding(strandId: string): Promise<void> {
1578
1864
  const instance = this.instances.get(strandId);
@@ -1755,7 +2041,8 @@ export class StrandInstanceManager {
1755
2041
  // count — a strand whose member rows became unreadable — this merge must gain an explicit
1756
2042
  // clear rather than silently declaring a stale number over a serving set it can no longer
1757
2043
  // see. Same applies to `bootstrapNodes` above, where a stale seed is harmless.
1758
- servingMachines: overrides?.servingMachines ?? launchConfig.servingMachines
2044
+ servingMachines: overrides?.servingMachines ?? launchConfig.servingMachines,
2045
+ partyMemberPrivateKey: overrides?.partyMemberPrivateKey ?? launchConfig.partyMemberPrivateKey
1759
2046
  };
1760
2047
  this.launchConfigs.set(strandId, resumeConfig);
1761
2048
 
@@ -2186,6 +2473,7 @@ export class StrandInstanceManager {
2186
2473
  instance.status = 'stopped';
2187
2474
  this.instances.delete(strandId);
2188
2475
  this.launchConfigs.delete(strandId);
2476
+ this.seedRemovalsAnnounced.delete(strandId);
2189
2477
  this.closedQueues.delete(strandId);
2190
2478
  // Storage is released only here — NOT in releaseRuntime, which a quiesce shares.
2191
2479
  await this.disposeStrandStorage(strandId);