@cotal-ai/cli 0.172.1 → 0.173.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +34 -20
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +8 -6
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/backup.d.ts.map +1 -1
  8. package/dist/commands/backup.js +15 -10
  9. package/dist/commands/backup.js.map +1 -1
  10. package/dist/commands/channel-members.d.ts.map +1 -1
  11. package/dist/commands/channel-members.js +2 -1
  12. package/dist/commands/channel-members.js.map +1 -1
  13. package/dist/commands/channels.d.ts.map +1 -1
  14. package/dist/commands/channels.js +19 -9
  15. package/dist/commands/channels.js.map +1 -1
  16. package/dist/commands/clean.d.ts.map +1 -1
  17. package/dist/commands/clean.js +2 -3
  18. package/dist/commands/clean.js.map +1 -1
  19. package/dist/commands/doctor.js +5 -2
  20. package/dist/commands/doctor.js.map +1 -1
  21. package/dist/commands/down-preserve.d.ts +74 -0
  22. package/dist/commands/down-preserve.d.ts.map +1 -0
  23. package/dist/commands/down-preserve.js +626 -0
  24. package/dist/commands/down-preserve.js.map +1 -0
  25. package/dist/commands/down.d.ts +2 -61
  26. package/dist/commands/down.d.ts.map +1 -1
  27. package/dist/commands/down.js +26 -617
  28. package/dist/commands/down.js.map +1 -1
  29. package/dist/commands/endpoint-authoring.d.ts.map +1 -1
  30. package/dist/commands/endpoint-authoring.js +16 -4
  31. package/dist/commands/endpoint-authoring.js.map +1 -1
  32. package/dist/commands/history-clear.d.ts.map +1 -1
  33. package/dist/commands/history-clear.js +10 -3
  34. package/dist/commands/history-clear.js.map +1 -1
  35. package/dist/commands/history-limit.js +2 -2
  36. package/dist/commands/history-limit.js.map +1 -1
  37. package/dist/commands/history.d.ts.map +1 -1
  38. package/dist/commands/history.js +49 -19
  39. package/dist/commands/history.js.map +1 -1
  40. package/dist/commands/join.d.ts.map +1 -1
  41. package/dist/commands/join.js +30 -7
  42. package/dist/commands/join.js.map +1 -1
  43. package/dist/commands/manager-service.d.ts.map +1 -1
  44. package/dist/commands/manager-service.js +5 -1
  45. package/dist/commands/manager-service.js.map +1 -1
  46. package/dist/commands/meshes-add.d.ts +4 -1
  47. package/dist/commands/meshes-add.d.ts.map +1 -1
  48. package/dist/commands/meshes-add.js +19 -1
  49. package/dist/commands/meshes-add.js.map +1 -1
  50. package/dist/commands/meshes-wizard.d.ts.map +1 -1
  51. package/dist/commands/meshes-wizard.js +5 -5
  52. package/dist/commands/meshes-wizard.js.map +1 -1
  53. package/dist/commands/meshes.d.ts.map +1 -1
  54. package/dist/commands/meshes.js +4 -3
  55. package/dist/commands/meshes.js.map +1 -1
  56. package/dist/commands/persona-remote.js +2 -2
  57. package/dist/commands/persona-remote.js.map +1 -1
  58. package/dist/commands/persona.d.ts.map +1 -1
  59. package/dist/commands/persona.js +13 -5
  60. package/dist/commands/persona.js.map +1 -1
  61. package/dist/commands/personas.d.ts.map +1 -1
  62. package/dist/commands/personas.js +4 -1
  63. package/dist/commands/personas.js.map +1 -1
  64. package/dist/commands/reset-space-apply.js +2 -2
  65. package/dist/commands/reset-space-apply.js.map +1 -1
  66. package/dist/commands/reset-store-apply.d.ts +2 -2
  67. package/dist/commands/reset-store-apply.d.ts.map +1 -1
  68. package/dist/commands/reset-store-apply.js +10 -7
  69. package/dist/commands/reset-store-apply.js.map +1 -1
  70. package/dist/commands/reset.js +2 -2
  71. package/dist/commands/reset.js.map +1 -1
  72. package/dist/commands/send.d.ts.map +1 -1
  73. package/dist/commands/send.js +21 -9
  74. package/dist/commands/send.js.map +1 -1
  75. package/dist/commands/service-actions.d.ts.map +1 -1
  76. package/dist/commands/service-actions.js +15 -4
  77. package/dist/commands/service-actions.js.map +1 -1
  78. package/dist/commands/service-registry.d.ts.map +1 -1
  79. package/dist/commands/service-registry.js +16 -5
  80. package/dist/commands/service-registry.js.map +1 -1
  81. package/dist/commands/space-delete.d.ts.map +1 -1
  82. package/dist/commands/space-delete.js +46 -31
  83. package/dist/commands/space-delete.js.map +1 -1
  84. package/dist/commands/space-registration.d.ts +4 -3
  85. package/dist/commands/space-registration.d.ts.map +1 -1
  86. package/dist/commands/space-registration.js +65 -45
  87. package/dist/commands/space-registration.js.map +1 -1
  88. package/dist/commands/space.d.ts.map +1 -1
  89. package/dist/commands/space.js +18 -6
  90. package/dist/commands/space.js.map +1 -1
  91. package/dist/commands/spawn-flags.d.ts +205 -0
  92. package/dist/commands/spawn-flags.d.ts.map +1 -0
  93. package/dist/commands/spawn-flags.js +34 -0
  94. package/dist/commands/spawn-flags.js.map +1 -0
  95. package/dist/commands/spawn-foreground.d.ts +74 -0
  96. package/dist/commands/spawn-foreground.d.ts.map +1 -0
  97. package/dist/commands/spawn-foreground.js +355 -0
  98. package/dist/commands/spawn-foreground.js.map +1 -0
  99. package/dist/commands/spawn-managed-launch.d.ts +43 -0
  100. package/dist/commands/spawn-managed-launch.d.ts.map +1 -0
  101. package/dist/commands/spawn-managed-launch.js +631 -0
  102. package/dist/commands/spawn-managed-launch.js.map +1 -0
  103. package/dist/commands/spawn-preview.d.ts.map +1 -1
  104. package/dist/commands/spawn-preview.js +10 -7
  105. package/dist/commands/spawn-preview.js.map +1 -1
  106. package/dist/commands/spawn.d.ts +6 -220
  107. package/dist/commands/spawn.d.ts.map +1 -1
  108. package/dist/commands/spawn.js +21 -1009
  109. package/dist/commands/spawn.js.map +1 -1
  110. package/dist/commands/stack-down.d.ts.map +1 -1
  111. package/dist/commands/stack-down.js +7 -4
  112. package/dist/commands/stack-down.js.map +1 -1
  113. package/dist/commands/stack-up.d.ts +5 -1
  114. package/dist/commands/stack-up.d.ts.map +1 -1
  115. package/dist/commands/stack-up.js +46 -15
  116. package/dist/commands/stack-up.js.map +1 -1
  117. package/dist/commands/status-delivery.d.ts +9 -0
  118. package/dist/commands/status-delivery.d.ts.map +1 -0
  119. package/dist/commands/status-delivery.js +19 -0
  120. package/dist/commands/status-delivery.js.map +1 -0
  121. package/dist/commands/status-legacy.d.ts +7 -0
  122. package/dist/commands/status-legacy.d.ts.map +1 -0
  123. package/dist/commands/status-legacy.js +35 -0
  124. package/dist/commands/status-legacy.js.map +1 -0
  125. package/dist/commands/status-stop-impact.d.ts +3 -0
  126. package/dist/commands/status-stop-impact.d.ts.map +1 -0
  127. package/dist/commands/status-stop-impact.js +34 -0
  128. package/dist/commands/status-stop-impact.js.map +1 -0
  129. package/dist/commands/status.d.ts.map +1 -1
  130. package/dist/commands/status.js +48 -105
  131. package/dist/commands/status.js.map +1 -1
  132. package/dist/commands/team-agent-apply.js +11 -11
  133. package/dist/commands/team-agent-apply.js.map +1 -1
  134. package/dist/commands/team-boot-controller.d.ts.map +1 -1
  135. package/dist/commands/team-boot-controller.js +21 -4
  136. package/dist/commands/team-boot-controller.js.map +1 -1
  137. package/dist/commands/team-deploy-apply.js +2 -2
  138. package/dist/commands/team-deploy-apply.js.map +1 -1
  139. package/dist/commands/team.d.ts.map +1 -1
  140. package/dist/commands/team.js +37 -42
  141. package/dist/commands/team.js.map +1 -1
  142. package/dist/commands/telemetry.d.ts +1 -1
  143. package/dist/commands/telemetry.d.ts.map +1 -1
  144. package/dist/commands/telemetry.js +17 -7
  145. package/dist/commands/telemetry.js.map +1 -1
  146. package/dist/commands/up-target.d.ts +7 -0
  147. package/dist/commands/up-target.d.ts.map +1 -0
  148. package/dist/commands/up-target.js +42 -0
  149. package/dist/commands/up-target.js.map +1 -0
  150. package/dist/commands/up.d.ts +5 -10
  151. package/dist/commands/up.d.ts.map +1 -1
  152. package/dist/commands/up.js +55 -156
  153. package/dist/commands/up.js.map +1 -1
  154. package/dist/commands/update-caches.d.ts +4 -0
  155. package/dist/commands/update-caches.d.ts.map +1 -0
  156. package/dist/commands/update-caches.js +82 -0
  157. package/dist/commands/update-caches.js.map +1 -0
  158. package/dist/commands/update.d.ts.map +1 -1
  159. package/dist/commands/update.js +35 -121
  160. package/dist/commands/update.js.map +1 -1
  161. package/dist/commands/watch.d.ts.map +1 -1
  162. package/dist/commands/watch.js +5 -2
  163. package/dist/commands/watch.js.map +1 -1
  164. package/dist/commands/whoami.d.ts.map +1 -1
  165. package/dist/commands/whoami.js +3 -2
  166. package/dist/commands/whoami.js.map +1 -1
  167. package/dist/help.d.ts +1 -1
  168. package/dist/help.d.ts.map +1 -1
  169. package/dist/help.js +5 -2
  170. package/dist/help.js.map +1 -1
  171. package/dist/index.d.ts.map +1 -1
  172. package/dist/index.js +4 -2
  173. package/dist/index.js.map +1 -1
  174. package/dist/lib/broker-log.d.ts +8 -0
  175. package/dist/lib/broker-log.d.ts.map +1 -0
  176. package/dist/lib/broker-log.js +27 -0
  177. package/dist/lib/broker-log.js.map +1 -0
  178. package/dist/lib/choose-target.d.ts.map +1 -1
  179. package/dist/lib/choose-target.js +12 -9
  180. package/dist/lib/choose-target.js.map +1 -1
  181. package/dist/lib/credential-authority.d.ts.map +1 -1
  182. package/dist/lib/credential-authority.js +22 -5
  183. package/dist/lib/credential-authority.js.map +1 -1
  184. package/dist/lib/endpoint-errors.d.ts.map +1 -1
  185. package/dist/lib/endpoint-errors.js +9 -2
  186. package/dist/lib/endpoint-errors.js.map +1 -1
  187. package/dist/lib/persona-files.d.ts.map +1 -1
  188. package/dist/lib/persona-files.js +2 -3
  189. package/dist/lib/persona-files.js.map +1 -1
  190. package/dist/lib/restore.d.ts +2 -1
  191. package/dist/lib/restore.d.ts.map +1 -1
  192. package/dist/lib/restore.js +4 -3
  193. package/dist/lib/restore.js.map +1 -1
  194. package/dist/lib/service-preset-target.d.ts.map +1 -1
  195. package/dist/lib/service-preset-target.js +6 -2
  196. package/dist/lib/service-preset-target.js.map +1 -1
  197. package/dist/lib/service-presets.d.ts +2 -0
  198. package/dist/lib/service-presets.d.ts.map +1 -1
  199. package/dist/lib/service-presets.js +19 -2
  200. package/dist/lib/service-presets.js.map +1 -1
  201. package/dist/lib/spawn-defaults.d.ts +7 -0
  202. package/dist/lib/spawn-defaults.d.ts.map +1 -1
  203. package/dist/lib/spawn-defaults.js +16 -0
  204. package/dist/lib/spawn-defaults.js.map +1 -1
  205. package/dist/lib/stack-journal.d.ts +4 -4
  206. package/dist/lib/stack-journal.d.ts.map +1 -1
  207. package/dist/lib/stack-journal.js +16 -6
  208. package/dist/lib/stack-journal.js.map +1 -1
  209. package/dist/lib/store-dir.d.ts +3 -1
  210. package/dist/lib/store-dir.d.ts.map +1 -1
  211. package/dist/lib/store-dir.js +20 -4
  212. package/dist/lib/store-dir.js.map +1 -1
  213. package/dist/lib/team-deploy-inspection.d.ts +2 -1
  214. package/dist/lib/team-deploy-inspection.d.ts.map +1 -1
  215. package/dist/lib/team-deploy-inspection.js +6 -1
  216. package/dist/lib/team-deploy-inspection.js.map +1 -1
  217. package/dist/lib/up-broker-address.d.ts +7 -0
  218. package/dist/lib/up-broker-address.d.ts.map +1 -0
  219. package/dist/lib/up-broker-address.js +76 -0
  220. package/dist/lib/up-broker-address.js.map +1 -0
  221. package/dist/lib/up-report.d.ts +2 -0
  222. package/dist/lib/up-report.d.ts.map +1 -1
  223. package/dist/lib/up-report.js +8 -1
  224. package/dist/lib/up-report.js.map +1 -1
  225. package/dist/lib/update-connector-config.d.ts +6 -0
  226. package/dist/lib/update-connector-config.d.ts.map +1 -0
  227. package/dist/lib/update-connector-config.js +44 -0
  228. package/dist/lib/update-connector-config.js.map +1 -0
  229. package/dist/seed/launch.d.ts +1 -1
  230. package/dist/seed/launch.d.ts.map +1 -1
  231. package/dist/seed/launch.js +3 -3
  232. package/dist/seed/launch.js.map +1 -1
  233. package/dist/seed/reconcile.d.ts +1 -1
  234. package/dist/seed/reconcile.d.ts.map +1 -1
  235. package/dist/seed/reconcile.js +28 -11
  236. package/dist/seed/reconcile.js.map +1 -1
  237. 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, 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, 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,8 +43,9 @@ 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
