@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
@@ -7,6 +7,7 @@ import { strandNetworkStatePersistence } from './strand-network-state.js';
7
7
  import { StrandRevocationEnforcer, createRevocationConnectionGater, readStrandRevocationRows } from './strand-revocation-enforcer.js';
8
8
  import { StrandMembershipReconciler } from './strand-membership-reconciler.js';
9
9
  import { removeMemberPeer } from './strand-membership-writer.js';
10
+ import { StrandPartyMachines, cohortGateWaitingForMachines, watchRemovedMachinesInSeed } from './strand-party-machines.js';
10
11
  import { strandMemberKeyPair } from './strand-member-key.js';
11
12
  import { assertSchemaSignature } from './schema-verification.js';
12
13
  import { assertStrandScopeKey } from './storage-scope.js';
@@ -211,6 +212,21 @@ export class StrandInstanceManager {
211
212
  * nobody and a resume redials over the new node.
212
213
  */
213
214
  this.peerRedials = new Map();
215
+ /**
216
+ * The party's other machines known to hold each strand (`strand-party-machines.ts`), keyed
217
+ * by strand id, on a node offering offline mode for a launch with a party-machine seam. Same
218
+ * lifecycle as {@link peerRedials}: built in `buildStrandRuntime` before the libp2p node (the
219
+ * node's redial loop, the database's offline gate and its commit record read it), stopped and dropped in
220
+ * `releaseRuntime`, so a resume reads the control database afresh. Refreshed by
221
+ * {@link notifyPartyPeersChanged}.
222
+ */
223
+ this.partyMachines = new Map();
224
+ /**
225
+ * Per strand, the removed machines' peer ids a rebuild was asked for
226
+ * ({@link watchRemovedMachinesInSeed}). Outlives a runtime, which is its point: it is what stops
227
+ * a rebuilt node whose seed still names one from asking again. Dropped with the launch config.
228
+ */
229
+ this.seedRemovalsAnnounced = new Map();
214
230
  /**
215
231
  * The resolved (cache-wrapped) raw storage per strand id — the instance's OWN
216
232
  * store, resolved once in `startStrand` and held until `stopStrand` disposes it.
@@ -375,6 +391,7 @@ export class StrandInstanceManager {
375
391
  // reads both, and a config without an instance would strand the config.
376
392
  this.instances.delete(strandId);
377
393
  this.launchConfigs.delete(strandId);
394
+ this.seedRemovalsAnnounced.delete(strandId);
378
395
  // The cleanup above remembered the half-built database's queue; an untracked strand keeps none.
379
396
  this.closedQueues.delete(strandId);
380
397
  // The store this launch resolved goes with it: nothing owns it any more, and a
@@ -495,7 +512,11 @@ export class StrandInstanceManager {
495
512
  // therefore means "no transport right now", which the enforcer
496
513
  // treats as "nothing to tear down".
497
514
  getNetwork: () => instance.libp2pNode,
498
- onSelfRevoked: () => config.onSelfRevoked?.(strandId)
515
+ onSelfRevoked: () => config.onSelfRevoked?.(strandId),
516
+ // The membership reconciler below stops on a self-revocation ("stop rather than
517
+ // fight"); a sibling binding this machine back in is what restarts it. Looked up
518
+ // at call time: the reconciler is built after the enforcer, and dropped with it.
519
+ onSelfRestored: () => this.rearmMembershipReconciler(strandId, 'this machine is no longer revoked')
499
520
  }, config.revocationEnforcement)
500
521
  : undefined;
501
522
  if (revocationEnforcer) {
@@ -516,12 +537,36 @@ export class StrandInstanceManager {
516
537
  if (reactivityOption.cohortTopic) {
517
538
  log('strand %s: change notifications on', strandId);
518
539
  }
540
+ // The party's other machines holding this strand, for the offline queue's gate, each commit's
541
+ // durability record and the redial loop below (`strand-party-machines.ts`). Only a node offering offline mode pays
542
+ // for the control reads, which leaves out the always-on programs. Built BEFORE the libp2p
543
+ // node, and its first read started now, so a queue restored at launch waits on rows that
544
+ // were asked for before the node existed. Registered in the map at once, so the failure
545
+ // rollback (releaseRuntime) stops it like every other runtime component.
546
+ const partyMachines = config.offline && config.partyPeers
547
+ ? new StrandPartyMachines({ label: strandId, source: config.partyPeers })
548
+ : undefined;
549
+ if (partyMachines) {
550
+ this.partyMachines.set(strandId, partyMachines);
551
+ this.watchSeedForRemovedMachines(strandId, config, partyMachines);
552
+ partyMachines.refresh();
553
+ }
519
554
  try {
520
555
  let t0 = performance.now();
521
556
  const node = await createLibp2pNode({
522
557
  port: 0, // Random port
523
558
  bootstrapNodes: config.bootstrapNodes ?? [],
524
559
  networkName,
560
+ // A machine removed from the party stops counting as a member, ahead of whatever this node
561
+ // remembers of it, so a queue stops waiting for it. Read live, and everyone else takes the
562
+ // path they would with no predicate.
563
+ //
564
+ // NOTE: a machine can state any id in its own `StrandPeer` row before its removal, and that
565
+ // id is then refused here, leaving that peer out of this node's cohorts. One id per
566
+ // (strand, machine), in a row a machine the party trusted then signed, and an id a live
567
+ // sibling recorded is never read as removed. If a peer is ever seen left out of cohorts
568
+ // this way, the row needs a proof that the id it states is the machine's own.
569
+ ...(partyMachines && { isNetworkMember: (peerId) => !partyMachines.removed().has(peerId) }),
525
570
  storage: strandStorage,
526
571
  fretProfile: config.profile === 'storage' ? 'core' : 'edge',
527
572
  relay: relayServer.enabled,
@@ -616,6 +661,16 @@ export class StrandInstanceManager {
616
661
  });
617
662
  timing('[buildStrandRuntime:%s] createLibp2pNode: %dms', strandId, Math.round(performance.now() - t0));
618
663
  instance.libp2pNode = node;
664
+ // This machine's statement of its peer id in the strand, for the party's control
665
+ // database (`StrandPeer`): a background write that never fails or delays the launch.
666
+ // The seam defers it while a write could fork the party and retries it on cohort
667
+ // growth and from every membership reconciler pass, so a refusal here is not final.
668
+ // Written for open strands too: their row is what a sibling's offline queue waits for.
669
+ if (config.partyPeers) {
670
+ void config.partyPeers.publishOwn(node.peerId.toString()).catch((error) => {
671
+ log('Strand %s: publishing this machine\'s StrandPeer row threw (retried later): %o', strandId, error);
672
+ });
673
+ }
619
674
  // One reservation supervisor PER RELAY, started now so the first attempts
620
675
  // overlap the database bring-up below (the relay is never in a strand's
621
676
  // Optimystic cohort — its protocol ids are namespaced `/optimystic/strand-<id>/…`
@@ -628,12 +683,20 @@ export class StrandInstanceManager {
628
683
  // declared link gives a relayed dial — what reconnects two restarted phones on a slow
629
684
  // link, where FRET's own redial cannot (`strand-peer-redial.ts`). The relays are
630
685
  // excluded by peer id: the node is connected to them throughout, and they are no member.
686
+ // The party's machines holding the strand are dialed too, at the addresses the
687
+ // strand-addr RPC put in the address book, so a sibling's blocked port that opens is
688
+ // reached without a connection ever having been made to it.
689
+ // A machine removed from the party is revoked to this loop on an open strand too: neither a
690
+ // peer to dial nor a connection that stands in for reaching the party's other machines.
631
691
  this.peerRedials.set(strandId, superviseStrandPeerRedial({
632
692
  label: strandId,
633
693
  node,
634
694
  seed: config.bootstrapNodes ?? [],
635
695
  excluded: new Set(groupAddrsByPeerId([...relayDialAddrs]).keys()),
636
- ...(revocationEnforcer && { isRevoked: (peerId) => revocationEnforcer.isRevoked(peerId) })
696
+ ...((revocationEnforcer || partyMachines) && {
697
+ isRevoked: (peerId) => revocationEnforcer?.isRevoked(peerId) === true || partyMachines?.removed().has(peerId) === true
698
+ }),
699
+ ...(partyMachines && { partyMachines: () => partyMachines.machines().map((machine) => machine.strandPeerId) })
637
700
  }, strandRedialTimings(config.network?.linkRoundTripMs)));
638
701
  const databaseBuild = await this.buildStrandDatabase(instance, config, node);
639
702
  if (!this.isCurrentRuntime(instance, node)) {
@@ -657,30 +720,7 @@ export class StrandInstanceManager {
657
720
  // (`bindFounderPeer`), so the first pass finds them and stops. Armed AFTER the database
658
721
  // phase above, so a gated or deferred launch always has a reconciler registered by the
659
722
  // time it can publish.
660
- if (config.strandRow.Type === 'c' && config.partyMemberPrivateKey
661
- && config.membershipReconciliation?.enabled !== false) {
662
- const reconciler = new StrandMembershipReconciler({
663
- label: strandId,
664
- partyMemberPrivateKey: config.partyMemberPrivateKey,
665
- // Read per pass, never captured — same lifecycle argument as the
666
- // enforcer's getNetwork: quiesce drops both handles.
667
- getDatabase: () => instance.database?.getDatabase(),
668
- getOwnPeerId: () => instance.libp2pNode?.peerId.toString(),
669
- pendingInvite: config.pendingMembershipInvite,
670
- // The enforcer's CURRENT snapshot view of this node's own peer id — the
671
- // reconciler stops rather than fight a self-revocation. Absent when the
672
- // gate is disarmed (fail-open: the loop just runs).
673
- isSelfRevoked: revocationEnforcer
674
- ? () => {
675
- const ownPeerId = instance.libp2pNode?.peerId.toString();
676
- return ownPeerId !== undefined && revocationEnforcer.isRevoked(ownPeerId);
677
- }
678
- : undefined,
679
- onRejoinBlocked: () => config.onRejoinBlocked?.(strandId)
680
- }, config.membershipReconciliation);
681
- this.membershipReconcilers.set(strandId, reconciler);
682
- reconciler.start();
683
- }
723
+ this.armMembershipReconciler(instance, config, revocationEnforcer);
684
724
  // Peer-join block catch-up: push this strand's own blocks to each newly
685
725
  // connected peer, so a machine that joined after blocks were committed
686
726
  // still ends up physically holding them (without per-strand storage there
@@ -782,6 +822,7 @@ export class StrandInstanceManager {
782
822
  // a partially-initialized db), and the app only ever sees `instance.database` once this
783
823
  // machine is allowed to write to the strand.
784
824
  let t0 = performance.now();
825
+ const partyMachines = this.partyMachines.get(strandId);
785
826
  const strandDb = new StrandDatabase({
786
827
  strandId,
787
828
  sAppConfig: config.sAppConfig,
@@ -801,8 +842,9 @@ export class StrandInstanceManager {
801
842
  bindFounderPeer: config.membershipReconciliation?.enabled !== false,
802
843
  onCommitDurability: config.onCommitDurability,
803
844
  onCommitHeld: config.onCommitHeld,
804
- offline: this.offlineDatabaseConfig(strandId, config.offline),
805
- appSchema: config.appSchema
845
+ offline: this.offlineDatabaseConfig(strandId, config.offline, this.offlineCohortGate(strandId, node)),
846
+ appSchema: config.appSchema,
847
+ ...(partyMachines && { partyMachines: () => partyMachines.machines() })
806
848
  });
807
849
  const storageRepo = node.storageRepo;
808
850
  const gate = new StrandFirstSyncGate({
@@ -877,10 +919,10 @@ export class StrandInstanceManager {
877
919
  }
878
920
  /**
879
921
  * One build's {@link StrandDatabaseOffline}: the strand's journal, which the database resolves as
880
- * it initializes (a throw or rejection fails the build), and the strand's mode, which it reads each
881
- * time it applies it.
922
+ * it initializes (a throw or rejection fails the build), the strand's mode, which it reads each
923
+ * time it applies it, and the gate its queue asks, when one could be built.
882
924
  */
883
- offlineDatabaseConfig(strandId, offline) {
925
+ offlineDatabaseConfig(strandId, offline, cohortReachability) {
884
926
  if (!offline) {
885
927
  return undefined;
886
928
  }
@@ -888,9 +930,59 @@ export class StrandInstanceManager {
888
930
  return {
889
931
  ...listeners,
890
932
  journal: () => journal(strandId),
891
- mode: () => this.currentOfflineMode(strandId, offline)
933
+ mode: () => this.currentOfflineMode(strandId, offline),
934
+ ...(cohortReachability && { cohortReachability })
892
935
  };
893
936
  }
937
+ /**
938
+ * The gate a build's offline queue asks: the node's own, closed also while the party has
939
+ * machines holding the strand that this node is alone in a cohort without
940
+ * (`cohortGateWaitingForMachines`). None when the launch tracks no party machines (no offline
941
+ * mode, or no party-machine seam), or when the node carries no gate or key network to compose
942
+ * over; the queue then asks the node's own gate, as before.
943
+ */
944
+ offlineCohortGate(strandId, node) {
945
+ const partyMachines = this.partyMachines.get(strandId);
946
+ if (!partyMachines) {
947
+ return undefined;
948
+ }
949
+ if (!node.cohortReachability || !node.keyNetwork) {
950
+ log('Strand %s: its node carries no %s, so its offline queue does not wait for the party\'s machines', strandId, node.cohortReachability ? 'key network' : 'reachability gate');
951
+ return undefined;
952
+ }
953
+ return cohortGateWaitingForMachines(node.cohortReachability, node.keyNetwork, node.peerId.toString(), partyMachines);
954
+ }
955
+ /** Ask the launcher for a rebuild when a machine removed from the party is in this runtime's seed. */
956
+ watchSeedForRemovedMachines(strandId, config, machines) {
957
+ const { onRemovedMachineInSeed } = config;
958
+ if (!onRemovedMachineInSeed) {
959
+ return;
960
+ }
961
+ let announced = this.seedRemovalsAnnounced.get(strandId);
962
+ if (!announced) {
963
+ announced = new Set();
964
+ this.seedRemovalsAnnounced.set(strandId, announced);
965
+ }
966
+ const seedPeers = new Set(groupAddrsByPeerId(config.bootstrapNodes ?? []).keys());
967
+ watchRemovedMachinesInSeed(machines, seedPeers, announced, () => onRemovedMachineInSeed(strandId), strandId);
968
+ }
969
+ /**
970
+ * The party's other machines known to hold `strandId` with no open connection from its strand
971
+ * node: what an offline queue reporting `waitingFor: 'cohort'` may be waiting for
972
+ * (`docs/strands.md` → "Waiting for the party's own machines"). Empty for a strand not tracked
973
+ * or not running here, and on a launch that tracks no party machines.
974
+ */
975
+ unreachedPartyMachines(strandId) {
976
+ const partyMachines = this.partyMachines.get(strandId);
977
+ const node = this.instances.get(strandId)?.libp2pNode;
978
+ if (!partyMachines || !node) {
979
+ return [];
980
+ }
981
+ const connected = new Set(node.getConnections()
982
+ .filter((connection) => connection.status === 'open')
983
+ .map((connection) => connection.remotePeer.toString()));
984
+ return partyMachines.machines().filter((machine) => !connected.has(machine.strandPeerId));
985
+ }
894
986
  /**
895
987
  * Whether this strand's raw store holds no block. False for a store that cannot list its
896
988
  * blocks, or whose listing fails, so such a launch probes at once.
@@ -1020,6 +1112,9 @@ export class StrandInstanceManager {
1020
1112
  }
1021
1113
  this.peerRedials.get(instance.strandId)?.stop();
1022
1114
  this.peerRedials.delete(instance.strandId);
1115
+ // The party-machine tracker with the loop and gate that read it; a resume reads afresh.
1116
+ this.partyMachines.get(instance.strandId)?.stop();
1117
+ this.partyMachines.delete(instance.strandId);
1023
1118
  // Backfill next — before the database closes and the libp2p node stops — so
1024
1119
  // no NEW catch-up push is issued against a torn-down transport. A push already
1025
1120
  // in flight is not awaited; it fails into the module's own per-chunk catch.
@@ -1167,12 +1262,136 @@ export class StrandInstanceManager {
1167
1262
  * loop's own serialized chain and never rejects.
1168
1263
  */
1169
1264
  notifyMembershipInviteStaged(strandId) {
1265
+ if (!this.rearmMembershipReconciler(strandId, 'a fresh invitation')) {
1266
+ log('notifyMembershipInviteStaged: strand %s has no armed membership reconciler — bring-up will find the invitation', strandId);
1267
+ }
1268
+ }
1269
+ /**
1270
+ * The party's machines changed in the control database — a `StrandPeer` row, a `CadrePeer`
1271
+ * row or a tombstone arrived or was written here (`CadreNode`'s watch on those tables,
1272
+ * coalesced). Re-arm every armed membership reconciler, so a sibling's row is bound, or a
1273
+ * removed machine's binding cleared, within the watch's window rather than at the next
1274
+ * resume, and read every strand's party machines again, so an offline queue waits for a
1275
+ * machine as soon as its row arrives and stops waiting for one as soon as it is removed.
1276
+ * Table events carry no row keys, so every strand's loop and tracker is woken; a loop with
1277
+ * nothing to do confirms and stops again. Returns at once; each pass runs on its loop's own
1278
+ * serialized chain and never rejects.
1279
+ */
1280
+ notifyPartyPeersChanged() {
1281
+ for (const strandId of this.membershipReconcilers.keys()) {
1282
+ this.rearmMembershipReconciler(strandId, 'a change to the party\'s machines');
1283
+ }
1284
+ for (const partyMachines of this.partyMachines.values()) {
1285
+ partyMachines.refresh();
1286
+ }
1287
+ }
1288
+ /** Re-arm `strandId`'s membership reconciler for `cause`; `false` when none is armed. */
1289
+ rearmMembershipReconciler(strandId, cause) {
1170
1290
  const reconciler = this.membershipReconcilers.get(strandId);
1171
1291
  if (!reconciler) {
1172
- log('notifyMembershipInviteStaged: strand %s has no armed membership reconciler — bring-up will find the invitation', strandId);
1292
+ return false;
1293
+ }
1294
+ void reconciler.rearm(cause);
1295
+ return true;
1296
+ }
1297
+ /**
1298
+ * Build and start `instance`'s membership reconciler from `config`, for a closed strand that
1299
+ * carries the party's own membership key with the loop enabled; nothing otherwise. Called by
1300
+ * {@link buildStrandRuntime} after the database phase, and by {@link rekeyParty} over a
1301
+ * running instance with the re-keyed config. Every dependency is read per pass, never
1302
+ * captured, so the loop follows the instance through quiesce and resume.
1303
+ */
1304
+ armMembershipReconciler(instance, config, revocationEnforcer) {
1305
+ if (config.strandRow.Type !== 'c' || !config.partyMemberPrivateKey || config.membershipReconciliation?.enabled === false) {
1173
1306
  return;
1174
1307
  }
1175
- void reconciler.rearm();
1308
+ const strandId = instance.strandId;
1309
+ const reconciler = new StrandMembershipReconciler({
1310
+ label: strandId,
1311
+ partyMemberPrivateKey: config.partyMemberPrivateKey,
1312
+ // Read per pass, never captured — same lifecycle argument as the
1313
+ // enforcer's getNetwork: quiesce drops both handles.
1314
+ getDatabase: () => instance.database?.getDatabase(),
1315
+ getOwnPeerId: () => instance.libp2pNode?.peerId.toString(),
1316
+ pendingInvite: config.pendingMembershipInvite,
1317
+ partyPeers: config.partyPeers,
1318
+ // The enforcer's CURRENT snapshot view of this node's own peer id — the
1319
+ // reconciler stops rather than fight a self-revocation. Absent when the
1320
+ // gate is disarmed (fail-open: the loop just runs).
1321
+ isSelfRevoked: revocationEnforcer
1322
+ ? () => {
1323
+ const ownPeerId = instance.libp2pNode?.peerId.toString();
1324
+ return ownPeerId !== undefined && revocationEnforcer.isRevoked(ownPeerId);
1325
+ }
1326
+ : undefined,
1327
+ onRejoinBlocked: () => config.onRejoinBlocked?.(strandId),
1328
+ onPendingKeySeated: () => config.onPartyKeySeated?.(strandId)
1329
+ }, config.membershipReconciliation);
1330
+ this.membershipReconcilers.set(strandId, reconciler);
1331
+ reconciler.start();
1332
+ }
1333
+ /**
1334
+ * Move a tracked closed strand onto `partyMemberPrivateKey`, the party's membership key the
1335
+ * control record now names (a party key rotation finished here or replicated from the machine
1336
+ * that finished it: `strand-party-key-rotation.ts`). The retained launch config is replaced
1337
+ * with a fresh object carrying the key ({@link foundExistingStrand}'s idiom: the caller's
1338
+ * config object is not ours to rewrite), so every later resume rebuilds under it, and the
1339
+ * founder bootstrap a resume re-runs derives from it (insert-if-absent; the strand's rows
1340
+ * already hold the new key as member and manager, so it writes nothing). The running
1341
+ * instance's membership reconciler, which signs with the key, is stopped and awaited, then
1342
+ * rebuilt and started over the re-keyed config, so its next pass binds under the new key.
1343
+ *
1344
+ * A tracked instance with no party key before (a storage replica launched before the party's
1345
+ * row reached this node) is keyed the same way and gains its reconciler now rather than at its
1346
+ * next resume. A build in flight is waited out first, so the reconciler it arms is the one
1347
+ * replaced here rather than a second one beside it; a key the retained config already names
1348
+ * is answered before that wait, since the party key watch asks this for every tracked closed
1349
+ * strand on every change to the key tables.
1350
+ *
1351
+ * @returns `rekeyed` when a running instance's reconciler was rebuilt; `retained` when only the
1352
+ * config changed (a hibernating instance, or one with the loop disabled); `unchanged` when
1353
+ * the key already matched or the strand is open; `untracked` when the strand is not here.
1354
+ */
1355
+ async rekeyParty(strandId, partyMemberPrivateKey) {
1356
+ const before = this.rekeyNeeded(strandId, partyMemberPrivateKey);
1357
+ if (before !== 'needed') {
1358
+ return before;
1359
+ }
1360
+ await this.settleRuntimeBuilds(strandId);
1361
+ const after = this.rekeyNeeded(strandId, partyMemberPrivateKey);
1362
+ if (after !== 'needed') {
1363
+ return after;
1364
+ }
1365
+ const instance = this.instances.get(strandId);
1366
+ const config = this.launchConfigs.get(strandId);
1367
+ const rekeyed = { ...config, partyMemberPrivateKey };
1368
+ this.launchConfigs.set(strandId, rekeyed);
1369
+ const reconciler = this.membershipReconcilers.get(strandId);
1370
+ if (reconciler) {
1371
+ reconciler.stop();
1372
+ await reconciler.settle();
1373
+ this.membershipReconcilers.delete(strandId);
1374
+ }
1375
+ if (!instance.libp2pNode || this.isQuiescing(strandId)) {
1376
+ log('rekeyParty: strand %s has no live runtime; the re-keyed config waits for its resume', strandId);
1377
+ return 'retained';
1378
+ }
1379
+ this.armMembershipReconciler(instance, rekeyed, this.revocationEnforcers.get(strandId));
1380
+ const armed = this.membershipReconcilers.has(strandId);
1381
+ log('rekeyParty: strand %s re-keyed (%s)', strandId, armed ? 'membership reconciler rebuilt' : 'membership reconciliation disabled');
1382
+ return armed ? 'rekeyed' : 'retained';
1383
+ }
1384
+ /** Whether {@link rekeyParty} has anything to do for `strandId`: the retained config is a closed strand's and names another key. */
1385
+ rekeyNeeded(strandId, partyMemberPrivateKey) {
1386
+ const config = this.launchConfigs.get(strandId);
1387
+ if (!config || !this.instances.has(strandId)) {
1388
+ return 'untracked';
1389
+ }
1390
+ return config.strandRow.Type !== 'c' || config.partyMemberPrivateKey === partyMemberPrivateKey ? 'unchanged' : 'needed';
1391
+ }
1392
+ /** The ids of every tracked closed strand, running or hibernating. */
1393
+ trackedClosedStrandIds() {
1394
+ return [...this.launchConfigs].filter(([, config]) => config.strandRow.Type === 'c').map(([strandId]) => strandId);
1176
1395
  }
1177
1396
  /**
1178
1397
  * Best-effort removal of THIS machine's own `Strand.MemberPeer` binding — the
@@ -1191,13 +1410,16 @@ export class StrandInstanceManager {
1191
1410
  * and its in-flight pass awaited — FIRST, so a pass that was already past its
1192
1411
  * own stopped check cannot re-register the binding this is about to clear.
1193
1412
  *
1194
- * NOTE: deliberately NOT handled here (or anywhere yet): clearing the bindings
1195
- * of a machine removed from the CADRE at the control layer, or of a party's
1196
- * OTHER machines when the party unpublishes — the party still holds the key on
1197
- * every surviving machine and can clear from any of them, and the stale rows
1198
- * grant nothing while admission is deny-list only. Revisit when
1199
- * `feat-strand-member-allowlist-admission` lands and a stale binding starts
1200
- * granting admission rather than merely mis-crediting diversity.
1413
+ * A machine removed from the CADRE at the control layer is not cleared here either: the
1414
+ * party replaces its key in the strand instead (`strand-party-key-rotation.ts`), which
1415
+ * leaves that machine's binding an orphan the revoked-peer gate denies, and the membership
1416
+ * reconciler clears what a lagging sibling wrote under the new key.
1417
+ *
1418
+ * NOTE: deliberately NOT handled here (or anywhere yet): clearing the bindings of a party's
1419
+ * OTHER machines when the party unpublishes — the party still holds the key on every
1420
+ * surviving machine and can clear from any of them, and the stale rows grant nothing while
1421
+ * admission is deny-list only. Revisit when `feat-strand-member-allowlist-admission` lands
1422
+ * and a stale binding starts granting admission rather than merely mis-crediting diversity.
1201
1423
  */
1202
1424
  async clearOwnMemberPeerBinding(strandId) {
1203
1425
  const instance = this.instances.get(strandId);
@@ -1368,7 +1590,8 @@ export class StrandInstanceManager {
1368
1590
  // count — a strand whose member rows became unreadable — this merge must gain an explicit
1369
1591
  // clear rather than silently declaring a stale number over a serving set it can no longer
1370
1592
  // see. Same applies to `bootstrapNodes` above, where a stale seed is harmless.
1371
- servingMachines: overrides?.servingMachines ?? launchConfig.servingMachines
1593
+ servingMachines: overrides?.servingMachines ?? launchConfig.servingMachines,
1594
+ partyMemberPrivateKey: overrides?.partyMemberPrivateKey ?? launchConfig.partyMemberPrivateKey
1372
1595
  };
1373
1596
  this.launchConfigs.set(strandId, resumeConfig);
1374
1597
  instance.status = 'starting';
@@ -1769,6 +1992,7 @@ export class StrandInstanceManager {
1769
1992
  instance.status = 'stopped';
1770
1993
  this.instances.delete(strandId);
1771
1994
  this.launchConfigs.delete(strandId);
1995
+ this.seedRemovalsAnnounced.delete(strandId);
1772
1996
  this.closedQueues.delete(strandId);
1773
1997
  // Storage is released only here — NOT in releaseRuntime, which a quiesce shares.
1774
1998
  await this.disposeStrandStorage(strandId);