@cotal-ai/cli 0.172.0 → 0.172.2

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 (243) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +68 -47
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts +2 -2
  5. package/dist/commands/agents.d.ts.map +1 -1
  6. package/dist/commands/agents.js +19 -12
  7. package/dist/commands/agents.js.map +1 -1
  8. package/dist/commands/channel-members.d.ts.map +1 -1
  9. package/dist/commands/channel-members.js +2 -1
  10. package/dist/commands/channel-members.js.map +1 -1
  11. package/dist/commands/channels.d.ts.map +1 -1
  12. package/dist/commands/channels.js +20 -9
  13. package/dist/commands/channels.js.map +1 -1
  14. package/dist/commands/clean.d.ts.map +1 -1
  15. package/dist/commands/clean.js +35 -9
  16. package/dist/commands/clean.js.map +1 -1
  17. package/dist/commands/completion.d.ts.map +1 -1
  18. package/dist/commands/completion.js +3 -2
  19. package/dist/commands/completion.js.map +1 -1
  20. package/dist/commands/config.d.ts.map +1 -1
  21. package/dist/commands/config.js +24 -7
  22. package/dist/commands/config.js.map +1 -1
  23. package/dist/commands/describe.js +2 -2
  24. package/dist/commands/describe.js.map +1 -1
  25. package/dist/commands/doctor.d.ts.map +1 -1
  26. package/dist/commands/doctor.js +25 -7
  27. package/dist/commands/doctor.js.map +1 -1
  28. package/dist/commands/down.d.ts.map +1 -1
  29. package/dist/commands/down.js +43 -12
  30. package/dist/commands/down.js.map +1 -1
  31. package/dist/commands/endpoint-authoring.d.ts.map +1 -1
  32. package/dist/commands/endpoint-authoring.js +16 -4
  33. package/dist/commands/endpoint-authoring.js.map +1 -1
  34. package/dist/commands/endpoint.d.ts.map +1 -1
  35. package/dist/commands/endpoint.js +8 -3
  36. package/dist/commands/endpoint.js.map +1 -1
  37. package/dist/commands/ext.d.ts.map +1 -1
  38. package/dist/commands/ext.js +9 -8
  39. package/dist/commands/ext.js.map +1 -1
  40. package/dist/commands/history-clear.d.ts.map +1 -1
  41. package/dist/commands/history-clear.js +10 -3
  42. package/dist/commands/history-clear.js.map +1 -1
  43. package/dist/commands/history-limit.js +2 -2
  44. package/dist/commands/history-limit.js.map +1 -1
  45. package/dist/commands/history.d.ts +1 -1
  46. package/dist/commands/history.d.ts.map +1 -1
  47. package/dist/commands/history.js +101 -41
  48. package/dist/commands/history.js.map +1 -1
  49. package/dist/commands/join.d.ts.map +1 -1
  50. package/dist/commands/join.js +54 -23
  51. package/dist/commands/join.js.map +1 -1
  52. package/dist/commands/manager-service.d.ts.map +1 -1
  53. package/dist/commands/manager-service.js +5 -1
  54. package/dist/commands/manager-service.js.map +1 -1
  55. package/dist/commands/meshes-add.d.ts +4 -0
  56. package/dist/commands/meshes-add.d.ts.map +1 -1
  57. package/dist/commands/meshes-add.js +35 -1
  58. package/dist/commands/meshes-add.js.map +1 -1
  59. package/dist/commands/meshes-wizard.d.ts.map +1 -1
  60. package/dist/commands/meshes-wizard.js +5 -5
  61. package/dist/commands/meshes-wizard.js.map +1 -1
  62. package/dist/commands/meshes.d.ts.map +1 -1
  63. package/dist/commands/meshes.js +4 -3
  64. package/dist/commands/meshes.js.map +1 -1
  65. package/dist/commands/mint.d.ts.map +1 -1
  66. package/dist/commands/mint.js +11 -4
  67. package/dist/commands/mint.js.map +1 -1
  68. package/dist/commands/persona-remote.js +2 -2
  69. package/dist/commands/persona-remote.js.map +1 -1
  70. package/dist/commands/persona.d.ts.map +1 -1
  71. package/dist/commands/persona.js +28 -9
  72. package/dist/commands/persona.js.map +1 -1
  73. package/dist/commands/personas.d.ts.map +1 -1
  74. package/dist/commands/personas.js +17 -15
  75. package/dist/commands/personas.js.map +1 -1
  76. package/dist/commands/reset-space-apply.js +4 -4
  77. package/dist/commands/reset-space-apply.js.map +1 -1
  78. package/dist/commands/reset-store-apply.d.ts +2 -8
  79. package/dist/commands/reset-store-apply.d.ts.map +1 -1
  80. package/dist/commands/reset-store-apply.js +12 -28
  81. package/dist/commands/reset-store-apply.js.map +1 -1
  82. package/dist/commands/reset.js +2 -2
  83. package/dist/commands/reset.js.map +1 -1
  84. package/dist/commands/send.d.ts.map +1 -1
  85. package/dist/commands/send.js +21 -9
  86. package/dist/commands/send.js.map +1 -1
  87. package/dist/commands/service-actions.d.ts.map +1 -1
  88. package/dist/commands/service-actions.js +15 -4
  89. package/dist/commands/service-actions.js.map +1 -1
  90. package/dist/commands/service-registry.d.ts.map +1 -1
  91. package/dist/commands/service-registry.js +16 -5
  92. package/dist/commands/service-registry.js.map +1 -1
  93. package/dist/commands/setup.d.ts.map +1 -1
  94. package/dist/commands/setup.js +18 -10
  95. package/dist/commands/setup.js.map +1 -1
  96. package/dist/commands/space-delete.d.ts.map +1 -1
  97. package/dist/commands/space-delete.js +72 -33
  98. package/dist/commands/space-delete.js.map +1 -1
  99. package/dist/commands/space-export.js +1 -1
  100. package/dist/commands/space-export.js.map +1 -1
  101. package/dist/commands/space-registration.d.ts +4 -3
  102. package/dist/commands/space-registration.d.ts.map +1 -1
  103. package/dist/commands/space-registration.js +63 -41
  104. package/dist/commands/space-registration.js.map +1 -1
  105. package/dist/commands/space.d.ts.map +1 -1
  106. package/dist/commands/space.js +24 -8
  107. package/dist/commands/space.js.map +1 -1
  108. package/dist/commands/spawn-enrollment.d.ts +93 -0
  109. package/dist/commands/spawn-enrollment.d.ts.map +1 -0
  110. package/dist/commands/spawn-enrollment.js +195 -0
  111. package/dist/commands/spawn-enrollment.js.map +1 -0
  112. package/dist/commands/spawn-flags.d.ts +205 -0
  113. package/dist/commands/spawn-flags.d.ts.map +1 -0
  114. package/dist/commands/spawn-flags.js +34 -0
  115. package/dist/commands/spawn-flags.js.map +1 -0
  116. package/dist/commands/spawn-foreground.d.ts +74 -0
  117. package/dist/commands/spawn-foreground.d.ts.map +1 -0
  118. package/dist/commands/spawn-foreground.js +355 -0
  119. package/dist/commands/spawn-foreground.js.map +1 -0
  120. package/dist/commands/spawn-managed-launch.d.ts +43 -0
  121. package/dist/commands/spawn-managed-launch.d.ts.map +1 -0
  122. package/dist/commands/spawn-managed-launch.js +631 -0
  123. package/dist/commands/spawn-managed-launch.js.map +1 -0
  124. package/dist/commands/spawn-preview.d.ts.map +1 -1
  125. package/dist/commands/spawn-preview.js +7 -4
  126. package/dist/commands/spawn-preview.js.map +1 -1
  127. package/dist/commands/spawn.d.ts +8 -266
  128. package/dist/commands/spawn.d.ts.map +1 -1
  129. package/dist/commands/spawn.js +21 -1198
  130. package/dist/commands/spawn.js.map +1 -1
  131. package/dist/commands/stack-down.d.ts +3 -2
  132. package/dist/commands/stack-down.d.ts.map +1 -1
  133. package/dist/commands/stack-down.js +72 -31
  134. package/dist/commands/stack-down.js.map +1 -1
  135. package/dist/commands/stack-up.d.ts +2 -0
  136. package/dist/commands/stack-up.d.ts.map +1 -1
  137. package/dist/commands/stack-up.js +16 -7
  138. package/dist/commands/stack-up.js.map +1 -1
  139. package/dist/commands/status-stop-impact.d.ts +3 -0
  140. package/dist/commands/status-stop-impact.d.ts.map +1 -0
  141. package/dist/commands/status-stop-impact.js +34 -0
  142. package/dist/commands/status-stop-impact.js.map +1 -0
  143. package/dist/commands/status.d.ts.map +1 -1
  144. package/dist/commands/status.js +96 -80
  145. package/dist/commands/status.js.map +1 -1
  146. package/dist/commands/team-boot-controller.d.ts.map +1 -1
  147. package/dist/commands/team-boot-controller.js +21 -4
  148. package/dist/commands/team-boot-controller.js.map +1 -1
  149. package/dist/commands/team.d.ts.map +1 -1
  150. package/dist/commands/team.js +25 -23
  151. package/dist/commands/team.js.map +1 -1
  152. package/dist/commands/telemetry.d.ts +1 -1
  153. package/dist/commands/telemetry.d.ts.map +1 -1
  154. package/dist/commands/telemetry.js +17 -7
  155. package/dist/commands/telemetry.js.map +1 -1
  156. package/dist/commands/up-target.d.ts +7 -0
  157. package/dist/commands/up-target.d.ts.map +1 -0
  158. package/dist/commands/up-target.js +42 -0
  159. package/dist/commands/up-target.js.map +1 -0
  160. package/dist/commands/up.d.ts +4 -11
  161. package/dist/commands/up.d.ts.map +1 -1
  162. package/dist/commands/up.js +212 -207
  163. package/dist/commands/up.js.map +1 -1
  164. package/dist/commands/update-caches.d.ts +4 -0
  165. package/dist/commands/update-caches.d.ts.map +1 -0
  166. package/dist/commands/update-caches.js +82 -0
  167. package/dist/commands/update-caches.js.map +1 -0
  168. package/dist/commands/update.d.ts.map +1 -1
  169. package/dist/commands/update.js +29 -115
  170. package/dist/commands/update.js.map +1 -1
  171. package/dist/commands/use.d.ts.map +1 -1
  172. package/dist/commands/use.js +43 -22
  173. package/dist/commands/use.js.map +1 -1
  174. package/dist/commands/who.d.ts.map +1 -1
  175. package/dist/commands/who.js +2 -3
  176. package/dist/commands/who.js.map +1 -1
  177. package/dist/console/commands.d.ts.map +1 -1
  178. package/dist/console/commands.js +3 -2
  179. package/dist/console/commands.js.map +1 -1
  180. package/dist/help.d.ts.map +1 -1
  181. package/dist/help.js +2 -1
  182. package/dist/help.js.map +1 -1
  183. package/dist/index.d.ts.map +1 -1
  184. package/dist/index.js +5 -2
  185. package/dist/index.js.map +1 -1
  186. package/dist/lib/broker-log.d.ts +8 -0
  187. package/dist/lib/broker-log.d.ts.map +1 -0
  188. package/dist/lib/broker-log.js +27 -0
  189. package/dist/lib/broker-log.js.map +1 -0
  190. package/dist/lib/completion-install.d.ts.map +1 -1
  191. package/dist/lib/completion-install.js +17 -10
  192. package/dist/lib/completion-install.js.map +1 -1
  193. package/dist/lib/credential-authority.d.ts +7 -3
  194. package/dist/lib/credential-authority.d.ts.map +1 -1
  195. package/dist/lib/credential-authority.js +44 -11
  196. package/dist/lib/credential-authority.js.map +1 -1
  197. package/dist/lib/manifest/ledger.d.ts.map +1 -1
  198. package/dist/lib/manifest/ledger.js +7 -3
  199. package/dist/lib/manifest/ledger.js.map +1 -1
  200. package/dist/lib/paths.d.ts.map +1 -1
  201. package/dist/lib/paths.js +3 -3
  202. package/dist/lib/paths.js.map +1 -1
  203. package/dist/lib/restore.d.ts +32 -3
  204. package/dist/lib/restore.d.ts.map +1 -1
  205. package/dist/lib/restore.js +65 -54
  206. package/dist/lib/restore.js.map +1 -1
  207. package/dist/lib/service-preset-target.d.ts +2 -2
  208. package/dist/lib/service-preset-target.d.ts.map +1 -1
  209. package/dist/lib/service-preset-target.js +30 -15
  210. package/dist/lib/service-preset-target.js.map +1 -1
  211. package/dist/lib/service-presets.d.ts +2 -0
  212. package/dist/lib/service-presets.d.ts.map +1 -1
  213. package/dist/lib/service-presets.js +19 -2
  214. package/dist/lib/service-presets.js.map +1 -1
  215. package/dist/lib/spawn-defaults.d.ts +5 -0
  216. package/dist/lib/spawn-defaults.d.ts.map +1 -1
  217. package/dist/lib/spawn-defaults.js +5 -0
  218. package/dist/lib/spawn-defaults.js.map +1 -1
  219. package/dist/lib/stack-journal.d.ts +7 -4
  220. package/dist/lib/stack-journal.d.ts.map +1 -1
  221. package/dist/lib/stack-journal.js +31 -15
  222. package/dist/lib/stack-journal.js.map +1 -1
  223. package/dist/lib/transient.d.ts +3 -3
  224. package/dist/lib/transient.d.ts.map +1 -1
  225. package/dist/lib/transient.js +6 -5
  226. package/dist/lib/transient.js.map +1 -1
  227. package/dist/lib/up-broker-address.d.ts +7 -0
  228. package/dist/lib/up-broker-address.d.ts.map +1 -0
  229. package/dist/lib/up-broker-address.js +76 -0
  230. package/dist/lib/up-broker-address.js.map +1 -0
  231. package/dist/lib/up-report.d.ts +2 -0
  232. package/dist/lib/up-report.d.ts.map +1 -1
  233. package/dist/lib/up-report.js +8 -1
  234. package/dist/lib/up-report.js.map +1 -1
  235. package/dist/lib/update-connector-config.d.ts +6 -0
  236. package/dist/lib/update-connector-config.d.ts.map +1 -0
  237. package/dist/lib/update-connector-config.js +44 -0
  238. package/dist/lib/update-connector-config.js.map +1 -0
  239. package/dist/seed/reconcile.d.ts +1 -1
  240. package/dist/seed/reconcile.d.ts.map +1 -1
  241. package/dist/seed/reconcile.js +113 -35
  242. package/dist/seed/reconcile.js.map +1 -1
  243. package/package.json +4 -4