- import { bindReaches, canonicalServer, controllerStackApplies, recheckExistingStore, requestedStackMode, requestsTls, stackUp, stackUpForegroundNotice, stackUpInterrupted, keptOnUp, selectedOnUp, unparsableDaemonCredsNotice, } from "./stack-up.js";
48
+ import { bindReaches, canonicalServer, controllerStackApplies, recheckExistingStore, requestedStackMode, refuseForegroundStackHolder, requestsTls, stackUp, stackUpForegroundNotice, stackUpInterrupted, keptOnUp, selectedOnUp, unparsableDaemonCredsNotice, } from "./stack-up.js";
47
49
  import { handOverStartupNotice, noticeOnInterrupt, releaseStartupNotice } from "../lib/interrupt-notice.js";
48
50
  import { claimForegroundHold, foregroundHolder, releaseForegroundHold } from "../lib/foreground-hold.js";
49
51
  import { settleInterruptedLaunches } from "../lib/service-process.js";
@@ -59,7 +61,7 @@ import { serviceSupervisorStore } from "../lib/service-supervision.js";
59
61
  import { serviceInstallIntents } from "../lib/service-install-intent.js";
60
62
  import { serviceUninstallIntents } from "../lib/service-uninstall-intent.js";
61
63
  import { serviceUnitActionStore } from "../lib/service-unit-action.js";
