@cotal-ai/cli 0.100.2 → 0.101.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 (618) hide show
  1. package/dist/chat/chat-view.d.ts.map +1 -1
  2. package/dist/chat/chat-view.js +5 -1
  3. package/dist/chat/chat-view.js.map +1 -1
  4. package/dist/chat/engine.d.ts +2 -1
  5. package/dist/chat/engine.d.ts.map +1 -1
  6. package/dist/chat/engine.js +2 -1
  7. package/dist/chat/engine.js.map +1 -1
  8. package/dist/chat/frontend.d.ts.map +1 -1
  9. package/dist/chat/frontend.js +13 -7
  10. package/dist/chat/frontend.js.map +1 -1
  11. package/dist/chat/native-session.d.ts +22 -3
  12. package/dist/chat/native-session.d.ts.map +1 -1
  13. package/dist/chat/native-session.js +91 -19
  14. package/dist/chat/native-session.js.map +1 -1
  15. package/dist/chat/open-session.d.ts +1 -0
  16. package/dist/chat/open-session.d.ts.map +1 -1
  17. package/dist/chat/open-session.js +1 -1
  18. package/dist/chat/open-session.js.map +1 -1
  19. package/dist/chat/picker.d.ts +5 -0
  20. package/dist/chat/picker.d.ts.map +1 -1
  21. package/dist/chat/picker.js +23 -10
  22. package/dist/chat/picker.js.map +1 -1
  23. package/dist/chat/plain.d.ts.map +1 -1
  24. package/dist/chat/plain.js +36 -10
  25. package/dist/chat/plain.js.map +1 -1
  26. package/dist/chat/session.d.ts +5 -0
  27. package/dist/chat/session.d.ts.map +1 -1
  28. package/dist/chat/static-session.d.ts +1 -0
  29. package/dist/chat/static-session.d.ts.map +1 -1
  30. package/dist/chat/static-session.js +24 -8
  31. package/dist/chat/static-session.js.map +1 -1
  32. package/dist/chat/stdio-io.d.ts +2 -0
  33. package/dist/chat/stdio-io.d.ts.map +1 -1
  34. package/dist/chat/stdio-io.js +6 -6
  35. package/dist/chat/stdio-io.js.map +1 -1
  36. package/dist/chat/stdio.d.ts +3 -2
  37. package/dist/chat/stdio.d.ts.map +1 -1
  38. package/dist/chat/stdio.js +26 -25
  39. package/dist/chat/stdio.js.map +1 -1
  40. package/dist/chat/user-session.d.ts +1 -0
  41. package/dist/chat/user-session.d.ts.map +1 -1
  42. package/dist/chat/user-session.js +1 -1
  43. package/dist/chat/user-session.js.map +1 -1
  44. package/dist/chat/view.d.ts +5 -4
  45. package/dist/chat/view.d.ts.map +1 -1
  46. package/dist/chat/view.js +10 -8
  47. package/dist/chat/view.js.map +1 -1
  48. package/dist/command.d.ts +5 -0
  49. package/dist/command.d.ts.map +1 -1
  50. package/dist/command.js +295 -82
  51. package/dist/command.js.map +1 -1
  52. package/dist/commands/agents.d.ts +29 -5
  53. package/dist/commands/agents.d.ts.map +1 -1
  54. package/dist/commands/agents.js +100 -35
  55. package/dist/commands/agents.js.map +1 -1
  56. package/dist/commands/backup-maintenance.d.ts.map +1 -1
  57. package/dist/commands/backup-maintenance.js +54 -21
  58. package/dist/commands/backup-maintenance.js.map +1 -1
  59. package/dist/commands/backup-read.d.ts.map +1 -1
  60. package/dist/commands/backup-read.js +12 -15
  61. package/dist/commands/backup-read.js.map +1 -1
  62. package/dist/commands/backup-restore.d.ts.map +1 -1
  63. package/dist/commands/backup-restore.js +20 -4
  64. package/dist/commands/backup-restore.js.map +1 -1
  65. package/dist/commands/backup.d.ts.map +1 -1
  66. package/dist/commands/backup.js +156 -28
  67. package/dist/commands/backup.js.map +1 -1
  68. package/dist/commands/channel-members.d.ts +1 -1
  69. package/dist/commands/channel-members.d.ts.map +1 -1
  70. package/dist/commands/channel-members.js +115 -29
  71. package/dist/commands/channel-members.js.map +1 -1
  72. package/dist/commands/channels.d.ts +11 -1
  73. package/dist/commands/channels.d.ts.map +1 -1
  74. package/dist/commands/channels.js +109 -20
  75. package/dist/commands/channels.js.map +1 -1
  76. package/dist/commands/chat.d.ts +11 -3
  77. package/dist/commands/chat.d.ts.map +1 -1
  78. package/dist/commands/chat.js +50 -22
  79. package/dist/commands/chat.js.map +1 -1
  80. package/dist/commands/clean.d.ts +10 -5
  81. package/dist/commands/clean.d.ts.map +1 -1
  82. package/dist/commands/clean.js +245 -42
  83. package/dist/commands/clean.js.map +1 -1
  84. package/dist/commands/completion.d.ts +15 -2
  85. package/dist/commands/completion.d.ts.map +1 -1
  86. package/dist/commands/completion.js +91 -26
  87. package/dist/commands/completion.js.map +1 -1
  88. package/dist/commands/config.d.ts +24 -1
  89. package/dist/commands/config.d.ts.map +1 -1
  90. package/dist/commands/config.js +65 -13
  91. package/dist/commands/config.js.map +1 -1
  92. package/dist/commands/console.d.ts.map +1 -1
  93. package/dist/commands/console.js +5 -4
  94. package/dist/commands/console.js.map +1 -1
  95. package/dist/commands/describe.d.ts +4 -2
  96. package/dist/commands/describe.d.ts.map +1 -1
  97. package/dist/commands/describe.js +4 -4
  98. package/dist/commands/describe.js.map +1 -1
  99. package/dist/commands/doctor.d.ts +1 -1
  100. package/dist/commands/doctor.d.ts.map +1 -1
  101. package/dist/commands/doctor.js +261 -34
  102. package/dist/commands/doctor.js.map +1 -1
  103. package/dist/commands/down-manifest.d.ts.map +1 -1
  104. package/dist/commands/down-manifest.js +9 -6
  105. package/dist/commands/down-manifest.js.map +1 -1
  106. package/dist/commands/down-services.d.ts +17 -16
  107. package/dist/commands/down-services.d.ts.map +1 -1
  108. package/dist/commands/down-services.js +29 -53
  109. package/dist/commands/down-services.js.map +1 -1
  110. package/dist/commands/down.d.ts +2 -2
  111. package/dist/commands/down.d.ts.map +1 -1
  112. package/dist/commands/down.js +96 -67
  113. package/dist/commands/down.js.map +1 -1
  114. package/dist/commands/endpoint-deregister.d.ts.map +1 -1
  115. package/dist/commands/endpoint-deregister.js +2 -2
  116. package/dist/commands/endpoint-deregister.js.map +1 -1
  117. package/dist/commands/endpoint.d.ts +2 -1
  118. package/dist/commands/endpoint.d.ts.map +1 -1
  119. package/dist/commands/endpoint.js +2 -2
  120. package/dist/commands/endpoint.js.map +1 -1
  121. package/dist/commands/endpoints.d.ts +1 -0
  122. package/dist/commands/endpoints.d.ts.map +1 -1
  123. package/dist/commands/endpoints.js +20 -5
  124. package/dist/commands/endpoints.js.map +1 -1
  125. package/dist/commands/feedback.d.ts.map +1 -1
  126. package/dist/commands/feedback.js +40 -2
  127. package/dist/commands/feedback.js.map +1 -1
  128. package/dist/commands/help.d.ts.map +1 -1
  129. package/dist/commands/help.js +2 -1
  130. package/dist/commands/help.js.map +1 -1
  131. package/dist/commands/history-clear.d.ts.map +1 -1
  132. package/dist/commands/history-clear.js +67 -51
  133. package/dist/commands/history-clear.js.map +1 -1
  134. package/dist/commands/history.d.ts +17 -2
  135. package/dist/commands/history.d.ts.map +1 -1
  136. package/dist/commands/history.js +221 -34
  137. package/dist/commands/history.js.map +1 -1
  138. package/dist/commands/join.d.ts +2 -0
  139. package/dist/commands/join.d.ts.map +1 -1
  140. package/dist/commands/join.js +132 -80
  141. package/dist/commands/join.js.map +1 -1
  142. package/dist/commands/meshes-add.d.ts +19 -4
  143. package/dist/commands/meshes-add.d.ts.map +1 -1
  144. package/dist/commands/meshes-add.js +114 -15
  145. package/dist/commands/meshes-add.js.map +1 -1
  146. package/dist/commands/meshes-wizard.d.ts +1 -0
  147. package/dist/commands/meshes-wizard.d.ts.map +1 -1
  148. package/dist/commands/meshes-wizard.js +45 -13
  149. package/dist/commands/meshes-wizard.js.map +1 -1
  150. package/dist/commands/meshes.d.ts +1 -1
  151. package/dist/commands/meshes.d.ts.map +1 -1
  152. package/dist/commands/meshes.js +76 -47
  153. package/dist/commands/meshes.js.map +1 -1
  154. package/dist/commands/mint.d.ts.map +1 -1
  155. package/dist/commands/mint.js +212 -19
  156. package/dist/commands/mint.js.map +1 -1
  157. package/dist/commands/models.d.ts +5 -1
  158. package/dist/commands/models.d.ts.map +1 -1
  159. package/dist/commands/models.js +21 -13
  160. package/dist/commands/models.js.map +1 -1
  161. package/dist/commands/persona-remote.d.ts.map +1 -1
  162. package/dist/commands/persona-remote.js +24 -13
  163. package/dist/commands/persona-remote.js.map +1 -1
  164. package/dist/commands/persona.d.ts +1 -1
  165. package/dist/commands/persona.d.ts.map +1 -1
  166. package/dist/commands/persona.js +92 -23
  167. package/dist/commands/persona.js.map +1 -1
  168. package/dist/commands/personas.d.ts.map +1 -1
  169. package/dist/commands/personas.js +59 -40
  170. package/dist/commands/personas.js.map +1 -1
  171. package/dist/commands/reset-space-apply.d.ts.map +1 -1
  172. package/dist/commands/reset-space-apply.js +69 -17
  173. package/dist/commands/reset-space-apply.js.map +1 -1
  174. package/dist/commands/reset-store-apply.d.ts +16 -0
  175. package/dist/commands/reset-store-apply.d.ts.map +1 -1
  176. package/dist/commands/reset-store-apply.js +122 -23
  177. package/dist/commands/reset-store-apply.js.map +1 -1
  178. package/dist/commands/reset.d.ts.map +1 -1
  179. package/dist/commands/reset.js +8 -7
  180. package/dist/commands/reset.js.map +1 -1
  181. package/dist/commands/revoke-credential.d.ts +5 -0
  182. package/dist/commands/revoke-credential.d.ts.map +1 -0
  183. package/dist/commands/revoke-credential.js +128 -0
  184. package/dist/commands/revoke-credential.js.map +1 -0
  185. package/dist/commands/send.d.ts +11 -3
  186. package/dist/commands/send.d.ts.map +1 -1
  187. package/dist/commands/send.js +284 -47
  188. package/dist/commands/send.js.map +1 -1
  189. package/dist/commands/service-actions.d.ts +2 -1
  190. package/dist/commands/service-actions.d.ts.map +1 -1
  191. package/dist/commands/service-actions.js +117 -21
  192. package/dist/commands/service-actions.js.map +1 -1
  193. package/dist/commands/service-log-follow.js +1 -1
  194. package/dist/commands/service-log-follow.js.map +1 -1
  195. package/dist/commands/service-registry.d.ts +1 -1
  196. package/dist/commands/service-registry.d.ts.map +1 -1
  197. package/dist/commands/service-registry.js +74 -30
  198. package/dist/commands/service-registry.js.map +1 -1
  199. package/dist/commands/service-set-stop.d.ts.map +1 -1
  200. package/dist/commands/service-set-stop.js +3 -2
  201. package/dist/commands/service-set-stop.js.map +1 -1
  202. package/dist/commands/setup-start.d.ts.map +1 -1
  203. package/dist/commands/setup-start.js +46 -5
  204. package/dist/commands/setup-start.js.map +1 -1
  205. package/dist/commands/setup.d.ts.map +1 -1
  206. package/dist/commands/setup.js +28 -13
  207. package/dist/commands/setup.js.map +1 -1
  208. package/dist/commands/space-delete.d.ts.map +1 -1
  209. package/dist/commands/space-delete.js +130 -41
  210. package/dist/commands/space-delete.js.map +1 -1
  211. package/dist/commands/space-registration.d.ts +13 -6
  212. package/dist/commands/space-registration.d.ts.map +1 -1
  213. package/dist/commands/space-registration.js +167 -46
  214. package/dist/commands/space-registration.js.map +1 -1
  215. package/dist/commands/space.d.ts +15 -1
  216. package/dist/commands/space.d.ts.map +1 -1
  217. package/dist/commands/space.js +66 -24
  218. package/dist/commands/space.js.map +1 -1
  219. package/dist/commands/spawn-preview.d.ts.map +1 -1
  220. package/dist/commands/spawn-preview.js +48 -10
  221. package/dist/commands/spawn-preview.js.map +1 -1
  222. package/dist/commands/spawn.d.ts +36 -13
  223. package/dist/commands/spawn.d.ts.map +1 -1
  224. package/dist/commands/spawn.js +263 -129
  225. package/dist/commands/spawn.js.map +1 -1
  226. package/dist/commands/stack-down.d.ts +9 -3
  227. package/dist/commands/stack-down.d.ts.map +1 -1
  228. package/dist/commands/stack-down.js +344 -64
  229. package/dist/commands/stack-down.js.map +1 -1
  230. package/dist/commands/stack-gone.d.ts +17 -0
  231. package/dist/commands/stack-gone.d.ts.map +1 -0
  232. package/dist/commands/stack-gone.js +218 -0
  233. package/dist/commands/stack-gone.js.map +1 -0
  234. package/dist/commands/stack-up.d.ts +64 -4
  235. package/dist/commands/stack-up.d.ts.map +1 -1
  236. package/dist/commands/stack-up.js +482 -55
  237. package/dist/commands/stack-up.js.map +1 -1
  238. package/dist/commands/status.d.ts +76 -2
  239. package/dist/commands/status.d.ts.map +1 -1
  240. package/dist/commands/status.js +550 -112
  241. package/dist/commands/status.js.map +1 -1
  242. package/dist/commands/team-agent-apply.d.ts.map +1 -1
  243. package/dist/commands/team-agent-apply.js +4 -3
  244. package/dist/commands/team-agent-apply.js.map +1 -1
  245. package/dist/commands/team-agent-remove.d.ts.map +1 -1
  246. package/dist/commands/team-agent-remove.js +4 -4
  247. package/dist/commands/team-agent-remove.js.map +1 -1
  248. package/dist/commands/team-boot-controller.d.ts.map +1 -1
  249. package/dist/commands/team-boot-controller.js +8 -2
  250. package/dist/commands/team-boot-controller.js.map +1 -1
  251. package/dist/commands/team-channel-remove.d.ts.map +1 -1
  252. package/dist/commands/team-channel-remove.js +26 -10
  253. package/dist/commands/team-channel-remove.js.map +1 -1
  254. package/dist/commands/team-deploy-apply.d.ts.map +1 -1
  255. package/dist/commands/team-deploy-apply.js +4 -3
  256. package/dist/commands/team-deploy-apply.js.map +1 -1
  257. package/dist/commands/team-mixed-remove.js +5 -5
  258. package/dist/commands/team-mixed-remove.js.map +1 -1
  259. package/dist/commands/team.d.ts.map +1 -1
  260. package/dist/commands/team.js +94 -32
  261. package/dist/commands/team.js.map +1 -1
  262. package/dist/commands/telemetry.d.ts.map +1 -1
  263. package/dist/commands/telemetry.js +3 -1
  264. package/dist/commands/telemetry.js.map +1 -1
  265. package/dist/commands/topology.d.ts.map +1 -1
  266. package/dist/commands/topology.js +11 -7
  267. package/dist/commands/topology.js.map +1 -1
  268. package/dist/commands/up.d.ts +6 -6
  269. package/dist/commands/up.d.ts.map +1 -1
  270. package/dist/commands/up.js +963 -240
  271. package/dist/commands/up.js.map +1 -1
  272. package/dist/commands/update.d.ts.map +1 -1
  273. package/dist/commands/update.js +9 -3
  274. package/dist/commands/update.js.map +1 -1
  275. package/dist/commands/use.d.ts +5 -1
  276. package/dist/commands/use.d.ts.map +1 -1
  277. package/dist/commands/use.js +55 -12
  278. package/dist/commands/use.js.map +1 -1
  279. package/dist/commands/watch.d.ts +4 -1
  280. package/dist/commands/watch.d.ts.map +1 -1
  281. package/dist/commands/watch.js +15 -3
  282. package/dist/commands/watch.js.map +1 -1
  283. package/dist/commands/who.d.ts +2 -0
  284. package/dist/commands/who.d.ts.map +1 -1
  285. package/dist/commands/who.js +18 -5
  286. package/dist/commands/who.js.map +1 -1
  287. package/dist/commands/whoami.d.ts +44 -5
  288. package/dist/commands/whoami.d.ts.map +1 -1
  289. package/dist/commands/whoami.js +168 -16
  290. package/dist/commands/whoami.js.map +1 -1
  291. package/dist/console/app.d.ts +1 -1
  292. package/dist/console/app.d.ts.map +1 -1
  293. package/dist/console/app.js +15 -9
  294. package/dist/console/app.js.map +1 -1
  295. package/dist/console/launch.d.ts +25 -0
  296. package/dist/console/launch.d.ts.map +1 -0
  297. package/dist/console/launch.js +56 -0
  298. package/dist/console/launch.js.map +1 -0
  299. package/dist/console/ui/CommandPalette.d.ts +5 -4
  300. package/dist/console/ui/CommandPalette.d.ts.map +1 -1
  301. package/dist/console/ui/CommandPalette.js +136 -45
  302. package/dist/console/ui/CommandPalette.js.map +1 -1
  303. package/dist/console/ui/Help.js +1 -1
  304. package/dist/console/ui/Help.js.map +1 -1
  305. package/dist/console/ui/Modal.d.ts +10 -0
  306. package/dist/console/ui/Modal.d.ts.map +1 -0
  307. package/dist/console/ui/Modal.js +8 -0
  308. package/dist/console/ui/Modal.js.map +1 -0
  309. package/dist/console/ui/NewAgent.d.ts +14 -0
  310. package/dist/console/ui/NewAgent.d.ts.map +1 -0
  311. package/dist/console/ui/NewAgent.js +114 -0
  312. package/dist/console/ui/NewAgent.js.map +1 -0
  313. package/dist/console/ui/StatusBar.d.ts +1 -2
  314. package/dist/console/ui/StatusBar.d.ts.map +1 -1
  315. package/dist/console/ui/StatusBar.js +6 -8
  316. package/dist/console/ui/StatusBar.js.map +1 -1
  317. package/dist/console/ui/topo/Map.d.ts.map +1 -1
  318. package/dist/console/ui/topo/Map.js +1 -2
  319. package/dist/console/ui/topo/Map.js.map +1 -1
  320. package/dist/console/ui/topo/Matrix.js +2 -2
  321. package/dist/console/ui/topo/Matrix.js.map +1 -1
  322. package/dist/console/ui/topo/Sequence.d.ts.map +1 -1
  323. package/dist/console/ui/topo/Sequence.js +5 -4
  324. package/dist/console/ui/topo/Sequence.js.map +1 -1
  325. package/dist/console/ui/topo/model.d.ts +2 -1
  326. package/dist/console/ui/topo/model.d.ts.map +1 -1
  327. package/dist/console/ui/topo/model.js +4 -3
  328. package/dist/console/ui/topo/model.js.map +1 -1
  329. package/dist/exec-endpoint/service-adapter.d.ts.map +1 -1
  330. package/dist/exec-endpoint/service-adapter.js +13 -3
  331. package/dist/exec-endpoint/service-adapter.js.map +1 -1
  332. package/dist/ext-loader.d.ts +4 -0
  333. package/dist/ext-loader.d.ts.map +1 -1
  334. package/dist/ext-loader.js +6 -0
  335. package/dist/ext-loader.js.map +1 -1
  336. package/dist/help.d.ts.map +1 -1
  337. package/dist/help.js +44 -23
  338. package/dist/help.js.map +1 -1
  339. package/dist/index.d.ts.map +1 -1
  340. package/dist/index.js +59 -54
  341. package/dist/index.js.map +1 -1
  342. package/dist/lib/agent-skills.d.ts.map +1 -1
  343. package/dist/lib/agent-skills.js +2 -1
  344. package/dist/lib/agent-skills.js.map +1 -1
  345. package/dist/lib/attach-client.js +2 -2
  346. package/dist/lib/attach-client.js.map +1 -1
  347. package/dist/lib/backup-artifact.d.ts +29 -8
  348. package/dist/lib/backup-artifact.d.ts.map +1 -1
  349. package/dist/lib/backup-artifact.js +147 -26
  350. package/dist/lib/backup-artifact.js.map +1 -1
  351. package/dist/lib/broker-service.d.ts +27 -3
  352. package/dist/lib/broker-service.d.ts.map +1 -1
  353. package/dist/lib/broker-service.js +135 -27
  354. package/dist/lib/broker-service.js.map +1 -1
  355. package/dist/lib/broker-store-health.d.ts +89 -0
  356. package/dist/lib/broker-store-health.d.ts.map +1 -0
  357. package/dist/lib/broker-store-health.js +171 -0
  358. package/dist/lib/broker-store-health.js.map +1 -0
  359. package/dist/lib/cancel.d.ts +4 -4
  360. package/dist/lib/cancel.d.ts.map +1 -1
  361. package/dist/lib/cancel.js +5 -5
  362. package/dist/lib/cancel.js.map +1 -1
  363. package/dist/lib/completion-install.d.ts +11 -2
  364. package/dist/lib/completion-install.d.ts.map +1 -1
  365. package/dist/lib/completion-install.js +79 -21
  366. package/dist/lib/completion-install.js.map +1 -1
  367. package/dist/lib/completion-scripts.d.ts.map +1 -1
  368. package/dist/lib/completion-scripts.js +2 -2
  369. package/dist/lib/completion-scripts.js.map +1 -1
  370. package/dist/lib/completion.d.ts +5 -1
  371. package/dist/lib/completion.d.ts.map +1 -1
  372. package/dist/lib/completion.js +10 -0
  373. package/dist/lib/completion.js.map +1 -1
  374. package/dist/lib/concrete-channel.d.ts +6 -0
  375. package/dist/lib/concrete-channel.d.ts.map +1 -0
  376. package/dist/lib/concrete-channel.js +17 -0
  377. package/dist/lib/concrete-channel.js.map +1 -0
  378. package/dist/lib/confirmation-required.d.ts +3 -12
  379. package/dist/lib/confirmation-required.d.ts.map +1 -1
  380. package/dist/lib/confirmation-required.js +9 -8
  381. package/dist/lib/confirmation-required.js.map +1 -1
  382. package/dist/lib/connect.d.ts +9 -0
  383. package/dist/lib/connect.d.ts.map +1 -1
  384. package/dist/lib/connect.js +27 -0
  385. package/dist/lib/connect.js.map +1 -1
  386. package/dist/lib/control.d.ts +42 -12
  387. package/dist/lib/control.d.ts.map +1 -1
  388. package/dist/lib/control.js +130 -31
  389. package/dist/lib/control.js.map +1 -1
  390. package/dist/lib/controller-restore.d.ts.map +1 -1
  391. package/dist/lib/controller-restore.js +12 -7
  392. package/dist/lib/controller-restore.js.map +1 -1
  393. package/dist/lib/credential-authority.d.ts.map +1 -1
  394. package/dist/lib/credential-authority.js +3 -0
  395. package/dist/lib/credential-authority.js.map +1 -1
  396. package/dist/lib/credential-exports.d.ts +17 -0
  397. package/dist/lib/credential-exports.d.ts.map +1 -0
  398. package/dist/lib/credential-exports.js +21 -0
  399. package/dist/lib/credential-exports.js.map +1 -0
  400. package/dist/lib/debug-flag.d.ts +4 -0
  401. package/dist/lib/debug-flag.d.ts.map +1 -0
  402. package/dist/lib/debug-flag.js +7 -0
  403. package/dist/lib/debug-flag.js.map +1 -0
  404. package/dist/lib/default-persona.d.ts +2 -0
  405. package/dist/lib/default-persona.d.ts.map +1 -1
  406. package/dist/lib/default-persona.js +2 -0
  407. package/dist/lib/default-persona.js.map +1 -1
  408. package/dist/lib/delivery-proc.d.ts +1 -1
  409. package/dist/lib/delivery-proc.d.ts.map +1 -1
  410. package/dist/lib/delivery-proc.js +5 -4
  411. package/dist/lib/delivery-proc.js.map +1 -1
  412. package/dist/lib/delivery-responder.d.ts +7 -3
  413. package/dist/lib/delivery-responder.d.ts.map +1 -1
  414. package/dist/lib/delivery-responder.js +8 -4
  415. package/dist/lib/delivery-responder.js.map +1 -1
  416. package/dist/lib/denied-write.d.ts +8 -0
  417. package/dist/lib/denied-write.d.ts.map +1 -0
  418. package/dist/lib/denied-write.js +24 -0
  419. package/dist/lib/denied-write.js.map +1 -0
  420. package/dist/lib/endpoint-capability-gates.js +2 -2
  421. package/dist/lib/endpoint-capability-gates.js.map +1 -1
  422. package/dist/lib/flag-value-refusal.d.ts +8 -0
  423. package/dist/lib/flag-value-refusal.d.ts.map +1 -0
  424. package/dist/lib/flag-value-refusal.js +10 -0
  425. package/dist/lib/flag-value-refusal.js.map +1 -0
  426. package/dist/lib/install-umask.d.ts +5 -0
  427. package/dist/lib/install-umask.d.ts.map +1 -1
  428. package/dist/lib/install-umask.js +25 -0
  429. package/dist/lib/install-umask.js.map +1 -1
  430. package/dist/lib/interrupt-notice.d.ts +23 -1
  431. package/dist/lib/interrupt-notice.d.ts.map +1 -1
  432. package/dist/lib/interrupt-notice.js +27 -6
  433. package/dist/lib/interrupt-notice.js.map +1 -1
  434. package/dist/lib/interrupt-report.d.ts +7 -0
  435. package/dist/lib/interrupt-report.d.ts.map +1 -0
  436. package/dist/lib/interrupt-report.js +24 -0
  437. package/dist/lib/interrupt-report.js.map +1 -0
  438. package/dist/lib/isolated-broker.d.ts +1 -1
  439. package/dist/lib/isolated-broker.d.ts.map +1 -1
  440. package/dist/lib/isolated-broker.js +17 -8
  441. package/dist/lib/isolated-broker.js.map +1 -1
  442. package/dist/lib/legacy-start.d.ts +8 -6
  443. package/dist/lib/legacy-start.d.ts.map +1 -1
  444. package/dist/lib/legacy-start.js +36 -36
  445. package/dist/lib/legacy-start.js.map +1 -1
  446. package/dist/lib/manager-choice.d.ts +45 -4
  447. package/dist/lib/manager-choice.d.ts.map +1 -1
  448. package/dist/lib/manager-choice.js +214 -24
  449. package/dist/lib/manager-choice.js.map +1 -1
  450. package/dist/lib/manager-proc.d.ts.map +1 -1
  451. package/dist/lib/manager-proc.js +7 -6
  452. package/dist/lib/manager-proc.js.map +1 -1
  453. package/dist/lib/manifest/index.d.ts +5 -1
  454. package/dist/lib/manifest/index.d.ts.map +1 -1
  455. package/dist/lib/manifest/index.js +50 -5
  456. package/dist/lib/manifest/index.js.map +1 -1
  457. package/dist/lib/manifest/preflight.d.ts +4 -0
  458. package/dist/lib/manifest/preflight.d.ts.map +1 -1
  459. package/dist/lib/manifest/preflight.js +18 -1
  460. package/dist/lib/manifest/preflight.js.map +1 -1
  461. package/dist/lib/manifest/resolve.d.ts +8 -0
  462. package/dist/lib/manifest/resolve.d.ts.map +1 -1
  463. package/dist/lib/manifest/resolve.js +104 -11
  464. package/dist/lib/manifest/resolve.js.map +1 -1
  465. package/dist/lib/missing-flags.js +1 -1
  466. package/dist/lib/missing-flags.js.map +1 -1
  467. package/dist/lib/nats-bin.d.ts +28 -5
  468. package/dist/lib/nats-bin.d.ts.map +1 -1
  469. package/dist/lib/nats-bin.js +85 -7
  470. package/dist/lib/nats-bin.js.map +1 -1
  471. package/dist/lib/nearest-word.d.ts +14 -0
  472. package/dist/lib/nearest-word.d.ts.map +1 -0
  473. package/dist/lib/nearest-word.js +76 -0
  474. package/dist/lib/nearest-word.js.map +1 -0
  475. package/dist/lib/no-expiry-record.d.ts +8 -0
  476. package/dist/lib/no-expiry-record.d.ts.map +1 -0
  477. package/dist/lib/no-expiry-record.js +27 -0
  478. package/dist/lib/no-expiry-record.js.map +1 -0
  479. package/dist/lib/paths.d.ts +31 -0
  480. package/dist/lib/paths.d.ts.map +1 -1
  481. package/dist/lib/paths.js +92 -2
  482. package/dist/lib/paths.js.map +1 -1
  483. package/dist/lib/persona-files.d.ts +29 -6
  484. package/dist/lib/persona-files.d.ts.map +1 -1
  485. package/dist/lib/persona-files.js +179 -36
  486. package/dist/lib/persona-files.js.map +1 -1
  487. package/dist/lib/personas.d.ts +18 -1
  488. package/dist/lib/personas.d.ts.map +1 -1
  489. package/dist/lib/personas.js +65 -6
  490. package/dist/lib/personas.js.map +1 -1
  491. package/dist/lib/prompts.d.ts +7 -1
  492. package/dist/lib/prompts.d.ts.map +1 -1
  493. package/dist/lib/prompts.js +43 -3
  494. package/dist/lib/prompts.js.map +1 -1
  495. package/dist/lib/registry-errors.d.ts +2 -1
  496. package/dist/lib/registry-errors.d.ts.map +1 -1
  497. package/dist/lib/registry-errors.js +6 -2
  498. package/dist/lib/registry-errors.js.map +1 -1
  499. package/dist/lib/reset-space-plan.d.ts +2 -0
  500. package/dist/lib/reset-space-plan.d.ts.map +1 -1
  501. package/dist/lib/reset-space-plan.js +1 -1
  502. package/dist/lib/reset-space-plan.js.map +1 -1
  503. package/dist/lib/restore.d.ts +45 -3
  504. package/dist/lib/restore.d.ts.map +1 -1
  505. package/dist/lib/restore.js +233 -39
  506. package/dist/lib/restore.js.map +1 -1
  507. package/dist/lib/rolled-back-runs.d.ts +36 -0
  508. package/dist/lib/rolled-back-runs.d.ts.map +1 -0
  509. package/dist/lib/rolled-back-runs.js +96 -0
  510. package/dist/lib/rolled-back-runs.js.map +1 -0
  511. package/dist/lib/service-definitions.d.ts +16 -3
  512. package/dist/lib/service-definitions.d.ts.map +1 -1
  513. package/dist/lib/service-definitions.js +99 -27
  514. package/dist/lib/service-definitions.js.map +1 -1
  515. package/dist/lib/service-instances.d.ts +13 -1
  516. package/dist/lib/service-instances.d.ts.map +1 -1
  517. package/dist/lib/service-instances.js +56 -12
  518. package/dist/lib/service-instances.js.map +1 -1
  519. package/dist/lib/service-presets.d.ts.map +1 -1
  520. package/dist/lib/service-presets.js +16 -0
  521. package/dist/lib/service-presets.js.map +1 -1
  522. package/dist/lib/service-process.d.ts +51 -8
  523. package/dist/lib/service-process.d.ts.map +1 -1
  524. package/dist/lib/service-process.js +385 -48
  525. package/dist/lib/service-process.js.map +1 -1
  526. package/dist/lib/space-streams.d.ts +18 -0
  527. package/dist/lib/space-streams.d.ts.map +1 -0
  528. package/dist/lib/space-streams.js +35 -0
  529. package/dist/lib/space-streams.js.map +1 -0
  530. package/dist/lib/spawn-defaults.d.ts +25 -1
  531. package/dist/lib/spawn-defaults.d.ts.map +1 -1
  532. package/dist/lib/spawn-defaults.js +37 -1
  533. package/dist/lib/spawn-defaults.js.map +1 -1
  534. package/dist/lib/stack-journal.d.ts +157 -14
  535. package/dist/lib/stack-journal.d.ts.map +1 -1
  536. package/dist/lib/stack-journal.js +406 -49
  537. package/dist/lib/stack-journal.js.map +1 -1
  538. package/dist/lib/stack-listeners.d.ts +17 -0
  539. package/dist/lib/stack-listeners.d.ts.map +1 -0
  540. package/dist/lib/stack-listeners.js +54 -0
  541. package/dist/lib/stack-listeners.js.map +1 -0
  542. package/dist/lib/stack-members.d.ts +13 -0
  543. package/dist/lib/stack-members.d.ts.map +1 -0
  544. package/dist/lib/stack-members.js +24 -0
  545. package/dist/lib/stack-members.js.map +1 -0
  546. package/dist/lib/stack-resume.d.ts.map +1 -1
  547. package/dist/lib/stack-resume.js +5 -2
  548. package/dist/lib/stack-resume.js.map +1 -1
  549. package/dist/lib/stack-runs.d.ts +34 -0
  550. package/dist/lib/stack-runs.d.ts.map +1 -0
  551. package/dist/lib/stack-runs.js +75 -0
  552. package/dist/lib/stack-runs.js.map +1 -0
  553. package/dist/lib/status.d.ts +11 -0
  554. package/dist/lib/status.d.ts.map +1 -1
  555. package/dist/lib/status.js +4 -5
  556. package/dist/lib/status.js.map +1 -1
  557. package/dist/lib/stdout-owner.d.ts +12 -3
  558. package/dist/lib/stdout-owner.d.ts.map +1 -1
  559. package/dist/lib/stdout-owner.js +33 -5
  560. package/dist/lib/stdout-owner.js.map +1 -1
  561. package/dist/lib/store-dir.d.ts +68 -4
  562. package/dist/lib/store-dir.d.ts.map +1 -1
  563. package/dist/lib/store-dir.js +253 -17
  564. package/dist/lib/store-dir.js.map +1 -1
  565. package/dist/lib/team-additive-attempt.d.ts +1 -1
  566. package/dist/lib/team-channel-removal.d.ts.map +1 -1
  567. package/dist/lib/team-channel-removal.js +4 -0
  568. package/dist/lib/team-channel-removal.js.map +1 -1
  569. package/dist/lib/team-deploy-inspection.d.ts +13 -0
  570. package/dist/lib/team-deploy-inspection.d.ts.map +1 -1
  571. package/dist/lib/team-deploy-inspection.js +12 -0
  572. package/dist/lib/team-deploy-inspection.js.map +1 -1
  573. package/dist/lib/team-text.d.ts +6 -0
  574. package/dist/lib/team-text.d.ts.map +1 -0
  575. package/dist/lib/team-text.js +36 -0
  576. package/dist/lib/team-text.js.map +1 -0
  577. package/dist/lib/transient.d.ts +14 -8
  578. package/dist/lib/transient.d.ts.map +1 -1
  579. package/dist/lib/transient.js +72 -11
  580. package/dist/lib/transient.js.map +1 -1
  581. package/dist/lib/unusable-file.d.ts +13 -0
  582. package/dist/lib/unusable-file.d.ts.map +1 -0
  583. package/dist/lib/unusable-file.js +12 -0
  584. package/dist/lib/unusable-file.js.map +1 -0
  585. package/dist/lib/up-report.d.ts +6 -0
  586. package/dist/lib/up-report.d.ts.map +1 -1
  587. package/dist/lib/up-report.js +13 -0
  588. package/dist/lib/up-report.js.map +1 -1
  589. package/dist/lib/verdict.d.ts +14 -0
  590. package/dist/lib/verdict.d.ts.map +1 -0
  591. package/dist/lib/verdict.js +15 -0
  592. package/dist/lib/verdict.js.map +1 -0
  593. package/dist/managed-handoff.d.ts +11 -6
  594. package/dist/managed-handoff.d.ts.map +1 -1
  595. package/dist/managed-handoff.js +27 -18
  596. package/dist/managed-handoff.js.map +1 -1
  597. package/dist/render.d.ts +5 -2
  598. package/dist/render.d.ts.map +1 -1
  599. package/dist/render.js +44 -10
  600. package/dist/render.js.map +1 -1
  601. package/dist/telemetry.d.ts +4 -3
  602. package/dist/telemetry.d.ts.map +1 -1
  603. package/dist/telemetry.js +14 -6
  604. package/dist/telemetry.js.map +1 -1
  605. package/dist/ui.d.ts +3 -2
  606. package/dist/ui.d.ts.map +1 -1
  607. package/dist/ui.js +6 -4
  608. package/dist/ui.js.map +1 -1
  609. package/dist/view/mesh-view.d.ts.map +1 -1
  610. package/dist/view/mesh-view.js +4 -1
  611. package/dist/view/mesh-view.js.map +1 -1
  612. package/dist/watch-data.d.ts +9 -1
  613. package/dist/watch-data.d.ts.map +1 -1
  614. package/dist/watch-data.js +17 -3
  615. package/dist/watch-data.js.map +1 -1
  616. package/dist/watch-json.js +4 -3
  617. package/dist/watch-json.js.map +1 -1
  618. package/package.json +5 -5