@@ -1,13 +1,14 @@
1
1
  import { noManagerCredentialWarning } from "../lib/daemon-credential-warning.js";
2
2
  import { drainAndClose } from "@cotal-ai/core";
3
3
  import {} from "node:child_process";
4
+ import { openBrokerLog, prepareForegroundBrokerLog } from "../lib/broker-log.js";
4
5
  import { spawnBroker } from "../lib/broker-spawn.js";
5
6
  import { randomUUID } from "node:crypto";
6
7
  import { createConnection, createServer, isIP } from "node:net";
7
8
  import { homedir, hostname } from "node:os";
8
9
  import { accessSync, constants, mkdirSync, readFileSync, existsSync, statSync, closeSync, lstatSync, realpathSync, readdirSync, rmdirSync, } from "node:fs";
9
10
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
10
- import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, SERVICE_AUTHORITY_MAX_BYTES, SERVICE_CALLER_PAYLOAD_FLOOR, CONTRACT_ARTIFACT_MAX_BYTES, MANAGER_START_PAYLOAD_FLOOR, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, removeIssuedStoresBeforeRetention, IssuedStoreBeforeRetentionError, IssuedStoreRecreateRefusal, reconcileSpaceMemoryBuckets, membershipStoreDefinition, LEGACY_MEMBERSHIP_MAX_BYTES, MEMBERSHIP_MAX_VALUE_SIZE, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, spaceDeletionStreams, isJetStreamMissing, seedChannelRegistry, ensureDefaultDeliveryClass, UndecodableRegistryEntry, LEASE_TTL_MS, EpEnvelopeError, mkSecretDir, openPrivateAppend, writeSecretFile, } from "@cotal-ai/core";
11
+ import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, SERVICE_AUTHORITY_MAX_BYTES, SERVICE_CALLER_PAYLOAD_FLOOR, CONTRACT_ARTIFACT_MAX_BYTES, MANAGER_START_PAYLOAD_FLOOR, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, removeIssuedStoresBeforeRetention, IssuedStoreBeforeRetentionError, IssuedStoreRecreateRefusal, reconcileSpaceMemoryBuckets, recreateMembershipStore, membershipStoreDefinition, LEGACY_MEMBERSHIP_MAX_BYTES, MEMBERSHIP_MAX_VALUE_SIZE, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, spaceDeletionStreams, isJetStreamMissing, seedChannelRegistry, ensureDefaultDeliveryClass, UndecodableRegistryEntry, LEASE_TTL_MS, EpEnvelopeError, mkSecretDir, writeSecretFile, } from "@cotal-ai/core";
11
12
  import { JetStreamApiCodes, jetstreamManager, StorageType } from "@nats-io/jetstream";
12
13
  import { Kvm } from "@nats-io/kv";
13
14
  import { assertManagerName, processStopped, readManagerName, readManagerSeatCap, recordManagerName, parseSeatCapFlag, seatCapText, CommandFailure, codeSpan, commandFailureReport, failureEnvelope, writeEnvelope, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, brokerPolicyPath, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, brokerAddressKey, canonicalRoot, rootPathProblem, rootControlProblem, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, legacyStackOtherHome, stackHomeRemedy, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, keepsRegistration, oneLine, presentationOf, writeResult, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, WEB_CREDS_KIND, webCredsKey, parsePositiveIntegerFlag, recordMesh, retainedLegacyBroker, meshesForRoot, removeMesh, rotateSystemCreds, setAdoptedCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessMaintenanceClaim, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, rootNamesNoSpace, readMaintenanceResumeDocument, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, writeBrokerPolicy, brokerAccountResolver, removePidPair, writePidPair, verifyIdentityPin, processesNaming, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, recordsElsewhereError, recordOperationWarning, retainSystemSigningSeed, restoreLeftOut, SPACE_NAME_MAX, spaceNameTooLong, NATS_PIDFILE, MANAGER_PIDFILE, DELIVERY_PIDFILE, AUTH_PIDFILE, localProcessPath, UNTRUSTED_CERTIFICATE, exitCode, canonicalLocalProcessPath, DELIVERY_LOGFILE, terminalWidth, } from "@cotal-ai/workspace";
@@ -19,7 +20,7 @@ import { admitAndRestoreSeatCheckpoints } from "../lib/seat-resume.js";
19
20
  import { NATS_DEFAULT_MAX_PAYLOAD, natsServerLabel, resolveNatsServer, unreadVersion } from "../lib/nats-bin.js";
20
21
  import { cotalPath, cotalRoot, homeHoldsStack, linkedCotalRefusal } from "../lib/paths.js";
21
22
  import { channelsReads, readChannelsFile, readDefaultChannelsFile } from "../lib/channel-seed.js";
22
- import { detachedNext, renderDetachedSummary } from "../lib/up-report.js";
23
+ import { controllerManifestRemedy, detachedNext, renderDetachedSummary } from "../lib/up-report.js";
23
24
  import { seedDefaultPersona } from "../lib/default-persona.js";