62
- import { assertStoreDirArgument, configuredStoreDir, lastServedStore, lastServedStores, missingStoreWarning, servedStore, sharedStoreAtStart, sharedStoreWarning, storeWriteProblem, warnForeignStoreEntries } from "../lib/store-dir.js";
64
+ import { assertStoreDirArgument, configuredStoreDir, lastServedStore, lastServedStores, missingStoreWarning, servedStore, sharedStoreAtStart, sharedStoreWarning, startupStoreProblem, warnForeignStoreEntries } from "../lib/store-dir.js";
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";
@@ -67,6 +69,7 @@ import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeRe
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`" },
@@ -125,8 +128,8 @@ export const upFlags = [
125
128
  { name: "no-manager", type: "boolean", description: "broker-only boot: start the broker and, in auth mode, the delivery daemon, and no local manager (refuses on a mesh whose manager is live)" },
126
129
  { name: "file", type: "string", short: "f", value: "<cotal.yaml>", description: "launch a whole mesh from a manifest" },
127
130
  { name: "dry-run", type: "boolean", description: "with -f: print the plan, mutate nothing" },
128
- { ...jsonFlag, description: "controller-owned stack only: one structured receipt on stdout" },
129
- { ...plainFlag, description: "controller-owned stack only: plain line-oriented receipt" },
131
+ { ...jsonFlag, description: "one structured receipt on stdout (controller-owned stack only, without --foreground)" },
132
+ { ...plainFlag, description: "plain line-oriented receipt (controller-owned stack only, without --foreground)" },
130
133
  ];
131
134
  /** Completion for `cotal up` — `--runtime <TAB>` offers `pty` + installed runtime providers (the same
132
135
  * offline source `spawn` uses; a <TAB> never imports or probes). Run `cotal runtimes` to also see the
@@ -217,7 +220,7 @@ export function validateUpArguments(args) {
217
220
  if (args.values.file !== undefined && args.values.foreground === true)
218
221
  throw new CommandFailure("refused", "UNSUPPORTED", "manifest boot has no native foreground custody path; a detached broker was not substituted for the requested terminal-bound lifetime");
219
222
  if (args.values.foreground === true && (args.values.json === true || args.values.plain === true))
220
- throw new CommandFailure("refused", "USAGE_INVALID", "foreground up keeps native terminal custody and cannot produce a finite JSON or plain receipt");
223
+ throw new CommandFailure("refused", "USAGE_INVALID", "foreground up keeps native terminal custody and cannot produce a finite JSON or plain receipt", { remedy: `omit ${args.values.json ? "--json" : "--plain"} to keep the stack in this terminal, or omit --foreground for a finite receipt from a controller-owned stack` });
221
224
  // Flag values and combinations are usage, so they refuse here, before any effect. The run keeps
222
225
  // its own checks for maintenance re-entries, which do not pass through this validation.
223
226
  parsePositiveIntegerFlag("--max-sessions", args.values["max-sessions"]);
@@ -228,7 +231,9 @@ export function validateUpArguments(args) {
228
231
  throw new CommandFailure("refused", "USAGE_INVALID", "--log-file must be a non-empty file path without control characters");
229
232
  const logfileSizeLimit = parsePositiveIntegerFlag("--logfile-size-limit", args.values["logfile-size-limit"]);
230
233
  const logfileMaxNum = parsePositiveIntegerFlag("--logfile-max-num", args.values["logfile-max-num"]);
231
- if (!args.values.file && logFile === undefined && (logfileSizeLimit !== undefined || logfileMaxNum !== undefined))
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))
232
237
  throw new CommandFailure("refused", "USAGE_INVALID", "--logfile-size-limit and --logfile-max-num require --log-file");
233
238
  // The timeout belongs to the auth callout, which only a user-auth space has. A manifest or a
234
239
  // restore starts the broker its own record describes, so neither takes it.
@@ -336,24 +341,7 @@ function assertUpRootWritable(root) {
336
341
  * a start here opens, as `--store-dir` names it, as the stack or legacy records name it, or `.cotal/nats`,
337
342
  * is refused here, by name, when this account cannot write it. */
338
343
  function assertUpStoreWritable(root, storeDir) {
339
- let recorded;
340
- try {
341
- recorded = readStackJournal(root)?.journal.broker?.storeDir;
342
- }
343
- catch {
344
- recorded = undefined;
345
- }
346
- const defaultStore = join(root, ".cotal", "nats");
347
- if (storeDir === undefined && recorded === undefined) {
348
- const local = localMeshesForRoot(root);
349
- recorded = local.length === 1 ? local[0].storeDir : undefined;
350
- if (recorded === undefined && !existsSync(join(defaultStore, "jetstream"))) {
351
- const served = lastServedStores(root, defaultStore);
352
- if (served.length === 1)
353
- recorded = served[0];
354
- }
355
- }
356
- const problem = storeWriteProblem(storeDir !== undefined ? resolve(storeDir) : recorded ?? defaultStore);
344
+ const problem = startupStoreProblem(root, storeDir);
357
345
  if (problem)
358
346
  throw new CommandFailure("refused", "PERMISSION_DENIED", `${problem.message}; nothing was started or written`, { target: { root, path: problem.path }, remedy: problem.remedy });
359
347
  }
@@ -514,27 +502,7 @@ function machineHomeRoot() {
514
502
  const root = cotalRoot();
515
503
  return canonicalRoot(root) === canonicalRoot(homedir()) || canonicalRoot(join(root, ".cotal")) === canonicalRoot(homeCotalDir()) ? root : undefined;
516
504
  }
517
- /** An explicit root is an existing local workspace, not a hint to find another ancestor or
518
- * create trust in an arbitrary directory. Validation runs before the dispatcher seeds extensions. */
519
- export function preparedUpRoot(value) {
520
- if (!value)
521
- throw new CommandFailure("refused", "USAGE_INVALID", "--root needs an existing prepared project directory; an empty value is not the current folder");
522
- let root;
523
- try {
524
- root = realpathSync(resolve(value));
525
- if (!statSync(root).isDirectory())
526
- throw new Error("not a directory");
527
- const cotal = lstatSync(join(root, ".cotal"));
528
- if (!cotal.isDirectory() || cotal.isSymbolicLink())
529
- throw new Error("not a private project directory");
530
- }
531
- catch {
532
- 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" });
533
- }
534
- if (canonicalRoot(root) === canonicalRoot(homedir()) || canonicalRoot(join(root, ".cotal")) === canonicalRoot(homeCotalDir()))
535
- 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>`" });
536
- return root;
537
- }
505
+ export { preparedUpRoot } from "./up-target.js";
538
506
  /** The fresh team entry refuses retained custody before `up -f` can write a launch spec,
539
507
  * regenerate trust or stop a leftover manager. Only a recorded local root is eligible. */
