rollbridge 0.1.35 → 0.1.37

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.
package/README.md CHANGED
@@ -240,9 +240,11 @@ later deploys continue to honor the original drain boundary.
240
240
 
241
241
  There is one explicit compatibility boundary: the first upgrade from a genuine
242
242
  pre-owner-replacement Rollbridge guardian and daemon cannot share its listeners
243
- on supported Node 20. After authenticating the guardian, exact daemon PID/socket,
244
- runtime authority, and durable owned-process state, `ensure-daemon` performs a
245
- one-time **disruptive** bridge. Existing proxy/control connections may close,
243
+ on supported Node 20. The same boundary applies to a retained transition guardian
244
+ that supports prepare/stage but predates the retired-owner commit command. After
245
+ an explicit capability probe and authentication of the guardian, exact daemon
246
+ PID/socket, runtime authority, and durable owned-process state, `ensure-daemon`
247
+ performs a one-time **disruptive** bridge. Existing proxy/control connections may close,
246
248
  the retained processes keep their exact PIDs under guardian supervision, and
247
249
  `status.ownerTransition` reports `mode: "legacy-first-upgrade"` with
248
250
  `disruptive: true`. The bridge requires the existing config identity unchanged;
@@ -1,9 +1,16 @@
1
1
  ### Fixed
2
2
 
3
3
  - Select retired-owner commit proof from the guardian-published committed owner
4
- snapshot rather than candidate-local process order, and independently require
5
- that proof to remain registered while retaining the replacement transaction,
6
- authority, and control-path fences.
4
+ snapshot rather than candidate-local process order, reserve its incumbent-owned
5
+ registration through commit, then attach it to the committed candidate while
6
+ retaining the replacement transaction, authority, and control-path fences.
7
7
  - Fail closed when an older retained guardian cannot commit that replacement
8
8
  atomically after the incumbent control socket disappears, preserving the
9
9
  incumbent owner, retained connections, and guardian-managed release processes.
10
+ - Explicitly classify retained guardian replacement capabilities before preparing
11
+ a transaction. Guardians with prepare/stage support but no retired-owner commit
12
+ command use the fully attested one-time disruptive legacy upgrade bridge;
13
+ malformed, stale, or ambiguous protocol responses continue to fail closed. The
14
+ partial guardian's prepared transaction remains the mutation fence through
15
+ candidate reconstruction and boundary revalidation, and failed preparation
16
+ notifies the incumbent to resume paused release drains.
package/docs/cli.md CHANGED
@@ -103,7 +103,8 @@ the candidate binds and validates its listeners, and an authenticated fenced
103
103
  transaction commits guardian authority and the final control socket. A lost
104
104
  control response is accepted only when the guardian confirms the exact committed
105
105
  transaction id. The first authenticated upgrade from a genuine pre-replacement
106
- guardian/daemon is the sole exception: `ensure-daemon` preserves its exact
106
+ guardian/daemon, or from a retained prepare/stage guardian that explicitly lacks
107
+ the retired-owner commit capability, is the sole exception: `ensure-daemon` preserves its exact
107
108
  guardian-owned processes but deliberately retires the old listeners before the
108
109
  Node 20 candidate binds, so existing proxy/control connections may close.
109
110
  Successful status JSON records this as `ownerTransition.disruptive: true` and
package/docs/config.md CHANGED
@@ -151,8 +151,10 @@ config reloads remain unchanged.
151
151
 
152
152
  The first upgrade from an authenticated pre-replacement Rollbridge guardian and
153
153
  daemon uses an explicitly disruptive compatibility bridge because that legacy
154
- owner cannot transfer listeners on Node 20. Rollbridge attests the exact guardian
155
- and daemon processes, sockets, runtime/config authority, and durable process
154
+ owner cannot transfer listeners on Node 20. A retained guardian that supports
155
+ replacement prepare/stage but lacks the retired-owner commit command is explicitly
156
+ classified and uses the same bridge. Rollbridge attests the exact guardian and
157
+ daemon processes, sockets, runtime/config authority, and durable process
156
158
  registrations before retiring the legacy listeners. Managed process PIDs and
157
159
  release state remain supervised, but live proxy/control connections may close.