24
25
  import { seedBeforeLaunch, seedMoveNote } from "../seed/launch.js";
25
26
  import { seedDir } from "../seed/paths.js";
@@ -42,6 +43,7 @@ import { failManifest, refuseManifestSpaceMismatch } from "./topology.js";
42
43
  import { liveMeshProcesses } from "./clean.js";
43
44
  import { checkSpaceFlagValue, checkSpaceName } from "./meshes-add.js";
44
45
  import { checkLocalSpace } from "./space-registration.js";
46
+ import { checkNewUpSpace, preparedUpRoot } from "./up-target.js";
45
47
  import { cleanedManifestStart, interruptedStartBroker, namedOpenConfig, retainedOpenSpace } from "../lib/legacy-start.js";
46
48
  import { bindReaches, canonicalServer, controllerStackApplies, recheckExistingStore, requestedStackMode, requestsTls, stackUp, stackUpForegroundNotice, stackUpInterrupted, keptOnUp, selectedOnUp, unparsableDaemonCredsNotice, } from "./stack-up.js";
47
49
  import { handOverStartupNotice, noticeOnInterrupt, releaseStartupNotice } from "../lib/interrupt-notice.js";
@@ -63,10 +65,11 @@ import { assertStoreDirArgument, configuredStoreDir, lastServedStore, lastServed
63
65
  import { extensionNames, preflightRuntime } from "../ext-loader.js";
64
66
  import { completingFlagValue } from "../lib/completion.js";
65
67
  import { metadataPositionals } from "../lib/command-path.js";
66
- import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, heldClaim, movedFolderRefusal, prepareRestore, preservedSourceState, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, journaledMaxFileStore, journaledRestoredStreams, leftOutNotes, rearmUnboundRestore, replacePreparedDeadRestoreListener, restoreComposition, restoreNextStep, restoreOnlyCopy, } from "../lib/restore.js";
68
+ import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, heldClaim, movedFolderRefusal, prepareRestore, restoreArtifactPath, restoreLaunch, preservedSourceState, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, journaledMaxFileStore, journaledRestoredStreams, leftOutNotes, rearmUnboundRestore, replacePreparedDeadRestoreListener, restoreComposition, restoreNextStep, restoreOnlyCopy, } from "../lib/restore.js";
67
69
  import { attemptProcessesGone } from "../lib/isolated-broker.js";
68
70
  import { assertEndpointUnreachable } from "../lib/endpoint-cut.js";
69
71
  import { addressHolder, brokerListenAddress, listenerBindError } from "../lib/broker-service.js";
72
+ import { freePort, freshStackServer, retryStackAddress, serverWithFreePort } from "../lib/up-broker-address.js";
70
73
  import { askManager } from "@cotal-ai/workspace/control";
71
74
  import { cliControl } from "../lib/control.js";
72
75
  const pendingRestores = new Map();