540
508
  function assertFreshTeamBootOwnership(root, space, mode, own) {
@@ -780,6 +748,9 @@ export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink
780
748
  let adopted = false;
781
749
  try {
782
750
  validateUpArguments(args);
751
+ const root = args.values.root === undefined ? undefined : preparedUpRoot(String(args.values.root));
752
+ const fresh = args.values.root === undefined ? freshFolderRoot(args.values) : undefined;
753
+ checkNewUpSpace(args.values.space, root ?? fresh);
783
754
  // The broker reads an explicit channels file only once it is being prepared, so a file it would
784
755
  // refuse is named here, before the stack journal or anything else is written.
785
756
  if (typeof args.values.channels === "string")
@@ -789,13 +760,11 @@ export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink
789
760
  args = { ...args, values: { ...args.values, space: folderNamed, __folderNamed: true } };
790
761
  // A fresh folder under the machine home gets its own `.cotal` before anything resolves the root, so
791
762
  // every later step uses this folder. A run that stops before writing there removes it again.
792
- const fresh = args.values.root === undefined ? freshFolderRoot(args.values) : undefined;
793
763
  if (fresh) {
794
764
  mkdirSync(join(fresh, ".cotal"), { mode: 0o700 });
795
765
  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))
796
766
  console.error(line);
797
767
  }
798
- const root = args.values.root === undefined ? undefined : preparedUpRoot(String(args.values.root));
799
768
  const previousCwd = process.cwd();
800
769
  // Path flags still mean paths relative to the invoking directory, not the selected root.
801
770
  // The recursive restore/resume re-entries inherit absolute paths and the same absolute root.
@@ -823,7 +792,7 @@ export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink
823
792
  }
824
793
  }