@@ -1,28 +1,31 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
2
3
  import { createHash, randomUUID } from "node:crypto";
3
- import { createConnection, createServer } from "node:net";
4
+ import { createConnection, createServer, isIP } from "node:net";
4
5
  import { homedir, hostname } from "node:os";
5
- import { accessSync, constants, mkdirSync, readFileSync, existsSync, openSync, fstatSync, statSync, readSync, closeSync, lstatSync, realpathSync, readdirSync, } from "node:fs";
6
- import { dirname, isAbsolute, join, resolve } from "node:path";
7
- import { isReachable, DEFAULT_SERVER, DEFAULT_SPACE, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, reconcileSpaceTtls, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, seedChannelRegistry, ensureDefaultDeliveryClass, LEASE_TTL_MS, mkSecretDir, openPrivateAppend, realDirNoSymlink, writeSecretFile, } from "@cotal-ai/core";
8
- import { connect } from "@nats-io/transport-node";
9
- import { jetstreamManager, StorageType } from "@nats-io/jetstream";
6
+ import { accessSync, constants, mkdirSync, readFileSync, existsSync, statSync, closeSync, lstatSync, realpathSync, readdirSync, rmdirSync, unlinkSync, } from "node:fs";
7
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
8
+ import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, reconcileSpaceTtls, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, MEMBERSHIP_MAX_BYTES, spaceDeletionStreams, isJetStreamMissing, seedChannelRegistry, ensureDefaultDeliveryClass, assertValidChannel, isConcreteChannel, validateChannelConfig, validateChannelDefaults, LEASE_TTL_MS, mkSecretDir, openPrivateAppend, realDirNoSymlink, writeSecretFile, writeSecretFileAtomic, utf16Problem, } from "@cotal-ai/core";
9
+ import { JetStreamApiCodes, jetstreamManager, StorageType } from "@nats-io/jetstream";
10
10
  import { Kvm } from "@nats-io/kv";
11
- import { CommandFailure, commandFailureReport, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, terminalWidth, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, canonicalRoot, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, oneLine, presentationOf, writeResult, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, parsePositiveIntegerFlag, recordMesh, meshesForRoot, removeMesh, rotateSystemCreds, setCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessMaintenanceClaim, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, readMaintenanceResumeDocument, seatCheckpointDir, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, writeBrokerPolicy, removePidPair, writePidPair, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, retainSystemSigningSeed, } from "@cotal-ai/workspace";
11
+ import { assertManagerName, readManagerName, recordManagerName, assertRecordIdentity, formatRecord, identityRecord, parseRecord, CommandFailure, commandFailureReport, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, terminalWidth, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, canonicalRoot, rootPathProblem, rootControlProblem, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, keepsRegistration, oneLine, presentationOf, writeResult, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, parsePositiveIntegerFlag, recordMesh, retainedLegacyBroker, meshesForRoot, removeMesh, rotateSystemCreds, setCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessMaintenanceClaim, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, rootNamesNoSpace, readMaintenanceResumeDocument, seatCheckpointDir, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, writeBrokerPolicy, removePidPair, writePidPair, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, recordOperationWarning, retainSystemSigningSeed, restoreLeftOut, SPACE_NAME_MAX, spaceNameTooLong, MIN_FILE_STORE, exitCode, } from "@cotal-ai/workspace";
12
+ import { FlagValueRefusal } from "../lib/flag-value-refusal.js";
12
13
  import { ensureAuthService, resolveAuthProvider, stopAuthService } from "../lib/auth-proc.js";
13
14
  import { resolveSpace } from "../lib/status.js";
14
- import { c } from "../ui.js";
15
+ import { c, stderrLine } from "../ui.js";
15
16
  import { admitAndRestoreSeatCheckpoints } from "../lib/seat-resume.js";
16
- import { resolveNatsServer } from "../lib/nats-bin.js";
17
- import { cotalPath, cotalRoot } from "../lib/paths.js";
18
- import { renderDetachedSummary } from "../lib/up-report.js";
17
+ import { natsServerLabel, resolveNatsServer } from "../lib/nats-bin.js";
18
+ import { cotalPath, cotalRoot, homeHoldsStack, linkedCotalRefusal } from "../lib/paths.js";
19
+ import { detachedNext, renderDetachedSummary } from "../lib/up-report.js";
19
20
  import { seedDefaultPersona } from "../lib/default-persona.js";
20
21
  import { upSystemdSupervisionWarning } from "../lib/systemd-supervision.js";
21
22
  import { deliveryStoppedByDown, deliveryUp, ensureControlPlane, ensureDelivery, stopDelivery } from "../lib/delivery-proc.js";
22
23
  import { RESPONDER_UNBOUND_CONSEQUENCE } from "../lib/delivery-responder.js";
23
24
  import { displayCmd } from "../lib/self-exec.js";
25
+ import { shellWord } from "../lib/endpoint-errors.js";
24
26
  import { clearManagerArtifacts, liveManagerWouldApplyMaxSessions, managerHasDeliveryMarker, managerLogDisplayPath, managerRecordState, managerUp, stopManager } from "../lib/manager-proc.js";
25
- import { loadManifest } from "../lib/manifest/index.js";
27
+ import { ManifestError, formatIssue, loadManifest } from "../lib/manifest/index.js";
28
+ import { UnusableFile } from "../lib/unusable-file.js";
26
29
  import { buildLaunchSpec, genRunId, manifestToChannels, preflightConnectors, writeLaunchSpec } from "../lib/manifest/apply.js";
27
30
  import { listLedgerFiles } from "../lib/manifest/ledger.js";
28
31
  import { freshTeamAttemptSettled, listFreshTeamAttempts, listFreshTeamSummaries, writeFreshTeamAttempt, writeFreshTeamSummary } from "../lib/team-fresh.js";
@@ -31,25 +34,33 @@ import { renderUpPlan, renderInherited, renderWarnings } from "../lib/manifest/r
31
34
  import { idpUrlProblem, serverUrlProblems } from "../lib/manifest/resolve.js";
32
35
  import { failManifest, refuseManifestSpaceMismatch } from "./topology.js";
33
36
  import { liveMeshProcesses } from "./clean.js";
34
- import { cleanedManifestStart, retainedLegacyBroker } from "../lib/legacy-start.js";
35
- import { controllerStackApplies, recheckExistingStore, requestedStackMode, stackUp, stackUpForegroundNotice } from "./stack-up.js";
37
+ import { checkSpaceFlagValue, checkSpaceName } from "./meshes-add.js";
38
+ import { checkLocalSpace } from "./space-registration.js";
39
+ import { cleanedManifestStart, namedOpenConfig, retainedOpenSpace } from "../lib/legacy-start.js";
40
+ import { bindReaches, canonicalServer, controllerStackApplies, recheckExistingStore, requestedStackMode, requestsTls, stackUp, stackUpForegroundNotice, stackUpInterruptNotice, keptOnUp, selectedOnUp, unparsableDaemonCredsNotice, } from "./stack-up.js";
41
+ import { handOverStartupNotice, noticeOnInterrupt, releaseStartupNotice } from "../lib/interrupt-notice.js";
42
+ import { settleInterruptedLaunches } from "../lib/service-process.js";
36
43
  import { assertUserStackTransport, preflightUserStack } from "./stack-user-auth.js";
37
44
  import { stackDown } from "./stack-down.js";
38
45
  import { assertControllerCoupling, assertControllerMembersLive, assertControllerResumeEligible, beginControllerResume, bindControllerBroker, controllerAttemptBrokerInstance, currentControllerAttempt, managerResumeAttempt, relaunchCommittedManager, settleControllerResume, startControllerMember, startControllerMembers, } from "../lib/controller-resume.js";
39
46
  import { removeRetiredBrokerInstance } from "../lib/controller-restore.js";
40
- import { acquireStackOperationLock, admittedStackRestore, readStackJournal, refuseControllerCut } from "../lib/stack-journal.js";
41
- import { serviceInstances } from "../lib/service-instances.js";
47
+ import { acquireStackOperationLock, admittedStackRestore, readStackJournal, refuseControllerCut, STACK_DEFINITION, STACK_ROLES } from "../lib/stack-journal.js";
48
+ import { observeServiceProcess, serviceInstances } from "../lib/service-instances.js";
49
+ import { serviceDefinitionStore } from "../lib/service-definitions.js";
50
+ import { MissingFlags } from "../lib/missing-flags.js";
42
51
  import { serviceSupervisorStore } from "../lib/service-supervision.js";
43
52
  import { serviceInstallIntents } from "../lib/service-install-intent.js";
44
53
  import { serviceUninstallIntents } from "../lib/service-uninstall-intent.js";
45
54
  import { serviceUnitActionStore } from "../lib/service-unit-action.js";
46
- import { assertStoreDirArgument } from "../lib/store-dir.js";
55
+ import { assertStoreDirArgument, configuredStoreDir, lastServedStore, missingStoreWarning, servedStore, sharedStoreAtStart, sharedStoreWarning, storeWriteProblem, warnForeignStoreEntries } from "../lib/store-dir.js";
47
56
  import { extensionNames, preflightRuntime } from "../ext-loader.js";
48
57
  import { completingFlagValue } from "../lib/completion.js";
49
58
  import { metadataPositionals } from "../lib/command-path.js";
50
59
  import { askManager } from "../lib/control.js";
51
- import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, heldClaim, movedFolderRefusal, prepareRestore, preservedSourceState, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, replacePreparedDeadRestoreListener, } from "../lib/restore.js";
60
+ import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, heldClaim, movedFolderRefusal, prepareRestore, preservedSourceState, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, journaledRestoredStreams, leftOutNotes, replacePreparedDeadRestoreListener, restoreComposition, restoreNextStep, restoreOnlyCopy, } from "../lib/restore.js";
52
61
  import { attemptProcessesGone } from "../lib/isolated-broker.js";