158
160
  The resulting status includes `ownerTransition: {disruptive: true, mode:
@@ -11,6 +11,9 @@ cannot authenticate and attest an allowed owner transition.
11
11
 
12
12
  **Fix.** With `ownerRecovery`, a genuine pre-owner-replacement Rollbridge daemon
13
13
  and guardian can cross the documented one-time disruptive bridge automatically.
14
+ A retained guardian that implements replacement prepare/stage but lacks the
15
+ retired-owner commit capability uses that same bridge only after the exact
16
+ non-mutating capability signature and legacy process dispatch are confirmed.
14
17
  Its existing proxy/control connections may close; successful status reports
15
18
  `ownerTransition.mode: "legacy-first-upgrade"`. Keep the incumbent config
16
19
  identity unchanged for that first invocation, then apply config/socket changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rollbridge",
3
- "version": "0.1.35",
3
+ "version": "0.1.37",
4
4
  "description": "Zero-downtime process supervisor and local traffic switcher for deploy-managed apps.",
5
5
  "keywords": [
6
6
  "deploy",
package/src/daemon.js CHANGED
@@ -29,7 +29,7 @@ const STATE_PERSIST_INTERVAL_MS = 5000
29
29
  * @typedef {{configDigest: string, format: number, guardian: {pid?: number, socketPath: string, token: string}, reconnectGraceMs: number}} OwnerRecoveryMetadata
30
30
  * @typedef {DaemonStatus & {recovery: OwnerRecoveryMetadata, singletonReleaseIds?: Record<string, string>}} OwnerRecoverySnapshot
31
31
  * @typedef {{authority: JsonValue, config: import("./config.js").RollbridgeConfig, releaseConfigs?: Record<string, import("./config.js").RollbridgeConfig>, singletonReleaseIds?: Record<string, string>, snapshot: OwnerRecoverySnapshot}} PrivateOwnerState
32
- * @typedef {{boundaryCrossed: boolean, incumbentControl: Awaited<ReturnType<typeof openControlSession>>, incumbentStartTime: string, prepared: {ownerState: JsonValue, replacementId: string}, recoverySnapshot: OwnerRecoverySnapshot}} LegacyOwnerBridge
32
+ * @typedef {{boundaryCrossed: boolean, incumbentControl?: Awaited<ReturnType<typeof openControlSession>>, incumbentStartTime: string, legacyGuardian: GuardianClient, legacyInventory: {key: string, provenance: string}[], legacyPrepared?: {ownerState: JsonValue, replacementId: string}, legacySnapshot: OwnerRecoverySnapshot, prepared: {ownerState: JsonValue, replacementId: string}, recoverySnapshot: OwnerRecoverySnapshot}} LegacyOwnerBridge
33
33
  */
34
34
 
35
35
  export default class RollbridgeDaemon {
@@ -325,24 +325,38 @@ export default class RollbridgeDaemon {
325
325
  configDigest: persisted.recovery.configDigest,
326
326
  runtime: persisted.daemonRuntime ? {...persisted.daemonRuntime} : null
327
327
  }
328
- let legacyBridge
329
- let prepared
328
+ const replacementProtocol = await this.guardian.ownerReplacementProtocol()
329
+ const legacyBridge = replacementProtocol === "legacy"
330
+ ? await this.prepareLegacyOwnerReplacement({persisted, persistedAuthority})
331
+ : undefined
332
+ const prepared = legacyBridge?.prepared ?? await this.guardian.prepareOwnerReplacement(persistedAuthority, this.ownerAuthority())
333
+ let preparedStatus
334
+ let reservedProcessKey
335
+ let transfer
330
336
 
331
337
  try {
332
- prepared = await this.guardian.prepareOwnerReplacement(persistedAuthority, this.ownerAuthority())
338
+ preparedStatus = await this.guardian.replacementStatus()
339
+ transfer = /** @type {PrivateOwnerState} */ (prepared.ownerState)
340
+ if (!transfer?.config || !transfer.snapshot) throw new Error("Committed owner published incomplete replacement state")
341
+ const registeredProcesses = new Map((await this.guardian.inventory()).map(({key, provenance}) => [key, provenance]))
342
+
343
+ reservedProcessKey = legacyBridge ? undefined : ownerSnapshotProcessKeys(transfer.snapshot, transfer.singletonReleaseIds)
344
+ .find((key) => registeredProcesses.has(key))
345
+ if (reservedProcessKey) this.guardian.reserveProcessRecovery(reservedProcessKey, /** @type {string} */ (registeredProcesses.get(reservedProcessKey)))
346
+ await this.restoreOwnerState(transfer.snapshot, {config: transfer.config, releaseConfigs: transfer.releaseConfigs, resumeDrains: false, singletonReleaseIds: transfer.singletonReleaseIds, synchronizeLifecycleRoles: false})
333
347
  } catch (error) {
334
- legacyBridge = await this.prepareLegacyOwnerReplacement({
335
- error: error instanceof Error ? error : String(error),
336
- persisted,
337
- persistedAuthority
338
- })
339
- prepared = legacyBridge.prepared
348
+ legacyBridge?.incumbentControl?.close()
349
+ if (legacyBridge) {
350
+ try {
351
+ await this.abandonLegacyOwnerBridge(legacyBridge)
352
+ } catch (cleanupError) {
353
+ throw new AggregateError([error, cleanupError], "Legacy owner replacement reconstruction failed and its upgrade coordinator could not be abandoned", {cause: cleanupError})
354
+ }
355
+ } else {
356
+ this.guardian.disconnect()
357
+ }
358
+ throw error
340
359
  }
341
- const preparedStatus = await this.guardian.replacementStatus()
342
- const transfer = /** @type {PrivateOwnerState} */ (prepared.ownerState)
343
-
344
- if (!transfer?.config || !transfer.snapshot) throw new Error("Committed owner published incomplete replacement state")
345
- await this.restoreOwnerState(transfer.snapshot, {config: transfer.config, releaseConfigs: transfer.releaseConfigs, resumeDrains: false, singletonReleaseIds: transfer.singletonReleaseIds, synchronizeLifecycleRoles: false})
346
360
  for (const release of this.releases.values()) release.preserveConfigOnRetirement = true
347
361
  this.logger("owner replacement candidate prepared", {activeReleaseId: this.activeRelease?.releaseId ?? null, replacementId: prepared.replacementId})
348
362
 
@@ -386,6 +400,7 @@ export default class RollbridgeDaemon {
386
400
  if (incumbentControl) {
387
401
  const listenerSession = incumbentControl
388
402
 
403
+ if (reservedProcessKey) await this.guardian.recoverReservedProcess(reservedProcessKey)
389
404
  incumbentControl.onEvent((event) => this.handleIncumbentListenerEvent(event, listenerSession))
390
405
  await incumbentControl.request({
391
406
  command: "yield-owner-listeners",
@@ -414,15 +429,20 @@ export default class RollbridgeDaemon {
414
429
  snapshot: this.status()
415
430
  })
416
431
 
432
+ if (staged.committed && reservedProcessKey) {
433
+ committedAuthority = true
434
+ await this.guardian.recoverReservedProcess(reservedProcessKey)
435
+ }
436
+
417
437
  if (!staged.committed) {
418
438
  if (retiredIncumbentControl) {
419
- const recoveredProcesses = this.guardian.processes
420
- const processKey = ownerSnapshotProcessKeys(transfer.snapshot, transfer.singletonReleaseIds)
421
- .find((key) => recoveredProcesses.has(key))
439
+ const processKey = reservedProcessKey
422
440
 
423
- if (!processKey) throw new Error("Retired owner replacement requires an exact recovered process from committed owner state")
441
+ if (!processKey || !this.guardian.processes.has(processKey)) throw new Error("Retired owner replacement requires an exact reserved process from committed owner state")
424
442
  try {
425
443
  await this.guardian.commitRetiredOwnerReplacement(prepared.replacementId, processKey)
444
+ committedAuthority = true
445
+ await this.guardian.recoverReservedProcess(processKey)
426
446
  } catch (error) {
427
447
  if (!(error instanceof Error) || error.message !== "Guardian commit-retired-owner-replacement requires the committed owner") throw error
428
448
  throw new Error(
@@ -484,12 +504,13 @@ export default class RollbridgeDaemon {
484
504
  }
485
505
  if (legacyBridge && !legacyBridge.boundaryCrossed) {
486
506
  try {
487
- await this.guardian.abandonLegacyUpgrade()
507
+ await this.abandonLegacyOwnerBridge(legacyBridge)
488
508
  } catch (failure) {
489
509
  abortError = failure instanceof Error ? failure : new Error(String(failure))
490
510
  }
491
511
  } else {
492
512
  this.guardian.disconnect()
513
+ legacyBridge?.legacyGuardian.disconnect()
493
514
  }
494
515
  if (committed) {
495
516
  const commitmentError = await committed
@@ -540,56 +561,74 @@ export default class RollbridgeDaemon {
540
561
  }
541
562
 
542
563
  /**
543
- * Authenticates and prepares the one-time disruptive bridge for a genuine pre-split guardian.
544
- * @param {{error: Error | string, persisted: OwnerRecoverySnapshot, persistedAuthority: {configDigest: string, runtime: import("./daemon-runtime.js").DaemonRuntimeIdentity | null}}} options - Legacy evidence.
564
+ * Authenticates and prepares the one-time disruptive bridge for an exact legacy guardian protocol.
565
+ * @param {{persisted: OwnerRecoverySnapshot, persistedAuthority: {configDigest: string, runtime: import("./daemon-runtime.js").DaemonRuntimeIdentity | null}}} options - Legacy evidence.
545
566
  * @returns {Promise<LegacyOwnerBridge>} Prepared bridge.
546
567
  */
547
- async prepareLegacyOwnerReplacement({error, persisted, persistedAuthority}) {
548
- const diagnostic = error instanceof Error ? error.message : String(error)
568
+ async prepareLegacyOwnerReplacement({persisted, persistedAuthority}) {
549
569
  const legacyProcessKey = ownerSnapshotProcessKeys(persisted, persisted.singletonReleaseIds)[0]
570
+ const legacyGuardian = this.guardian
571
+ let legacyPrepared
572
+
573
+ if (!legacyProcessKey) throw new Error("Legacy disruptive owner replacement requires an exact guardian-owned process registration in durable state")
574
+ if (!legacyGuardian) throw new Error("Legacy disruptive replacement is missing its authenticated guardian connection")
575
+ try {
576
+ legacyPrepared = await legacyGuardian.prepareOwnerReplacement(persistedAuthority, this.ownerAuthority())
577
+ } catch (error) {
578
+ const diagnostic = error instanceof Error ? error.message : String(error)
579
+
580
+ if (!isLegacyGuardianPrepareDiagnostic(diagnostic)) throw error
581
+ let probeAccepted = false
550
582
 
551
- if (!isLegacyGuardianPrepareDiagnostic(diagnostic)) throw error
552
- if (!legacyProcessKey) throw new Error("Legacy disruptive owner replacement requires an exact guardian-owned process registration in durable state", {cause: error})
553
- if (diagnostic !== "Unknown guardian command: prepare-owner-replacement") {
554
583
  try {
555
- await this.guardian?.request({
584
+ await legacyGuardian.request({
556
585
  authority: persistedAuthority,
557
586
  command: "prepare-owner-replacement",
558
587
  key: legacyProcessKey,
559
588
  nextAuthority: this.ownerAuthority()
560
589
  })
561
- throw new Error("Legacy guardian protocol probe unexpectedly accepted owner replacement")
590
+ probeAccepted = true
562
591
  } catch (probeError) {
563
592
  if (!(probeError instanceof Error) || probeError.message !== "Unknown guardian command: prepare-owner-replacement") {
564
593
  throw new Error("Guardian does not match the authenticated pre-split replacement protocol signature", {cause: probeError})
565
594
  }
566
595
  }
596
+ if (probeAccepted) throw new Error("Legacy guardian protocol probe unexpectedly accepted owner replacement", {cause: error})
567
597
  }
568
- if (persisted.recovery.configDigest !== this.ownerRecoveryConfigDigest()) {
569
- throw new Error("The one-time legacy guardian bridge requires the incumbent config identity unchanged; retry the config change after the bridge establishes split-3 authority")
570
- }
571
- if (!this.legacyIncumbentPid) throw new Error("The authenticated pre-split guardian requires an exact incumbent PID from ensure-daemon for the disruptive bridge")
572
- if (!this.guardianIdentity?.pid) throw new Error("The authenticated pre-split guardian state is missing its exact guardian PID")
573
- const legacyGuardian = this.guardian
574
-
575
- if (!legacyGuardian) throw new Error("Legacy disruptive replacement is missing its authenticated guardian connection")
576
-
577
- await verifyLegacyGuardianProcess(this.guardianIdentity.pid, this.guardianIdentity.socketPath)
578
- const incumbentStartTime = await verifyLegacyDaemonProcess(this.legacyIncumbentPid, this.configPath, persisted.control.path)
579
- const incumbentControl = await openControlSession(persisted.control.path)
598
+ let incumbentControl
580
599
  let upgraded
581
600
 
582
601
  try {
583
- const incumbentStatus = await incumbentControl.request({command: "status"})
602
+ if (persisted.recovery.configDigest !== this.ownerRecoveryConfigDigest()) {
603
+ throw new Error("The one-time legacy guardian bridge requires the incumbent config identity unchanged; retry the config change after the bridge establishes split-3 authority")
604
+ }
605
+ if (!this.legacyIncumbentPid) throw new Error("The authenticated legacy guardian requires an exact incumbent PID from ensure-daemon for the disruptive bridge")
606
+ if (!this.guardianIdentity?.pid) throw new Error("The authenticated legacy guardian state is missing its exact guardian PID")
607
+ await verifyLegacyGuardianProcess(this.guardianIdentity.pid, this.guardianIdentity.socketPath)
608
+ const incumbentStartTime = await verifyLegacyDaemonProcess(this.legacyIncumbentPid, this.configPath, persisted.control.path)
609
+ if (legacyPrepared) assertLegacyPrivateOwnerState(legacyPrepared.ownerState, persisted, persistedAuthority)
610
+ try {
611
+ incumbentControl = await openControlSession(persisted.control.path)
612
+ } catch (error) {
613
+ if (!legacyPrepared || !error || typeof error !== "object" || !("code" in error) || error.code !== "ENOENT") throw error
614
+ }
615
+ if (incumbentControl) {
616
+ const incumbentStatus = await incumbentControl.request({command: "status"})
584
617
 
585
- assertLegacyIncumbentStatus(incumbentStatus, persisted)
586
- const ownerState = {
587
- authority: persistedAuthority,
588
- config: this.config,
589
- releaseConfigs: Object.fromEntries(persisted.releases.map((release) => [release.releaseId, this.config])),
590
- singletonReleaseIds: Object.fromEntries(persisted.singletons.map((singleton) => [singleton.id, persisted.activeReleaseId]).filter((entry) => entry[1] !== null)),
591
- snapshot: persisted
618
+ assertLegacyIncumbentStatus(incumbentStatus, persisted)
592
619
  }
620
+ const ownerState = legacyPrepared
621
+ ? legacyPrepared.ownerState
622
+ : {
623
+ authority: persistedAuthority,
624
+ config: this.config,
625
+ releaseConfigs: Object.fromEntries(persisted.releases.map((release) => [release.releaseId, this.config])),
626
+ singletonReleaseIds: Object.fromEntries(persisted.singletons.map((singleton) => [singleton.id, persisted.activeReleaseId]).filter((entry) => entry[1] !== null)),
627
+ snapshot: persisted
628
+ }
629
+ const legacyInventory = normalizeLegacyGuardianInventory(await legacyGuardian.inventory())
630
+
631
+ assertLegacyGuardianInventoryMembership(legacyInventory, /** @type {PrivateOwnerState} */ (ownerState))
593
632
  const upgradedIdentity = /** @type {{pid?: number, socketPath: string, token: string}} */ ({
594
633
  socketPath: `${this.statePath}.split3-guardian.sock`,
595
634
  token: crypto.randomBytes(32).toString("hex")
@@ -598,7 +637,6 @@ export default class RollbridgeDaemon {
598
637
  await assertPathAbsent(upgradedIdentity.socketPath, "Legacy upgrade guardian socket")
599
638
  upgraded = await legacyGuardian.upgradeLegacyGuardian({ownerState, ...upgradedIdentity})
600
639
  upgradedIdentity.pid = upgraded.pid
601
- legacyGuardian.disconnect()
602
640
  this.guardian = upgraded
603
641
  this.guardianIdentity = upgradedIdentity
604
642
  const prepared = await upgraded.prepareOwnerReplacement(persistedAuthority, this.ownerAuthority())
@@ -612,36 +650,102 @@ export default class RollbridgeDaemon {
612
650
  incumbentPid: this.legacyIncumbentPid,
613
651
  replacementId: prepared.replacementId
614
652
  })
615
- return {boundaryCrossed: false, incumbentControl, incumbentStartTime, prepared, recoverySnapshot}
653
+ return {boundaryCrossed: false, incumbentControl, incumbentStartTime, legacyGuardian, legacyInventory, legacyPrepared, legacySnapshot: persisted, prepared, recoverySnapshot}
616
654
  } catch (upgradeError) {
617
- incumbentControl.close()
618
- if (upgraded) await upgraded.abandonLegacyUpgrade()
655
+ incumbentControl?.close()
656
+ let cleanupError
657
+
658
+ if (upgraded) {
659
+ try {
660
+ await upgraded.abandonLegacyUpgrade()
661
+ } catch (error) {
662
+ cleanupError = error instanceof Error ? error : new Error(String(error))
663
+ }
664
+ }
665
+ legacyGuardian.disconnect()
666
+ if (cleanupError) {
667
+ throw new AggregateError([upgradeError, cleanupError], "Legacy owner replacement validation failed and its upgrade coordinator could not be abandoned", {cause: upgradeError})
668
+ }
619
669
  throw upgradeError
620
670
  }
621
671
  }
622
672
 
673
+ /**
674
+ * Abandons the uncommitted coordinator before releasing the incumbent guardian transaction.
675
+ * @param {LegacyOwnerBridge} bridge - Prepared bridge.
676
+ */
677
+ async abandonLegacyOwnerBridge(bridge) {
678
+ let cleanupError
679
+
680
+ try {
681
+ await this.guardian?.abandonLegacyUpgrade()
682
+ } catch (error) {
683
+ cleanupError = error instanceof Error ? error : new Error(String(error))
684
+ }
685
+ bridge.legacyGuardian.disconnect()
686
+ if (cleanupError) throw cleanupError
687
+ }
688
+
623
689
  /**
624
690
  * Crosses the explicitly disruptive legacy-only boundary after candidate reconstruction.
625
691
  * @param {LegacyOwnerBridge} bridge - Prepared bridge.
626
692
  */
627
693
  async crossLegacyDisruptiveBoundary(bridge) {
628
694
  if (!this.legacyIncumbentPid || !this.statePath) throw new Error("Legacy disruptive boundary is missing its exact incumbent identity")
695
+ if (!this.guardian) throw new Error("Legacy disruptive boundary is missing its authenticated upgraded guardian")
696
+ if (!bridge.legacyGuardian.pid) throw new Error("Legacy disruptive boundary is missing its authenticated retained guardian PID")
697
+ await verifyLegacyGuardianProcess(bridge.legacyGuardian.pid, bridge.legacyGuardian.socketPath)
629
698
  const currentStartTime = await verifyLegacyDaemonProcess(this.legacyIncumbentPid, this.configPath, bridge.recoverySnapshot.control.path)
630
699
 
631
700
  if (currentStartTime !== bridge.incumbentStartTime) throw new Error("Legacy incumbent PID identity changed before the disruptive boundary")
701
+ if (!isDeepStrictEqual(await readState(this.statePath), bridge.legacySnapshot)) {
702
+ throw new Error("Legacy owner recovery state changed before the disruptive boundary")
703
+ }
704
+ if (bridge.incumbentControl) {
705
+ assertLegacyIncumbentStatus(await bridge.incumbentControl.request({command: "status"}), bridge.legacySnapshot)
706
+ }
707
+ const currentInventory = normalizeLegacyGuardianInventory(await bridge.legacyGuardian.inventory())
708
+
709
+ if (!isDeepStrictEqual(currentInventory, bridge.legacyInventory)) {
710
+ throw new Error("Legacy guardian process inventory changed before the disruptive boundary")
711
+ }
712
+ const candidateOwnerState = {
713
+ authority: this.ownerAuthority(),
714
+ config: this.config,
715
+ releaseConfigs: Object.fromEntries([...this.releases].map(([releaseId, release]) => [releaseId, release.config])),
716
+ singletonReleaseIds: Object.fromEntries(this.singletonReleaseIds),
717
+ snapshot: this.status()
718
+ }
719
+
720
+ assertLegacyGuardianInventoryMembership(currentInventory, candidateOwnerState)
721
+ let legacyCommitted
722
+
723
+ if (bridge.legacyPrepared) {
724
+ const status = await bridge.legacyGuardian.replacementStatus()
725
+
726
+ if (!status.ownerClaimed) throw new Error("Legacy guardian incumbent ownership changed before the disruptive boundary")
727
+ legacyCommitted = bridge.legacyGuardian.waitForEvent("replacement-committed")
728
+ const staged = await bridge.legacyGuardian.stageOwnerReplacement(bridge.legacyPrepared.replacementId, candidateOwnerState)
729
+
730
+ if (staged.committed) throw new Error("Legacy guardian committed replacement before the authenticated disruptive boundary")
731
+ }
632
732
  this.logger("legacy owner replacement disruptive boundary", {
633
733
  disruptive: true,
634
734
  incumbentPid: this.legacyIncumbentPid,
635
- reason: "pre-split guardian and daemon lacked atomic replacement protocol"
735
+ reason: "retained guardian and daemon lacked atomic replacement protocol"
636
736
  })
737
+ await this.guardian.beginLegacyOwnerClaim(bridge.prepared.replacementId, bridge.recoverySnapshot.recovery.reconnectGraceMs)
637
738
  process.kill(this.legacyIncumbentPid, "SIGKILL")
638
739
  bridge.boundaryCrossed = true
639
- await bridge.incumbentControl.closed()
740
+ await bridge.incumbentControl?.closed()
741
+ if (legacyCommitted) await legacyCommitted
742
+ bridge.legacyGuardian.disconnect()
743
+ await this.guardian.completeLegacyOwnerClaim(bridge.prepared.replacementId)
640
744
  await writeState(this.statePath, bridge.recoverySnapshot)
641
745
  this.ownerTransition = /** @type {OwnerTransition} */ ({
642
746
  disruptive: true,
643
747
  mode: "legacy-first-upgrade",
644
- reason: "pre-split guardian and daemon lacked atomic replacement protocol"
748
+ reason: "retained guardian and daemon lacked atomic replacement protocol"
645
749
  })
646
750
  }
647
751
 
@@ -1998,7 +2102,7 @@ export function isLegacyGuardianPrepareDiagnostic(diagnostic) {
1998
2102
  }
1999
2103
 
2000
2104
  /**
2001
- * @param {OwnerRecoverySnapshot} snapshot - Durable committed owner snapshot.
2105
+ * @param {DaemonStatus} snapshot - Serialized owner process snapshot.
2002
2106
  * @param {Record<string, string>} [singletonReleaseIds] - Exact singleton owner releases.
2003
2107
  * @returns {string[]} Exact guardian registration keys present in the snapshot.
2004
2108
  */
@@ -2017,6 +2121,40 @@ function ownerSnapshotProcessKeys(snapshot, singletonReleaseIds = {}) {
2017
2121
  return keys
2018
2122
  }
2019
2123
 
2124
+ /**
2125
+ * Canonicalizes the authenticated guardian inventory without relying on map insertion order.
2126
+ * @param {{key: string, provenance: string}[]} inventory - Guardian inventory response.
2127
+ * @returns {{key: string, provenance: string}[]} Exact key/provenance fence.
2128
+ */
2129
+ function normalizeLegacyGuardianInventory(inventory) {
2130
+ const normalized = inventory.map((entry) => {
2131
+ if (!entry || typeof entry.key !== "string" || !entry.key || typeof entry.provenance !== "string" || !entry.provenance) {
2132
+ throw new Error("Legacy guardian returned an invalid process inventory")
2133
+ }
2134
+ return {key: entry.key, provenance: entry.provenance}
2135
+ }).sort((left, right) => left.key.localeCompare(right.key))
2136
+
2137
+ if (new Set(normalized.map(({key}) => key)).size !== normalized.length) {
2138
+ throw new Error("Legacy guardian returned duplicate process registrations")
2139
+ }
2140
+ return normalized
2141
+ }
2142
+
2143
+ /**
2144
+ * Requires every and only the process registrations serialized by committed private owner state.
2145
+ * @param {{key: string, provenance: string}[]} inventory - Canonical guardian inventory.
2146
+ * @param {{snapshot: DaemonStatus, singletonReleaseIds?: Record<string, string>}} ownerState - Authenticated owner process snapshot.
2147
+ */
2148
+ function assertLegacyGuardianInventoryMembership(inventory, ownerState) {
2149
+ if (!ownerState?.snapshot) throw new Error("Legacy guardian owner state is missing its committed process snapshot")
2150
+ const inventoryKeys = inventory.map(({key}) => key)
2151
+ const snapshotKeys = ownerSnapshotProcessKeys(ownerState.snapshot, ownerState.singletonReleaseIds).sort((left, right) => left.localeCompare(right))
2152
+
2153
+ if (!isDeepStrictEqual(inventoryKeys, snapshotKeys)) {
2154
+ throw new Error("Legacy guardian process inventory does not match committed owner state")
2155
+ }
2156
+ }
2157
+
2020
2158
  /**
2021
2159
  * Verifies the exact authenticated guardian process and socket without scanning other PIDs.
2022
2160
  * @param {number} pid - Persisted guardian PID.
@@ -2026,7 +2164,7 @@ async function verifyLegacyGuardianProcess(pid, socketPath) {
2026
2164
  const args = await processArguments(pid, "legacy guardian")
2027
2165
  const script = args.find((argument) => argument.endsWith("process-guardian.js"))
2028
2166
 
2029
- if (!script || !args.includes(socketPath)) throw new Error(`Persisted guardian PID ${pid} does not match the pre-split guardian command and socket`)
2167
+ if (!script || !args.includes(socketPath)) throw new Error(`Persisted guardian PID ${pid} does not match the retained guardian command and socket`)
2030
2168
  await verifyProcessUser(pid, "legacy guardian")
2031
2169
  await verifyUnixSocketOwner(pid, socketPath, "legacy guardian")
2032
2170
  }
@@ -2045,7 +2183,7 @@ async function verifyLegacyDaemonProcess(pid, configPath, socketPath) {
2045
2183
  const configIndex = args.indexOf("--config")
2046
2184
 
2047
2185
  if (daemonIndex < 0 || configIndex < 0 || args[configIndex + 1] !== configPath) {
2048
- throw new Error(`Daemon PID ${pid} does not match the exact pre-split daemon config command`)
2186
+ throw new Error(`Daemon PID ${pid} does not match the exact retained daemon config command`)
2049
2187
  }
2050
2188
  await verifyProcessUser(pid, "legacy daemon")
2051
2189
  await verifyUnixSocketOwner(pid, socketPath, "legacy daemon")
@@ -2121,10 +2259,38 @@ function assertLegacyIncumbentStatus(status, persisted) {
2121
2259
  if (status.application !== persisted.application || !control || typeof control !== "object" || Array.isArray(control) || control.path !== persisted.control.path ||
2122
2260
  !runtime || typeof runtime !== "object" || Array.isArray(runtime) || runtime.digest !== persisted.daemonRuntime?.digest ||
2123
2261
  !ownerRecovery || typeof ownerRecovery !== "object" || Array.isArray(ownerRecovery) || ownerRecovery.configDigest !== persisted.recovery.configDigest) {
2124
- throw new Error("Responsive incumbent does not match the exact persisted pre-split daemon authority")
2262
+ throw new Error("Responsive incumbent does not match the exact persisted retained-daemon authority")
2125
2263
  }
2126
2264
  }
2127
2265
 
2266
+ /**
2267
+ * Validates private committed state returned by a partial transaction guardian.
2268
+ * @param {JsonValue} value - Authenticated guardian owner state.
2269
+ * @param {OwnerRecoverySnapshot} persisted - Durable expected identity.
2270
+ * @param {{configDigest: string, runtime: import("./daemon-runtime.js").DaemonRuntimeIdentity | null}} persistedAuthority - Exact committed authority.
2271
+ */
2272
+ function assertLegacyPrivateOwnerState(value, persisted, persistedAuthority) {
2273
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Partial legacy guardian returned invalid committed owner state")
2274
+ const state = /** @type {Record<string, JsonValue>} */ (value)
2275
+ const config = state.config
2276
+ const snapshot = state.snapshot
2277
+
2278
+ if (!isDeepStrictEqual(state.authority, persistedAuthority) || !config || typeof config !== "object" || Array.isArray(config) ||
2279
+ ownerConfigDigest(/** @type {import("./config.js").RollbridgeConfig} */ (config)) !== persistedAuthority.configDigest ||
2280
+ !snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) {
2281
+ throw new Error("Partial legacy guardian committed owner state does not match the persisted authority")
2282
+ }
2283
+ const privateSnapshot = /** @type {OwnerRecoverySnapshot} */ (snapshot)
2284
+
2285
+ assertLegacyIncumbentStatus(/** @type {Record<string, JsonValue>} */ (snapshot), persisted)
2286
+ if (!isDeepStrictEqual(
2287
+ ownerSnapshotProcessKeys(privateSnapshot, state.singletonReleaseIds && typeof state.singletonReleaseIds === "object" && !Array.isArray(state.singletonReleaseIds)
2288
+ ? /** @type {Record<string, string>} */ (state.singletonReleaseIds)
2289
+ : {}).sort(),
2290
+ ownerSnapshotProcessKeys(persisted, persisted.singletonReleaseIds).sort()
2291
+ )) throw new Error("Partial legacy guardian committed process membership does not match durable recovery state")
2292
+ }
2293
+
2128
2294
  /**
2129
2295
  * @param {string} candidatePath - Path that must not preexist.
2130
2296
  * @param {string} label - Diagnostic label.