825
794
  try {
826
- return await runUp(invocation, inheritedLock, () => { adopted = true; }, freshTeamBoot, restoreSink);
795
+ return await runUp(invocation, previousCwd, inheritedLock, () => { adopted = true; }, freshTeamBoot, restoreSink);
827
796
  }
828
797
  catch (error) {
829
798
  if (fresh)
@@ -856,7 +825,7 @@ const NO_MANAGER_DURING_RECOVERY = "--no-manager is refused while this root has
856
825
  function retainedStartupPresentationRefusal(root) {
857
826
  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" });
858
827
  }
859
- async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restoreSink) {
828
+ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot = false, restoreSink) {
860
829
  const values = args.values;
861
830
  if (freshTeamBoot && (!values.file || values.restore || values.__restoreAttempt || values.__ordinaryResumeAttempt || values["rotate-sys"] || values["no-manager"]))
862
831
  throw new CommandFailure("refused", "USAGE_INVALID", "fresh team boot accepts one manifest and its selected lifetime, not a restore, rotation or manager-free override");
@@ -899,9 +868,9 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
899
868
  "accept-missing-source": undefined,
900
869
  __restoreAttempt: attemptId,
901
870
  space: values.space ?? launch.space,
902
- server: launch.server,
903
- host: launch.host,
871
+ server: launch.server, host: launch.host,
904
872
  runtime: launch.runtime,
873
+ "max-file-store": launch.maxFileStore === undefined ? undefined : String(launch.maxFileStore),
905
874
  open: launch.mode === "open",
906
875
  "user-auth": launch.mode === "user",
907
876
  } };
@@ -1370,19 +1339,17 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1370
1339
  const logFile = values["log-file"] === undefined ? undefined : resolve(values["log-file"]);
1371
1340
  const logfileSizeLimit = parsePositiveIntegerFlag("--logfile-size-limit", values["logfile-size-limit"]);
1372
1341
  const logfileMaxNum = parsePositiveIntegerFlag("--logfile-max-num", values["logfile-max-num"]);
1373
- if (!values.file && logFile === undefined && (logfileSizeLimit !== undefined || logfileMaxNum !== undefined))
1374
- throw new CommandFailure("refused", "USAGE_INVALID", "--logfile-size-limit and --logfile-max-num require --log-file");
1375
1342
  const authTimeout = parseAuthTimeout(values["auth-timeout"]);
1376
1343
  const maxPayload = parseMaxPayload(values["max-payload"]);
1377
1344
  const accountResolver = parseAccountResolver(values["account-resolver"]);
1378
1345
  // The manifest path renders its broker from the manifest, which has no store fields, so the flag
1379
1346
  // would be accepted and never rendered. Refuse it rather than drop it.
1380
1347
  if (maxFileStore !== undefined && values.file)
1381
- 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");
1348
+ 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");
1382
1349
  // An open mesh has no operator, no system account, and no $SYS creds, so there is nothing to
1383
1350
  // rotate; the request is a misunderstanding to name, never a silent no-op that reports success.
1384
1351
  if (values["rotate-sys"] && values.open) {
1385
- throw new Error("--rotate-sys is for auth meshes: an open mesh (--open) has no system account or $SYS credentials to rotate");
1352
+ 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");
1386
1353
  }
1387
1354
  // THE EFFECTIVE PROJECT ROOT IS PINNED BEFORE THE TRANSPORT IS DECIDED.
1388
1355
  //
@@ -1506,7 +1473,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1506
1473
  // one, it takes that stack's lifetime over and says so before it blocks.
1507
1474
  const holder = values.foreground ? foregroundHolder(meshRoot) : undefined;
1508
1475
  if (holder !== undefined)
1509
- throw new CommandFailure("refused", "CONFLICT", `a foreground \`cotal up\` in process ${holder} already holds this stack's lifetime; this terminal did not take it over and nothing was started`, { target: { root: meshRoot, space: stackSpace, holderPid: holder }, remedy: `use the terminal that runs process ${holder}, where Ctrl-C stops the stack, or stop it with \`cotal down --yes\` from ${meshRoot} and run \`cotal up --foreground\` again` });
1476
+ refuseForegroundStackHolder(meshRoot, stackSpace, holder);
1510
1477
  const takeover = values.foreground === true && STACK_ROLES.some((role) => serviceInstances(stackSpace, STACK_DEFINITION[role]).some((row) => observeServiceProcess(row.record.value) === "running"));
1511
1478
  // A signal ends a detached start where it is, after it records a launch it had not yet pinned to
1512
1479
  // its child, and the notice names what it left running. It is installed before the lock, so no
@@ -1527,7 +1494,9 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1527
1494
  const stackServer = values.server ?? readStackJournal(meshRoot)?.journal.server ?? localMeshesForRoot(meshRoot).find((m) => m.space === stackSpace)?.server ?? await unrecordedStackServer(meshRoot, stackSpace, values.host);
1528
1495
  if (values.foreground && presentation !== "json")
1529
1496
  stackUpForegroundNotice(presentation, stackSpace, takeover);
1530
- 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);
1497
+ 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,
1498
+ retryAtAnotherAddress: (host) => retryStackAddress(args.raw, invokedFrom, stackServer, host),
1499
+ }, native);
1531
1500
  }
1532
1501
  finally {
1533
1502
  releaseMaintenanceLock(stackLock);
@@ -1581,7 +1550,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1581
1550
  if (controller)
1582
1551
  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`, {
1583
1552
  target: { root: meshRoot, space: controller.journal.space },
1584
- 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}\``,
1553
+ remedy: controllerManifestRemedy(meshRoot, controller.journal.space, resolve(values.file)),
1585
1554
  });