62
+ import { assertEndpointUnreachable } from "../lib/endpoint-cut.js";
63
+ import { addressHolder, brokerListenAddress, listenerBindError } from "../lib/broker-service.js";
53
64
  const pendingRestores = new Map();
54
65
  const restoreSinks = new Map();
55
66
  /** Run the guarded `up --restore` startup and return its result instead of printing it. The
@@ -69,9 +80,9 @@ export const upFlags = [
69
80
  { name: "server", type: "string", value: "<url>", description: "listen URL; a stack's first up records it and later ups keep it" },
70
81
  { name: "host", type: "string", value: "<host>", description: "bind host override (an IP/hostname, not a URL; the URL is --server)" },
71
82
  { name: "space", type: "string", value: "<s>", description: "space name (default: the folder's)" },
72
- { name: "root", type: "string", value: "<dir>", description: "use this existing prepared local root instead of the current folder" },
83
+ { name: "root", type: "string", value: "<dir>", description: "start the project in this folder instead of the current one; it must already have its own .cotal" },
73
84
  { name: "store-dir", type: "string", value: "<dir>", description: "JetStream store directory" },
74
- { 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; recorded and kept across `down --preserve-state`" },
85
+ { 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`" },
75
86
  { name: "channels", type: "string", value: "<path>", description: "channel-registry seed file (JSON; default .cotal/channels.json)" },
76
87
  { name: "tls-cert", type: "string", value: "<file>", description: "serve the broker over TLS with this certificate (requires --tls-key)" },
77
88
  { name: "tls-key", type: "string", value: "<file>", description: "the private key for --tls-cert" },
@@ -89,10 +100,11 @@ export const upFlags = [
89
100
  { name: "service-endpoints", type: "boolean", description: "with --user-auth: the auth service also hosts service endpoints (the registration door and the owner-decision host route)" },
90
101
  { name: "agent-provisioning-url", type: "string", value: "<https://…>", description: "with --exchange-public-port: the deployment's remote agent-provisioning endpoint the public bundle advertises" },
91
102
  { name: "rotate-sys", type: "boolean", description: "renew the expired/expiring $SYS creds by rotating the system account (agents, data and creds survive; needs a stopped mesh)" },
92
- { name: "detach", type: "boolean", description: "run in the background (the default; stop with cotal down)" },
103
+ { name: "detach", type: "boolean", short: "d", description: "run in the background (the default; stop with cotal down)" },
93
104
  { name: "foreground", type: "boolean", description: "keep a non-manifest native stack in this terminal; -f currently refuses" },
94
105
  { name: "runtime", type: "string", value: "<name>", description: "agent runtime for the mesh manager (default pty; extension runtimes are explicit-only, see `cotal runtimes`); with -f overrides the manifest's runtime" },
95
106
  { name: "max-sessions", type: "string", value: "<n>", description: "live-session ceiling for the mesh manager (default 64; one session per console pane, so size for agents × panes). Recorded and reused by later manager launches" },
107
+ { name: "manager-name", type: "string", value: "<name>", description: "name this root's manager for who --all, the manager choice and --on; kept for later starts" },
96
108
  { 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)" },
97
109
  { name: "file", type: "string", short: "f", value: "<cotal.yaml>", description: "launch a whole mesh from a manifest" },
98
110
  { name: "dry-run", type: "boolean", description: "with -f: print the plan, mutate nothing" },
@@ -121,6 +133,10 @@ export function upComplete(argv) {
121
133
  * re-entry supplies its recorded mode explicitly rather than inheriting the new public default. */