@@ -92,8 +95,8 @@ export const upFlags = [
92
95
  { name: "store-dir", type: "string", value: "<dir>", description: "JetStream store directory" },
93
96
  { name: "max-file-store", type: "string", value: "<bytes>", description: "JetStream file storage cap in bytes (default: nats-server's dynamic cap). Fixed at broker start and recorded for the next `up`; a legacy root also keeps it across `down --preserve-state`" },
94
97
  { name: "log-file", type: "string", value: "<path>", description: "nats-server log file path; recorded and reused by later starts" },
95
- { name: "logfile-size-limit", type: "string", value: "<bytes>", description: "nats-server log rotation threshold in bytes; requires --log-file or broker.logFile in a manifest" },
96
- { name: "logfile-max-num", type: "string", value: "<count>", description: "maximum total broker log files retained; requires --log-file or broker.logFile in a manifest" },
98
+ { name: "logfile-size-limit", type: "string", value: "<bytes>", description: "nats-server log rotation threshold in bytes; requires --log-file, a saved controller log path, or broker.logFile in a manifest" },
99
+ { name: "logfile-max-num", type: "string", value: "<count>", description: "maximum total broker log files retained; requires --log-file, a saved controller log path, or broker.logFile in a manifest" },
97
100
  { name: "auth-timeout", type: "string", value: "<seconds>", description: "user-auth only: how long the broker waits for the auth callout, 1 to 60 seconds (default: nats-server's 2); the auth service answers inside it. Fixed at broker start and recorded for the next `up`" },
98
101
  { name: "max-payload", type: "string", value: "<bytes>", description: `broker-wide message size limit in bytes (default: nats-server's ${NATS_DEFAULT_MAX_PAYLOAD}). A manager-backed start needs at least 263168, and service endpoint caller grants need at least 2098176. Fixed at broker start and recorded for the next \`up\`` },
99
102
  { name: "account-resolver", type: "string", value: "<memory|full>", description: "how the broker resolves space accounts: memory (default) knows only the accounts its configuration lists, so adding one means a reload; full also keeps pushed account claims in .cotal/account-jwts, so a host can add and retire accounts on the running broker without a reload. Fixed at broker start and recorded for the next `up`" },
@@ -168,8 +171,14 @@ export function validateUpArguments(args) {
168
171
  throw linked;
169
172
  if (args.values["user-auth"] === true && args.values.open === true)
170
173
  throw new CommandFailure("refused", "USAGE_INVALID", "--user-auth and --open contradict - a user-auth space cannot run unauthenticated", { remedy: "drop --open for user auth, or drop --user-auth for an open space" });
174
+ if (args.values.open === true) {
175
+ publicExchangeArgs(args.values, false);
176
+ serviceEndpointsArgs(args.values, false);
177
+ }
171
178
  if (args.values.idp !== undefined && args.values["user-auth"] !== true && !args.values.file)
172
179
  throw new CommandFailure("refused", "USAGE_INVALID", '--idp is for user-auth spaces; pair it with --user-auth, or set broker.auth: "user" in a manifest', { remedy: "use --user-auth --idp <auth base URL>, without --open" });
180
+ if (args.values.restore !== undefined && args.values["no-manager"] === true)
181
+ throw new CommandFailure("refused", "USAGE_INVALID", "--no-manager cannot be combined with --restore: the restore needs a manager to commit its state; nothing was restored", { remedy: "rerun the restore without --no-manager" });
173
182
  if (args.values["no-manager"] === true && args.values.runtime !== undefined)
174
183
  throw new CommandFailure("refused", "USAGE_INVALID", "--no-manager cannot be combined with --runtime because no manager starts", { remedy: "drop --runtime, or drop --no-manager to select a manager runtime" });
175
184
  // Only an omitted --runtime selects the default runtime. An empty one, as an unset variable gives,
@@ -220,6 +229,12 @@ export function validateUpArguments(args) {
220
229
  const logFile = args.values["log-file"];
221
230
  if (logFile !== undefined && (!logFile.trim() || /[\u0000-\u001f\u007f]/u.test(logFile)))
222
231
  throw new CommandFailure("refused", "USAGE_INVALID", "--log-file must be a non-empty file path without control characters");
232
+ const logfileSizeLimit = parsePositiveIntegerFlag("--logfile-size-limit", args.values["logfile-size-limit"]);
233
+ const logfileMaxNum = parsePositiveIntegerFlag("--logfile-max-num", args.values["logfile-max-num"]);
234
+ // A controller restart can use its saved path. A restore still needs an explicit path.
235
+ if (!args.values.file && logFile === undefined && (logfileSizeLimit !== undefined || logfileMaxNum !== undefined)
236
+ && (args.values.restore !== undefined || readStackJournal(tlsRoot)?.journal.broker?.logFile === undefined))
237
+ throw new CommandFailure("refused", "USAGE_INVALID", "--logfile-size-limit and --logfile-max-num require --log-file");
223
238
  // The timeout belongs to the auth callout, which only a user-auth space has. A manifest or a
224
239
  // restore starts the broker its own record describes, so neither takes it.
225
240
  if (parseAuthTimeout(args.values["auth-timeout"]) !== undefined) {
@@ -504,27 +519,7 @@ function machineHomeRoot() {
504
519
  const root = cotalRoot();
505
520
  return canonicalRoot(root) === canonicalRoot(homedir()) || canonicalRoot(join(root, ".cotal")) === canonicalRoot(homeCotalDir()) ? root : undefined;
506
521
  }
507
- /** An explicit root is an existing local workspace, not a hint to find another ancestor or
508
- * create trust in an arbitrary directory. Validation runs before the dispatcher seeds extensions. */
509
- export function preparedUpRoot(value) {
510
- if (!value)
511
- throw new CommandFailure("refused", "USAGE_INVALID", "--root needs an existing prepared project directory; an empty value is not the current folder");
512
- let root;
513
- try {
514
- root = realpathSync(resolve(value));
515
- if (!statSync(root).isDirectory())
516
- throw new Error("not a directory");
517
- const cotal = lstatSync(join(root, ".cotal"));
518
- if (!cotal.isDirectory() || cotal.isSymbolicLink())
519
- throw new Error("not a private project directory");
520
- }
521
- catch {
522
- throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "--root must name an existing prepared local project with its own .cotal directory; no ancestor or other space was selected", { target: { root: resolve(value) }, remedy: "prepare it with `cotal space create <space> --root <dir>`, then retry with that root" });
523
- }
524
- if (canonicalRoot(root) === canonicalRoot(homedir()) || canonicalRoot(join(root, ".cotal")) === canonicalRoot(homeCotalDir()))
525
- throw new CommandFailure("refused", "CONFLICT", "--root names the machine's home store, not a prepared project; no stack was started there", { target: { root }, remedy: "prepare the space in a project folder with `cotal space create <space> --root <dir>`" });
526
- return root;
527
- }
522
+ export { preparedUpRoot } from "./up-target.js";
528
523
  /** The fresh team entry refuses retained custody before `up -f` can write a launch spec,
529
524
  * regenerate trust or stop a leftover manager. Only a recorded local root is eligible. */
530
525
  function assertFreshTeamBootOwnership(root, space, mode, own) {
@@ -626,16 +621,16 @@ function hangupForegroundStack(root) {
626
621
  * the start left. A failed start still runs the stop, and its failure is thrown once the stop returns.
627
622
  * The hold's end sets the exit code: 0 when another command completed the stop or preserve, 129 after
628
623
  * a hangup, 130 or 143 after a stop signal, whatever the start receipt set. */
629
- export async function holdForegroundStack(root, start) {
624
+ export async function holdForegroundStack(root, start, releaseRestoreNotice) {
630
625
  claimForegroundHold(root);
631
626
  try {
632
- await holdStack(root, start);
627
+ await holdStack(root, start, releaseRestoreNotice);
633
628
  }
634
629
  finally {
635
630
  releaseForegroundHold(root);
636
631
  }
637
632
  }
638
- async function holdStack(root, start) {
633
+ async function holdStack(root, start, releaseRestoreNotice) {
639
634
  // The start's listeners go only once the hold's own are installed. Node runs a listener for a
640
635
  // signal when the loop next polls, and drops the signal if its last listener was removed first,
641
636
  // so a signal that lands in the start's last synchronous step would be lost in between.
@@ -719,6 +714,7 @@ async function holdStack(root, start) {
719
714
  process.on("SIGHUP", hangup);
720
715
  releaseStart();
721
716
  handOverStartupNotice();
717
+ releaseRestoreNotice?.();
722
718
  });
723
719
  }
724
720
  /** The registered `up` command. When a background run is the main process of a systemd unit, it
@@ -769,6 +765,9 @@ export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink
769
765
  let adopted = false;
770
766
  try {
771
767
  validateUpArguments(args);
768
+ const root = args.values.root === undefined ? undefined : preparedUpRoot(String(args.values.root));
769
+ const fresh = args.values.root === undefined ? freshFolderRoot(args.values) : undefined;
770
+ checkNewUpSpace(args.values.space, root ?? fresh);
772
771
  // The broker reads an explicit channels file only once it is being prepared, so a file it would
773
772
  // refuse is named here, before the stack journal or anything else is written.
774
773
  if (typeof args.values.channels === "string")
@@ -778,13 +777,11 @@ export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink
778
777
  args = { ...args, values: { ...args.values, space: folderNamed, __folderNamed: true } };
779
778
  // A fresh folder under the machine home gets its own `.cotal` before anything resolves the root, so
780
779
  // every later step uses this folder. A run that stops before writing there removes it again.
781
- const fresh = args.values.root === undefined ? freshFolderRoot(args.values) : undefined;
782
780
  if (fresh) {
783
781
  mkdirSync(join(fresh, ".cotal"), { mode: 0o700 });
784
782
  for (const line of hang("", `made ${join(fresh, ".cotal")} for this folder's records; the machine's home .cotal was not used`, terminalWidth(process.stderr), c.dim))
785
783
  console.error(line);
786
784
  }
787
- const root = args.values.root === undefined ? undefined : preparedUpRoot(String(args.values.root));
788
785
  const previousCwd = process.cwd();
789
786
  // Path flags still mean paths relative to the invoking directory, not the selected root.
790
787
  // The recursive restore/resume re-entries inherit absolute paths and the same absolute root.
@@ -812,7 +809,7 @@ export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink
812
809
  }
813
810
  }
814
811
  try {
815
- return await runUp(invocation, inheritedLock, () => { adopted = true; }, freshTeamBoot, restoreSink);
812
+ return await runUp(invocation, previousCwd, inheritedLock, () => { adopted = true; }, freshTeamBoot, restoreSink);
816
813
  }
817
814
  catch (error) {
818
815
  if (fresh)
@@ -842,7 +839,10 @@ function removeEmptyRecords(path) {
842
839
  }
843
840
  }
844
841
  const NO_MANAGER_DURING_RECOVERY = "--no-manager is refused while this root has a maintenance attempt to recover - a resume needs a manager to commit the preserved inventory; recover it (`cotal up` alone) or roll it back first";
845
- async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restoreSink) {
842
+ function retainedStartupPresentationRefusal(root) {
843
+ return new CommandFailure("refused", "UNSUPPORTED", "this startup uses the retained native launcher, which has no structured or plain receipt; nothing was started", { target: { root }, remedy: "use a fresh prepared root with static auth, --open, or plain-loopback --user-auth for the controller-owned stack, or omit --json/--plain" });
844
+ }
845
+ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot = false, restoreSink) {
846
846
  const values = args.values;
847
847
  if (freshTeamBoot && (!values.file || values.restore || values.__restoreAttempt || values.__ordinaryResumeAttempt || values["rotate-sys"] || values["no-manager"]))
848
848
  throw new CommandFailure("refused", "USAGE_INVALID", "fresh team boot accepts one manifest and its selected lifetime, not a restore, rotation or manager-free override");
@@ -865,70 +865,102 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
865
865
  throw new Error("--restore cannot be combined with --rotate-sys - restore the space and verify it first, then rotate: `cotal down` then `cotal up --rotate-sys`");
866
866
  // A restore rewrites the shared store and the trust root under it, from an artifact that names
867
867
  // one space (see `cotal backup`) - it cannot leave the root's other tenants standing.
868
- assertSingleSpaceBroker(authDir(cotalRoot()), "cotal up --restore");
868
+ const root = cotalRoot();
869
+ assertSingleSpaceBroker(authDir(root), "cotal up --restore");
870
+ const flags = values;
871
+ const journal = readMaintenanceJournal(root);
872
+ const nextArgs = (launch, attemptId) => {
873
+ const defaultStore = join(launch.root, ".cotal", "nats");
874
+ const atDefault = launch.targetPath === defaultStore || (() => { try {
875
+ return realpathSync(defaultStore) === launch.targetPath;
876
+ }
877
+ catch {
878
+ return false;
879
+ } })();
880
+ return { ...args, values: {
881
+ ...values,
882
+ ...(values["store-dir"] === undefined && !atDefault ? { "store-dir": launch.targetPath } : {}),
883
+ restore: undefined,
884
+ "restore-only": undefined,
885
+ "accept-missing-source": undefined,
886
+ __restoreAttempt: attemptId,
887
+ space: values.space ?? launch.space,
888
+ server: launch.server, host: launch.host,
889
+ runtime: launch.runtime,
890
+ "max-file-store": launch.maxFileStore === undefined ? undefined : String(launch.maxFileStore),
891
+ open: launch.mode === "open",
892
+ "user-auth": launch.mode === "user",
893
+ } };
894
+ };
895
+ const validateLaunch = async (launch, controller) => {
896
+ if (controller)
897
+ return;
898
+ const next = nextArgs(launch);
899
+ validateUpArguments(next);
900
+ const wantUser = launch.mode === "user";
901
+ publicExchangeArgs(values, wantUser);
902
+ serviceEndpointsArgs(values, wantUser);
903
+ if (values.json || values.plain)
904
+ throw retainedStartupPresentationRefusal(root);
905
+ const transport = resolveTransport(values, undefined, root, { persist: false, quiet: true });
906
+ assertTlsIntentServed(launch.server, transport, "--server");
907
+ assertTlsAddressServed(launch.server, transport, root);
908
+ assertServesDialHost(transport, new URL(launch.server).hostname);
909
+ loadChannelsFile();
910
+ if (wantUser && values.idp !== undefined)
911
+ await preflightUserStack(root, launch.space, values.idp);
912
+ try {
913
+ await preflightRuntime(launch.runtime);
914
+ }
915
+ catch (error) {
916
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "the requested runtime did not pass preflight; nothing was restored", { target: { root, space: launch.space, runtime: launch.runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
917
+ }
918
+ };
919
+ // Validate the synthesized re-entry before preparation, then recheck the launch read under the
920
+ // restore lock before staging, in case the preserved cut changed in the meantime.
921
+ if (journal?.state === "ready" && !cutController(journal.cut)) {
922
+ restoreArtifactPath(root, flags.restore, journal.source.path);
923
+ await validateLaunch(restoreLaunch(root, flags, journal).launch, false);
924
+ }
869
925
  // `up` keeps the startup interrupt notice (`keepsStartupNotice`); a restore reports its own.
870
926
  await releaseStartupNotice();
871
927
  // A `backup restore` owns stdout for its receipt, so its seat admission lines go to stderr.
872
- const prepared = await prepareRestore(cotalRoot(), values, restoreSink ? (line) => console.error(line) : undefined);
928
+ const prepared = await prepareRestore(root, flags, validateLaunch, restoreSink ? (line) => console.error(line) : undefined);
873
929
  pendingRestores.set(prepared.attemptId, prepared);
874
- const committed = readMaintenanceJournal(prepared.root);
875
- if (committed && cutController(committed.cut)) {
876
- // A controller restore continues through its recorded members. A member
877
- // that cannot start holds the attempt at commit intent for bare `cotal up` to continue; it is
878
- // not marked degraded, because a degraded attempt starts nothing.
879
- const lock = acquireMaintenanceLock(prepared.root);
880
- let foreground;
930
+ try {
931
+ const committed = readMaintenanceJournal(prepared.root);
932
+ if (committed && cutController(committed.cut)) {
933
+ // A controller restore continues through its recorded members. A member
934
+ // that cannot start holds the attempt at commit intent for bare `cotal up` to continue; it is
935
+ // not marked degraded, because a degraded attempt starts nothing.
936
+ const lock = acquireMaintenanceLock(prepared.root);
937
+ let foreground;
938
+ try {
939
+ foreground = await resumeControllerStack(lock, prepared.root, values, restoreSink);
940
+ }
941
+ finally {
942
+ releaseMaintenanceLock(lock);
943
+ }
944
+ if (foreground)
945
+ await holdForegroundStack(prepared.root, undefined, prepared.releaseInterruptNotice);
946
+ return;
947
+ }
948
+ if (restoreSink)
949
+ restoreSinks.set(prepared.attemptId, restoreSink);
881
950
  try {
882
- foreground = await resumeControllerStack(lock, prepared.root, values, restoreSink);
951
+ await up(nextArgs(prepared, prepared.attemptId));
883
952
  }
884
- finally {
885
- pendingRestores.delete(prepared.attemptId);
886
- releaseMaintenanceLock(lock);
953
+ catch (error) {
954
+ // The re-entry has already released its startup lock, so this helper takes its own.
955
+ markPreparedRestoreDegraded(prepared.root, prepared.attemptId, error.message);
956
+ throw error;
887
957
  }
888
- if (foreground)
889
- await holdForegroundStack(prepared.root);
890
- return;
891
958
  }
892
- if (restoreSink)
893
- restoreSinks.set(prepared.attemptId, restoreSink);
894
- // The launch opens the store the restore wrote. With no --store-dir that was the default store,
895
- // or the store it links to, until a missing source came to be rebuilt at its recorded path (#7049).
896
- const defaultStore = join(prepared.root, ".cotal", "nats");
897
- const atDefault = prepared.targetPath === defaultStore || (() => { try {
898
- return realpathSync(defaultStore) === prepared.targetPath;
899
- }
900
- catch {
901
- return false;
902
- } })();
903
- const next = {
904
- ...values,
905
- ...(values["store-dir"] === undefined && !atDefault ? { "store-dir": prepared.targetPath } : {}),
906
- restore: undefined,
907
- "restore-only": undefined,
908
- "accept-missing-source": undefined,
909
- __restoreAttempt: prepared.attemptId,
910
- space: values.space ?? prepared.space,
911
- server: values.server ?? prepared.server,
912
- host: values.host ?? prepared.host,
913
- runtime: values.runtime ?? prepared.runtime,
914
- open: prepared.mode === "open",
915
- "user-auth": prepared.mode === "user",
916
- };
917
- try {
918
- await up({ ...args, values: next });
919
- }
920
- catch (error) {
959
+ finally {
960
+ prepared.releaseInterruptNotice?.();
921
961
  pendingRestores.delete(prepared.attemptId);
922
962
  restoreSinks.delete(prepared.attemptId);
923
- // The one journal writer deliberately NOT handed a lock, and the reason is structural rather
924
- // than stylistic: no lock is held in this frame either way. This invocation returns just below
925
- // without ever reaching the `startupLock` acquire, and the re-entry that did hold one released
926
- // it in its own `finally` on the way out through this very throw. So the helper must take its
927
- // own — passing something here would mean passing `undefined`, which reads as an oversight.
928
- markPreparedRestoreDegraded(prepared.root, prepared.attemptId, error.message);
929
- throw error;
930
963
  }
931
- restoreSinks.delete(prepared.attemptId);
932
964
  return;
933
965
  }
934
966
  // A result sink belongs to the explicit restore entry above, never to a recovery, resume or
@@ -1186,7 +1218,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1186
1218
  // one is durably retired before a fresh spawn, ambiguity refuses, and a manager-committed
1187
1219
  // resume never replaces the listener its durable token is bound to.
1188
1220
  let adoptProof;
1189
- let recoveredProof = journal.listenerProof;
1221
+ const recoveredProof = journal.listenerProof;
1190
1222
  let recoveredState = journal.state;
1191
1223
  if (recoveredProof) {
1192
1224
  const status = localProcessOwnerStatus(recoveredProof.processOwner);
@@ -1208,7 +1240,6 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1208
1240
  recoveredState = "resume-degraded";
1209
1241
  }
1210
1242
  replaceDeadOrdinaryResumeListener(lock, recoveredProof);
1211
- recoveredProof = undefined;
1212
1243
  }
1213
1244
  }
1214
1245
  const freshNonce = randomUUID().replaceAll("-", "");
@@ -1325,19 +1356,17 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1325
1356
  const logFile = values["log-file"] === undefined ? undefined : resolve(values["log-file"]);
1326
1357
  const logfileSizeLimit = parsePositiveIntegerFlag("--logfile-size-limit", values["logfile-size-limit"]);
1327
1358
  const logfileMaxNum = parsePositiveIntegerFlag("--logfile-max-num", values["logfile-max-num"]);
1328
- if (!values.file && logFile === undefined && (logfileSizeLimit !== undefined || logfileMaxNum !== undefined))
1329
- throw new CommandFailure("refused", "USAGE_INVALID", "--logfile-size-limit and --logfile-max-num require --log-file");
1330
1359
  const authTimeout = parseAuthTimeout(values["auth-timeout"]);
1331
1360
  const maxPayload = parseMaxPayload(values["max-payload"]);
1332
1361
  const accountResolver = parseAccountResolver(values["account-resolver"]);
1333
1362
  // The manifest path renders its broker from the manifest, which has no store fields, so the flag
1334
1363
  // would be accepted and never rendered. Refuse it rather than drop it.
1335
1364
  if (maxFileStore !== undefined && values.file)
1336
- throw new Error("--max-file-store cannot be combined with --file/-f - a manifest launch does not render a store cap; drop --max-file-store, or start the mesh without -f");
1365
+ throw new FlagValueRefusal("--max-file-store cannot be combined with --file/-f: a manifest launch does not render a store cap, so nothing was started", "drop --max-file-store, or start the mesh without -f");
1337
1366
  // An open mesh has no operator, no system account, and no $SYS creds, so there is nothing to
1338
1367
  // rotate; the request is a misunderstanding to name, never a silent no-op that reports success.
1339
1368
  if (values["rotate-sys"] && values.open) {
1340
- throw new Error("--rotate-sys is for auth meshes: an open mesh (--open) has no system account or $SYS credentials to rotate");
1369
+ throw new FlagValueRefusal("--rotate-sys is for auth meshes: an open mesh (--open) has no system account or $SYS credentials to rotate, so nothing was started", "drop --rotate-sys, or drop --open to rotate an auth mesh's system account");
1341
1370
  }
1342
1371
  // THE EFFECTIVE PROJECT ROOT IS PINNED BEFORE THE TRANSPORT IS DECIDED.
1343
1372
  //
@@ -1482,7 +1511,9 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1482
1511
  const stackServer = values.server ?? readStackJournal(meshRoot)?.journal.server ?? localMeshesForRoot(meshRoot).find((m) => m.space === stackSpace)?.server ?? await unrecordedStackServer(meshRoot, stackSpace, values.host);
1483
1512
  if (values.foreground && presentation !== "json")
1484
1513
  stackUpForegroundNotice(presentation, stackSpace, takeover);
1485
- await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, managerSeatCap, ...(stackMode ? { mode: stackMode } : {}), ...(values.idp ? { idp: values.idp } : {}), ...(values.host ? { host: values.host } : {}), ...(values["store-dir"] ? { storeDir: values["store-dir"] } : {}), ...(values["rotate-sys"] ? { rotateSys: true } : {}), ...(values["recreate-membership-store"] ? { recreateMembershipStore: true } : {}), ...(values["recreate-issued-stores"] !== undefined ? { recreateIssuedStores: resolve(values["recreate-issued-stores"]) } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(logFile !== undefined ? { logFile } : {}), ...(logfileSizeLimit !== undefined ? { logfileSizeLimit } : {}), ...(logfileMaxNum !== undefined ? { logfileMaxNum } : {}), ...(authTimeout !== undefined ? { authTimeout } : {}), ...(maxPayload !== undefined ? { maxPayload } : {}), ...(accountResolver !== undefined ? { accountResolver } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), ...(values.__invokedRoot ? { invokedRoot: values.__invokedRoot } : {}), foreground: values.foreground === true, presentation }, native);
1514
+ await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, managerSeatCap, ...(stackMode ? { mode: stackMode } : {}), ...(values.idp ? { idp: values.idp } : {}), ...(values.host ? { host: values.host } : {}), ...(values["store-dir"] ? { storeDir: values["store-dir"] } : {}), ...(values["rotate-sys"] ? { rotateSys: true } : {}), ...(values["recreate-membership-store"] ? { recreateMembershipStore: true } : {}), ...(values["recreate-issued-stores"] !== undefined ? { recreateIssuedStores: resolve(values["recreate-issued-stores"]) } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(logFile !== undefined ? { logFile } : {}), ...(logfileSizeLimit !== undefined ? { logfileSizeLimit } : {}), ...(logfileMaxNum !== undefined ? { logfileMaxNum } : {}), ...(authTimeout !== undefined ? { authTimeout } : {}), ...(maxPayload !== undefined ? { maxPayload } : {}), ...(accountResolver !== undefined ? { accountResolver } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), ...(values.__invokedRoot ? { invokedRoot: values.__invokedRoot } : {}), foreground: values.foreground === true, presentation,
1515
+ retryAtAnotherAddress: (host) => retryStackAddress(args.raw, invokedFrom, stackServer, host),
1516
+ }, native);
1486
1517
  }
1487
1518
  finally {
1488
1519
  releaseMaintenanceLock(stackLock);
@@ -1523,7 +1554,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1523
1554
  }
1524
1555
  throw new CommandFailure("refused", "UNSUPPORTED", "up -f starts its manifest on the retained native launcher, which has no structured or plain receipt; nothing was started", { target: { root: meshRoot, path }, remedy: `omit ${values.json ? "--json" : "--plain"}` });
1525
1556
  }
1526
- throw new CommandFailure("refused", "UNSUPPORTED", "this startup uses the retained native launcher, which has no structured or plain receipt; nothing was started", { target: { root: meshRoot }, remedy: "use a fresh prepared root with static auth, --open, or plain-loopback --user-auth for the controller-owned stack, or omit --json/--plain" });
1557
+ throw retainedStartupPresentationRefusal(meshRoot);
1527
1558
  }
1528
1559
  // `up -f cotal.yaml` is a distinct path: bring up a FRESH mesh described by a manifest (broker +
1529
1560
  // channels + booted agents). It owns the whole space; the additive team deploy route is separate.
@@ -1536,7 +1567,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1536
1567
  if (controller)
1537
1568
  throw new CommandFailure("refused", "CONFLICT", `this root holds the controller stack of space ${controller.journal.space}, and up -f does not start a manifest beside it; nothing was started`, {
1538
1569
  target: { root: meshRoot, space: controller.journal.space },
1539
- remedy: `add the manifest's channels and agents to the running stack with \`cotal team deploy ${values.file}\`, or stop it with \`cotal down --yes\` and start the manifest through the controller with \`cotal team boot ${values.file}\``,
1570
+ remedy: controllerManifestRemedy(meshRoot, controller.journal.space, resolve(values.file)),
1540
1571
  });
1541
1572
  if (values["dry-run"]) {
1542
1573
  await upManifest(values.file, {
@@ -1877,8 +1908,9 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1877
1908
  // contract on the limit the broker already serves, so a recorded one below the floor is refused
1878
1909
  // before that launch rather than dying on the publish.
1879
1910
  const refreshPayload = maxPayload ?? runningPolicy?.maxPayload;
1880
- if (!noManager && held.mode !== "open" && refreshPayload !== undefined && refreshPayload < MANAGER_START_PAYLOAD_FLOOR) {
1911
+ if (!noManager && refreshPayload !== undefined && refreshPayload < MANAGER_START_PAYLOAD_FLOOR) {
1881
1912
  console.error(c.red(`✗ --max-payload ${refreshPayload} is below ${MANAGER_START_PAYLOAD_FLOOR} bytes, the least the space's manager starts on: it publishes its contract artifacts, one message each, and the largest is bounded at ${CONTRACT_ARTIFACT_MAX_BYTES} bytes with ${MANAGER_START_PAYLOAD_FLOOR - CONTRACT_ARTIFACT_MAX_BYTES} more for the publish; nothing was started`));
1913
+ console.error(` From the stack's project root, run \`cotal down --yes\`, then \`cotal up --max-payload ${NATS_DEFAULT_MAX_PAYLOAD}\`, or keep it broker-only with \`cotal up --no-manager\`.`);
1882
1914
  process.exit(1);
1883
1915
  }
1884
1916
  // The store directory is fixed the same way: an explicit --store-dir on a live refresh can
@@ -2072,7 +2104,13 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2072
2104
  console.log(`\n${renderReport({ sections: [{ title: "Next", blocks: detachedNext({ manager: managerRecord.state === "alive", controlPlane: controlPlane !== undefined, machineHome: canonicalRoot(root) === canonicalRoot(homedir()), ...(values.root ? { root } : {}), ...(managerRecord.state === "unattributable" ? { unattributableManager: managerRecord.path, noManager } : {}) }, held.space) }] }, "rich", process.stdout)}`);
2073
2105
  return;
2074
2106
  }
2075
- const who = held ? `mesh "${held.space}" (${held.root})` : "a broker not started here";
2107
+ // The address explains the collision even when this invocation cannot refresh that space.
2108
+ // The registration does not prove that the process answering the probe belongs to it.
2109
+ const address = brokerAddressKey(server);
2110
+ const registered = address === undefined ? undefined : meshes.find((m) => m.origin !== "manual" && m.origin !== "catalog" && brokerAddressKey(m.server) === address);
2111
+ const registeredAt = registered && `address registered to mesh "${registered.space}" (${registered.root})`;
2112
+ const occupant = "a broker not started here";
2113
+ const occupied = registeredAt ? `already in use (${registeredAt})` : `already in use by ${occupant}`;
2076
2114
  // Reaching here with `--rotate-sys` means something IS answering at the requested address and it
2077
2115
  // is not this root's recorded mesh (that case was refused above). The ordinary response is to pick
2078
2116
  // a free port and carry on, which for a rotation is the wrong instinct: the unidentified listener
@@ -2081,17 +2119,17 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2081
2119
  // it retires the account it is still serving and opens its store a second time. Nothing available
2082
2120
  // here can identify it (that is what unidentified means), so refuse instead of stepping past it.
2083
2121
  if (values["rotate-sys"]) {
2084
- console.error(c.red(`✗ ${server} is answering and it is not this root's recorded mesh (${who})`) +
2122
+ console.error(c.red(`✗ ${server} is answering and it is not this root's recorded mesh (${registeredAt ?? occupant})`) +
2085
2123
  c.dim(" - `--rotate-sys` will not start on another port around an unidentified broker: it may be serving this root's own server.conf and JetStream store. Stop whatever is listening there (`cotal down` if it was started here), then rotate."));
2086
2124
  process.exit(1);
2087
2125
  }
2088
2126
  if (values.server === undefined && (!held || held.root !== root)) {
2089
2127
  const next = await serverWithFreePort(server, host);
2090
- console.log(c.dim(`${server} is already in use by ${who}; starting "${space}" at ${next} instead`));
2128
+ console.log(c.dim(`${server} is ${occupied}; starting "${space}" at ${next} instead`));
2091
2129
  server = next;
2092
2130
  }
2093
2131
  else {
2094
- console.error(c.red(`✗ ${server} is already in use by ${who} - to run "${space}" use \`--server nats://${host}:<port>\` with a free port`));
2132
+ console.error(c.red(`✗ ${server} is ${occupied} - to run "${space}" use \`--server nats://${host}:<port>\` with a free port`));
2095
2133
  process.exit(1);
2096
2134
  }
2097
2135
  }
@@ -2229,6 +2267,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2229
2267
  }
2230
2268
  if (values["store-dir"])
2231
2269
  warnForeignStoreEntries(storeDir);
2270
+ prepareForegroundBrokerLog(logFile);
2232
2271
  // Owner-private regardless of umask: a recursive create also makes a missing `.cotal`, which every
2233
2272
  // later protection check walks as an ancestor.
2234
2273
  mkdirSync(storeDir, { recursive: true, mode: 0o700 });
@@ -2237,7 +2276,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2237
2276
  // Decided above the branch; the dial host is only settled here (a port collision may have moved
2238
2277
  // the server, and the hostname is what the certificate has to match).
2239
2278
  assertServesDialHost(transport, new URL(server).hostname);
2240
- const brokerSetup = useAuth ? await authSetup(storeDir, server, space, host, wantUser ? { idpUrl: values.idp } : undefined, transport, values["rotate-sys"], maxFileStore, false, { authTimeout, maxPayload, accountResolver, manager: values["no-manager"] !== true }) : undefined;
2279
+ const brokerSetup = useAuth ? await authSetup(storeDir, server, space, host, wantUser ? { idpUrl: values.idp } : undefined, transport, values["rotate-sys"], maxFileStore, false, { authTimeout, maxPayload, accountResolver, manager: values["no-manager"] !== true, logFile, logfileSizeLimit, logfileMaxNum }) : undefined;
2241
2280
  const brokerMaxPayload = brokerSetup?.maxPayload ?? maxPayload ?? readBrokerPolicy(cotalRoot())?.maxPayload;
2242
2281
  const port = Number(new URL(server).port) || 4222;
2243
2282
  // Both modes go through a RENDERER, never bare CLI flags. Open mode used to start from
@@ -2247,13 +2286,14 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2247
2286
  const renderingBinary = brokerSetup?.brokerBinary ?? await resolveNatsServer();
2248
2287
  if (!renderingBinary.version)
2249
2288
  throw unreadVersion(renderingBinary);
2250
- const confPath = brokerSetup ? brokerSetup.confPath : writeOpenBrokerConf(storeDir, space, { brokerVersion: renderingBinary.version, port, host, transport, maxFileStore, maxPayload: brokerMaxPayload });
2289
+ const confPath = brokerSetup ? brokerSetup.confPath : writeOpenBrokerConf(storeDir, space, { brokerVersion: renderingBinary.version, port, host, transport, maxFileStore, maxPayload: brokerMaxPayload, logFile, logfileSizeLimit, logfileMaxNum });
2251
2290
  const natsArgs = [
2252
2291
  "-c", confPath,
2253
2292
  ...(boundListener ? ["--name", boundListener.serverName] : []),
2254
2293
  ];
2255
2294
  const natsServer = renderingBinary;
2256
2295
  const bin = natsServer.path;
2296
+ const brokerOutput = logFile ?? "the terminal output above";
2257
2297
  await seedBeforeLaunch();
2258
2298
  const setup = brokerSetup && { ...brokerSetup, creds: await brokerSetup.mintProvisioner() };
2259
2299
  const starting = `Starting ${natsServerLabel(natsServer)} (JetStream, ${useAuth ? "JWT auth" : "OPEN/no-auth"}) - store: ${storeDir}, bind: ${host}`;
@@ -2323,6 +2363,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2323
2363
  };
2324
2364
  process.on("SIGINT", () => stop("SIGINT"));
2325
2365
  process.on("SIGTERM", () => stop("SIGTERM"));
2366
+ restored?.releaseInterruptNotice?.();
2326
2367
  // The broker is gone. Drop the registration this stop recorded, and the `current` pointer when it
2327
2368
  // names that registration, so a later `cotal spawn` does not join a dead mesh. A space named after
2328
2369
  // its folder keeps both, as `cotal down` does, so the name stays the folder's.
@@ -2365,10 +2406,10 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2365
2406
  // The record is kept ON PURPOSE: it still names the store this broker opened, so a repair
2366
2407
  // `up` reopens that SAME store instead of falling back to the root's default, and a
2367
2408
  // supervising unit's restart takes the refresh path against the recorded store rather than
2368
- // racing a second broker into existence. Foreground stdio is inherited (its own log lines
2369
- // are already on this terminal, above), so there is no `.cotal/nats.log` to name here.
2409
+ // racing a second broker into existence. NATS logs to this terminal unless a native log was
2410
+ // requested, so there is no `.cotal/nats.log` to name here.
2370
2411
  const detail = signal ? `signal ${signal}` : `code ${code}`;
2371
- const repair = `log: see the terminal output above; repair: \`cotal up --server ${server} --space ${space}\``;
2412
+ const repair = `log: see ${brokerOutput}; repair: ${codeSpan(`cotal up --server ${shellWord(server)} --space ${shellWord(space)}`)}`;
2372
2413
  // Retention is read from the registry, not assumed: a broker that exits before it first
2373
2414
  // answers was never recorded, and running the same `up` again only repeats that exit, so its
2374
2415
  // step is the one a detached start gives. A registry that cannot be read is not claimed
@@ -2378,7 +2419,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2378
2419
  const mine = findMesh(space);
2379
2420
  outcome = mine && mine.server === server && mine.root === cotalRoot()
2380
2421
  ? `; the mesh "${space}" stays recorded (\`cotal meshes\` lists it offline); ${repair}`
2381
- : ` before the mesh "${space}" was recorded; next: ${listenerExitRemedy(natsServer, "the terminal output above")}`;
2422
+ : ` before the mesh "${space}" was recorded; next: ${listenerExitRemedy(natsServer, brokerOutput)}`;
2382
2423
  }
2383
2424
  catch {
2384
2425
  outcome = `; whether the mesh "${space}" stays recorded could not be read; ${repair}`;
@@ -2392,7 +2433,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2392
2433
  process.exit(exitCode("failed", "OPERATION_FAILED"));
2393
2434
  }
2394
2435
  });
2395
- await awaitSpawnedListener({ child, executable: natsServer, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: "the terminal output above", boundListener });
2436
+ await awaitSpawnedListener({ child, executable: natsServer, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: brokerOutput, boundListener });
2396
2437
  listenerReady = true;
2397
2438
  {
2398
2439
  // A DAEMON THAT DIES UNDER THIS RUNNING BROKER IS RESTARTED HERE (#2469). It exits on its own once
@@ -3261,10 +3302,11 @@ function publicExchangeArgs(v, wantUser) {
3261
3302
  const provisioning = v["agent-provisioning-url"];
3262
3303
  if (port === undefined && url === undefined && !proxy && advertised === undefined && provisioning === undefined)
3263
3304
  return [];
3305
+ const flags = [port !== undefined && "--exchange-public-port", url !== undefined && "--exchange-public-url", proxy && "--exchange-trusted-proxy", advertised !== undefined && "--advertised-server", provisioning !== undefined && "--agent-provisioning-url"].filter(Boolean);
3264
3306
  if (!wantUser)
3265
- throw new Error("--exchange-public-port/--exchange-public-url/--exchange-trusted-proxy/--advertised-server/--agent-provisioning-url are for user-auth spaces - pair them with --user-auth");
3307
+ throw userAuthFlagsRefusal(flags.join(", "));
3266
3308
  if (port === undefined)
3267
- throw new Error("--exchange-public-url/--exchange-trusted-proxy/--advertised-server/--agent-provisioning-url require --exchange-public-port");
3309
+ throw new CommandFailure("refused", "USAGE_INVALID", `${flags.join(", ")} ${flags.length === 1 ? "requires" : "require"} --exchange-public-port. Nothing started.`, { remedy: "add --exchange-public-port with the public listener port, or remove the flags that need it" });
3268
3310
  return [
3269
3311
  "--exchange-public-port", port,
3270
3312
  ...(url !== undefined ? ["--exchange-public-url", url] : []),
@@ -3279,9 +3321,12 @@ function serviceEndpointsArgs(v, wantUser) {
3279
3321
  if (!v["service-endpoints"])
3280
3322
  return [];
3281
3323
  if (!wantUser)
3282
- throw new Error("--service-endpoints is for user-auth spaces - pair it with --user-auth");
3324
+ throw userAuthFlagsRefusal("--service-endpoints");
3283
3325
  return ["--service-endpoints"];
3284
3326
  }
3327
+ function userAuthFlagsRefusal(flags) {
3328
+ return new CommandFailure("refused", "USAGE_INVALID", `${flags} can only be used with user auth. Nothing started.`, { remedy: "remove the incompatible flags for an open space, or use them with --user-auth instead of --open" });
3329
+ }
3285
3330
  /** Bring the space's USER-AUTH service up with the broker (user mode only — `setup.prepared` is the
3286
3331
  * provider's output). Loud both ways (U5): a ready service prints the login line; a service that
3287
3332
  * never became ready prints the exact consequence + recourse. Returns the registry metadata either
@@ -3460,6 +3505,10 @@ function manifestFileRefusal(e, path) {
3460
3505
  const issues = e.issues.map((issue) => ({ ...issue, message: issue.message.split("\n")[0].replace(/(at line \d+, column \d+):$/, "$1") }));
3461
3506
  return new CommandFailure("refused", "SCHEMA_INVALID", `the manifest does not validate, so nothing was started: ${issues.map((issue) => formatIssue(e.file, issue)).join("; ")}`, { target: { path, issues }, remedy: "fix each named problem and run the command again" });
3462
3507
  }
3508
+ // A refusal that already names the problem, such as a directory given as the manifest, keeps its
3509
+ // own sentence and remedy, as the text path prints them.
3510
+ if (e instanceof CommandFailure)
3511
+ return e;
3463
3512
  const code = e?.code;
3464
3513
  return new UnusableFile(code === "ENOENT" ? `manifest file not found: ${path}` : `the manifest ${path} could not be read (${code ?? e.message})`, { file: path });
3465
3514
  }
@@ -3573,7 +3622,7 @@ async function upManifest(file, opts) {
3573
3622
  // nothing: a rotation ask answered with silent success, the exact failure class this change
3574
3623
  // exists to remove. Before the dry-run print and before anything boots.
3575
3624
  if (opts.rotateSys && open)
3576
- throw new Error("--rotate-sys is for auth meshes: this manifest sets broker.auth: false (open), so there is no system account or $SYS credentials to rotate");
3625
+ throw new FlagValueRefusal("--rotate-sys is for auth meshes: this manifest sets broker.auth: false (open), so there is no system account or $SYS credentials to rotate, and nothing was started", "drop --rotate-sys for this open manifest");
3577
3626
  // Before the dry-run print and before connector preflight or any write, as the refusals above.
3578
3627
  if (!opts.storeDir)
3579
3628
  refuseUnnamedLastStore(cotalPath("nats"));
@@ -3582,6 +3631,13 @@ async function upManifest(file, opts) {
3582
3631
  if (userAuth)
3583
3632
  await preflightUserStack(cotalRoot(), m.space, userAuth.idpUrl);
3584
3633
  checkStartStore(opts.storeDir, m.space);
3634
+ // Preview and apply resolve and probe the same runtime before showing a plan or starting a broker.
3635
+ try {
3636
+ await preflightRuntime(runtime);
3637
+ }
3638
+ catch (error) {
3639
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `the requested runtime did not pass preflight; ${opts.freshTeamBoot ? "no fresh boot intent or broker was started" : "no broker was started"}`, { target: { space: m.space, runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
3640
+ }
3585
3641
  if (opts.dryRun) {
3586
3642
  // Dial-host SAN must refuse here too (S6). The real route runs assertServesDialHost after
3587
3643
  // the plan is computed; dry-run used to return before that check and green-lit a launch
@@ -3605,14 +3661,6 @@ async function upManifest(file, opts) {
3605
3661
  console.log(c.dim(" no manager will start on this host (--no-manager): broker, channels and, in auth mode, the delivery daemon come up, and no agents launch from here"));
3606
3662
  return;
3607
3663
  }
3608
- // Preflight an extension runtime before starting the broker. The detached manager re-execs this
3609
- // CLI and resolves the same installed package when `supervise --runtime <name>` starts.
3610
- try {
3611
- await preflightRuntime(runtime);
3612
- }
3613
- catch (error) {
3614
- throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `the requested runtime did not pass preflight; ${opts.freshTeamBoot ? "no fresh boot intent or broker was started" : "no broker was started"}`, { target: { space: m.space, runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
3615
- }
3616
3664
  // up -f never adopts a running broker. The old spawn -f route is no longer a manifest deploy.
3617
3665
  if (await isReachable(server)) {
3618
3666
  if (opts.freshTeamBoot)
@@ -3620,7 +3668,7 @@ async function upManifest(file, opts) {
3620
3668
  // This folder's own mesh for the manifest's space is named as running, as a bare `up` names it,
3621
3669
  // with the routes that change it instead of the advice for a foreign broker.
3622
3670
  if (loadMeshes().some((row) => row.server === server && row.root === cotalRoot() && row.space === m.space)) {
3623
- stderrLine("✗ ", `mesh "${m.space}" is already running at ${brokerAddressForDisplay(server) ?? "its address"} from this folder - \`up -f\` boots a fresh mesh and does not apply a manifest to a running one; \`cotal team deploy ${file}\` adds all-new channels and agents to it, or \`cotal down\` it first, then \`cotal up -f ${file}\``, c.red);
3671
+ stderrLine("✗ ", `mesh "${m.space}" is already running at ${brokerAddressForDisplay(server) ?? "its address"} from this folder - \`up -f\` boots a fresh mesh and does not apply a manifest to a running one; stop it with \`cotal down\`, then retry your original command`, c.red);
3624
3672
  process.exit(1);
3625
3673
  }
3626
3674
  stderrLine("✗ ", `${brokerAddressForDisplay(server) ?? "selected address"} already has a broker - a fresh boot will not adopt it. Stop the owned stack or select another address; team deploy supports only all-new channel cards, not agent apply.`, c.red);
@@ -3977,17 +4025,19 @@ function listenerExitRemedy(executable, log) {
3977
4025
  */
3978
4026
  async function serveReadyListener(l) {
3979
4027
  const { child, server, space, setup, transport } = l;
3980
- if (l.resumeAttempt)
3981
- await recreateMemoryBuckets(server, space, setup);
3982
- else {
3983
- try {
3984
- await postStart(server, space, setup, l.seedFile, l.recreateIssuedStores, l.recreateMembershipStore, true);
4028
+ try {
4029
+ if (l.resumeAttempt) {
4030
+ const ordinaryResume = pendingOrdinaryResumes.has(l.resumeAttempt);
4031
+ await recreateMemoryBuckets(server, space, setup, ordinaryResume ? { convertMembership: l.recreateMembershipStore === true } : undefined);
3985
4032
  }
3986
- catch (e) {
3987
- await stopFailedListener(child);
3988
- throw e;
4033
+ else {
4034
+ await postStart(server, space, setup, l.seedFile, l.recreateIssuedStores, l.recreateMembershipStore, true);
3989
4035
  }
3990
4036
  }
4037
+ catch (e) {
4038
+ await stopFailedListener(child);
4039
+ throw e;
4040
+ }
3991
4041
  // Register the prepared trust before delivery starts. Auth follows delivery's liveness oracle,
3992
4042
  // then the manager: a crashed auth claim cannot be reclaimed while that oracle is absent.
3993
4043
  let svc = {
@@ -4122,21 +4172,7 @@ export async function prepareBrokerStart(opts) {
4122
4172
  const { path: bin, source, version } = renderingBinary;
4123
4173
  return { root, server, space, useAuth, storeDir, seedFile, host, transport, setup, maxPayload, confPath, args, bin, source, version };
4124
4174
  }
4125
- /**
4126
- * Open the detached broker's log with {@link openPrivateAppend}: created `0600` whatever the umask,
4127
- * never through a symlink, and an earlier log this user owns set to `0600`. A symlink, a log another
4128
- * user owns or a name that is not a regular file is refused and left unchanged.
4129
- */
4130
- export function openBrokerLog(path) {
4131
- try {
4132
- return openPrivateAppend(path);
4133
- }
4134
- catch (error) {
4135
- if (error.code !== "EPERM")
4136
- throw error;
4137
- throw new CommandFailure("refused", "PERMISSION_DENIED", `no broker was started: ${error.message}`, { target: { path }, remedy: `remove ${path} or replace it with a regular file you own, then run \`cotal up\` again` });
4138
- }
4139
- }
4175
+ export { openBrokerLog };
4140
4176
  /**
4141
4177
  * Start a background nats-server (JetStream), wait until it's reachable, pre-create the
4142
4178
  * space's streams, and leave it running detached (pid in `.cotal/nats.pid`). Used by
@@ -4569,8 +4605,7 @@ async function waitReady(server, creds, tls = false, log) {
4569
4605
  return false;
4570
4606
  }
4571
4607
  /** Bytes plus completed-restore lines in the broker log, and whether a restore is in flight. A
4572
- * foreground launch inherits the terminal and has no file to read, so it contributes no evidence
4573
- * and keeps the silent-probe bound. */
4608
+ * foreground broker logging to the terminal has no file to read, so it keeps the silent-probe bound. */
4574
4609
  function brokerRecoveryEvidence(log) {
4575
4610
  const none = { evidence: 0, restoring: false };
4576
4611
  if (!log || log.startsWith("the terminal"))
@@ -4774,63 +4809,9 @@ function refuseRegisteredAddress(server, space, elsewhere) {
4774
4809
  remedy: `${elsewhere}, or free that one with \`cotal space forget ${held.space}\``,
4775
4810
  });
4776
4811
  }
4777
- /** Choose only a first implicit address. A saved or explicitly requested address is never moved.
4778
- * The broker still validates and binds its own listener; this inspection cannot reserve the port. */
4779
- async function freshStackServer(server, bindHost) {
4780
- const url = new URL(server);
4781
- const host = (bindHost ?? url.hostname).replace(/^\[|\]$/g, "");
4782
- const reserved = new Set();
4783
- // A recorded address this cannot take apart reserves nothing: it names no host and port to avoid.
4784
- for (const mesh of loadMeshes()) {
4785
- const key = brokerAddressKey(mesh.server);
4786
- if (key !== undefined)
4787
- reserved.add(key);
4788
- }
4789
- let candidate = server;
4790
- for (let attempt = 0; attempt < 16; attempt++) {
4791
- const address = new URL(candidate);
4792
- const key = brokerAddressKey(candidate);
4793
- if (key === undefined || !reserved.has(key)) {
4794
- try {
4795
- await freePort(host, Number(address.port) || 4222);
4796
- return candidate;
4797
- }
4798
- catch (error) {
4799
- if (error.code !== "EADDRINUSE")
4800
- throw error;
4801
- }
4802
- }
4803
- candidate = await serverWithFreePort(server, host);
4804
- }
4805
- throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "no unreserved local broker address could be selected; no broker was started");
4806
- }
4807
- async function serverWithFreePort(server, host) {
4808
- const url = new URL(server);
4809
- url.port = String(await freePort(host));
4810
- return url.toString();
4811
- }
4812
- function freePort(host, requestedPort = 0) {
4813
- return new Promise((resolve, reject) => {
4814
- const srv = createServer();
4815
- srv.unref();
4816
- srv.once("error", reject);
4817
- srv.listen(requestedPort, host, () => {
4818
- const addr = srv.address();
4819
- const port = typeof addr === "object" && addr ? addr.port : undefined;
4820
- srv.close((err) => {
4821
- if (err)
4822
- reject(err);
4823
- else if (port)
4824
- resolve(port);
4825
- else
4826
- reject(new Error("could not allocate a free port"));
4827
- });
4828
- });
4829
- });
4830
- }
4831
- function membershipConversionRefusal(space) {
4812
+ function membershipConversionRefusal(space, remedy = "stop the stack with `cotal down --yes`, then run `cotal up --recreate-membership-store`") {
4832
4813
  return new CommandFailure("refused", "LIFECYCLE_BLOCKED", `space ${space} has a legacy File-backed membership store; it was not changed while its broker or membership services may be in use`, {
4833
- target: { space }, remedy: "stop the stack with `cotal down --yes`, then run `cotal up --recreate-membership-store`",
4814
+ target: { space }, remedy,
4834
4815
  });
4835
4816
  }
4836
4817
  async function fileMembershipStore(server, space, creds, stockOnly = false) {
@@ -4946,10 +4927,32 @@ async function recreateIssuedStoresBeforeSetup(server, space, authenticated, bac
4946
4927
  /** A resume or restore skips `postStart` because the preserved store already holds every canonical
4947
4928
  * stream. A memory-backed bucket is the exception: the broker stop that preserved the store emptied
4948
4929
  * it, stream and all (#1356 made presence memory-backed). Recreate those, and only those, from the
4949
- * same `ttlBuckets` list `setupSpaceStreams` creates them from, before any daemon opens them. */
4950
- async function recreateMemoryBuckets(server, space, setup) {
4951
- if (await fileMembershipStore(server, space, setup?.creds))
4952
- throw membershipConversionRefusal(space);
4930
+ * same `ttlBuckets` list `setupSpaceStreams` creates them from, before any daemon opens them.
4931
+ * Only an ordinary resume that just started this listener may opt into replacing a File feed. */
4932
+ async function recreateMemoryBuckets(server, space, setup, ownedResume) {
4933
+ const legacy = await fileMembershipStore(server, space, setup?.creds);
4934
+ if (legacy) {
4935
+ if (!ownedResume?.convertMembership)
4936
+ throw membershipConversionRefusal(space, ownedResume && "retry this preserved resume with `cotal up --recreate-membership-store`");
4937
+ const running = serviceInstances(space).filter((row) => row.record.value.definition !== STACK_DEFINITION.broker).some((row) => !["gone", "previous-boot", "foreign-pid"].includes(observeServiceProcess(row.record.value)));
4938
+ if (running)
4939
+ throw membershipConversionRefusal(space, "stop the remaining membership services, then retry the preserved resume with `cotal up --recreate-membership-store`");
4940
+ try {
4941
+ const auth = setup && await getSpaceAuth(workspaceSecretStore(cotalRoot()), space);
4942
+ if (setup && !auth)
4943
+ throw new Error(`space "${space}" has no trust material under ${authDir(cotalRoot())}`);
4944
+ await recreateMembershipStore({
4945
+ servers: server, space, provisionerCreds: setup?.creds,
4946
+ recreateCreds: auth ? await mintCreds(auth, newIdentity(), "membership-store-recreate") : undefined,
4947
+ });
4948
+ }
4949
+ catch (error) {
4950
+ throw new CommandFailure("failed", "OPERATION_FAILED", `could not convert the preserved membership store: ${error.message}`, {
4951
+ target: { space }, remedy: "fix the reported cause, then retry this preserved resume with `cotal up --recreate-membership-store`",
4952
+ });
4953
+ }
4954
+ console.error(`Converted ${membershipStoreDefinition(space).bucket} from File to Memory; broker-sourced membership rebuilds on startup.`);
4955
+ }
4953
4956
  const nc = await dialerFor(server)({ servers: server, ...standaloneConnectOpts({ creds: setup?.creds, tls: false }) });
4954
4957
  try {
4955
4958
  requireBrokerFloor(nc);
@@ -4957,8 +4960,10 @@ async function recreateMemoryBuckets(server, space, setup) {
4957
4960
  for (const [bucket, ttl, storage] of ttlBuckets(space))
4958
4961
  if (storage === StorageType.Memory)
4959
4962
  await kvm.create(bucket, { ttl, storage });
4960
- const membership = membershipStoreDefinition(space);
4961
- await kvm.create(membership.bucket, membership.createOptions);
4963
+ if (!legacy) {
4964
+ const membership = membershipStoreDefinition(space);
4965
+ await kvm.create(membership.bucket, membership.createOptions);
4966
+ }
4962
4967
  }
4963
4968
  finally {
4964
4969
  await drainAndClose(nc);