1586
1555
  if (values["dry-run"]) {
1587
1556
  await upManifest(values.file, {
@@ -2281,6 +2250,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2281
2250
  }
2282
2251
  if (values["store-dir"])
2283
2252
  warnForeignStoreEntries(storeDir);
2253
+ prepareForegroundBrokerLog(logFile);
2284
2254
  // Owner-private regardless of umask: a recursive create also makes a missing `.cotal`, which every
2285
2255
  // later protection check walks as an ancestor.
2286
2256
  mkdirSync(storeDir, { recursive: true, mode: 0o700 });
@@ -2289,7 +2259,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2289
2259
  // Decided above the branch; the dial host is only settled here (a port collision may have moved
2290
2260
  // the server, and the hostname is what the certificate has to match).
2291
2261
  assertServesDialHost(transport, new URL(server).hostname);
2292
- 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;
2262
+ 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;
2293
2263
  const brokerMaxPayload = brokerSetup?.maxPayload ?? maxPayload ?? readBrokerPolicy(cotalRoot())?.maxPayload;
2294
2264
  const port = Number(new URL(server).port) || 4222;
2295
2265
  // Both modes go through a RENDERER, never bare CLI flags. Open mode used to start from
@@ -2299,13 +2269,14 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2299
2269
  const renderingBinary = brokerSetup?.brokerBinary ?? await resolveNatsServer();
2300
2270
  if (!renderingBinary.version)
2301
2271
  throw unreadVersion(renderingBinary);
2302
- const confPath = brokerSetup ? brokerSetup.confPath : writeOpenBrokerConf(storeDir, space, { brokerVersion: renderingBinary.version, port, host, transport, maxFileStore, maxPayload: brokerMaxPayload });
2272
+ const confPath = brokerSetup ? brokerSetup.confPath : writeOpenBrokerConf(storeDir, space, { brokerVersion: renderingBinary.version, port, host, transport, maxFileStore, maxPayload: brokerMaxPayload, logFile, logfileSizeLimit, logfileMaxNum });
2303
2273
  const natsArgs = [
2304
2274
  "-c", confPath,
2305
2275
  ...(boundListener ? ["--name", boundListener.serverName] : []),
2306
2276
  ];
2307
2277
  const natsServer = renderingBinary;
2308
2278
  const bin = natsServer.path;
2279
+ const brokerOutput = logFile ?? "the terminal output above";
2309
2280
  await seedBeforeLaunch();
2310
2281
  const setup = brokerSetup && { ...brokerSetup, creds: await brokerSetup.mintProvisioner() };
2311
2282
  const starting = `Starting ${natsServerLabel(natsServer)} (JetStream, ${useAuth ? "JWT auth" : "OPEN/no-auth"}) - store: ${storeDir}, bind: ${host}`;
@@ -2418,10 +2389,10 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2418
2389
  // The record is kept ON PURPOSE: it still names the store this broker opened, so a repair
2419
2390
  // `up` reopens that SAME store instead of falling back to the root's default, and a
2420
2391
  // supervising unit's restart takes the refresh path against the recorded store rather than
2421
- // racing a second broker into existence. Foreground stdio is inherited (its own log lines
2422
- // are already on this terminal, above), so there is no `.cotal/nats.log` to name here.
2392
+ // racing a second broker into existence. NATS logs to this terminal unless a native log was
2393
+ // requested, so there is no `.cotal/nats.log` to name here.
2423
2394
  const detail = signal ? `signal ${signal}` : `code ${code}`;
2424
- const repair = `log: see the terminal output above; repair: \`cotal up --server ${server} --space ${space}\``;
2395
+ const repair = `log: see ${brokerOutput}; repair: ${codeSpan(`cotal up --server ${shellWord(server)} --space ${shellWord(space)}`)}`;
2425
2396
  // Retention is read from the registry, not assumed: a broker that exits before it first
2426
2397
  // answers was never recorded, and running the same `up` again only repeats that exit, so its
2427
2398
  // step is the one a detached start gives. A registry that cannot be read is not claimed
@@ -2431,7 +2402,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2431
2402
  const mine = findMesh(space);
2432
2403
  outcome = mine && mine.server === server && mine.root === cotalRoot()
2433
2404
  ? `; the mesh "${space}" stays recorded (\`cotal meshes\` lists it offline); ${repair}`
2434
- : ` before the mesh "${space}" was recorded; next: ${listenerExitRemedy(natsServer, "the terminal output above")}`;
2405
+ : ` before the mesh "${space}" was recorded; next: ${listenerExitRemedy(natsServer, brokerOutput)}`;
2435
2406
  }
2436
2407
  catch {
2437
2408
  outcome = `; whether the mesh "${space}" stays recorded could not be read; ${repair}`;
@@ -2445,7 +2416,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2445
2416
  process.exit(exitCode("failed", "OPERATION_FAILED"));
2446
2417
  }
2447
2418
  });
2448
- await awaitSpawnedListener({ child, executable: natsServer, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: "the terminal output above", boundListener });
2419
+ await awaitSpawnedListener({ child, executable: natsServer, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: brokerOutput, boundListener });
2449
2420
  listenerReady = true;