122
134
  export function validateUpArguments(args) {
123
135
  presentationOf(args.values);
136
+ // A `.cotal` that is a link, or leads nowhere, is refused before anything reads through it.
137
+ const linked = args.values.root === undefined ? linkedCotalRefusal("up") : undefined;
138
+ if (linked)
139
+ throw linked;
124
140
  if (args.values["user-auth"] === true && args.values.open === true)
125
141
  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" });
126
142
  if (args.values.idp !== undefined && args.values["user-auth"] !== true && !args.values.file)
@@ -131,14 +147,34 @@ export function validateUpArguments(args) {
131
147
  throw new CommandFailure("refused", "USAGE_INVALID", "--no-manager cannot be combined with --max-sessions because no manager starts", { remedy: "drop --max-sessions, or drop --no-manager to set the manager session ceiling" });
132
148
  if (args.values.foreground === true && args.values.detach === true)
133
149
  throw new CommandFailure("refused", "USAGE_INVALID", "choose --foreground or --detach, not both");
150
+ // Only a manifest launch has a plan to print; without -f every route would start the stack.
151
+ if (args.values["dry-run"] === true && !args.values.file)
152
+ throw new CommandFailure("refused", "USAGE_INVALID", "--dry-run previews a manifest launch and needs -f <cotal.yaml>; nothing was started or written", { remedy: "pass -f <cotal.yaml> to print that manifest's plan; cotal status shows what this folder records" });
153
+ // The stack passes its space to its own children as `--space <name>`, which a leading - breaks.
154
+ const named = typeof args.values.space === "string" ? checkSpaceFlagValue(args.values.space) : undefined;
155
+ if (named && !named.ok)
156
+ throw new CommandFailure("refused", "USAGE_INVALID", `${named.message.replace(/^✗ /, "")}; nothing was started or written`, { remedy: named.remedy });
134
157
  // A manifest boot checks its own `--server` override against `broker.servers`.
135
158
  const serverProblem = args.values.server !== undefined && !args.values.file ? upServerProblem(String(args.values.server)) : undefined;
136
159
  if (serverProblem)
137
- throw new CommandFailure("refused", "USAGE_INVALID", `${serverProblem}; nothing was started or written`, { remedy: "pass the address the local broker listens on, for example --server nats://127.0.0.1:4222" });
138
- // A URL or port-bearing --host, or one naming another address than --server, refuses here, before
139
- // the controller stack writes its journal or trust.
140
- if (args.values.host !== undefined && !args.values.file)
141
- reconcileHostAndServer(String(args.values.host), args.values.server === undefined ? undefined : String(args.values.server));
160
+ throw new FlagValueRefusal(`${serverProblem}; nothing was started or written`, `pass the IP address the local broker listens on, for example ${serverExample(String(args.values.server))}`);
161
+ // A --host that is no bind host, or a bind that does not serve --server's address, refuses here,
162
+ // before the controller stack writes its journal or trust.
163
+ const hostProblem = !args.values.file ? upHostProblem(args.values.host, args.values.server) : undefined;
164
+ if (hostProblem)
165
+ throw new CommandFailure("refused", "USAGE_INVALID", `${hostProblem.problem}; nothing was started or written`, { remedy: hostProblem.remedy });
166
+ const spaceTooLong = typeof args.values.space === "string" ? spaceNameTooLong(args.values.space) : undefined;
167
+ if (spaceTooLong)
168
+ throw new CommandFailure("refused", "USAGE_INVALID", `${spaceTooLong}; nothing was started or written`, { remedy: `choose a space name of at most ${SPACE_NAME_MAX} characters` });
169
+ // A prepared or controller-owned root has no route that serves TLS, so any TLS input refuses here,
170
+ // once and naming the route that does, before the checks below send it from one TLS form to another.
171
+ const tlsRoot = typeof args.values.root === "string" ? resolve(args.values.root) : freshFolderRoot(args.values) ?? cotalRoot();
172
+ if (!args.values.file && requestsTls(args.values) && !readMaintenanceJournal(tlsRoot))
173
+ controllerStackApplies(tlsRoot, args.values.space ?? folderSpace(), args.values);
174
+ // A --tls-cert broker serves TLS only, and its address says so, so every client dials tls:// and
175
+ // checks the certificate against the address it names.
176
+ if (!args.values.file && args.values["tls-cert"] !== undefined && typeof args.values.server === "string" && /^nats:\/\//i.test(args.values.server))
177
+ throw new CommandFailure("refused", "USAGE_INVALID", "--tls-cert serves the broker over TLS, so --server must be a tls:// address; nothing was started or written", { remedy: `pass --server ${tlsAddress(args.values.server)}` });
142
178
  if (args.values.file !== undefined && args.values.foreground === true)
143
179
  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");
144
180
  if (args.values.foreground === true && (args.values.json === true || args.values.plain === true))
@@ -146,9 +182,9 @@ export function validateUpArguments(args) {
146
182
  // Flag values and combinations are usage, so they refuse here, before any effect. The run keeps
147
183
  // its own checks for maintenance re-entries, which do not pass through this validation.
148
184
  parsePositiveIntegerFlag("--max-sessions", args.values["max-sessions"]);
149
- parsePositiveIntegerFlag("--max-file-store", args.values["max-file-store"]);
185
+ parseMaxFileStore(args.values["max-file-store"]);
150
186
  if (typeof args.values["store-dir"] === "string")
151
- assertStoreDirArgument(args.values["store-dir"], typeof args.values.root === "string" ? resolve(args.values.root) : cotalRoot());
187
+ assertStoreDirArgument(args.values["store-dir"], typeof args.values.root === "string" ? resolve(args.values.root) : freshFolderRoot(args.values) ?? cotalRoot());
152
188
  const restoreOnly = args.values["restore-only"];
153
189
  if (restoreOnly !== undefined && restoreOnly !== "registry")
154
190
  throw new CommandFailure("refused", "USAGE_INVALID", `--restore-only takes registry (got ${JSON.stringify(restoreOnly)})`);
@@ -156,29 +192,47 @@ export function validateUpArguments(args) {
156
192
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore-only and --accept-missing-source require --restore <dir>");
157
193
  if (args.values.restore && (args.values.file !== undefined || args.values.channels !== undefined))
158
194
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --file/-f or --channels");
159
- // The broker reads an explicit channels file only once it is being prepared, so a file it would
160
- // refuse is named here, before the stack journal or anything else is written.
161
- if (typeof args.values.channels === "string")
162
- readChannelsFile(resolve(args.values.channels));
163
195
  if (args.values.restore && args.values["rotate-sys"] === true)
164
196
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --rotate-sys", { remedy: "restore the space and verify it first, then rotate: cotal down, then cotal up --rotate-sys" });
165
197
  if (args.values.root !== undefined)
166
198
  preparedUpRoot(String(args.values.root));
167
- else {
199
+ else if (!(args.values.file && args.values["dry-run"] === true)) {
168
200
  const inheritedRoot = inheritedMachineHomeRoot();
169
- if (inheritedRoot && !(args.values.file && args.values["dry-run"] === true))
170
- throw new CommandFailure("refused", "CONFLICT", "this folder inherits the machine's home .cotal; up did not start a stack in that home root", { target: { root: process.cwd(), inheritedRoot }, remedy: "prepare this folder with cotal space create <space> --root ., then use cotal up --root .; to start the home stack, run up from home itself" });
201
+ if (inheritedRoot) {
202
+ if (!freshFolderRoot(args.values))
203
+ throw new CommandFailure("refused", "CONFLICT", "this folder inherits the machine's home .cotal; up did not start a stack in that home root", { target: { root: process.cwd(), inheritedRoot }, remedy: "prepare this folder with cotal space create <space> --root ., then run cotal up again from this folder" });
204
+ }
205
+ else {
206
+ const home = machineHomeRoot();
207
+ if (home && !homeHoldsStack(home))
208
+ throw new CommandFailure("refused", "CONFLICT", `${home} is your home folder, whose .cotal holds this machine's own records, so up started no stack there`, { target: { root: home }, remedy: "prepare a project folder with cotal space create <space> --root <dir>, then run cotal up there, or pass --root <dir> from here" });
209
+ }
171
210
  }
172
211
  if (args.values.restore !== undefined)
173
212
  refuseControllerCut(args.values.root !== undefined ? preparedUpRoot(String(args.values.root)) : cotalRoot(), "up --restore");
174
- if (!(args.values.file && args.values["dry-run"] === true))
175
- assertUpRootWritable(args.values.root !== undefined ? preparedUpRoot(String(args.values.root)) : cotalRoot());
213
+ if (!(args.values.file && args.values["dry-run"] === true)) {
214
+ const root = args.values.root !== undefined ? preparedUpRoot(String(args.values.root)) : freshFolderRoot(args.values) ?? cotalRoot();
215
+ // A path with a control character or a bidirectional formatting mark is refused before any write.
216
+ const pathProblem = rootPathProblem(root) ?? rootPathProblem(canonicalRoot(root));
217
+ if (pathProblem)
218
+ throw new CommandFailure("refused", "USAGE_INVALID", `${pathProblem}; nothing was started or written`, { target: { root }, remedy: "rename the folder without those characters, then run cotal up there" });
219
+ const control = rootControlProblem(root);
220
+ if (control)
221
+ throw new CommandFailure("refused", "CONFLICT", `${control.message}; nothing was started or written`, { target: { root, controlDirectory: control.controlDirectory }, remedy: control.project === undefined
222
+ ? "prepare a project folder with cotal space create <space> --root <dir>, then run cotal up there"
223
+ : `run cotal up from the project folder ${shellWord(control.project)}` });
224
+ assertUpRootWritable(root);
225
+ // A restore and a manifest name their own store.
226
+ if (args.values.restore === undefined && args.values.file === undefined)
227
+ assertUpStoreWritable(root, typeof args.values["store-dir"] === "string" ? args.values["store-dir"] : undefined);
228
+ }
176
229
  }
177
230
  /** Every launch route writes under the root's .cotal first, or makes it when it is missing. A folder
178
231
  * this account cannot write is refused here, by name, instead of as the raw error of whichever
179
232
  * write came first. */
180
233
  function assertUpRootWritable(root) {
181
- const path = existsSync(join(root, ".cotal")) ? join(root, ".cotal") : root;
234
+ // A `.cotal` that is a file is refused by name before any command runs, so only a directory is tested here.
235
+ const path = statSync(join(root, ".cotal"), { throwIfNoEntry: false })?.isDirectory() ? join(root, ".cotal") : root;
182
236
  try {
183
237
  accessSync(path, constants.W_OK | constants.X_OK);
184
238
  }
@@ -186,13 +240,28 @@ function assertUpRootWritable(root) {
186
240
  const code = error.code;
187
241
  if (code !== "EACCES" && code !== "EPERM" && code !== "EROFS")
188
242
  throw error;
189
- throw new CommandFailure("refused", "PERMISSION_DENIED", `${path} is not writable by this account (${code}); nothing was started or written`, { target: { root, path }, remedy: `make it writable by you, for example with chmod u+w ${path}` });
243
+ throw new CommandFailure("refused", "PERMISSION_DENIED", `${path} is not writable by this account (${code}); nothing was started or written`, { target: { root, path }, remedy: `make it writable by you, for example with chmod u+w ${shellWord(path)}` });
244
+ }
245
+ }
246
+ /** The broker exits when it cannot write its store, naming the cause only in its own log. The store
247
+ * a start here opens, as `--store-dir` names it, as the stack journal recorded it, or `.cotal/nats`,
248
+ * is refused here, by name, when this account cannot write it. */
249
+ function assertUpStoreWritable(root, storeDir) {
250
+ let recorded;
251
+ try {
252
+ recorded = readStackJournal(root)?.journal.broker?.storeDir;
253
+ }
254
+ catch {
255
+ recorded = undefined;
190
256
  }
257
+ const problem = storeWriteProblem(storeDir !== undefined ? resolve(storeDir) : recorded ?? join(root, ".cotal", "nats"));
258
+ if (problem)
259
+ throw new CommandFailure("refused", "PERMISSION_DENIED", `${problem.message}; nothing was started or written`, { target: { root, path: problem.path }, remedy: problem.remedy });
191
260
  }
192
261
  /** Why `--server` cannot be the address a local broker listens on, or undefined when it can. Both
193
- * launch routes need one nats:// or tls:// URL with a host and a TCP port, and without this check
194
- * a typo reached their first write. The message never repeats the value, which may carry a
195
- * credential. */
262
+ * launch routes need one nats:// or tls:// URL with an IP address and a TCP port, and without this
263
+ * check a typo reached their first write. The message names at most the host, never the whole
264
+ * value, which may carry a credential. */
196
265
  function upServerProblem(server) {
197
266
  let url;
198
267
  try {
@@ -209,14 +278,127 @@ function upServerProblem(server) {
209
278
  return "--server must be one broker URL without a path, query or fragment";
210
279
  if (!url.hostname)
211
280
  return "--server names no host";
281
+ // An explicit address is taken as given, so a missing port is never filled in with the default.
282
+ if (!url.port)
283
+ return "--server names no port";
212
284
  if (url.port === "0")
213
285
  return "--server needs a TCP port from 1 to 65535";
286
+ if (url.hostname.startsWith("["))
287
+ return IPV6_UNSERVED("--server");
288
+ // The broker reports its listener by IP address, which is how both launch routes find it ready.
289
+ if (!isIP(url.hostname))
290
+ return `--server names the host ${url.hostname}, and up needs the IP address the broker listens on`;
214
291
  return undefined;
215
292
  }
293
+ /** The `--server` a refusal gives as its example: 127.0.0.1 on the port the user passed, or a
294
+ * placeholder when the value names none. */
295
+ function serverExample(server) {
296
+ let port;
297
+ try {
298
+ port = new URL(server).port || undefined;
299
+ }
300
+ catch {
301
+ port = undefined;
302
+ }
303
+ port ??= /:(\d{1,5})\/?$/.exec(server)?.[1];
304
+ const valid = port !== undefined && Number(port) >= 1 && Number(port) <= 65535;
305
+ return `--server ${/^tls:/i.test(server) ? "tls" : "nats"}://127.0.0.1:${valid ? Number(port) : "<port>"}`;
306
+ }
307
+ /** The local stack's own clients cannot reach a broker on an IPv6 address, so neither flag may name one. */
308
+ const IPV6_UNSERVED = (flag) => `${flag} names an IPv6 address, and the local stack's own clients cannot reach a broker there`;
309
+ /** Why `--host` cannot be the local broker's bind address beside `server`, with the step that fixes
310
+ * it, or undefined when it can. A wildcard bind keeps a loopback URL, so it pairs with any address.
311
+ * With no `--host` the broker binds 127.0.0.1, so a `--server` naming another IPv4 address needs one. */
312
+ function upHostProblem(host, server) {
313
+ if (host === undefined) {
314
+ const named = server === undefined ? undefined : new URL(server).hostname;
315
+ return named !== undefined && isIP(named) === 4 && named !== "127.0.0.1" && !WILDCARD_HOSTS.has(named)
316
+ ? { problem: `--server ${server} names ${named}, and with no --host the broker binds 127.0.0.1, so it would not listen where its clients connect`, remedy: `pass --host ${named} to bind the broker there` }
317
+ : undefined;
318
+ }
319
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(host))
320
+ return { problem: `--host ${host} looks like a URL, and it takes a bind host only (an IP or hostname, no scheme)`, remedy: "pass the broker URL with --server instead" };
321
+ if (WILDCARD_HOSTS.has(host))
322
+ return undefined;
323
+ const bare = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
324
+ if (isIP(bare) === 6)
325
+ return { problem: IPV6_UNSERVED("--host"), remedy: "pass an IPv4 bind address, for example --host 127.0.0.1" };
326
+ let url;
327
+ try {
328
+ url = new URL(`nats://${host}:1`);
329
+ }
330
+ catch {
331
+ url = undefined;
332
+ }
333
+ if (!url || url.port !== "1" || url.pathname || url.search || url.hash || url.username || url.password)
334
+ return { problem: `--host ${host} is not a valid bind host: an IP or hostname only, with no port; the port comes from --server (or its default)`, remedy: "pass the port in --server, for example --server nats://127.0.0.1:4222" };
335
+ if (server !== undefined && !bindReaches(host, server))
336
+ return { problem: `--host ${host} and --server ${server} name different addresses: the broker would bind ${host} but be probed at ${new URL(server).hostname}`, remedy: "pass one of them, or make both name the same address" };
337
+ return undefined;
338
+ }
339
+ /** The invoking folder, when a bare `up` makes it its own project root: the only `.cotal` above it is
340
+ * the machine home's. The folder has no records of its own, so `up` starts it as it starts a folder
341
+ * with no `.cotal` above it. A stack an earlier release started in the home is left as it is and
342
+ * still starts from the home. A manifest or a restore still needs a prepared folder. */
343
+ function freshFolderRoot(values) {
344
+ if (values.root !== undefined || values.file !== undefined || values.restore !== undefined)
345
+ return undefined;
346
+ return inheritedMachineHomeRoot() !== undefined ? resolve(process.cwd()) : undefined;
347
+ }
348
+ /** The space a bare `up` starts in a new project: the name of the project folder, when no `--space`
349
+ * names one and the folder's records name no space. The name passes the rules `space create`
350
+ * applies, and a name another folder on this machine holds, running, stopped or prepared, refuses
351
+ * rather than being taken over. Each refusal names `--space`, before anything is written. */
352
+ function folderNamedSpace(values) {
353
+ if (values.space !== undefined || values.root !== undefined || values.file !== undefined || values.restore !== undefined)
354
+ return undefined;
355
+ const root = freshFolderRoot(values) ?? (machineHomeRoot() ? undefined : cotalRoot());
356
+ if (root === undefined || !recordsNameNoSpace(root))
357
+ return undefined;
358
+ const space = basename(resolve(root));
359
+ const named = `up names a new project's space after its folder, and`;
360
+ const checked = checkSpaceName(space);
361
+ const invalid = spaceNameTooLong(space) ?? (checked.ok ? undefined : checked.message.replace(/^✗ /, ""));
362
+ if (invalid)
363
+ throw new CommandFailure("refused", "USAGE_INVALID", `${named} the folder name ${JSON.stringify(space)} cannot be one: ${invalid}; nothing was started or written`, { target: { root }, remedy: "name the space with cotal up --space <name>", selfContained: true });
364
+ assertSelectionNotMoved(root, space);
365
+ const held = findMesh(space) ?? findPreparedSpace(space);
366
+ if (held)
367
+ throw new CommandFailure("refused", "CONFLICT", `${named} "${space}" is already ${"server" in held ? `registered at ${held.server}` : "prepared"} for ${held.root}; nothing was started or written`, { target: { root, space, heldBy: held.root }, remedy: "name this folder's space with cotal up --space <name>, naming one this machine does not use; cotal space lists the names in use" });
368
+ checkLocalSpace(space, root, "--root", false);
369
+ return space;
370
+ }
371
+ /** Whether no record names a space for `root`: this machine prepared and registered none there, and
372
+ * it has no `.cotal`, an empty one, or one with no account, stack journal, runtime record, broker
373
+ * configuration or maintenance attempt. */
374
+ function recordsNameNoSpace(root) {
375
+ if (preparedSpaceAt(root) || meshesForRoot(root).length)
376
+ return false;
377
+ const control = join(root, ".cotal");
378
+ let entries;
379
+ try {
380
+ entries = readdirSync(control);
381
+ }
382
+ catch (error) {
383
+ return error.code === "ENOENT";
384
+ }
385
+ try {
386
+ if (readMaintenanceJournal(root))
387
+ return false;
388
+ }
389
+ catch {
390
+ return false;
391
+ }
392
+ return entries.length === 0 || rootNamesNoSpace(root);
393
+ }
216
394
  function inheritedMachineHomeRoot() {
395
+ const root = machineHomeRoot();
396
+ return root !== undefined && canonicalRoot(process.cwd()) !== canonicalRoot(root) ? root : undefined;
397
+ }
398
+ /** The root this `up` resolves when it is the machine home, whose `.cotal` holds this machine's own records. */
399
+ function machineHomeRoot() {
217
400
  const root = cotalRoot();
218
- const machineHome = canonicalRoot(root) === canonicalRoot(homedir()) || canonicalRoot(join(root, ".cotal")) === canonicalRoot(homeCotalDir());
219
- return machineHome && canonicalRoot(process.cwd()) !== canonicalRoot(root) ? root : undefined;
401
+ return canonicalRoot(root) === canonicalRoot(homedir()) || canonicalRoot(join(root, ".cotal")) === canonicalRoot(homeCotalDir()) ? root : undefined;
220
402
  }
221
403
  /** An explicit root is an existing local workspace, not a hint to find another ancestor or
222
404
  * create trust in an arbitrary directory. Validation runs before the dispatcher seeds extensions. */
@@ -331,6 +513,15 @@ function stopForegroundStack(root, signal) {
331
513
  * sets the exit code: 0 when another command completed the stop or preserve, 130 or 143 after a
332
514
  * signal, whatever the start receipt set. */
333
515
  export async function holdForegroundStack(root, start) {
516
+ claimForegroundHold(root);
517
+ try {
518
+ await holdStack(root, start);
519
+ }
520
+ finally {
521
+ releaseForegroundHold(root);
522
+ }
523
+ }
524
+ async function holdStack(root, start) {
334
525
  if (start) {
335
526
  let requested;
336
527
  const request = (signal) => {
@@ -342,6 +533,7 @@ export async function holdForegroundStack(root, start) {
342
533
  const interrupt = () => request("SIGINT"), terminate = () => request("SIGTERM");
343
534
  process.on("SIGINT", interrupt);
344
535
  process.on("SIGTERM", terminate);
536
+ handOverStartupNotice();
345
537
  let failure;
346
538
  try {
347
539
  await start();
@@ -398,8 +590,41 @@ export async function holdForegroundStack(root, start) {
398
590
  const terminate = () => stop("SIGTERM");
399
591
  process.on("SIGINT", interrupt);
400
592
  process.on("SIGTERM", terminate);
593
+ handOverStartupNotice();
401
594
  });
402
595
  }
596
+ /** Where a foreground `up` records the process that holds its stack's lifetime. */
597
+ const foregroundHoldPath = (root) => join(root, ".cotal", "stack-foreground.hold");
598
+ /** The process of another foreground `up` that holds `root`'s stack, while that exact process runs. */
599
+ export function foregroundHolder(root) {
600
+ let raw;
601
+ try {
602
+ raw = readFileSync(foregroundHoldPath(root), "utf8");
603
+ }
604
+ catch {
605
+ return undefined;
606
+ }
607
+ const read = parseRecord(raw);
608
+ if (read.kind !== "record" || read.record.pid === process.pid)
609
+ return undefined;
610
+ return assertRecordIdentity(read.record).kind === "match" ? read.record.pid : undefined;
611
+ }
612
+ /** Record this process as the foreground holder of `root`'s stack. A host that cannot pin a process
613
+ * start records nothing, so no later `up` refuses on a pid that may have been reused. */
614
+ function claimForegroundHold(root) {
615
+ const record = identityRecord(process.pid);
616
+ if ("token" in record)
617
+ writeSecretFileAtomic(foregroundHoldPath(root), `${formatRecord(record)}\n`);
618
+ }
619
+ /** Remove this process's foreground hold record, and leave one another process wrote. */
620
+ function releaseForegroundHold(root) {
621
+ try {
622
+ const read = parseRecord(readFileSync(foregroundHoldPath(root), "utf8"));
623
+ if (read.kind === "record" && read.record.pid === process.pid)
624
+ unlinkSync(foregroundHoldPath(root));
625
+ }
626
+ catch { /* nothing recorded */ }
627
+ }
403
628
  /** The registered `up` command. When a background run is the main process of a systemd unit, it
404
629
  * names that unit and the `--foreground` remedy once startup returns: controller stack, retained
405
630
  * launcher, refresh and restore alike. It never changes the run's mode. Internal callers of
@@ -413,16 +638,39 @@ export async function upCommand(args) {
413
638
  /** `inheritedLock` is the root maintenance lock a recovery re-entry hands down (see the re-entry
414
639
  * below). Ownership transfers with it: this call releases it at its own release point. */
415
640
  export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink) {
641
+ // One `up`, its re-entries included, reads each channels file once (see `channelsReads`).
642
+ if (!channelsReads.getStore())
643
+ return channelsReads.run(new Map(), () => up(args, inheritedLock, freshTeamBoot, restoreSink));
644
+ // A --server is recorded and compared in one spelling, the scheme in lower case with no bare
645
+ // trailing slash. A manifest boot checks its own override against broker.servers.
646
+ if (typeof args.values.server === "string" && !args.values.file)
647
+ args = { ...args, values: { ...args.values, server: canonicalServer(args.values.server) } };
416
648
  // A re-entry owns its inherited lock even if mode validation refuses before runUp adopts it.
417
649
  let adopted = false;
418
650
  try {
419
651
  validateUpArguments(args);
652
+ // The broker reads an explicit channels file only once it is being prepared, so a file it would
653
+ // refuse is named here, before the stack journal or anything else is written.
654
+ if (typeof args.values.channels === "string")
655
+ readChannelsFile(resolve(args.values.channels));
656
+ const folderNamed = folderNamedSpace(args.values);
657
+ if (folderNamed)
658
+ args = { ...args, values: { ...args.values, space: folderNamed, __folderNamed: true } };
659
+ // A fresh folder under the machine home gets its own `.cotal` before anything resolves the root, so
660
+ // every later step uses this folder. A run that stops before writing there removes it again.
661
+ const fresh = args.values.root === undefined ? freshFolderRoot(args.values) : undefined;
662
+ if (fresh) {
663
+ mkdirSync(join(fresh, ".cotal"), { mode: 0o700 });
664
+ console.error(c.dim(`made ${join(fresh, ".cotal")} for this folder's records; the machine's home .cotal was not used`));
665
+ }
420
666
  const root = args.values.root === undefined ? undefined : preparedUpRoot(String(args.values.root));
421
667
  const previousCwd = process.cwd();
422
668
  // Path flags still mean paths relative to the invoking directory, not the selected root.
423
669
  // The recursive restore/resume re-entries inherit absolute paths and the same absolute root.
424
670
  const paths = root ? Object.fromEntries(["file", "restore", "channels", "tls-cert", "tls-key", "store-dir"].filter((key) => typeof args.values[key] === "string" && args.values[key] !== "").map((key) => [key, resolve(String(args.values[key]))])) : {};
425
- const invocation = { ...args, values: { ...args.values, ...paths, ...(root ? { root } : {}), detach: args.values.foreground !== true } };
671
+ // The receipt's Next must run from the folder up was invoked in, which a re-entry inherits.
672
+ const invokedRoot = root && args.values.__invokedRoot === undefined ? { __invokedRoot: canonicalRoot(cotalRoot()) } : {};
673
+ const invocation = { ...args, values: { ...args.values, ...paths, ...(root ? { root } : {}), ...invokedRoot, detach: args.values.foreground !== true } };
426
674
  if (root) {
427
675
  try {
428
676
  process.chdir(root);
@@ -445,6 +693,11 @@ export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink
445
693
  try {
446
694
  return await runUp(invocation, inheritedLock, () => { adopted = true; }, freshTeamBoot, restoreSink);
447
695
  }
696
+ catch (error) {
697
+ if (fresh)
698
+ removeEmptyRecords(join(fresh, ".cotal"));
699
+ throw error;
700
+ }
448
701
  finally {
449
702
  if (root)
450
703
  process.chdir(previousCwd);
@@ -455,11 +708,25 @@ export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink
455
708
  releaseMaintenanceLock(inheritedLock);
456
709
  }
457
710
  }
711
+ /** Remove the `.cotal` a failed `up` made for a fresh folder when the run wrote nothing in it. One
712
+ * that holds anything stays, as the run's records. */
713
+ function removeEmptyRecords(path) {
714
+ try {
715
+ rmdirSync(path);
716
+ }
717
+ catch (error) {
718
+ const code = error.code;
719
+ if (code !== "ENOTEMPTY" && code !== "EEXIST")
720
+ console.error(c.yellow(`! ${path} was left in place (${code ?? "an error"})`));
721
+ }
722
+ }
458
723
  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";
459
724
  async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restoreSink) {
460
725
  const values = args.values;
461
726
  if (freshTeamBoot && (!values.file || values.restore || values.__restoreAttempt || values.__ordinaryResumeAttempt || values["rotate-sys"] || values["no-manager"]))
462
727
  throw new CommandFailure("refused", "USAGE_INVALID", "fresh team boot accepts one manifest and its selected lifetime, not a restore, rotation or manager-free override");
728
+ if (values["manager-name"] !== undefined && (values.restore || values.file || values["no-manager"]))
729
+ throw new CommandFailure("refused", "USAGE_INVALID", "--manager-name names the manager a plain cotal up starts; it cannot be combined with --restore, --file or --no-manager");
463
730
  // `space create` and `down` refuse a root other local accounts can write, so `up` refuses it too,
464
731
  // before anything is written: a stack started there could not be stopped from it.
465
732
  protectedLocalDirectory(canonicalRoot(cotalRoot()), "the project root");
@@ -476,6 +743,8 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
476
743
  // A restore rewrites the shared store and the trust root under it, from an artifact that names
477
744
  // one space (see `cotal backup`) - it cannot leave the root's other tenants standing.
478
745
  assertSingleSpaceBroker(authDir(cotalRoot()), "cotal up --restore");
746
+ // `up` keeps the startup interrupt notice (`keepsStartupNotice`); a restore reports its own.
747
+ await releaseStartupNotice();
479
748
  // A `backup restore` owns stdout for its receipt, so its seat admission lines go to stderr.
480
749
  const prepared = await prepareRestore(cotalRoot(), values, restoreSink ? (line) => console.error(line) : undefined);
481
750
  pendingRestores.set(prepared.attemptId, prepared);
@@ -566,7 +835,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
566
835
  // Refuse first-enable IdP failures and explicit pin conflicts before even recovery's lock
567
836
  // creates its layout. Existing recovery keeps its own recorded startup and trust checks.
568
837
  const stackSpace = values.space ?? folderSpace();
569
- if (values.space === undefined)
838
+ if (values.space === undefined && unnamedDefault(root, stackSpace))
570
839
  assertSelectionNotMoved(root, stackSpace);
571
840
  recordOperationSpace(stackSpace);
572
841
  if (!readMaintenanceJournal(root) && controllerStackApplies(root, stackSpace, values)) {
@@ -598,6 +867,9 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
598
867
  let handedOff = false;
599
868
  try {
600
869
  const journal = readMaintenanceJournal(root);
870
+ // A recorded maintenance attempt is recovered on its own terms, with no startup notice.
871
+ if (journal)
872
+ await releaseStartupNotice();
601
873
  if (journal?.state === "restore-ready") {
602
874
  // Ordinary up NEVER rolls back an in-progress restore: a live attempt's target may still be
603
875
  // written by its isolated broker. Refuse with the exact recovery recourse instead.
@@ -637,10 +909,9 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
637
909
  const status = localProcessOwnerStatus(journal.listenerProof.processOwner);
638
910
  if (status === "unknown")
639
911
  throw new Error(`restore attempt ${journal.restore.attemptId} active listener ownership is ambiguous; refusing ordinary startup`);
640
- if (status === "alive") {
641
- recoveredRestore = rehydratePreparedRestore(root, journal);
642
- pendingRestores.set(recoveredRestore.attemptId, recoveredRestore);
643
- }
912
+ // The restore committed and its broker runs, so there is nothing to hand off or adopt.
913
+ if (status === "alive")
914
+ throw restoredBrokerRuns(root, journal.restore.attemptId, journal.listenerProof.processOwner.pid);
644
915
  }
645
916
  else if (journal?.state === "ready") {
646
917
  const source = preservedSourceState(root, journal.source);
@@ -655,8 +926,28 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
655
926
  const runtimes = [...new Set(agents.map((agent) => agent.launch?.runtime).filter((value) => typeof value === "string"))];
656
927
  if (runtimes.length > 1)
657
928
  throw new Error(`resume inventory requires multiple runtimes: ${runtimes.join(", ")}`);
658
- const resumeServer = values.server ?? (typeof launch.server === "string" ? launch.server : DEFAULT_SERVER);
659
- const requestedStore = values["store-dir"] ?? (typeof launch.storeDir === "string" ? launch.storeDir : journal.source.path);
929
+ const resumeServer = typeof launch.server === "string" ? launch.server : DEFAULT_SERVER;
930
+ // A resume starts what `down --preserve-state` recorded. Another value is a new start, which
931
+ // follows a normal `down` of the resumed mesh.
932
+ const preservedOnly = (flag, given, what, preserved) => new CommandFailure("refused", "CONFLICT", `${flag} ${given} is not the ${what} that down --preserve-state recorded here (${preserved}), and a resume starts what it recorded; nothing was started`, {
933
+ target: { root, space: journal.space, flag, given: String(given), preserved },
934
+ remedy: `resume with cotal up without ${flag}; to use ${given}, stop the resumed mesh with cotal down, then run cotal up ${flag} ${given}`,
935
+ });
936
+ if (values.server !== undefined && values.server !== resumeServer)
937
+ throw preservedOnly("--server", values.server, "broker address", resumeServer);
938
+ const givenStore = values["store-dir"];
939
+ if (givenStore !== undefined && resolve(givenStore) !== journal.source.path) {
940
+ let same = false;
941
+ try {
942
+ same = sameStoreIdentity(readStoreIdentity(resolve(givenStore)), journal.source);
943
+ }
944
+ catch {
945
+ same = false;
946
+ }
947
+ if (!same)
948
+ throw preservedOnly("--store-dir", givenStore, "store", journal.source.path);
949
+ }
950
+ const requestedStore = givenStore ?? (typeof launch.storeDir === "string" ? launch.storeDir : journal.source.path);
660
951
  // Ordinary up resumes the exact preserved source: a different valid store passed via
661
952
  // --store-dir must not consume this maintenance cut under the recorded space's trust.
662
953
  if (!sameStoreIdentity(readStoreIdentity(resolve(requestedStore)), journal.source))
@@ -667,12 +958,17 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
667
958
  // The cap is part of the preserved launch, like the store: a resume re-renders it, and a
668
959
  // different --max-file-store is refused rather than silently resizing the preserved broker.
669
960
  const resumeMaxFileStore = journaledMaxFileStore(launch.maxFileStore);
670
- const requestedMaxFileStore = parsePositiveIntegerFlag("--max-file-store", values["max-file-store"]);
961
+ const requestedMaxFileStore = parseMaxFileStore(values["max-file-store"]);
671
962
  if (requestedMaxFileStore !== undefined && requestedMaxFileStore !== resumeMaxFileStore)
672
- throw new Error(`--max-file-store ${requestedMaxFileStore} is not the preserved launch cap (${resumeMaxFileStore ?? "unset"}); ordinary up resumes exactly the preserved cap - omit --max-file-store`);
963
+ throw preservedOnly("--max-file-store", requestedMaxFileStore, "file store cap", resumeMaxFileStore === undefined ? "no cap" : String(resumeMaxFileStore));
673
964
  if (values.runtime && runtimes[0] && values.runtime !== runtimes[0])
674
- throw new Error(`--runtime ${values.runtime} contradicts the preserved agent runtime ${runtimes[0]}; omit it to resume the same principals`);
965
+ throw preservedOnly("--runtime", values.runtime, "agent runtime", runtimes[0]);
675
966
  const resumeRuntime = values.runtime ?? runtimes[0] ?? "pty";
967
+ // The resumed broker binds this address, so another listener there would leave the resume
968
+ // degraded. It is refused here, before anything is journalled or started, as backup create does.
969
+ await assertEndpointUnreachable(resumeServer).catch((error) => {
970
+ throw new CommandFailure("refused", "CONFLICT", `${error.message}; the resumed broker needs that address, so nothing was started`, { target: { root, space: journal.space, server: resumeServer }, remedy: `stop the process that listens on ${resumeServer}, then run cotal up again` });
971
+ });
676
972
  // Admit every seat checkpoint the cut wrote and take custody, BEFORE the resume attempt is
677
973
  // journalled and long before a manager starts. A refusal here costs nothing because
678
974
  // nothing has been started; the same refusal after a launch would be a second writer.
@@ -719,7 +1015,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
719
1015
  const launch = journal.ordinaryResume.launch;
720
1016
  const attemptId = journal.ordinaryResume.attemptId;
721
1017
  const recoveredMaxFileStore = journaledMaxFileStore(launch.maxFileStore);
722
- const requestedMaxFileStore = parsePositiveIntegerFlag("--max-file-store", values["max-file-store"]);
1018
+ const requestedMaxFileStore = parseMaxFileStore(values["max-file-store"]);
723
1019
  if (requestedMaxFileStore !== undefined && requestedMaxFileStore !== recoveredMaxFileStore)
724
1020
  throw new Error(`--max-file-store ${requestedMaxFileStore} is not the preserved launch cap (${recoveredMaxFileStore ?? "unset"}); resume attempt ${attemptId} re-renders exactly the preserved cap - omit --max-file-store`);
725
1021
  // Recovery re-asserts the source identity rather than trusting the journaled spelling.
@@ -863,7 +1159,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
863
1159
  const noManager = Boolean(values["no-manager"]);
864
1160
  const publicExchange = [...publicExchangeArgs(values, wantUser), ...serviceEndpointsArgs(values, wantUser)];
865
1161
  const maxSessions = parsePositiveIntegerFlag("--max-sessions", values["max-sessions"]);
866
- const maxFileStore = parsePositiveIntegerFlag("--max-file-store", values["max-file-store"]);
1162
+ const maxFileStore = parseMaxFileStore(values["max-file-store"]);
867
1163
  // The manifest path renders its broker from the manifest, which has no store fields, so the flag
868
1164
  // would be accepted and never rendered. Refuse it rather than drop it.
869
1165
  if (maxFileStore !== undefined && values.file)
@@ -902,6 +1198,18 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
902
1198
  ensureRootForSpace(spaceForRoot);
903
1199
  }
904
1200
  }
1201
+ // `--manager-name` is recorded for this root, where the manager reads it at each start. A running
1202
+ // manager keeps the name it started with, so a different name while one runs is refused.
1203
+ if (values["manager-name"] !== undefined) {
1204
+ const name = assertManagerName(values["manager-name"]);
1205
+ const named = { root: cotalRoot(), space: values.space ?? folderSpace() };
1206
+ if (readManagerName(named) !== name) {
1207
+ if (managerRecordState(undefined, undefined, named.space, named.root).state === "alive")
1208
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `a manager already runs for space ${named.space}, and it keeps the name it started with`, { target: { root: named.root, space: named.space }, remedy: `stop it with cotal down, then run cotal up --manager-name ${shellWord(name)}` });
1209
+ if (!values["dry-run"])
1210
+ recordManagerName(named, name);
1211
+ }
1212
+ }
905
1213
  // THE TRANSPORT IS DECIDED HERE, ABOVE EVERY BRANCH, AND THIS POSITION IS THE FIX.
906
1214
  //
907
1215
  // It used to be resolved inside the foreground path only, which meant three routes to a listener
@@ -938,6 +1246,10 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
938
1246
  // require its own project root, while dry-run must write nothing to create one.
939
1247
  const previewRoot = values.file && values["dry-run"] && !values.root && inheritedMachineHomeRoot() ? process.cwd() : undefined;
940
1248
  const meshRoot = previewRoot ?? cotalRoot();
1249
+ // A bare start seeds the root's default channels file, so one it would refuse is named here,
1250
+ // before anything starts; an explicit --channels file was checked with the other flags.
1251
+ if (!values.file && !values.restore && values.channels === undefined)
1252
+ loadChannelsFile();
941
1253
  const transport = resolveTransport(values, undefined, meshRoot, {
942
1254
  persist: false,
943
1255
  quiet: true,
@@ -951,35 +1263,77 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
951
1263
  if (!values.file && controllerStackApplies(meshRoot, values.space ?? folderSpace(), values)) {
952
1264
  const stackSpace = values.space ?? folderSpace();
953
1265
  recordOperationSpace(stackSpace);
954
- const stackServer = values.server ?? readStackJournal(meshRoot)?.journal.server ?? localMeshesForRoot(meshRoot).find((m) => m.space === stackSpace)?.server ?? (values.host ? reconcileHostAndServer(values.host, undefined) : DEFAULT_SERVER);
955
1266
  const stackMode = requestedStackMode(values);
956
1267
  const presentation = presentationOf(values);
957
- const stackLock = acquireStackOperationLock(meshRoot);
958
- const native = controllerStackNative();
959
- // A foreground terminal holds the start as well, so a signal during it stops what it started.
960
- const start = async () => {
1268
+ // A foreground up holds a stack only one terminal holds. Over a stack that already runs without
1269
+ // one, it takes that stack's lifetime over and says so before it blocks.
1270
+ const holder = values.foreground ? foregroundHolder(meshRoot) : undefined;
1271
+ if (holder !== undefined)
1272
+ 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` });
1273
+ const takeover = values.foreground === true && STACK_ROLES.some((role) => serviceInstances(stackSpace, STACK_DEFINITION[role]).some((row) => observeServiceProcess(row.record.value) === "running"));
1274
+ // A signal ends a detached start where it is, after it records a launch it had not yet pinned to
1275
+ // its child, and the notice names what it left running. It is installed before the lock, so no
1276
+ // moment of the start exits without it.
1277
+ const release = values.foreground ? undefined : noticeOnInterrupt(() => { settleInterruptedLaunches(); return stackUpInterruptNotice(meshRoot, stackSpace, values["no-manager"] === true); });
1278
+ try {
1279
+ const stackLock = acquireStackOperationLock(meshRoot);
1280
+ const native = controllerStackNative();
1281
+ // A foreground terminal holds the start as well, so a signal during it stops what it started.
1282
+ const start = async () => {
1283
+ try {
1284
+ const stackServer = values.server ?? readStackJournal(meshRoot)?.journal.server ?? localMeshesForRoot(meshRoot).find((m) => m.space === stackSpace)?.server ?? await unrecordedStackServer(meshRoot, stackSpace, values.host);
1285
+ if (values.foreground && presentation !== "json")
1286
+ stackUpForegroundNotice(presentation, stackSpace, takeover);
1287
+ await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, ...(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 } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), ...(values.__invokedRoot ? { invokedRoot: values.__invokedRoot } : {}), foreground: values.foreground === true, presentation }, native);
1288
+ }
1289
+ finally {
1290
+ releaseMaintenanceLock(stackLock);
1291
+ }
1292
+ };
1293
+ if (values.foreground)
1294
+ await holdForegroundStack(meshRoot, start);
1295
+ else
1296
+ await start();
1297
+ }
1298
+ finally {
1299
+ release?.();
1300
+ }
1301
+ return;
1302
+ }
1303
+ // A manifest or retained-launcher start reports no interrupt notice of its own.
1304
+ await releaseStartupNotice();
1305
+ // A named space this machine runs from another folder is refused before anything is written here,
1306
+ // and in every presentation, since the launcher below has no structured receipt.
1307
+ if (!values.file && values.space !== undefined)
1308
+ await refuseRunningElsewhere(values.space, meshRoot);
1309
+ if (values.json || values.plain) {
1310
+ // `up -f` always takes the retained launcher, so the controller route is no remedy there. Its
1311
+ // manifest is checked first, so a manifest that does not validate gets its own refusal.
1312
+ if (values.file) {
1313
+ const path = resolve(values.file);
961
1314
  try {
962
- if (values.foreground && presentation !== "json")
963
- stackUpForegroundNotice(presentation, stackSpace);
964
- await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, ...(stackMode ? { mode: stackMode } : {}), ...(values.idp ? { idp: values.idp } : {}), ...(values.host ? { host: values.host } : {}), ...(values["store-dir"] ? { storeDir: values["store-dir"] } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), foreground: values.foreground === true, presentation }, native);
1315
+ loadManifest(path);
965
1316
  }
966
- finally {
967
- releaseMaintenanceLock(stackLock);
1317
+ catch (e) {
1318
+ throw manifestFileRefusal(e, path);
968
1319
  }
969
- };
970
- if (values.foreground)
971
- await holdForegroundStack(meshRoot, start);
972
- else
973
- await start();
974
- return;
975
- }
976
- if (values.json || values.plain)
1320
+ 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"}` });
1321
+ }
977
1322
  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" });
1323
+ }
978
1324
  // `up -f cotal.yaml` is a distinct path: bring up a FRESH mesh described by a manifest (broker +
979
1325
  // channels + booted agents). It owns the whole space; the additive team deploy route is separate.
980
1326
  // CLI flags override the manifest (flag > manifest > default) so the same file runs at a different
981
1327
  // port / runtime / auth without editing it. Its space is its target: `--space` may only repeat it.
982
1328
  if (values.file) {
1329
+ // A manifest start takes the legacy launcher, which never runs beside a controller stack, running
1330
+ // or stopped, so a dry run refuses as the start would.
1331
+ const controller = freshTeamBoot ? undefined : readStackJournal(meshRoot);
1332
+ if (controller)
1333
+ 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`, {
1334
+ target: { root: meshRoot, space: controller.journal.space },
1335
+ 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}`,
1336
+ });
983
1337
  if (values["dry-run"]) {
984
1338
  await upManifest(values.file, {
985
1339
  transport,
@@ -1008,7 +1362,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1008
1362
  throw new CommandFailure("refused", "USAGE_INVALID", "fresh team boot needs the manifest's exact selected space");
1009
1363
  assertFreshTeamBootOwnership(cotalRoot(), values.space);
1010
1364
  }
1011
- assertOrdinaryUpAllowed(cotalRoot());
1365
+ assertOrdinaryUpAllowed(cotalRoot(), undefined, values.file);
1012
1366
  await upManifest(values.file, {
1013
1367
  transport,
1014
1368
  dryRun: Boolean(values["dry-run"]),
@@ -1080,24 +1434,30 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1080
1434
  // on a free port, which this root's record keeps; a re-run must start from that URL, or every
1081
1435
  // lookup below misses its own mesh and the space claim refuses it (#3889).
1082
1436
  const recordedSpace = values.space ?? folderSpace();
1083
- const registeredServer = localMeshesForRoot(cotalRoot()).find((m) => m.space === recordedSpace)?.server;
1084
- // A stopped legacy root's `down` dropped the registration that kept its address, so its own files
1085
- // decide. With no address flag, it starts again at the address its last start rendered, and in
1086
- // open mode when that start was open and no mode is asked for. After `clean all` only a fresh
1087
- // team summary remains, and a start that would differ from it refuses, naming its manifest.
1437
+ const registration = localMeshesForRoot(cotalRoot()).find((m) => m.space === recordedSpace);
1438
+ // A stopped legacy root's own files decide its start: its `down` dropped the registration that
1439
+ // kept its address, or kept one for a space named after its folder, which only holds the name.
1440
+ // With no address flag, it starts again at the address its last start rendered, and in open
1441
+ // mode when that start was open and no mode is asked for. After `clean all` only a fresh team
1442
+ // summary remains, and a start that would differ from it refuses, naming its manifest.
1443
+ const keptStopped = registration !== undefined && !resumeAttempt && values.server === undefined && keepsRegistration(registration) && !(await isReachable(registration.server));
1444
+ const registeredServer = keptStopped ? undefined : registration?.server;
1088
1445
  const implicit = !resumeAttempt && registeredServer === undefined && values.server === undefined && values.host === undefined && !values["user-auth"];
1089
1446
  const retained = implicit ? retainedLegacyBroker(cotalRoot()) : undefined;
1447
+ // An address up chooses for a TLS broker names TLS, as an explicit one must.
1448
+ const serving = (url) => transport.kind === "tls-required" ? tlsAddress(url) : url;
1090
1449
  if (retained) {
1091
1450
  if (retained.open)
1092
1451
  values.open = true;
1093
- console.log(c.dim(`starting this folder's stopped stack as it last ran: ${retained.server}${values.open ? ", open" : ""}`));
1452
+ console.log(c.dim(`starting this folder's stopped stack as it last ran: ${serving(retained.server)}${values.open ? ", open" : ""}`));
1094
1453
  }
1095
1454
  else if (implicit) {
1096
1455
  const cleaned = cleanedManifestStart(cotalRoot(), recordedSpace, values.open === true);
1097
1456
  if (cleaned)
1098
1457
  throw new CommandFailure("refused", "CONFLICT", `this folder was deployed from a manifest as "${cleaned.space}" at ${cleaned.server} in ${cleaned.mode === "open" ? "open" : "static auth"} mode, and its identity and broker configuration were removed, so a bare up would not start it as it was deployed; nothing was started`, { target: { root: cotalRoot(), space: cleaned.space, server: cleaned.server }, remedy: `deploy it again with ${cleaned.command}` });
1099
1458
  }
1100
- const implicitServer = registeredServer ?? retained?.server ?? DEFAULT_SERVER;
1459
+ // A registered address stays as recorded, so a running stack is still found by it.
1460
+ const implicitServer = registeredServer ?? serving(retained?.server ?? DEFAULT_SERVER);
1101
1461
  let server = values.server ?? implicitServer;
1102
1462
  const host = values.host ?? "127.0.0.1";
1103
1463
  // `--host` is the BIND address; `server` is the URL the readiness probe, the mesh registry, and
@@ -1212,6 +1572,14 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1212
1572
  console.error(c.red(`✗ mesh "${held.space}" is already running at ${server} - a running broker can't rotate its system account (it would keep serving the retired one); \`cotal down\` it first, then \`cotal up --rotate-sys\``));
1213
1573
  process.exit(1);
1214
1574
  }
1575
+ // `--foreground` asks this terminal to hold the stack's lifetime, but this branch starts
1576
+ // nothing here: it used to print `✓ already running`, restart a missing manager detached and
1577
+ // exit 0. A service unit relying on `--foreground` read that exit as the stack ending, stopped
1578
+ // it, and restarted into the same branch. Refuse and name the remedy.
1579
+ if (values.foreground) {
1580
+ console.error(c.red(`✗ mesh "${held.space}" is already running at ${server} - \`cotal up --foreground\` starts nothing here, so it can't keep it in this terminal; \`cotal down\` it first, then \`cotal up --foreground\``));
1581
+ process.exit(1);
1582
+ }
1215
1583
  // A running broker cannot change its transport either, and for exactly the reason it cannot
1216
1584
  // change its auth mode: the listener's TLS config was fixed when nats-server read its config
1217
1585
  // file. This branch starts nothing, so `--tls-cert`/`--tls-key` here can only be a request to
@@ -1301,7 +1669,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1301
1669
  if (held.mode !== "open") {
1302
1670
  const spaceAuth = await getSpaceAuth(workspaceSecretStore(root), held.space);
1303
1671
  if (!spaceAuth) {
1304
- console.error(c.red(`✗ mesh "${held.space}" has no trust material under ${authDir(root)} - cannot reconcile its presence/lease TTLs; restore or re-provision \`.cotal/auth\``));
1672
+ stderrLine("✗ ", `mesh "${held.space}" has no trust material under ${authDir(root)} - cannot reconcile its presence/lease TTLs; restore or re-provision \`.cotal/auth\``, c.red);
1305
1673
  process.exit(1);
1306
1674
  }
1307
1675
  // Ephemeral, reconcile-only, discarded with the connection. Same enumerated `provisioner`
@@ -1316,7 +1684,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1316
1684
  console.log(c.dim(` reconciled ${r.stream} TTL ${r.fromMs === 0 ? "none" : `${r.fromMs}ms`} -> ${r.toMs}ms`));
1317
1685
  }
1318
1686
  catch (e) {
1319
- console.error(c.red(`✗ mesh "${held.space}" is running at ${server} but its presence/lease TTLs could not be reconciled: ${e.message}`));
1687
+ stderrLine("✗ ", `mesh "${held.space}" is running at ${server} but its presence/lease TTLs could not be reconciled: ${e.message}`, c.red);
1320
1688
  process.exit(1);
1321
1689
  }
1322
1690
  console.log(c.green(`✓ mesh "${held.space}" already running at ${server}`));
@@ -1328,7 +1696,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1328
1696
  if (held.mode === "user") {
1329
1697
  const auth = await getSpaceAuth(workspaceSecretStore(root), held.space);
1330
1698
  if (!auth) {
1331
- console.error(c.red(`✗ mesh "${held.space}" is user-auth but this root has no trust material under ${authDir(root)} - \`cotal down\` it, restore or re-provision \`.cotal/auth\`, then \`cotal up --user-auth\``));
1699
+ stderrLine("✗ ", `mesh "${held.space}" is user-auth but this root has no trust material under ${authDir(root)} - \`cotal down\` it, restore or re-provision \`.cotal/auth\`, then \`cotal up --user-auth\``, c.red);
1332
1700
  process.exit(1);
1333
1701
  }
1334
1702
  const stateDir = userAuthStateDir(root, held.space);
@@ -1344,7 +1712,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1344
1712
  });
1345
1713
  }
1346
1714
  catch (e) {
1347
- console.error(c.red(`✗ ${e.message}`));
1715
+ stderrLine("✗ ", `${e.message}`, c.red);
1348
1716
  process.exit(1);
1349
1717
  }
1350
1718
  const svc = await startUserAuthService(held.space, server, { prepared, stateDir }, publicExchange);
@@ -1401,16 +1769,6 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1401
1769
  seedPersonaAfterUp(root);
1402
1770
  return;
1403
1771
  }
1404
- // The broker answering here is the named space's own, started from another folder.
1405
- const owner = values.space !== undefined ? findMesh(space) : undefined;
1406
- if (owner && owner.server === server && owner.root !== root) {
1407
- let controller = false;
1408
- try {
1409
- controller = readStackJournal(owner.root)?.journal.space === space;
1410
- }
1411
- catch { /* named with the legacy stop */ }
1412
- throw new CommandFailure("refused", "CONFLICT", `space "${space}" runs at ${server}, started in ${owner.root}, so up did not start it again`, { target: { space, root: owner.root, server }, remedy: `use it from here with --space ${space}, or stop it with cotal down${controller ? " --yes" : ""} in ${owner.root}` });
1413
- }
1414
1772
  const who = held ? `mesh "${held.space}" (${held.root})` : "a broker not started here";
1415
1773
  // Reaching here with `--rotate-sys` means something IS answering at the requested address and it
1416
1774
  // is not this root's recorded mesh (that case was refused above). The ordinary response is to pick
@@ -1434,9 +1792,15 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1434
1792
  process.exit(1);
1435
1793
  }
1436
1794
  }
1795
+ await assertBrokerAddressFree(server, "cotal up");
1437
1796
  // A repair keeps its own store rules above, and a resume or restore names its store.
1438
- if (!resumeAttempt && !repairing && values["store-dir"] === undefined)
1439
- refuseUnnamedLastStore(cotalPath("nats"));
1797
+ if (!resumeAttempt && !repairing) {
1798
+ if (values["store-dir"] === undefined)
1799
+ refuseUnnamedLastStore(cotalPath("nats"));
1800
+ else
1801
+ refuseMissingNamedStore(resolve(values["store-dir"]));
1802
+ checkStartStore(values["store-dir"], values.space ?? folderSpace());
1803
+ }
1440
1804
  const restored = resumeAttempt ? pendingRestores.get(resumeAttempt) : undefined;
1441
1805
  const boundListener = restored ? {
1442
1806
  serverName: restored.serverName,
@@ -1452,7 +1816,12 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1452
1816
  if (values.detach) {
1453
1817
  // A `backup restore` owns its own receipt: the native launcher's progress lines stay off stdout.
1454
1818
  const quietRestore = restored !== undefined && restoreSinks.has(restored.attemptId);
1455
- const { pid, source, authService, controlPlane, delivery, manager } = await startMeshDetached({
1819
+ // The receipt names its space before the launch prints anything, as every report does.
1820
+ const receiptSpace = values.space ?? folderSpace();
1821
+ const unnamed = values.space === undefined && unnamedDefault(cotalRoot(), receiptSpace);
1822
+ if (!quietRestore)
1823
+ console.log(`${renderReport({ space: receiptSpace, sections: [] }, "rich", terminalWidth(process.stdout))}\n`);
1824
+ const { pid, executable, authService, controlPlane, delivery, manager } = await startMeshDetached({
1456
1825
  transport,
1457
1826
  server,
1458
1827
  storeDir: values["store-dir"],
@@ -1476,9 +1845,14 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1476
1845
  ...(quietRestore ? { quietBoot: true } : {}),
1477
1846
  });
1478
1847
  // Transport policy is committed inside startMeshDetached before delivery launch (S5+S9).
1848
+ const detached = { pid, delivery, authService: wantUser && authService, manager, machineHome: canonicalRoot(cotalRoot()) === canonicalRoot(homedir()), ...(values.root ? { root: cotalRoot() } : {}) };
1479
1849
  if (!quietRestore) {
1480
- console.log(c.dim(`Started nats-server (${source}).`));
1481
- console.log(c.green(renderDetachedSummary({ pid, delivery, authService: wantUser && authService, manager, machineHome: canonicalRoot(cotalRoot()) === canonicalRoot(homedir()), ...(values.root ? { root: cotalRoot() } : {}) })));
1850
+ console.log(c.dim(`Started ${executable}.`));
1851
+ console.log(c.green(renderDetachedSummary(detached)));
1852
+ if (unnamed)
1853
+ console.log(c.dim(` This folder names no space, so up started the default space "${receiptSpace}"; pass --space <name> to start another`));
1854
+ if (values.__folderNamed)
1855
+ console.log(c.dim(` This new project's space is named after its folder, "${receiptSpace}"; pass --space <name> to start another`));
1482
1856
  }
1483
1857
  if (restored && process.env.COTAL_SMOKE_FAIL_AFTER_RESTORE_LISTENER_READY === "1")
1484
1858
  throw new Error("smoke-injected failure after restore listener readiness");
@@ -1488,10 +1862,25 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1488
1862
  if (!authService || !controlPlane)
1489
1863
  process.exitCode = 1;
1490
1864
  await completeResumeActivation(resumeAttempt, controlPlane && authService, !authService ? "normal listener started but the user-auth service is unavailable" : "normal listener started but the control plane is degraded", server, startupLock);
1865
+ // `backup restore` prints its own receipt; `up --restore` names the attempt and its next step here.
1866
+ if (restored && !quietRestore) {
1867
+ console.log(c.green(`✓ restored the backup ${restored.selection === "registry" ? "registry" : "in full"} as restore attempt ${restored.attemptId}`));
1868
+ const composition = restoreComposition(restored.space, restored.restoredStreams, restored.mode);
1869
+ console.log(c.dim(`restored: ${composition.restoredWords}; recreated empty: ${composition.emptyWords}`));
1870
+ if (composition.note)
1871
+ console.log(c.yellow(composition.note));
1872
+ for (const line of leftOutNotes(restored.attemptId, restored.selection, restoreOnlyCopy(restored.root, restored.attemptId)))
1873
+ console.log(c.yellow(line));
1874
+ const journal = readMaintenanceJournal(restored.root);
1875
+ if (journal && "restore" in journal && journal.restore.attemptId === restored.attemptId)
1876
+ console.log(c.dim(`next: ${restoreNextStep(journal.state, restored.attemptId, restoreLeftOut(journal))}`));
1877
+ }
1878
+ if (!quietRestore)
1879
+ console.log(`\n${renderReport({ sections: [{ title: "Next", blocks: [{ kind: "commands", items: detachedNext(detached, receiptSpace) }] }] }, "rich", terminalWidth(process.stdout))}`);
1491
1880
  if (restored)
1492
1881
  restoreSinks.get(restored.attemptId)?.({
1493
1882
  attemptId: restored.attemptId, space: restored.space, root: restored.root, server: restored.server, mode: restored.mode,
1494
- selection: restored.selection, targetPath: restored.targetPath, runtime: restored.runtime, brokerPid: pid,
1883
+ selection: restored.selection, restoredStreams: restored.restoredStreams, targetPath: restored.targetPath, runtime: restored.runtime, brokerPid: pid,
1495
1884
  delivery, authService, controlPlane, manager,
1496
1885
  });
1497
1886
  return;
@@ -1510,6 +1899,8 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1510
1899
  if (!sameStoreIdentity(readStoreIdentity(storeDir), resumeJournal.source))
1511
1900
  throw new Error(`resume store ${storeDir} no longer matches the preserved source identity; refusing to open JetStream over it`);
1512
1901
  }
1902
+ if (values["store-dir"])
1903
+ warnForeignStoreEntries(storeDir);
1513
1904
  // Owner-private regardless of umask: a recursive create also makes a missing `.cotal`, which every
1514
1905
  // later protection check walks as an ancestor.
1515
1906
  mkdirSync(storeDir, { recursive: true, mode: 0o700 });
@@ -1524,19 +1915,21 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1524
1915
  // `-js -sd … -p … -a …`, which never called a renderer at all — so the required transport union
1525
1916
  // protected the auth path and was silent on the open one, and a cert/key pair passed to an
1526
1917
  // open-mode `up` would have been accepted while the listener came up in cleartext.
1527
- const confPath = setup ? setup.confPath : writeOpenBrokerConf(storeDir, { port, host, transport, maxFileStore });
1918
+ const confPath = setup ? setup.confPath : writeOpenBrokerConf(storeDir, space, { port, host, transport, maxFileStore });
1528
1919
  const natsArgs = [
1529
1920
  "-c", confPath,
1530
1921
  ...(boundListener ? ["--name", boundListener.serverName] : []),
1531
1922
  ];
1532
- const { bin, source } = await resolveNatsServer();
1533
- console.log(c.dim(`Starting nats-server (JetStream, ${useAuth ? "JWT auth" : "OPEN/no-auth"}, ${source}) - store: ${storeDir}, bind: ${host}`));
1923
+ const natsServer = await resolveNatsServer();
1924
+ const bin = natsServer.path;
1925
+ console.log(c.dim(`Starting ${natsServerLabel(natsServer)} (JetStream, ${useAuth ? "JWT auth" : "OPEN/no-auth"}) - store: ${storeDir}, bind: ${host}`));
1534
1926
  console.log(c.dim("Press Ctrl-C to stop.\n"));
1535
1927
  const listenerStartedAt = new Date().toISOString();
1536
1928
  // A terminal sends Ctrl-C to the whole foreground process group. Keep the broker outside it
1537
1929
  // on POSIX so only this owner receives the interrupt and can finish manager-first teardown
1538
1930
  // before signalling the broker. Keep the child referenced and its output in this terminal.
1539
- const child = spawn(bin, natsArgs, { stdio: "inherit", detached: process.platform !== "win32" });
1931
+ // The configuration names a store inside the root relative to it, so the broker runs from the root.
1932
+ const child = spawn(bin, natsArgs, { cwd: cotalRoot(), stdio: "inherit", detached: process.platform !== "win32" });
1540
1933
  let activationFinished = !resumeAttempt;
1541
1934
  await recordSpawnedListener(child, listenerStartedAt, boundListener);
1542
1935
  releaseStartupLock();
@@ -1628,15 +2021,28 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1628
2021
  // racing a second broker into existence. Foreground stdio is inherited (its own log lines
1629
2022
  // are already on this terminal, above), so there is no `.cotal/nats.log` to name here.
1630
2023
  const detail = signal ? `signal ${signal}` : `code ${code}`;
1631
- console.error(c.red(`✗ nats-server exited unexpectedly (${detail}); the mesh "${space}" stays recorded (\`cotal meshes\` lists it offline); log: see the terminal output above; repair: \`cotal up --server ${server} --space ${space}\``));
2024
+ // Retention is read from the registry, not assumed: a broker that exits before it first
2025
+ // answers was never recorded. A registry that cannot be read is not claimed either way, and
2026
+ // the read cannot throw past this handler, which still has to exit.
2027
+ let retention;
2028
+ try {
2029
+ const mine = findMesh(space);
2030
+ retention = mine && mine.server === server && mine.root === cotalRoot() ? `the mesh "${space}" stays recorded (\`cotal meshes\` lists it offline)` : `the mesh "${space}" was not recorded`;
2031
+ }
2032
+ catch {
2033
+ retention = `whether the mesh "${space}" stays recorded could not be read`;
2034
+ }
2035
+ console.error(c.red(`✗ nats-server exited unexpectedly (${detail}); ${retention}; log: see the terminal output above; repair: \`cotal up --server ${server} --space ${space}\``));
1632
2036
  // A foreground broker under `Restart=on-failure` must exit non-zero on a crash so the unit
1633
2037
  // restarts it; exiting 0 here (as an unconditional `code ?? 0` used to) looked like a clean
1634
- // stop and left the unit sitting dead.
2038
+ // stop and left the unit sitting dead. A broker that exited 0, as after an external `down`,
2039
+ // still exits 0. Any other exit is a failed run, 5, not the broker's own code, which the exit
2040
+ // table would read as a usage error (1) or a refusal (2).
1635
2041
  if (activationFinished)
1636
- process.exit(code ?? 1);
2042
+ process.exit(code === 0 ? 0 : exitCode("failed", "OPERATION_FAILED"));
1637
2043
  }
1638
2044
  });
1639
- await awaitSpawnedListener({ child, server, space, creds: setup?.creds, log: "the terminal output above", boundListener });
2045
+ await awaitSpawnedListener({ child, executable: natsServer, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: "the terminal output above", boundListener });
1640
2046
  {
1641
2047
  // A DAEMON THAT DIES UNDER THIS RUNNING BROKER IS RESTARTED HERE (#2469). It exits on its own once
1642
2048
  // it cannot reach the broker, and a starved host makes a running broker look unreachable, so it can
@@ -1711,22 +2117,60 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1711
2117
  releaseStartupLock();
1712
2118
  }
1713
2119
  }
1714
- function assertOrdinaryUpAllowed(root, storeDir) {
2120
+ /** The address of a prepared stack that neither a journal nor a registration records, as after a
2121
+ * damaged journal was removed once `down` had dropped the registration. Its saved broker definition
2122
+ * names it. With none, a root that holds this space's trust or a store from an earlier start refuses
2123
+ * rather than start at another address; only a fresh prepared root chooses an available address. */
2124
+ async function unrecordedStackServer(root, space, host) {
2125
+ const launch = serviceDefinitionStore(space).read(STACK_DEFINITION.broker)?.record.value.launch;
2126
+ const saved = launch?.type === "adapter" && typeof launch.options.server === "string" ? launch.options.server : undefined;
2127
+ if (saved !== undefined) {
2128
+ recordOperationWarning({ code: "STACK_ADDRESS_RECOVERED", target: { root, space, server: saved }, message: `no stack journal or registration records this stack's address, so it starts at ${saved}, the address its saved broker definition names` });
2129
+ return host ? reconcileHostAndServer(host, undefined, "--host", "--server", saved) : saved;
2130
+ }
2131
+ if (listSpaceAccounts(authDir(root)).includes(space) || existsSync(join(root, ".cotal", "nats")))
2132
+ throw new MissingFlags(`no stack journal, registration or saved broker definition records the address "${space}" ran at in ${root}, which holds its earlier trust or store; nothing was started`, "run cotal up --server <url> with the address it ran at", { root, space });
2133
+ return freshStackServer(host ? reconcileHostAndServer(host, undefined) : DEFAULT_SERVER, host);
2134
+ }
2135
+ /** A start over the broker a committed restore left running here. `up -f` boots a fresh mesh, so its
2136
+ * way out also retires the restore with `retire`. */
2137
+ function restoredBrokerRuns(root, attempt, pid, manifest, retire) {
2138
+ return new CommandFailure("refused", "CONFLICT", `the broker that restore attempt ${attempt} started still runs here (pid ${pid}), and a new start does not run beside it; nothing was started`, {
2139
+ target: { root, attempt, pid },
2140
+ remedy: manifest !== undefined ? `stop the restored stack with cotal down, retire the restore with ${retire}, then run cotal up -f ${manifest} again` : "stop the restored stack with cotal down, then run cotal up again",
2141
+ });
2142
+ }
2143
+ /** The cleanup that retires an active restore. One that left something out keeps its only copy in the
2144
+ * previous store, so its cleanup deletes that store only with `--discard-history`. */
2145
+ function retireRestore(attempt, leftOut) {
2146
+ return `cotal backup cleanup-fallback ${attempt} --yes${leftOut ? ` --discard-history, which deletes the previous store and the ${leftOut} only it holds` : ""}`;
2147
+ }
2148
+ /** `manifest` is the `up -f` file, which boots a fresh mesh and so needs the restore retired first. */
2149
+ function assertOrdinaryUpAllowed(root, storeDir, manifest) {
1715
2150
  const maintenance = readMaintenanceJournal(root);
1716
2151
  if (!maintenance)
1717
2152
  return;
1718
2153
  if (maintenance.state === "active") {
2154
+ const attempt = maintenance.restore.attemptId, retire = retireRestore(attempt, restoreLeftOut(maintenance));
1719
2155
  if (!isManagerCommittedRestore(maintenance))
1720
- throw new Error(`restore attempt ${maintenance.restore.attemptId} is active without durable manager commit evidence`);
2156
+ throw new Error(`restore attempt ${attempt} is active without durable manager commit evidence`);
1721
2157
  if (!maintenance.listenerProof)
1722
- throw new Error(`restore attempt ${maintenance.restore.attemptId} is active without a bound listener proof`);
2158
+ throw new Error(`restore attempt ${attempt} is active without a bound listener proof`);
1723
2159
  const status = localProcessOwnerStatus(maintenance.listenerProof.processOwner);
2160
+ if (status === "alive")
2161
+ throw restoredBrokerRuns(root, attempt, maintenance.listenerProof.processOwner.pid, manifest, retire);
1724
2162
  if (status !== "dead")
1725
- throw new Error(`restore attempt ${maintenance.restore.attemptId} active listener ownership is ${status}; refusing ordinary startup`);
2163
+ throw new Error(`restore attempt ${attempt} active listener ownership is ${status}; refusing ordinary startup`);
2164
+ // `up -f` boots a fresh mesh, so the restore it would start over is retired first.
2165
+ if (manifest !== undefined)
2166
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `restore attempt ${attempt} is still active here, and cotal up -f boots a fresh mesh, which does not start over a restore that is not retired; nothing was started`, {
2167
+ target: { root, attempt },
2168
+ remedy: `retire the restore with ${retire}, then run cotal up -f ${manifest} again; bare cotal up starts the restored stack instead`,
2169
+ });
1726
2170
  // Relaunching after restore must serve the exact recorded active target, not whatever store the
1727
2171
  // caller happens to name — the journal's provenance would otherwise describe a different mesh.
1728
2172
  if (!storeDir)
1729
- throw new Error(`restore attempt ${maintenance.restore.attemptId} is active; relaunch with bare \`cotal up\` over the recorded target ${maintenance.restore.target.path}`);
2173
+ throw new Error(`restore attempt ${attempt} is active; relaunch with bare \`cotal up\` over the recorded target ${maintenance.restore.target.path}`);
1730
2174
  if (!sameStoreIdentity(readStoreIdentity(resolve(storeDir)), maintenance.restore.target))
1731
2175
  throw new Error(`ordinary startup after restore must use the recorded active target store ${maintenance.restore.target.path}, not ${storeDir}`);
1732
2176
  return;
@@ -1949,7 +2393,7 @@ async function proveBoundListener(kind, attempt, proof, journalStore, store) {
1949
2393
  if (info.server_name !== proof.serverName)
1950
2394
  throw new Error(`${label} reached a foreign NATS server name/nonce`);
1951
2395
  const auth = await resumeControlAuth(attempt.root, attempt.mode);
1952
- const nc = await connect({
2396
+ const nc = await dialerFor(attempt.server)({
1953
2397
  servers: attempt.server,
1954
2398
  ...standaloneConnectOpts({ ...auth, /* not yet wired to a recorded transport - see broker-policy/MeshEntry work */ tls: false }),
1955
2399
  maxReconnectAttempts: 0,
@@ -2086,14 +2530,16 @@ async function resumeControllerStack(lock, root, values, restoreSink) {
2086
2530
  const has = (role) => cut.members.some((member) => member.role === role);
2087
2531
  const result = {
2088
2532
  attemptId, space, root, server: launch.server, mode: restored.mode, selection: restored.launch.restoreOnly === "registry" ? "registry" : "full",
2533
+ restoredStreams: journaledRestoredStreams(restored.launch, space, restored.mode),
2089
2534
  targetPath, runtime: launch.runtime, brokerPid: broker.pid, delivery: has("delivery"), authService: has("auth"), controlPlane: true, manager: true,
2090
2535
  };
2536
+ const composition = restoreComposition(space, result.restoredStreams, result.mode);
2091
2537
  if (restoreSink)
2092
2538
  restoreSink(result);
2093
2539
  else
2094
- writeResult(presentationOf(values), { command: "up", target: { root, space, server: launch.server }, result: { kind: "controller-stack-restore", root, space, server: launch.server, attemptId, targetPath, selection: result.selection, retiredBrokerRemoved: attempt.brokerRequired } }, (row) => ({ sections: [{ title: "Controller stack restored", blocks: [
2095
- { kind: "fields", rows: [["Space", row.space], ["Root", row.root], ["Broker", row.server], ["Attempt", row.attemptId], ["Store", row.targetPath], ["Selection", row.selection]] },
2096
- { kind: "lines", lines: ["Each recorded member was started or adopted for this attempt, and the retained agents were resumed under the same principals. The restore journal stays active until its fallback is cleaned up. This is not agent or task readiness."] },
2540
+ writeResult(presentationOf(values), { command: "up", target: { root, space, server: launch.server }, result: { kind: "controller-stack-restore", root, space, server: launch.server, attemptId, targetPath, selection: result.selection, restored: composition.restored, recreatedEmpty: composition.recreatedEmpty, retiredBrokerRemoved: attempt.brokerRequired } }, (row) => ({ sections: [{ title: "Controller stack restored", blocks: [
2541
+ { kind: "fields", rows: [["Space", row.space], ["Root", row.root], ["Broker", row.server], ["Attempt", row.attemptId], ["Store", row.targetPath], ["Selection", row.selection], ["Restored", composition.restoredWords], ["Recreated empty", composition.emptyWords]] },
2542
+ { kind: "lines", lines: ["Each recorded member was started or adopted for this attempt, and the retained agents were resumed under the same principals. The restore journal stays active until its fallback is cleaned up. This is not agent or task readiness.", ...(composition.note ? [composition.note] : []), ...leftOutNotes(attemptId, result.selection, restoreOnlyCopy(root, attemptId))] },
2097
2543
  ] }] }));
2098
2544
  return values.foreground === true && !restoreSink;
2099
2545
  }
@@ -2503,7 +2949,7 @@ async function startUserAuthService(space, server, setup, publicExchange, quietB
2503
2949
  return { userAuth: info, ok: true };
2504
2950
  }
2505
2951
  catch (e) {
2506
- console.error(c.red(`✗ user-auth service did not come up (${e.message}) - user connects to "${space}" will fail until a re-\`cotal up\` succeeds`));
2952
+ stderrLine("✗ ", `user-auth service did not come up (${e.message}) - user connects to "${space}" will fail until a re-\`cotal up\` succeeds`, c.red);
2507
2953
  return { userAuth: assertUserAuthInfo(setup.prepared.publicAuth), ok: false };
2508
2954
  }
2509
2955
  }
@@ -2620,13 +3066,25 @@ export function controllerStackNative() {
2620
3066
  return {
2621
3067
  prepareBroker: async (opts) => {
2622
3068
  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.seed !== undefined ? { seed: opts.seed } : opts.channels ? { channels: opts.channels } : {}), quietBoot: true });
2623
- return { root: prepared.root, server: prepared.server, space: prepared.space, storeDir: prepared.storeDir, transport: prepared.transport, ...(prepared.setup ? { setup: { creds: prepared.setup.creds, wsPort: prepared.setup.wsPort } } : {}), ...(prepared.setup?.prepared && prepared.setup.stateDir ? { user: { prepared: prepared.setup.prepared, stateDir: prepared.setup.stateDir } } : {}), confPath: prepared.confPath, bin: prepared.bin, seedFile: prepared.seedFile };
3069
+ return { root: prepared.root, server: prepared.server, space: prepared.space, storeDir: prepared.storeDir, transport: prepared.transport, ...(prepared.setup ? { setup: { creds: prepared.setup.creds, wsPort: prepared.setup.wsPort } } : {}), ...(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 };
2624
3070
  },
2625
3071
  initializeStreams: (server, space, setup, seedFile) => postStart(server, space, setup, seedFile),
3072
+ recreateDeletedStreams: ({ seed, ...opts }) => recreateDeletedStreams({ ...opts, ...(seed !== undefined ? { seed: seed } : {}) }),
2626
3073
  recordMesh: (entry) => recordOurMesh({ ...entry, ts: new Date().toISOString() }, "started", true),
2627
3074
  commitTransport: (root, chosen) => commitTransportPolicy(root, chosen, true),
2628
3075
  };
2629
3076
  }
3077
+ /** The structured refusal for a manifest `up -f` cannot use: the located problems of one that does
3078
+ * not validate, or the read failure of one that cannot be read. Both exit 1, as the text path does. */
3079
+ function manifestFileRefusal(e, path) {
3080
+ if (e instanceof ManifestError) {
3081
+ // One line per problem: a parse error's code frame stays out of the sentence.
3082
+ const issues = e.issues.map((issue) => ({ ...issue, message: issue.message.split("\n")[0].replace(/(at line \d+, column \d+):$/, "$1") }));
3083
+ 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" });
3084
+ }
3085
+ const code = e?.code;
3086
+ return new UnusableFile(code === "ENOENT" ? `manifest file not found: ${path}` : `the manifest ${path} could not be read (${code ?? e.message})`, { file: path });
3087
+ }
2630
3088
  /** `cotal up -f cotal.yaml` — bring up a FRESH mesh from a manifest (broker + channels + booted
2631
3089
  * agents). `up -f` is a broker-CREATION command: `broker.servers` is the bind address for the NEW
2632
3090
  * local broker, never a connect target. A broker already reachable there (local OR remote) means
@@ -2659,20 +3117,20 @@ async function upManifest(file, opts) {
2659
3117
  if (opts.userAuth && declared !== "user") {
2660
3118
  if (opts.freshTeamBoot)
2661
3119
  throw new CommandFailure("refused", "CONFLICT", "--user-auth contradicts this manifest's declared auth mode; no trust or broker was changed", { target: { space: prepared.manifest.space } });
2662
- console.error(c.red(`✗ --user-auth requires manifest broker.auth: "user" (this manifest's broker.auth is ${declaredStr}). Either set broker.auth: "user" in the manifest, or drop --user-auth.`));
3120
+ stderrLine("✗ ", `--user-auth requires manifest broker.auth: "user" (this manifest's broker.auth is ${declaredStr}). Either set broker.auth: "user" in the manifest, or drop --user-auth.`, c.red);
2663
3121
  process.exit(1);
2664
3122
  }
2665
3123
  if (opts.idp && declared !== "user") {
2666
3124
  if (opts.freshTeamBoot)
2667
3125
  throw new CommandFailure("refused", "CONFLICT", "--idp needs this manifest's user-auth mode; no trust or broker was changed", { target: { space: prepared.manifest.space } });
2668
- console.error(c.red(`✗ --idp is for user-auth spaces (this manifest's broker.auth is ${declaredStr}) - set broker.auth: "user" in the manifest, or drop --idp.`));
3126
+ stderrLine("✗ ", `--idp is for user-auth spaces (this manifest's broker.auth is ${declaredStr}) - set broker.auth: "user" in the manifest, or drop --idp.`, c.red);
2669
3127
  process.exit(1);
2670
3128
  }
2671
3129
  const idpProblem = opts.idp === undefined ? undefined : idpUrlProblem(opts.idp, "--idp");
2672
3130
  if (idpProblem) {
2673
3131
  if (opts.freshTeamBoot)
2674
3132
  throw new CommandFailure("refused", "SCHEMA_INVALID", idpProblem, { target: { space: prepared.manifest.space } });
2675
- console.error(c.red(`✗ ${idpProblem}`));
3133
+ stderrLine("✗ ", `${idpProblem}`, c.red);
2676
3134
  process.exit(1);
2677
3135
  }
2678
3136
  const serverProblems = opts.server === undefined ? [] : serverUrlProblems(opts.server, "--server");
@@ -2680,7 +3138,7 @@ async function upManifest(file, opts) {
2680
3138
  if (opts.freshTeamBoot)
2681
3139
  throw new CommandFailure("refused", "SCHEMA_INVALID", serverProblems.join("; "), { target: { space: prepared.manifest.space } });
2682
3140
  for (const problem of serverProblems)
2683
- console.error(c.red(`✗ ${problem}`));
3141
+ stderrLine("✗ ", `${problem}`, c.red);
2684
3142
  process.exit(1);
2685
3143
  }
2686
3144
  // Apply CLI overrides to one effective manifest (flag > manifest > default) so render + seed +
@@ -2692,6 +3150,12 @@ async function upManifest(file, opts) {
2692
3150
  // an explicit `broker.servers` would otherwise bind one address and be probed at another.
2693
3151
  const server = m.broker?.host ? reconcileHostAndServer(m.broker.host, m.broker?.servers, "broker.host", "broker.servers") : (m.broker?.servers ?? DEFAULT_SERVER);
2694
3152
  assertTlsIntentServed(server, opts.transport, opts.server !== undefined ? "--server" : "the manifest's broker.servers");
3153
+ // A --tls-cert broker serves TLS only, so its address says tls://, as a bare up requires of --server.
3154
+ if (opts.transport.kind === "tls-required" && server.split(",").some((url) => /^nats:\/\//i.test(url.trim())))
3155
+ throw new CommandFailure("refused", "USAGE_INVALID", `--tls-cert serves the broker over TLS, so ${opts.server !== undefined ? "--server" : "the manifest's broker.servers"} must be a tls:// address; nothing was started or written`, {
3156
+ target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable" },
3157
+ remedy: opts.server !== undefined ? `pass --server ${tlsAddress(server)}` : `set broker.servers to ${tlsAddress(server)} in ${file}`,
3158
+ });
2695
3159
  const open = m.broker?.auth === false; // default is auth
2696
3160
  const userAuth = m.broker?.auth === "user" ? { idpUrl: m.broker.idp } : undefined;
2697
3161
  const runtime = m.runtime ?? "pty";
@@ -2722,6 +3186,9 @@ async function upManifest(file, opts) {
2722
3186
  // Before the dry-run print and before connector preflight or any write, as the refusals above.
2723
3187
  if (!opts.storeDir)
2724
3188
  refuseUnnamedLastStore(cotalPath("nats"));
3189
+ else
3190
+ refuseMissingNamedStore(resolve(opts.storeDir));
3191
+ checkStartStore(opts.storeDir, m.space);
2725
3192
  if (opts.dryRun) {
2726
3193
  // Dial-host SAN must refuse here too (S6). The real route runs assertServesDialHost after
2727
3194
  // the plan is computed; dry-run used to return before that check and green-lit a launch
@@ -2733,7 +3200,7 @@ async function upManifest(file, opts) {
2733
3200
  // command refuses is the same green-lit-a-refusal failure class.
2734
3201
  const dryConn = await preflightConnectors(prepared);
2735
3202
  if (dryConn) {
2736
- console.error(c.red(`✗ connector preflight failed: ${dryConn}`));
3203
+ stderrLine("✗ ", `connector preflight failed: ${dryConn}`, c.red);
2737
3204
  process.exit(1);
2738
3205
  }
2739
3206
  if (opts.transport.kind === "tls-required")
@@ -2760,18 +3227,19 @@ async function upManifest(file, opts) {
2760
3227
  // This folder's own mesh for the manifest's space is named as running, as a bare `up` names it,
2761
3228
  // with the routes that change it instead of the advice for a foreign broker.
2762
3229
  if (loadMeshes().some((row) => row.server === server && row.root === cotalRoot() && row.space === m.space)) {
2763
- console.error(c.red(`✗ 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}\``));
3230
+ 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);
2764
3231
  process.exit(1);
2765
3232
  }
2766
- console.error(c.red(`✗ ${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.`));
3233
+ 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);
2767
3234
  process.exit(1);
2768
3235
  }
3236
+ await assertBrokerAddressFree(server, `cotal up -f ${file}`);
2769
3237
  // Connectors + their required binaries must exist before any mutation (no fallback).
2770
3238
  const conn = await preflightConnectors(prepared);
2771
3239
  if (conn) {
2772
3240
  if (opts.freshTeamBoot)
2773
3241
  throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "connector preflight failed before the fresh boot intent; no native effect was requested", { target: { space: m.space }, remedy: conn });
2774
- console.error(c.red(`✗ connector preflight failed: ${conn}`));
3242
+ stderrLine("✗ ", `connector preflight failed: ${conn}`, c.red);
2775
3243
  process.exit(1);
2776
3244
  }
2777
3245
  if (opts.freshTeamBoot) {
@@ -2805,7 +3273,7 @@ async function upManifest(file, opts) {
2805
3273
  catch (e) {
2806
3274
  if (opts.freshTeamBoot)
2807
3275
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the fresh user-auth owner preparation did not confirm; trust or provider state may have changed, but no launch spec or listener was requested", { target: { space: m.space, deploymentId, root: cotalRoot() }, remedy: "inspect the retained boot intent, trust state and login before deciding another action; do not repeat an uncertain preparation" });
2808
- console.error(c.red(`✗ ${e.message}`));
3276
+ stderrLine("✗ ", `${e.message}`, c.red);
2809
3277
  process.exit(1);
2810
3278
  }
2811
3279
  }
@@ -2852,7 +3320,10 @@ async function upManifest(file, opts) {
2852
3320
  catch (e) {
2853
3321
  if (opts.freshTeamBoot)
2854
3322
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the fresh broker startup did not confirm completion after its launch spec was written; the listener or control plane may have changed state and the boot was not retried", { target: { space: m.space, deploymentId, launchSpec: specPath }, changed: [{ kind: "launch-spec-written", path: specPath }], remedy: "inspect this exact run and the recorded local listener, manager and auth state before another boot" });
2855
- console.error(c.red(`✗ ${e.message}`));
3323
+ // A classified failure, such as a certificate this client refuses, keeps its code and next step.
3324
+ if (isCommandFailure(e))
3325
+ throw e;
3326
+ stderrLine("✗ ", `${e.message}`, c.red);
2856
3327
  process.exit(1);
2857
3328
  }
2858
3329
  // Transport committed inside startMeshDetached before delivery (S5+S9).
@@ -2916,7 +3387,7 @@ async function upManifest(file, opts) {
2916
3387
  console.log(c.green(`✓ launching ${eff.agents.length} agent(s)`) + c.dim(` via manager (${runtime})${owner ? ` as you (owner ${owner})` : ""} - see ${managerLogDisplayPath(m.space)}`));
2917
3388
  }
2918
3389
  else {
2919
- console.error(c.red(`✗ ${eff.agents.length} agent(s) NOT launched - the control plane did not come up (see above)`));
3390
+ stderrLine("✗ ", `${eff.agents.length} agent(s) NOT launched - the control plane did not come up (see above)`, c.red);
2920
3391
  }
2921
3392
  // Loud summary: any persona-inherited access an `include` manifest dragged in, plus warnings.
2922
3393
  const inherited = renderInherited(eff);
@@ -2984,7 +3455,7 @@ tlsRequired, mgr) {
2984
3455
  try {
2985
3456
  const plane = await ensureControlPlane({ space, server, tls: tlsRequired, ...(mgr ?? {}) });
2986
3457
  // #1576: `up` either BINDS the responder or SAYS SO HERE. The delivery daemon is a hard
2987
- // dependency of spawn, retirement and join, and this function used to return `true` for a boot
3458
+ // dependency of spawn, retirement and the durable backstop, and this function used to return `true` for a boot
2988
3459
  // that started a daemon whose responder never bound — so `cotal up` printed its success banner
2989
3460
  // over a control plane that could not perform any of the three. The reporter's fleet ran 22
2990
3461
  // hours in that state. This is not a failure of `up` (live messaging is unaffected and the
@@ -2998,7 +3469,7 @@ tlsRequired, mgr) {
2998
3469
  // Non-fatal (live messaging is unaffected) — but never SILENT: without the manager,
2999
3470
  // `spawn --detach` / cotal_spawn have no responder, and the operator must hear it here,
3000
3471
  // not as an unexplained "no manager reachable" later.
3001
- console.error(c.dim(`! control plane degraded: ${e.message} - durable delivery/manager may be down; start one with: cotal supervise`));
3472
+ console.error(c.dim(`! control plane degraded: ${e.message} - durable delivery/manager may be down; spawn and retirement require a functioning control plane`));
3002
3473
  return undefined;
3003
3474
  }
3004
3475
  }
@@ -3046,8 +3517,8 @@ async function awaitSpawnedListener(l) {
3046
3517
  const { child, server, space } = l;
3047
3518
  let facts;
3048
3519
  try {
3049
- if (!(await waitReady(server, l.creds)))
3050
- throw new Error(`nats-server did not become reachable at ${server} - see ${l.log}`);
3520
+ if (!(await waitReady(server, l.creds, l.tls)))
3521
+ throw exitedBeforeReady(l) ?? new Error(`nats-server did not become reachable at ${server} - see ${l.log}`);
3051
3522
  facts = await brokerVersion(server, space, l.creds);
3052
3523
  }
3053
3524
  catch (e) {
@@ -3059,6 +3530,20 @@ async function awaitSpawnedListener(l) {
3059
3530
  if (l.boundListener)
3060
3531
  await l.boundListener.verify();
3061
3532
  }
3533
+ /** The failure of a listener that exited before it answered: the executable, the exit code or signal
3534
+ * Node observed, and where its output went. Undefined when no exit was observed, so a listener that
3535
+ * only stayed silent keeps an unconfirmed outcome. */
3536
+ function exitedBeforeReady(l) {
3537
+ const { exitCode, signalCode } = l.child;
3538
+ if (exitCode === null && signalCode === null)
3539
+ return undefined;
3540
+ const exit = exitCode !== null ? `exited with code ${exitCode}` : `was stopped by ${signalCode}`;
3541
+ const { path, source } = l.executable;
3542
+ return new CommandFailure("failed", "OPERATION_FAILED", `${natsServerLabel(l.executable)} ${exit} before it answered at ${l.server}; see ${l.log}`, {
3543
+ target: { executable: path, ...(exitCode !== null ? { exitCode } : { signal: signalCode }), server: l.server, log: l.log },
3544
+ remedy: source === "path" ? `read ${l.log}, then fix ${path} or take it off PATH so cotal uses its bundled nats-server, and run cotal up again` : `read ${l.log}, then run cotal up again`,
3545
+ });
3546
+ }
3062
3547
  /**
3063
3548
  * Everything a launch runs once its listener answers: the space setup, the user-auth service, the
3064
3549
  * mesh record, the transport commit and the control plane. Foreground `up` and
@@ -3117,7 +3602,7 @@ async function serveReadyListener(l) {
3117
3602
  // Commit the policy only for a listener that is up and recorded (S5), and before the control
3118
3603
  // plane (S9). startDeliveryWithBroker is HANDED the transport decision, so it does not depend on
3119
3604
  // the file at all.
3120
- commitTransportPolicy(cotalRoot(), transport, l.quietBoot);
3605
+ commitTransportPolicy(cotalRoot(), transport, l.quietBoot, server);
3121
3606
  // The delivery daemon self-gates on `.cotal/auth`, so an open mesh has none. Class-2 credential
3122
3607
  // renewal is NOT wired here: the MANAGER is the renewal owner (it is resident in every mesh mode,
3123
3608
  // where a foreground `up` process is not).
@@ -3155,6 +3640,8 @@ export async function prepareBrokerStart(opts) {
3155
3640
  refuseOpenOverUserState(Boolean(opts.open), space);
3156
3641
  const root = cotalRoot();
3157
3642
  const storeDir = opts.storeDir ? resolve(opts.storeDir) : cotalPath("nats");
3643
+ if (opts.storeDir)
3644
+ warnForeignStoreEntries(storeDir);
3158
3645
  if (opts.existingStore) {
3159
3646
  if (opts.existingStore.named !== storeDir)
3160
3647
  throw new Error("prepareBrokerStart: the pinned existing store is not the store being prepared");
@@ -3173,7 +3660,7 @@ export async function prepareBrokerStart(opts) {
3173
3660
  const port = Number(new URL(server).port) || 4222;
3174
3661
  // Same rule as the foreground path: every route to a listener names its transport (see
3175
3662
  // `writeOpenBrokerConf`). Detach must not be the mode where the fence quietly does not apply.
3176
- const confPath = setup ? setup.confPath : writeOpenBrokerConf(storeDir, { port, host, transport, maxFileStore: opts.maxFileStore });
3663
+ const confPath = setup ? setup.confPath : writeOpenBrokerConf(storeDir, space, { port, host, transport, maxFileStore: opts.maxFileStore });
3177
3664
  // Trust preparation awaits; the pinned store is checked again before its config is handed back.
3178
3665
  if (opts.existingStore)
3179
3666
  recheckExistingStore(opts.existingStore, { space, storeDir });
@@ -3181,8 +3668,8 @@ export async function prepareBrokerStart(opts) {
3181
3668
  "-c", confPath,
3182
3669
  ...(opts.boundListener ? ["--name", opts.boundListener.serverName] : []),
3183
3670
  ];
3184
- const { bin, source } = await resolveNatsServer();
3185
- return { root, server, space, useAuth, storeDir, seedFile, host, transport, setup, confPath, args, bin, source };
3671
+ const { path: bin, source, version } = await resolveNatsServer();
3672
+ return { root, server, space, useAuth, storeDir, seedFile, host, transport, setup, confPath, args, bin, source, version };
3186
3673
  }
3187
3674
  /**
3188
3675
  * Open the detached broker's log with {@link openPrivateAppend}: created `0600` whatever the umask,
@@ -3202,32 +3689,21 @@ export function openBrokerLog(path) {
3202
3689
  /**
3203
3690
  * Start a background nats-server (JetStream), wait until it's reachable, pre-create the
3204
3691
  * space's streams, and leave it running detached (pid in `.cotal/nats.pid`). Used by
3205
- * `up --detach`. When `onLine` is given, boot output is tailed from the
3206
- * log file and forwarded — the child writes to the file (not a pipe), so it survives the
3207
- * parent exiting.
3692
+ * `up --detach`. The child writes to the log file, so it survives the parent exiting.
3208
3693
  */
3209
3694
  export async function startMeshDetached(
3210
3695
  // The `= {}` default is gone with the optional transport: an options object that can be omitted
3211
3696
  // entirely cannot carry a mandatory decision.
3212
3697
  opts) {
3213
- const { server, space, useAuth, storeDir, seedFile, transport, setup, args, bin, source } = await prepareBrokerStart(opts);
3698
+ const { server, space, useAuth, storeDir, seedFile, transport, setup, args, bin, source, version } = await prepareBrokerStart(opts);
3214
3699
  const logPath = cotalPath("nats.log");
3215
3700
  const fd = openBrokerLog(logPath);
3216
- const startOffset = fstatSync(fd).size;
3217
3701
  const listenerStartedAt = new Date().toISOString();
3218
- const child = spawn(bin, args, { detached: true, stdio: ["ignore", fd, fd] });
3702
+ const child = spawn(bin, args, { cwd: cotalRoot(), detached: true, stdio: ["ignore", fd, fd] });
3219
3703
  closeSync(fd);
3220
3704
  await recordSpawnedListener(child, listenerStartedAt, opts.boundListener);
3221
3705
  child.unref();
3222
- let tailing = Boolean(opts.onLine);
3223
- if (opts.onLine)
3224
- tailLines(logPath, startOffset, opts.onLine, () => !tailing);
3225
- try {
3226
- await awaitSpawnedListener({ child, server, space, creds: setup?.creds, log: logPath, boundListener: opts.boundListener });
3227
- }
3228
- finally {
3229
- tailing = false;
3230
- }
3706
+ await awaitSpawnedListener({ child, executable: { path: bin, source, version }, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: logPath, boundListener: opts.boundListener });
3231
3707
  const { authService, controlPlane } = await serveReadyListener({
3232
3708
  child, server, space, storeDir, setup, seedFile, transport,
3233
3709
  host: opts.host,
@@ -3244,7 +3720,7 @@ opts) {
3244
3720
  return {
3245
3721
  server,
3246
3722
  pid: child.pid ?? 0,
3247
- source,
3723
+ executable: natsServerLabel({ path: bin, source, version }),
3248
3724
  controlPlane: controlPlane !== undefined,
3249
3725
  authService,
3250
3726
  deliveryResponderBound: useAuth ? controlPlane?.responderBound === true : null,
@@ -3252,6 +3728,20 @@ opts) {
3252
3728
  manager: managerUp(space),
3253
3729
  };
3254
3730
  }
3731
+ /** Refuse a broker address another program holds without answering NATS, such as a web server, as
3732
+ * the controller stack refuses it. nats-server would exit on its bind with only a log line, and the
3733
+ * readiness probe would wait on that program instead. `command` is the start the remedy reruns. */
3734
+ async function assertBrokerAddressFree(server, command) {
3735
+ const bindError = await listenerBindError(server);
3736
+ if (bindError === undefined || bindError === "timeout" || bindError.code !== "EADDRINUSE")
3737
+ return;
3738
+ const { host, port } = brokerListenAddress(server), address = new URL(server);
3739
+ const { says, frees } = addressHolder("the broker address", host, port);
3740
+ throw new CommandFailure("refused", "CONFLICT", `${says} (bind failed: address already in use); no broker was launched`, {
3741
+ target: { root: cotalRoot(), server, bindError: bindError.code },
3742
+ remedy: `start it at another address with ${command} --server ${address.protocol}//${address.hostname}:<port>, or ${frees} and run ${command} again`,
3743
+ });
3744
+ }
3255
3745
  /** THE FLIP, open-boot edition: `--open` must never boot a credless broker over a root whose
3256
3746
  * space has user-auth state on disk — that would serve the space's existing JetStream store to
3257
3747
  * anyone and re-record the mesh "open" over its user entry. The same fail-closed rule authSetup
@@ -3292,7 +3782,7 @@ function ensureRootForSpace(space) {
3292
3782
  const gone = !existsSync(prepared.root);
3293
3783
  throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `space "${space}" is prepared in ${prepared.root}${gone ? ", which no longer exists" : ""}`, {
3294
3784
  target: { space, root: prepared.root },
3295
- remedy: gone ? `forget it with \`cotal space forget ${space}\`, then start it here` : `start it with \`cotal up\` there, or \`cotal space forget ${space}\` to start it here`,
3785
+ remedy: gone ? `forget it with \`cotal space forget ${space}\`, then start it here` : `start it in its folder with \`cotal up --root ${shellWord(prepared.root)} --space ${space}\`, or \`cotal space forget ${space}\` to start it here`,
3296
3786
  });
3297
3787
  }
3298
3788
  // What spaces does this root already host? Prefer auth material; fall back to a live MeshEntry
@@ -3321,7 +3811,8 @@ function ensureRootForSpace(space) {
3321
3811
  * the prepared record with a registration, so the space this root's stack journal or its locally
3322
3812
  * started registration names comes next. Without it a second `up` in the same folder resolved the
3323
3813
  * default space and refused its own mesh. Several names there are refused, never picked. Then the
3324
- * space prepared here, then the default.
3814
+ * space prepared here. A stopped open root with none prepared names its space in the broker
3815
+ * configuration its last start rendered. Then the default.
3325
3816
  *
3326
3817
  * Only `up` asks this. `resolveSpace` also decides whether identity cleanup may attribute a root to
3327
3818
  * a space (`reset-space-plan.ts`) and, through `resolveRuntimeSpace`, which space a legacy `down`
@@ -3337,15 +3828,21 @@ function folderSpace() {
3337
3828
  });
3338
3829
  if (named.length === 1)
3339
3830
  return named[0];
3831
+ // A stopped open root holds no account, so its broker configuration names its space.
3832
+ const deployed = preparedSpaceAt(root) ? undefined : retainedOpenSpace(root);
3833
+ if (deployed)
3834
+ return deployed;
3340
3835
  }
3341
3836
  return resolveSpace(process.cwd());
3342
3837
  }
3343
- /** A bare `up` in a folder that names no space starts the default space. When the selected space
3344
- * is prepared in a folder that no longer exists, as after that folder was moved, the default is not
3345
- * what was meant, so `up` refuses with the step that prepares the selection here. */
3838
+ /** Whether `space` is the default space a bare `up` starts because this folder names none. */
3839
+ function unnamedDefault(root, space) {
3840
+ return space === DEFAULT_SPACE && soleSpaceOf(authDir(root)) === undefined && !preparedSpaceAt(root) && !localMeshesForRoot(root).length && !readStackJournal(root);
3841
+ }
3842
+ /** A bare `up` in a folder that names no space starts a space it names itself. When the selected
3843
+ * space is prepared in a folder that no longer exists, as after that folder was moved, that space is
3844
+ * not what was meant, so `up` refuses with the step that prepares the selection here. */
3346
3845
  function assertSelectionNotMoved(root, space) {
3347
- if (space !== DEFAULT_SPACE || soleSpaceOf(authDir(root)) !== undefined || preparedSpaceAt(root) || localMeshesForRoot(root).length || readStackJournal(root))
3348
- return;
3349
3846
  const current = getCurrent();
3350
3847
  const prepared = current === undefined || current === space ? undefined : findPreparedSpace(current);
3351
3848
  if (!prepared || existsSync(prepared.root))
@@ -3439,8 +3936,15 @@ export async function claimSpace(space, server, root) {
3439
3936
  throw new CommandFailure("refused", "CONFLICT", `space "${space}" is registered to a mesh at ${existing.server} (${existing.root}) - it is ${existing.origin === "catalog" ? "owned by a signed-in space catalog" : "registered by hand"}, so \`cotal up\` neither takes it over nor reclaims the name`, { target, remedy: existing.origin === "catalog" ? "use a different `--space`, or remove access at the IdP and run `cotal sync`" : manualClaimRemedy(space, existing.server) });
3440
3937
  if (relative)
3441
3938
  throw new CommandFailure("refused", "CONFLICT", `space "${space}" is registered to ${existing.root}, which is not an absolute path - \`cotal up\` did not take the name`, { target, remedy: `drop that record with \`cotal meshes rm ${space}\`, or start this stack under a different \`--space\`` });
3442
- if (await isReachable(existing.server))
3443
- throw new CommandFailure("refused", "CONFLICT", `space "${space}" is already in use by a mesh at ${existing.server} (${existing.root})`, { target, remedy: "pick a different `--space`, or `cotal down` it first" });
3939
+ if (await isReachable(existing.server)) {
3940
+ // A space name is this machine's, so a separate space here needs a name of its own.
3941
+ let controller = false;
3942
+ try {
3943
+ controller = readStackJournal(existing.root)?.journal.space === space;
3944
+ }
3945
+ catch { /* named with the legacy stop */ }
3946
+ throw new CommandFailure("refused", "CONFLICT", `space "${space}" is already in use by a mesh at ${existing.server} (${existing.root})`, { target, remedy: `start a separate space in this folder with cotal up --space <name>, naming one no other folder uses, or stop "${space}" first with cotal down${controller ? " --yes" : ""} in ${shellWord(existing.root)}` });
3947
+ }
3444
3948
  // The recorded root is this root only where it physically resolves, so it is resolved before any
3445
3949
  // comparison, and one that cannot be resolved refuses. A dead holder at another root keeps its name
3446
3950
  // while that root holds a preserved cut or a restore: taking it would cut that root's recovery off
@@ -3507,8 +4011,8 @@ function journaledMaxFileStore(value) {
3507
4011
  export const recordOurMeshForTest = (m, provenance) => recordOurMesh(m, provenance);
3508
4012
  /** Record this mesh in the registry, and set it as the `current` default when there's no usable one
3509
4013
  * — i.e. the first mesh, OR when `current` dangles at a space that's no longer in the registry (a
3510
- * ghost pointer is not a default). Never silently redirect a `current` that still resolves to a live
3511
- * mesh; just say another is the default and how to switch. */
4014
+ * ghost pointer is not a default), and say so. Never silently redirect a `current` that still resolves
4015
+ * to a live mesh; just say another is the default and how to switch. */
3512
4016
  function recordOurMesh(m, provenance, quietBoot = false) {
3513
4017
  const cur = getCurrent();
3514
4018
  const usableCurrent = cur && (findMesh(cur) || findPreparedSpace(cur)) ? cur : undefined; // compute before recording m
@@ -3526,10 +4030,12 @@ function recordOurMesh(m, provenance, quietBoot = false) {
3526
4030
  removePreparedSpace(m.space); // started: the registration is its record now
3527
4031
  if (!usableCurrent) {
3528
4032
  setCurrent(m.space);
4033
+ if (!quietBoot)
4034
+ console.log(c.dim(selectedOnUp(m.space)));
3529
4035
  return;
3530
4036
  }
3531
4037
  if (usableCurrent !== m.space && !quietBoot)
3532
- console.log(c.dim(`"${m.space}" up; current is still "${usableCurrent}" - \`cotal use ${m.space}\` to switch`));
4038
+ console.log(c.dim(keptOnUp(m.space, usableCurrent)));
3533
4039
  }
3534
4040
  /** Write the default persona into the root this `up` started or refreshed when it has none, and
3535
4041
  * say so. The mesh is already up, so a write that fails is reported and the start stands. */
@@ -3545,45 +4051,49 @@ function seedPersonaAfterUp(root, quiet = false) {
3545
4051
  if (written && !quiet)
3546
4052
  console.log(c.dim(` wrote ${written.what}: ${written.path}`));
3547
4053
  }
3548
- /** Poll a growing log file and forward newly-appended lines until `stopped()` is true. */
3549
- function tailLines(path, from, onLine, stopped) {
3550
- let offset = from;
3551
- const tick = () => {
3552
- if (stopped())
3553
- return;
3554
- try {
3555
- const size = statSync(path).size;
3556
- if (size > offset) {
3557
- const fd = openSync(path, "r");
3558
- const buf = Buffer.alloc(size - offset);
3559
- readSync(fd, buf, 0, buf.length, offset);
3560
- closeSync(fd);
3561
- offset = size;
3562
- for (const line of buf.toString("utf8").split("\n"))
3563
- if (line.trim())
3564
- onLine(line);
3565
- }
3566
- }
3567
- catch {
3568
- // file may not exist yet on the first ticks — keep polling
3569
- }
3570
- setTimeout(tick, 150);
3571
- };
3572
- setTimeout(tick, 150);
3573
- }
3574
- async function waitReady(server, creds) {
4054
+ async function waitReady(server, creds, tls = false) {
3575
4055
  for (let i = 0; i < 50; i++) {
3576
- if (await isReachable(server, creds ? { creds } : undefined))
4056
+ // An open listener answers the plaintext probe before any handshake, so TLS is checked either way.
4057
+ const reachable = await isReachable(server, creds ? { creds } : undefined);
4058
+ if (tls)
4059
+ await refuseUntrustedListener(server, creds);
4060
+ if (reachable)
3577
4061
  return true;
3578
4062
  await new Promise((r) => setTimeout(r, 200));
3579
4063
  }
3580
4064
  return false;
3581
4065
  }
4066
+ /** Node's codes for a certificate chain this client does not trust. */
4067
+ const UNTRUSTED_CERTIFICATE = new Set(["DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN", "UNABLE_TO_GET_ISSUER_CERT", "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "CERT_UNTRUSTED"]);
4068
+ /** Throw when the TLS listener at `server` answers and this client refuses its certificate in the
4069
+ * handshake, which waiting does not change. It dials as the setup that follows does. */
4070
+ async function refuseUntrustedListener(server, creds) {
4071
+ let code, reason = "";
4072
+ try {
4073
+ const nc = await dialerFor(server)({ servers: server, timeout: 1_000, reconnect: false, maxReconnectAttempts: 0, ...standaloneConnectOpts({ creds, tls: false }) });
4074
+ await nc.close();
4075
+ return;
4076
+ }
4077
+ catch (e) {
4078
+ code = e?.code;
4079
+ reason = e instanceof Error ? e.message.split(";")[0] : String(e);
4080
+ }
4081
+ const untrusted = typeof code === "string" && UNTRUSTED_CERTIFICATE.has(code);
4082
+ if (!untrusted && code !== "ERR_TLS_CERT_ALTNAME_INVALID")
4083
+ return;
4084
+ const { hostname, port } = new URL(server);
4085
+ throw new CommandFailure("failed", "OPERATION_FAILED", `nats-server answered at ${server}, but this client refused its TLS certificate in the handshake (${reason}); up stopped it and recorded nothing`, {
4086
+ native: { code: String(code) },
4087
+ remedy: untrusted
4088
+ ? "trust the certificate's CA, or a self-signed certificate itself, by setting NODE_EXTRA_CA_CERTS to that PEM file for cotal up and every cotal command of this space, then run cotal up again"
4089
+ : /^tls:/i.test(server) ? `serve a certificate that names ${hostname}, then run cotal up again` : `pass --server tls://${hostname}:${port}, so every dial checks the certificate against ${hostname}`,
4090
+ });
4091
+ }
3582
4092
  /** The broker's version, and whether `space`'s presence stream exists file-backed. Cotal creates
3583
4093
  * it in memory (#1356), so only a bucket an older cotal created is file-backed; an absent one
3584
4094
  * will be created in memory by `setupSpaceStreams`. */
3585
4095
  async function brokerVersion(server, space, creds) {
3586
- const nc = await connect({ servers: server, ...standaloneConnectOpts({ creds, tls: false }) });
4096
+ const nc = await dialerFor(server)({ servers: server, ...standaloneConnectOpts({ creds, tls: false }) });
3587
4097
  try {
3588
4098
  requireBrokerFloor(nc);
3589
4099
  const version = nc.info?.version ?? "";
@@ -3716,17 +4226,43 @@ async function assertFreshTeamBindAvailable(server, host, space) {
3716
4226
  }
3717
4227
  });
3718
4228
  }
4229
+ /** Choose only a first implicit address. A saved or explicitly requested address is never moved.
4230
+ * The broker still validates and binds its own listener; this inspection cannot reserve the port. */
4231
+ async function freshStackServer(server, bindHost) {
4232
+ const url = new URL(server);
4233
+ const host = (bindHost ?? url.hostname).replace(/^\[|\]$/g, "");
4234
+ const reserved = new Set(loadMeshes().map((mesh) => {
4235
+ const address = new URL(mesh.server);
4236
+ return `${address.hostname}:${address.port || "4222"}`;
4237
+ }));
4238
+ let candidate = server;
4239
+ for (let attempt = 0; attempt < 16; attempt++) {
4240
+ const address = new URL(candidate);
4241
+ if (!reserved.has(`${address.hostname}:${address.port || "4222"}`)) {
4242
+ try {
4243
+ await freePort(host, Number(address.port) || 4222);
4244
+ return candidate;
4245
+ }
4246
+ catch (error) {
4247
+ if (error.code !== "EADDRINUSE")
4248
+ throw error;
4249
+ }
4250
+ }
4251
+ candidate = await serverWithFreePort(server, host);
4252
+ }
4253
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "no unreserved local broker address could be selected; no broker was started");
4254
+ }
3719
4255
  async function serverWithFreePort(server, host) {
3720
4256
  const url = new URL(server);
3721
4257
  url.port = String(await freePort(host));
3722
4258
  return url.toString();
3723
4259
  }
3724
- function freePort(host) {
4260
+ function freePort(host, requestedPort = 0) {
3725
4261
  return new Promise((resolve, reject) => {
3726
4262
  const srv = createServer();
3727
4263
  srv.unref();
3728
4264
  srv.once("error", reject);
3729
- srv.listen(0, host, () => {
4265
+ srv.listen(requestedPort, host, () => {
3730
4266
  const addr = srv.address();
3731
4267
  const port = typeof addr === "object" && addr ? addr.port : undefined;
3732
4268
  srv.close((err) => {
@@ -3767,7 +4303,7 @@ async function postStart(server, space, setup, seedFile) {
3767
4303
  * it, stream and all (#1356 made presence memory-backed). Recreate those, and only those, from the
3768
4304
  * same `ttlBuckets` list `setupSpaceStreams` creates them from, before any daemon opens them. */
3769
4305
  async function recreateMemoryBuckets(server, space, setup) {
3770
- const nc = await connect({ servers: server, ...standaloneConnectOpts({ creds: setup?.creds, tls: false }) });
4306
+ const nc = await dialerFor(server)({ servers: server, ...standaloneConnectOpts({ creds: setup?.creds, tls: false }) });
3771
4307
  try {
3772
4308
  requireBrokerFloor(nc);
3773
4309
  const kvm = new Kvm(nc);
@@ -3789,6 +4325,52 @@ async function recreateAdoptedMemoryBuckets(root, space, server, mode) {
3789
4325
  throw new Error(`space "${space}" has no trust material under ${authDir(root)}; cannot recreate its memory buckets on the adopted listener`);
3790
4326
  await recreateMemoryBuckets(server, space, { creds: await mintCreds(auth, newIdentity(), "provisioner") });
3791
4327
  }
4328
+ /** `cotal space delete` removes a space's streams from a broker that keeps running. When a stack
4329
+ * reuses that broker and every canonical stream of the space is gone, create them again, empty, as
4330
+ * a broker start does, and return true. A broker that still holds any of them is left as it is. */
4331
+ async function recreateDeletedStreams(opts) {
4332
+ let setup;
4333
+ if (opts.mode === "auth") {
4334
+ const auth = await getSpaceAuth(workspaceSecretStore(opts.root), opts.space);
4335
+ if (!auth)
4336
+ throw new Error(`space "${opts.space}" has no trust material under ${authDir(opts.root)}; cannot read its streams on the running broker`);
4337
+ setup = { creds: await mintCreds(auth, newIdentity(), "provisioner") };
4338
+ }
4339
+ else if (opts.mode !== "open")
4340
+ throw new Error("a user-auth stack's streams are not recreated on a running broker");
4341
+ const nc = await dialerFor(opts.server)({ servers: opts.server, ...standaloneConnectOpts({ creds: setup?.creds, tls: false }) });
4342
+ let held = false;
4343
+ try {
4344
+ requireBrokerFloor(nc);
4345
+ const jsm = await jetstreamManager(nc);
4346
+ for (const name of spaceDeletionStreams(opts.space)) {
4347
+ try {
4348
+ await jsm.streams.info(name);
4349
+ held = true;
4350
+ break;
4351
+ }
4352
+ catch (error) {
4353
+ if (!isJetStreamMissing(error, JetStreamApiCodes.StreamNotFound))
4354
+ throw error;
4355
+ }
4356
+ }
4357
+ }
4358
+ finally {
4359
+ await nc.drain();
4360
+ }
4361
+ if (held)
4362
+ return false;
4363
+ await postStart(opts.server, opts.space, setup, opts.seed ?? loadChannelsFile(opts.channels));
4364
+ return true;
4365
+ }
4366
+ /** `--max-file-store`, refused below {@link MIN_FILE_STORE}: a smaller cap cannot create the
4367
+ * space's streams. */
4368
+ function parseMaxFileStore(raw) {
4369
+ const cap = parsePositiveIntegerFlag("--max-file-store", raw);
4370
+ if (cap !== undefined && cap < MIN_FILE_STORE)
4371
+ throw new CommandFailure("refused", "USAGE_INVALID", `--max-file-store ${cap} is below ${MIN_FILE_STORE} bytes, the least the space's streams start on: its membership bucket reserves ${MEMBERSHIP_MAX_BYTES} bytes (64 MiB) of the broker's file store, and nats-server needs one more byte free to create the others; nothing was started`, { remedy: `pass --max-file-store ${MIN_FILE_STORE} or more, leaving room for messages, or omit it` });
4372
+ return cap;
4373
+ }
3792
4374
  /** Load the declarative channels-config file to seed the registry. An explicit `--channels`
3793
4375
  * path that's missing is a hard error; the default `.cotal/channels.json` is optional (absent
3794
4376
  * ⇒ nothing to seed). */
@@ -3798,24 +4380,112 @@ function loadChannelsFile(explicit) {
3798
4380
  const path = cotalPath("channels.json");
3799
4381
  if (!existsSync(path))
3800
4382
  return undefined;
3801
- return JSON.parse(readFileSync(path, "utf8"));
4383
+ return readChannelsFile(path, false);
3802
4384
  }
3803
- /** Read and parse an explicit `--channels` file. One that is missing, unreadable or not JSON is a
3804
- * usage refusal that names its path. */
3805
- function readChannelsFile(path) {
4385
+ /** Refuse `up --space` of a space this machine started from another folder while its broker answers,
4386
+ * naming that folder: the stack there is the one to use or stop. */
4387
+ async function refuseRunningElsewhere(space, root) {
4388
+ const owner = findMesh(space);
4389
+ if (!owner || owner.origin === "manual" || owner.origin === "catalog" || !isAbsolute(owner.root) || canonicalRoot(owner.root) === canonicalRoot(root) || !(await isReachable(owner.server)))
4390
+ return;
4391
+ let controller = false;
4392
+ try {
4393
+ controller = readStackJournal(owner.root)?.journal.space === space;
4394
+ }
4395
+ catch { /* named with the legacy stop */ }
4396
+ throw new CommandFailure("refused", "CONFLICT", `space "${space}" runs at ${owner.server}, started in ${owner.root}, so up did not start it again`, { target: { space, root: owner.root, server: owner.server }, remedy: `use it from here with --space ${space}, or stop it with cotal down${controller ? " --yes" : ""} in ${owner.root}` });
4397
+ }
4398
+ /** The channels files one `up` has read, by path. It reads its seed when it checks the flags, when it
4399
+ * prepares the broker and when it seeds the registry, and `--channels` may name a pipe or a FIFO,
4400
+ * which a second open finds empty or waits on for a writer that is gone. */
4401
+ const channelsReads = new AsyncLocalStorage();
4402
+ /** Read, parse and check a channels file: `explicit` is a `--channels` path, else the root's default
4403
+ * `.cotal/channels.json`. A `--channels` path that is missing, unreadable or not JSON is a usage
4404
+ * refusal. A default file that is not JSON, and either file whose content the registry would not
4405
+ * take, is a schema refusal. Each names the file. */
4406
+ function readChannelsFile(path, explicit = true) {
4407
+ const read = channelsReads.getStore()?.get(path);
4408
+ if (read)
4409
+ return read;
4410
+ const remedy = explicit ? "fix the file, or omit --channels" : `fix or remove ${path}`;
3806
4411
  let text;
4412
+ // A default file that is a FIFO or a device would block the read with no writer, so only a regular
4413
+ // default file is opened. An explicit path may name a pipe such as `<(…)`, read once (see `channelsReads`).
4414
+ if (!explicit && statSync(path, { throwIfNoEntry: false })?.isFile() === false)
4415
+ throw new CommandFailure("refused", "USAGE_INVALID", `the channels file ${path} is not a regular file, such as a FIFO; it was not read`, { remedy });
3807
4416
  try {
3808
4417
  text = readFileSync(path, "utf8");
3809
4418
  }
3810
4419
  catch {
3811
- throw new CommandFailure("refused", "USAGE_INVALID", `the channels file ${path} is missing or unreadable`, { remedy: "name an existing channels file with --channels <path>, or omit --channels" });
3812
- }
4420
+ throw new CommandFailure("refused", "USAGE_INVALID", `the channels file ${path} is missing or unreadable`, { remedy: explicit ? "name an existing channels file with --channels <path>, or omit --channels" : remedy });
4421
+ }
4422
+ const encoding = utf16Problem(text);
4423
+ if (encoding)
4424
+ throw new CommandFailure("refused", "USAGE_INVALID", `the channels file ${path} cannot be read: ${encoding}`, { remedy: `save ${path} as UTF-8` });
4425
+ let value;
4426
+ // An editor on Windows can begin the file with a UTF-8 byte-order mark, which RFC 8259 lets a
4427
+ // reader ignore.
3813
4428
  try {
3814
- return JSON.parse(text);
4429
+ value = JSON.parse(text.replace(/^\uFEFF/, ""));
3815
4430
  }
3816
4431
  catch (error) {
3817
- throw new CommandFailure("refused", "USAGE_INVALID", `the channels file ${path} is not valid JSON (${error.message})`, { remedy: "fix the file, or omit --channels" });
4432
+ throw new CommandFailure("refused", "USAGE_INVALID", `the channels file ${path} is not valid JSON (${error.message})`, { remedy });
4433
+ }
4434
+ const problem = channelsFileProblem(value);
4435
+ if (problem)
4436
+ throw new CommandFailure("refused", "SCHEMA_INVALID", `the channels file ${path} is invalid: ${problem}`, { remedy });
4437
+ channelsReads.getStore()?.set(path, value);
4438
+ return value;
4439
+ }
4440
+ const CHANNEL_DEFAULT_FIELDS = { replay: true, replayWindow: true, deliveryClass: true };
4441
+ const CHANNEL_FIELDS = { ...CHANNEL_DEFAULT_FIELDS, description: true, instructions: true };
4442
+ /** Why the registry would not take this seed: the shape, an unknown key, a channel name `channel set`
4443
+ * refuses, or a field value the registry's write checks refuse. Undefined when every entry passes. */
4444
+ function channelsFileProblem(value) {
4445
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4446
+ const fieldsProblem = (where, entry, fields, check) => {
4447
+ if (!isObject(entry))
4448
+ return `${where} must be an object`;
4449
+ for (const [field, fieldValue] of Object.entries(entry)) {
4450
+ if (!Object.hasOwn(fields, field))
4451
+ return `${where} has an unknown key ${JSON.stringify(field)}; it takes ${Object.keys(fields).join(", ")}`;
4452
+ try {
4453
+ check({ [field]: fieldValue });
4454
+ }
4455
+ catch (error) {
4456
+ return `${where} ${field}: ${error.message}`;
4457
+ }
4458
+ }
4459
+ return undefined;
4460
+ };
4461
+ if (!isObject(value))
4462
+ return 'it must be a JSON object with "defaults" and "channels"';
4463
+ for (const key of Object.keys(value))
4464
+ if (key !== "defaults" && key !== "channels")
4465
+ return `unknown key ${JSON.stringify(key)}; the file takes "defaults" and "channels"`;
4466
+ if (value.defaults !== undefined) {
4467
+ const problem = fieldsProblem('"defaults"', value.defaults, CHANNEL_DEFAULT_FIELDS, validateChannelDefaults);
4468
+ if (problem)
4469
+ return problem;
4470
+ }
4471
+ if (value.channels === undefined)
4472
+ return undefined;
4473
+ if (!isObject(value.channels))
4474
+ return '"channels" must be an object of channel names';
4475
+ for (const [name, config] of Object.entries(value.channels)) {
4476
+ try {
4477
+ assertValidChannel(name);
4478
+ }
4479
+ catch (error) {
4480
+ return error.message;
4481
+ }
4482
+ if (!isConcreteChannel(name))
4483
+ return `channel ${JSON.stringify(name)} is a wildcard; name one concrete channel`;
4484
+ const problem = fieldsProblem(`channel ${JSON.stringify(name)}`, config, CHANNEL_FIELDS, validateChannelConfig);
4485
+ if (problem)
4486
+ return problem;
3818
4487
  }
4488
+ return undefined;
3819
4489
  }
3820
4490
  /**
3821
4491
  * Turn the `--tls-cert`/`--tls-key` pair into a validated {@link BrokerTransport}, or `plaintext`
@@ -3853,7 +4523,7 @@ opts = {}) {
3853
4523
  recorded = readBrokerPolicy(root);
3854
4524
  }
3855
4525
  catch (e) {
3856
- console.error(c.red(`✗ ${e instanceof Error ? e.message : String(e)}`));
4526
+ stderrLine("✗ ", `${e instanceof Error ? e.message : String(e)}`, c.red);
3857
4527
  process.exit(1);
3858
4528
  }
3859
4529
  if (recorded?.transport.kind === "tls-required") {
@@ -3866,7 +4536,7 @@ opts = {}) {
3866
4536
  // Half a pair is a mistake, never a configuration. Refusing names the missing half rather than
3867
4537
  // failing later inside nats-server with a message about a file the operator did not mention.
3868
4538
  if (!certFile || !keyFile) {
3869
- console.error(c.red(`✗ --tls-cert and --tls-key must be given together (missing ${certFile ? "--tls-key" : "--tls-cert"})`));
4539
+ stderrLine("✗ ", `--tls-cert and --tls-key must be given together (missing ${certFile ? "--tls-key" : "--tls-cert"})`, c.red);
3870
4540
  process.exit(1);
3871
4541
  }
3872
4542
  const transport = { kind: "tls-required", certFile: resolve(certFile), keyFile: resolve(keyFile) };
@@ -3885,19 +4555,21 @@ function assertTlsIntentServed(server, transport, source) {
3885
4555
  throw new CommandFailure("refused", "USAGE_INVALID", `${source} names a tls:// address, but no TLS certificate and key are configured, so the broker would serve plaintext; nothing was started`, { target: { server: brokerAddressForDisplay(server) ?? "not displayable" }, remedy: "serve TLS with --tls-cert <cert.pem> --tls-key <key.pem>, or use a nats:// address" });
3886
4556
  }
3887
4557
  /** Persist a transport after its listener starts; a structured boot leaves stdout to its receipt. */
3888
- function commitTransportPolicy(root, transport, quietBoot = false) {
4558
+ function commitTransportPolicy(root, transport, quietBoot = false, server) {
3889
4559
  if (transport.kind !== "tls-required")
3890
4560
  return;
3891
4561
  writeBrokerPolicy(root, { version: 1, transport });
3892
4562
  if (!quietBoot)
3893
- announceTransport(transport);
4563
+ announceTransport(transport, server);
3894
4564
  }
3895
- function announceTransport(transport) {
4565
+ /** The `tls://` form of a broker URL, or of each URL in a list. */
4566
+ const tlsAddress = (server) => server.split(",").map((url) => url.trim().replace(/^nats:/i, "tls:")).join(",");
4567
+ function announceTransport(transport, server) {
3896
4568
  if (transport.kind !== "tls-required")
3897
4569
  return;
3898
4570
  try {
3899
4571
  const material = validateTlsMaterial(transport, {});
3900
- console.log(c.dim(`TLS: serving ${material.subject}, valid until ${material.notAfter.toISOString()}`));
4572
+ console.log(c.dim(`TLS: serving ${material.subject}${server ? ` at ${server}` : ""}, valid until ${material.notAfter.toISOString()}`));
3901
4573
  }
3902
4574
  catch {
3903
4575
  // Already validated at decide-time; announce is best-effort display.
@@ -3965,7 +4637,7 @@ function assertServesDialHost(transport, dialHost) {
3965
4637
  validateTlsMaterial(transport, { dialHost });
3966
4638
  }
3967
4639
  catch (e) {
3968
- console.error(c.red(`✗ ${e instanceof Error ? e.message : String(e)}`));
4640
+ stderrLine("✗ ", `${e instanceof Error ? e.message : String(e)}`, c.red);
3969
4641
  process.exit(1);
3970
4642
  }
3971
4643
  return transport;
@@ -3988,7 +4660,7 @@ function adoptedTlsRequired(root) {
3988
4660
  return readBrokerPolicy(root)?.transport.kind === "tls-required";
3989
4661
  }
3990
4662
  catch (e) {
3991
- console.error(c.red(`✗ ${e instanceof Error ? e.message : String(e)}`));
4663
+ stderrLine("✗ ", `${e instanceof Error ? e.message : String(e)}`, c.red);
3992
4664
  process.exit(1);
3993
4665
  }
3994
4666
  }
@@ -4004,30 +4676,45 @@ function validateRecorded(transport, dialHost, opts = {}) {
4004
4676
  catch (e) {
4005
4677
  // Surface the CERTIFICATE cause. A TLS failure reported as a generic startup error invites the
4006
4678
  // wrong remedy - operators go looking at ports and firewalls when the answer is the cert.
4007
- console.error(c.red(`✗ ${e instanceof Error ? e.message : String(e)}`));
4679
+ stderrLine("✗ ", `${e instanceof Error ? e.message : String(e)}`, c.red);
4008
4680
  process.exit(1);
4009
4681
  }
4010
4682
  return transport;
4011
4683
  }
4012
- /** `down` drops the record that named a custom or restored store, so a later start that names none
4013
- * would open an empty second store and leave the data where it was. Each real start writes its
4014
- * `store_dir` into the broker config it renders, and that file outlives `down`: while the store it
4015
- * names differs and still holds JetStream data, and the default store holds none, refuse and name it. */
4684
+ /** A start that names no store would open an empty second store and leave the data where it was:
4685
+ * while the last served store holds data and the default store holds none, refuse and name it. */
4016
4686
  function refuseUnnamedLastStore(storeDir) {
4017
4687
  if (existsSync(join(storeDir, "jetstream")))
4018
4688
  return;
4019
- for (const conf of [join(authDir(cotalRoot()), "server.conf"), cotalPath("server-open.conf")]) {
4020
- if (!existsSync(conf))
4021
- continue;
4022
- // The core renderer writes the path as a JSON string.
4023
- const named = /jetstream \{ store_dir: ("(?:[^"\\]|\\.)*")/.exec(readFileSync(conf, "utf8"))?.[1];
4024
- const last = named === undefined ? undefined : resolve(JSON.parse(named));
4025
- if (last !== undefined && last !== resolve(storeDir) && existsSync(join(last, "jetstream")))
4026
- throw new CommandFailure("refused", "CONFLICT", `this root's last broker served the store ${last}, and this start names no store, so it would open a new empty one at ${storeDir}; nothing was started`, { target: { root: cotalRoot(), storeDir: last }, remedy: `reopen it with --store-dir ${last}, or move that store away to start empty` });
4027
- }
4689
+ const last = lastServedStore(cotalRoot(), storeDir);
4690
+ if (last !== undefined)
4691
+ throw new CommandFailure("refused", "CONFLICT", `this root's last broker served the store ${last}, and this start names no store, so it would open a new empty one at ${storeDir}; nothing was started`, { target: { root: cotalRoot(), storeDir: last }, remedy: `reopen it with --store-dir ${last}, or move that store away to start empty` });
4692
+ }
4693
+ /** A `--store-dir` that does not exist yet, while the last served store holds data, is taken for a
4694
+ * mistyped path: the start would open a new empty store there. Creating the directory first names a
4695
+ * new store on purpose. */
4696
+ function refuseMissingNamedStore(storeDir) {
4697
+ if (existsSync(storeDir))
4698
+ return;
4699
+ const last = lastServedStore(cotalRoot(), storeDir);
4700
+ if (last !== undefined)
4701
+ throw new CommandFailure("refused", "CONFLICT", `this root's last broker served the store ${last}, and --store-dir names ${storeDir}, which does not exist, so this start would open a new empty store there; nothing was started`, { target: { root: cotalRoot(), storeDir: last, requested: storeDir }, remedy: `reopen it with --store-dir ${last}, or create ${storeDir} first to start on a new empty store` });
4702
+ }
4703
+ /** A start's store against the other spaces that use it. A `--store-dir` this root's last broker did
4704
+ * not serve refuses while another space uses it. The default or last served store starts with a
4705
+ * warning, and one whose folder that broker served is missing starts empty with a warning. */
4706
+ function checkStartStore(storeDir, space) {
4707
+ const path = storeDir === undefined ? cotalPath("nats") : resolve(storeDir);
4708
+ const served = servedStore(cotalRoot(), path);
4709
+ const tenants = sharedStoreAtStart(path, space, storeDir === undefined || served);
4710
+ if (tenants.length)
4711
+ console.error(c.yellow(`! ${sharedStoreWarning(path, tenants)}`));
4712
+ if (served && !existsSync(path))
4713
+ console.error(c.yellow(`! ${missingStoreWarning(path)}`));
4028
4714
  }
4029
4715
  /**
4030
- * Render and write the config for an OPEN (no-auth) broker, returning its path.
4716
+ * Render and write the config for an OPEN (no-auth) broker, returning its path. It names `space`,
4717
+ * because an open root holds no account that would ({@link namedOpenConfig}).
4031
4718
  *
4032
4719
  * The `authSetup` sibling for the no-auth mode. Open mode previously launched nats-server from
4033
4720
  * bare CLI flags and so never passed through any renderer — meaning the REQUIRED transport union
@@ -4036,11 +4723,39 @@ function refuseUnnamedLastStore(storeDir) {
4036
4723
  * mode through a renderer is what makes the union total: there is now no route to a listener that
4037
4724
  * does not state its transport.
4038
4725
  */
4039
- function writeOpenBrokerConf(storeDir, opts) {
4726
+ function writeOpenBrokerConf(storeDir, space, opts) {
4040
4727
  const confPath = cotalPath("server-open.conf");
4041
- writeSecretFile(confPath, openServerConfig({ port: opts.port, host: opts.host, storeDir, maxFileStore: opts.maxFileStore, transport: opts.transport }));
4728
+ writeBrokerConfig(confPath, namedOpenConfig(openServerConfig({ port: opts.port, host: opts.host, storeDir: configuredStoreDir(cotalRoot(), storeDir), maxFileStore: opts.maxFileStore, transport: opts.transport }), space));
4042
4729
  return confPath;
4043
4730
  }
4731
+ /** Write a broker configuration that `up` renders again on every start. Something other than this
4732
+ * account's own regular file at its path, such as a symlink or a folder, is refused by name and
4733
+ * left as it is. Moving it aside loses nothing, because the next `up` writes the file again. */
4734
+ function writeBrokerConfig(path, text) {
4735
+ try {
4736
+ writeSecretFile(path, text);
4737
+ }
4738
+ catch (error) {
4739
+ const code = error.code;
4740
+ if (code !== "EPERM" && code !== "EISDIR" && code !== "EACCES")
4741
+ throw error;
4742
+ const entry = lstatSync(path, { throwIfNoEntry: false });
4743
+ const what = entry?.isSymbolicLink() ? "is a symlink" : entry?.isDirectory() ? "is a folder" : code === "EACCES" ? "cannot be written by this account" : "is not a regular file this account owns";
4744
+ throw new CommandFailure("refused", "PERMISSION_DENIED", `the broker configuration ${path} ${what}, so up cannot write it; it was left as it is and nothing was started`, {
4745
+ target: { path }, remedy: `move it aside, as mv ${shellWord(path)} ${shellWord(`${path}.old`)} does, then run cotal up again, which writes it from the space's trust`,
4746
+ });
4747
+ }
4748
+ }
4749
+ /** The refusal for a trust record of the space that this account cannot read. It holds the space's
4750
+ * keys, so the step makes it readable again and never removes it. Any other error as it is. */
4751
+ function unreadableTrust(error) {
4752
+ const { code, path } = error;
4753
+ if (code !== "EACCES" && code !== "EPERM" || typeof path !== "string")
4754
+ return error;
4755
+ return new CommandFailure("refused", "PERMISSION_DENIED", `the space's trust record ${path} cannot be read by this account (${code}); nothing was started`, {
4756
+ target: { path }, remedy: `make it readable by you again, as chmod 600 ${shellWord(path)} does, then run cotal up again; it holds the space's keys, so keep it`,
4757
+ });
4758
+ }
4044
4759
  /** Ensure the space's trust material exists, render a server config, and mint a privileged
4045
4760
  * setup creds (used to pre-create streams once the server is up). The account signing key
4046
4761
  * in `.cotal/auth` is what `cotal mint` and the manager later use to issue per-agent creds.
@@ -4065,12 +4780,17 @@ async function authSetup(storeDir, server, space, host = "127.0.0.1", user,
4065
4780
  transport, rotateSys = false, maxFileStore, quietBoot = false) {
4066
4781
  const dir = authDir(cotalRoot()); // the broker config (server.conf) still lands under the FS auth dir
4067
4782
  const store = workspaceSecretStore(cotalRoot());
4068
- let auth = await getSpaceAuth(store, space);
4783
+ let auth = await getSpaceAuth(store, space).catch((error) => { throw unreadableTrust(error); });
4069
4784
  if (!auth) {
4070
4785
  auth = await createSpaceAuth(space);
4071
- await putSpaceAuth(store, auth); // strips the $SYS seed at rest, but leaves the in-memory `auth` intact …
4072
- await retainSystemSigningSeed(store, auth); // … and the host keeps the seed itself, beside the record, for own-broker caller issuance
4073
- await provisionMembershipCreds(auth, cotalRoot(), space); // … so the observer can still be minted here (fresh-space only)
4786
+ // The trust record is written last. Until it exists the next up treats the space as fresh and
4787
+ // mints all of this again, so an up stopped partway never leaves a space without its $SYS creds.
4788
+ await provisionMembershipCreds(auth, cotalRoot(), space); // the observer is minted while the $SYS seed is in memory (fresh-space only)
4789
+ // Smoke only: hold a new space with part of its material written, so a signal can land there.
4790
+ if (process.env.COTAL_SMOKE_HOLD_IN_SPACE_AUTH === "1")
4791
+ await new Promise((done) => setTimeout(done, 60_000));
4792
+ await retainSystemSigningSeed(store, auth); // the host keeps the seed itself, beside the record, for own-broker caller issuance
4793
+ await putSpaceAuth(store, auth); // strips the $SYS seed at rest
4074
4794
  // A fresh space's $SYS material was just minted from the seed this branch holds in memory, so
4075
4795
  // the ASK is already satisfied, so say so rather than rotating a one-second-old account, and never
4076
4796
  // report a rotation that did not happen.
@@ -4174,7 +4894,7 @@ transport, rotateSys = false, maxFileStore, quietBoot = false) {
4174
4894
  }
4175
4895
  // Owner-private regardless of umask, as `writeOpenBrokerConf` writes the open configuration: the
4176
4896
  // broker preset refuses a configuration that other local users can write.
4177
- writeSecretFile(confPath, serverConfig(auth, spaces, { transport, port, storeDir, maxFileStore, host, wsPort, wsHost: host, extraAccounts }));
4897
+ writeBrokerConfig(confPath, serverConfig(auth, spaces, { transport, port, storeDir: configuredStoreDir(cotalRoot(), storeDir), maxFileStore, host, wsPort, wsHost: host, extraAccounts }));
4178
4898
  // Ephemeral setup cred: used only to probe reachability, pre-create the space streams/buckets
4179
4899
  // (setupSpaceStreams) and seed the channel registry (seedChannelRegistry) — all within the
4180
4900
  // enumerated `provisioner` scope. No broad `manager` residual for the up path.
@@ -4267,10 +4987,13 @@ async function healMembershipDataCreds(auth, root, space, quietBoot = false) {
4267
4987
  const composition = { injected: false, root };
4268
4988
  const rwKey = membershipRwCredsKey(space, composition);
4269
4989
  const wrote = [];
4270
- if ((await store.get(rwKey)) === undefined) {
4990
+ const rw = await store.get(rwKey);
4991
+ if (rw === undefined) {
4271
4992
  await store.put(rwKey, await mintCreds(auth, newIdentity(), "membership-rw"));
4272
4993
  wrote.push(MEMBERSHIP_RW_CREDS_KIND); // the KIND is what an operator reads, never the segmented key
4273
4994
  }
4995
+ else if (credsProblem(rw) !== undefined && !quietBoot)
4996
+ console.error(c.yellow(`! ${unparsableDaemonCredsNotice([MEMBERSHIP_RW_CREDS_KIND])}`));
4274
4997
  const configPath = membershipConfigPath(root, space);
4275
4998
  if (!existsSync(configPath)) {
4276
4999
  mkSecretDir(dirname(configPath)); // harden the per-space dir before the file lands, as the fresh path does