2450
2421
  {
2451
2422
  // A DAEMON THAT DIES UNDER THIS RUNNING BROKER IS RESTARTED HERE (#2469). It exits on its own once
@@ -3500,7 +3471,7 @@ export async function recheckFreshTeamBoot(plan, own) {
3500
3471
  export function controllerStackNative() {
3501
3472
  return {
3502
3473
  prepareBroker: async (opts) => {
3503
- const prepared = await prepareBrokerStart({ transport: opts.transport, server: opts.server, space: opts.space, ...(opts.open ? { open: true } : {}), ...(opts.userAuth ? { userAuth: opts.userAuth } : {}), ...(opts.host ? { host: opts.host } : {}), ...(opts.storeDir ? { storeDir: opts.storeDir } : {}), ...(opts.existingStore ? { existingStore: opts.existingStore } : {}), ...(opts.maxFileStore !== undefined ? { maxFileStore: opts.maxFileStore } : {}), ...(opts.logFile !== undefined ? { logFile: opts.logFile } : {}), ...(opts.logfileSizeLimit !== undefined ? { logfileSizeLimit: opts.logfileSizeLimit } : {}), ...(opts.logfileMaxNum !== undefined ? { logfileMaxNum: opts.logfileMaxNum } : {}), ...(opts.authTimeout !== undefined ? { authTimeout: opts.authTimeout } : {}), ...(opts.maxPayload !== undefined ? { maxPayload: opts.maxPayload } : {}), ...(opts.accountResolver !== undefined ? { accountResolver: opts.accountResolver } : {}), ...(opts.noManager ? { noManager: true } : {}), ...(opts.seed !== undefined ? { seed: opts.seed } : opts.channels ? { channels: opts.channels } : {}), quietBoot: true });
3474
+ const prepared = await prepareBrokerStart({ transport: opts.transport, server: opts.server, space: opts.space, ...(opts.open ? { open: true } : {}), ...(opts.userAuth ? { userAuth: opts.userAuth } : {}), ...(opts.host ? { host: opts.host } : {}), ...(opts.wsPort !== undefined ? { wsPort: opts.wsPort } : {}), ...(opts.storeDir ? { storeDir: opts.storeDir } : {}), ...(opts.existingStore ? { existingStore: opts.existingStore } : {}), ...(opts.maxFileStore !== undefined ? { maxFileStore: opts.maxFileStore } : {}), ...(opts.logFile !== undefined ? { logFile: opts.logFile } : {}), ...(opts.logfileSizeLimit !== undefined ? { logfileSizeLimit: opts.logfileSizeLimit } : {}), ...(opts.logfileMaxNum !== undefined ? { logfileMaxNum: opts.logfileMaxNum } : {}), ...(opts.authTimeout !== undefined ? { authTimeout: opts.authTimeout } : {}), ...(opts.maxPayload !== undefined ? { maxPayload: opts.maxPayload } : {}), ...(opts.accountResolver !== undefined ? { accountResolver: opts.accountResolver } : {}), ...(opts.noManager ? { noManager: true } : {}), ...(opts.seed !== undefined ? { seed: opts.seed } : opts.channels ? { channels: opts.channels } : {}), quietBoot: true });
3504
3475
  return { root: prepared.root, server: prepared.server, space: prepared.space, storeDir: prepared.storeDir, transport: prepared.transport, ...(prepared.setup ? { setup: { mintProvisioner: prepared.setup.mintProvisioner, wsPort: prepared.setup.wsPort, moveWebsocketPort: prepared.setup.moveWebsocketPort } } : {}), ...(prepared.setup?.prepared && prepared.setup.stateDir ? { user: { prepared: prepared.setup.prepared, stateDir: prepared.setup.stateDir } } : {}), confPath: prepared.confPath, bin: prepared.bin, source: prepared.source, version: prepared.version, seedFile: prepared.seedFile, ...(prepared.setup?.authTimeout !== undefined ? { authTimeout: prepared.setup.authTimeout } : {}), ...(prepared.maxPayload !== undefined ? { maxPayload: prepared.maxPayload } : {}), ...(prepared.setup?.accountResolver !== undefined ? { accountResolver: prepared.setup.accountResolver } : {}) };
3505
3476
  },
3506
3477
  initializeStreams: async (server, space, setup, seedFile, recreateIssuedStores, recreateMembershipStore) => postStart(server, space, setup && { creds: await setup.mintProvisioner() }, seedFile, recreateIssuedStores, recreateMembershipStore, true),
@@ -3634,7 +3605,7 @@ async function upManifest(file, opts) {
3634
3605
  // nothing: a rotation ask answered with silent success, the exact failure class this change
3635
3606
  // exists to remove. Before the dry-run print and before anything boots.
3636
3607
  if (opts.rotateSys && open)
3637
- 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");
3608
+ 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");
3638
3609
  // Before the dry-run print and before connector preflight or any write, as the refusals above.
3639
3610
  if (!opts.storeDir)
3640
3611
  refuseUnnamedLastStore(cotalPath("nats"));
@@ -3643,6 +3614,13 @@ async function upManifest(file, opts) {
3643
3614
  if (userAuth)
3644
3615
  await preflightUserStack(cotalRoot(), m.space, userAuth.idpUrl);
3645
3616
  checkStartStore(opts.storeDir, m.space);
3617
+ // Preview and apply resolve and probe the same runtime before showing a plan or starting a broker.
3618
+ try {
3619
+ await preflightRuntime(runtime);
3620
+ }
3621
+ catch (error) {
3622
+ 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" });
3623
+ }
3646
3624
  if (opts.dryRun) {
3647
3625
  // Dial-host SAN must refuse here too (S6). The real route runs assertServesDialHost after
3648
3626
  // the plan is computed; dry-run used to return before that check and green-lit a launch
@@ -3666,14 +3644,6 @@ async function upManifest(file, opts) {
3666
3644
  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"));
3667
3645
  return;
3668
3646
  }
3669
- // Preflight an extension runtime before starting the broker. The detached manager re-execs this
3670
- // CLI and resolves the same installed package when `supervise --runtime <name>` starts.
3671
- try {
3672
- await preflightRuntime(runtime);
3673
- }
3674
- catch (error) {
3675
- 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" });
3676
- }
3677
3647
  // up -f never adopts a running broker. The old spawn -f route is no longer a manifest deploy.
3678
3648
  if (await isReachable(server)) {
3679
3649
  if (opts.freshTeamBoot)
@@ -3681,7 +3651,7 @@ async function upManifest(file, opts) {
3681
3651
  // This folder's own mesh for the manifest's space is named as running, as a bare `up` names it,
3682
3652
  // with the routes that change it instead of the advice for a foreign broker.
3683
3653
  if (loadMeshes().some((row) => row.server === server && row.root === cotalRoot() && row.space === m.space)) {
3684
- 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);
3654
+ 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);
3685
3655
  process.exit(1);
3686
3656
  }
3687
3657
  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);
@@ -4166,7 +4136,7 @@ export async function prepareBrokerStart(opts) {
4166
4136
  closeSync(fd);
4167
4137
  }
4168
4138
  }
4169
- const setup = useAuth ? await authSetup(storeDir, server, space, host, opts.userAuth, transport, opts.rotateSys, opts.maxFileStore, opts.quietBoot, { authTimeout: opts.authTimeout, maxPayload: opts.maxPayload, accountResolver: opts.accountResolver, manager: opts.noManager !== true, logFile, logfileSizeLimit: opts.logfileSizeLimit, logfileMaxNum: opts.logfileMaxNum }) : undefined;
4139
+ const setup = useAuth ? await authSetup(storeDir, server, space, host, opts.userAuth, transport, opts.rotateSys, opts.maxFileStore, opts.quietBoot, { authTimeout: opts.authTimeout, maxPayload: opts.maxPayload, accountResolver: opts.accountResolver, manager: opts.noManager !== true, logFile, logfileSizeLimit: opts.logfileSizeLimit, logfileMaxNum: opts.logfileMaxNum, wsPort: opts.wsPort }) : undefined;
4170
4140
  const maxPayload = setup?.maxPayload ?? opts.maxPayload ?? readBrokerPolicy(root)?.maxPayload;
4171
4141
  const port = Number(new URL(server).port) || 4222;
4172
4142
  // Same rule as the foreground path: every route to a listener names its transport (see
@@ -4185,21 +4155,7 @@ export async function prepareBrokerStart(opts) {
4185
4155
  const { path: bin, source, version } = renderingBinary;
4186
4156
  return { root, server, space, useAuth, storeDir, seedFile, host, transport, setup, maxPayload, confPath, args, bin, source, version };
4187
4157
  }
4188
- /**
4189
- * Open the detached broker's log with {@link openPrivateAppend}: created `0600` whatever the umask,
4190
- * never through a symlink, and an earlier log this user owns set to `0600`. A symlink, a log another
4191
- * user owns or a name that is not a regular file is refused and left unchanged.
4192
- */
4193
- export function openBrokerLog(path) {
4194
- try {
4195
- return openPrivateAppend(path);
4196
- }
4197
- catch (error) {
4198
- if (error.code !== "EPERM")
4199
- throw error;
4200
- 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` });
4201
- }
4202
- }
4158
+ export { openBrokerLog };
4203
4159
  /**
4204
4160
  * Start a background nats-server (JetStream), wait until it's reachable, pre-create the
4205
4161
  * space's streams, and leave it running detached (pid in `.cotal/nats.pid`). Used by
@@ -4632,8 +4588,7 @@ async function waitReady(server, creds, tls = false, log) {
4632
4588
  return false;
4633
4589
  }
4634
4590
  /** Bytes plus completed-restore lines in the broker log, and whether a restore is in flight. A
4635
- * foreground launch inherits the terminal and has no file to read, so it contributes no evidence
4636
- * and keeps the silent-probe bound. */
4591
+ * foreground broker logging to the terminal has no file to read, so it keeps the silent-probe bound. */
4637
4592
  function brokerRecoveryEvidence(log) {
4638
4593
  const none = { evidence: 0, restoring: false };
4639
4594
  if (!log || log.startsWith("the terminal"))
@@ -4837,60 +4792,6 @@ function refuseRegisteredAddress(server, space, elsewhere) {
4837
4792
  remedy: `${elsewhere}, or free that one with \`cotal space forget ${held.space}\``,
4838
4793
  });
4839
4794
  }
4840
- /** Choose only a first implicit address. A saved or explicitly requested address is never moved.
4841
- * The broker still validates and binds its own listener; this inspection cannot reserve the port. */
4842
- async function freshStackServer(server, bindHost) {
4843
- const url = new URL(server);
4844
- const host = (bindHost ?? url.hostname).replace(/^\[|\]$/g, "");
4845
- const reserved = new Set();
4846
- // A recorded address this cannot take apart reserves nothing: it names no host and port to avoid.
4847
- for (const mesh of loadMeshes()) {
4848
- const key = brokerAddressKey(mesh.server);
4849
- if (key !== undefined)
4850
- reserved.add(key);
4851
- }
4852
- let candidate = server;
4853
- for (let attempt = 0; attempt < 16; attempt++) {
4854
- const address = new URL(candidate);
4855
- const key = brokerAddressKey(candidate);
4856
- if (key === undefined || !reserved.has(key)) {
4857
- try {
4858
- await freePort(host, Number(address.port) || 4222);
4859
- return candidate;
4860
- }
4861
- catch (error) {
4862
- if (error.code !== "EADDRINUSE")
4863
- throw error;
4864
- }
4865
- }
4866
- candidate = await serverWithFreePort(server, host);
4867
- }
4868
- throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "no unreserved local broker address could be selected; no broker was started");
4869
- }
4870
- async function serverWithFreePort(server, host) {
4871
- const url = new URL(server);
4872
- url.port = String(await freePort(host));
4873
- return url.toString();
4874
- }
4875
- function freePort(host, requestedPort = 0) {
4876
- return new Promise((resolve, reject) => {
4877
- const srv = createServer();
4878
- srv.unref();
4879
- srv.once("error", reject);
4880
- srv.listen(requestedPort, host, () => {
4881
- const addr = srv.address();
4882
- const port = typeof addr === "object" && addr ? addr.port : undefined;
4883
- srv.close((err) => {
4884
- if (err)
4885
- reject(err);
4886
- else if (port)
4887
- resolve(port);
4888
- else
4889
- reject(new Error("could not allocate a free port"));
4890
- });
4891
- });
4892
- });
4893
- }
4894
4795
  function membershipConversionRefusal(space, remedy = "stop the stack with `cotal down --yes`, then run `cotal up --recreate-membership-store`") {
4895
4796
  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`, {
4896
4797
  target: { space }, remedy,
@@ -5607,10 +5508,8 @@ requested = {}) {
5607
5508
  }
5608
5509
  }
5609
5510
  const port = Number(new URL(server).port) || 4222;
5610
- // P2 item 6: allocate the broker's loopback WebSocket listener port — the console page becomes a
5611
- // mesh §13.6 session client over it (a NEW same-host attack surface, localhost-bound, no TLS). The
5612
- // manager's establisher builds its wsUrl from this; threaded to `supervise --ws-port`.
5613
- const wsPort = await freePort(host);
5511
+ // A reused controller manager advertises its launch-time WebSocket port.
5512
+ const wsPort = requested.wsPort ?? await freePort(host);
5614
5513
  const confPath = resolve(dir, "server.conf");
5615
5514
  // EVERY tenant of this root, not just the one being booted: `resolver_preload` is a whole-broker
5616
5515
  // map, so a config rendered from one space evicts the rest silently. `auth` leads the list because