@cotal-ai/cli 0.100.1 → 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 (619) 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 +13 -16
  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 +157 -29
  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 +91 -15
  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 +38 -19
  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 +1 -1
  263. package/dist/commands/telemetry.d.ts.map +1 -1
  264. package/dist/commands/telemetry.js +5 -3
  265. package/dist/commands/telemetry.js.map +1 -1
  266. package/dist/commands/topology.d.ts.map +1 -1
  267. package/dist/commands/topology.js +11 -7
  268. package/dist/commands/topology.js.map +1 -1
  269. package/dist/commands/up.d.ts +6 -6
  270. package/dist/commands/up.d.ts.map +1 -1
  271. package/dist/commands/up.js +963 -240
  272. package/dist/commands/up.js.map +1 -1
  273. package/dist/commands/update.d.ts.map +1 -1
  274. package/dist/commands/update.js +9 -3
  275. package/dist/commands/update.js.map +1 -1
  276. package/dist/commands/use.d.ts +5 -1
  277. package/dist/commands/use.d.ts.map +1 -1
  278. package/dist/commands/use.js +55 -12
  279. package/dist/commands/use.js.map +1 -1
  280. package/dist/commands/watch.d.ts +4 -1
  281. package/dist/commands/watch.d.ts.map +1 -1
  282. package/dist/commands/watch.js +15 -3
  283. package/dist/commands/watch.js.map +1 -1
  284. package/dist/commands/who.d.ts +2 -0
  285. package/dist/commands/who.d.ts.map +1 -1
  286. package/dist/commands/who.js +18 -5
  287. package/dist/commands/who.js.map +1 -1
  288. package/dist/commands/whoami.d.ts +44 -5
  289. package/dist/commands/whoami.d.ts.map +1 -1
  290. package/dist/commands/whoami.js +168 -16
  291. package/dist/commands/whoami.js.map +1 -1
  292. package/dist/console/app.d.ts +1 -1
  293. package/dist/console/app.d.ts.map +1 -1
  294. package/dist/console/app.js +15 -9
  295. package/dist/console/app.js.map +1 -1
  296. package/dist/console/launch.d.ts +25 -0
  297. package/dist/console/launch.d.ts.map +1 -0
  298. package/dist/console/launch.js +56 -0
  299. package/dist/console/launch.js.map +1 -0
  300. package/dist/console/ui/CommandPalette.d.ts +5 -4
  301. package/dist/console/ui/CommandPalette.d.ts.map +1 -1
  302. package/dist/console/ui/CommandPalette.js +136 -45
  303. package/dist/console/ui/CommandPalette.js.map +1 -1
  304. package/dist/console/ui/Help.js +1 -1
  305. package/dist/console/ui/Help.js.map +1 -1
  306. package/dist/console/ui/Modal.d.ts +10 -0
  307. package/dist/console/ui/Modal.d.ts.map +1 -0
  308. package/dist/console/ui/Modal.js +8 -0
  309. package/dist/console/ui/Modal.js.map +1 -0
  310. package/dist/console/ui/NewAgent.d.ts +14 -0
  311. package/dist/console/ui/NewAgent.d.ts.map +1 -0
  312. package/dist/console/ui/NewAgent.js +114 -0
  313. package/dist/console/ui/NewAgent.js.map +1 -0
  314. package/dist/console/ui/StatusBar.d.ts +1 -2
  315. package/dist/console/ui/StatusBar.d.ts.map +1 -1
  316. package/dist/console/ui/StatusBar.js +6 -8
  317. package/dist/console/ui/StatusBar.js.map +1 -1
  318. package/dist/console/ui/topo/Map.d.ts.map +1 -1
  319. package/dist/console/ui/topo/Map.js +1 -2
  320. package/dist/console/ui/topo/Map.js.map +1 -1
  321. package/dist/console/ui/topo/Matrix.js +2 -2
  322. package/dist/console/ui/topo/Matrix.js.map +1 -1
  323. package/dist/console/ui/topo/Sequence.d.ts.map +1 -1
  324. package/dist/console/ui/topo/Sequence.js +5 -4
  325. package/dist/console/ui/topo/Sequence.js.map +1 -1
  326. package/dist/console/ui/topo/model.d.ts +2 -1
  327. package/dist/console/ui/topo/model.d.ts.map +1 -1
  328. package/dist/console/ui/topo/model.js +4 -3
  329. package/dist/console/ui/topo/model.js.map +1 -1
  330. package/dist/exec-endpoint/service-adapter.d.ts.map +1 -1
  331. package/dist/exec-endpoint/service-adapter.js +13 -3
  332. package/dist/exec-endpoint/service-adapter.js.map +1 -1
  333. package/dist/ext-loader.d.ts +4 -0
  334. package/dist/ext-loader.d.ts.map +1 -1
  335. package/dist/ext-loader.js +6 -0
  336. package/dist/ext-loader.js.map +1 -1
  337. package/dist/help.d.ts.map +1 -1
  338. package/dist/help.js +44 -23
  339. package/dist/help.js.map +1 -1
  340. package/dist/index.d.ts.map +1 -1
  341. package/dist/index.js +59 -54
  342. package/dist/index.js.map +1 -1
  343. package/dist/lib/agent-skills.d.ts.map +1 -1
  344. package/dist/lib/agent-skills.js +2 -1
  345. package/dist/lib/agent-skills.js.map +1 -1
  346. package/dist/lib/attach-client.js +2 -2
  347. package/dist/lib/attach-client.js.map +1 -1
  348. package/dist/lib/backup-artifact.d.ts +36 -8
  349. package/dist/lib/backup-artifact.d.ts.map +1 -1
  350. package/dist/lib/backup-artifact.js +156 -26
  351. package/dist/lib/backup-artifact.js.map +1 -1
  352. package/dist/lib/broker-service.d.ts +27 -3
  353. package/dist/lib/broker-service.d.ts.map +1 -1
  354. package/dist/lib/broker-service.js +135 -27
  355. package/dist/lib/broker-service.js.map +1 -1
  356. package/dist/lib/broker-store-health.d.ts +89 -0
  357. package/dist/lib/broker-store-health.d.ts.map +1 -0
  358. package/dist/lib/broker-store-health.js +171 -0
  359. package/dist/lib/broker-store-health.js.map +1 -0
  360. package/dist/lib/cancel.d.ts +4 -4
  361. package/dist/lib/cancel.d.ts.map +1 -1
  362. package/dist/lib/cancel.js +5 -5
  363. package/dist/lib/cancel.js.map +1 -1
  364. package/dist/lib/completion-install.d.ts +11 -2
  365. package/dist/lib/completion-install.d.ts.map +1 -1
  366. package/dist/lib/completion-install.js +79 -21
  367. package/dist/lib/completion-install.js.map +1 -1
  368. package/dist/lib/completion-scripts.d.ts.map +1 -1
  369. package/dist/lib/completion-scripts.js +2 -2
  370. package/dist/lib/completion-scripts.js.map +1 -1
  371. package/dist/lib/completion.d.ts +5 -1
  372. package/dist/lib/completion.d.ts.map +1 -1
  373. package/dist/lib/completion.js +10 -0
  374. package/dist/lib/completion.js.map +1 -1
  375. package/dist/lib/concrete-channel.d.ts +6 -0
  376. package/dist/lib/concrete-channel.d.ts.map +1 -0
  377. package/dist/lib/concrete-channel.js +17 -0
  378. package/dist/lib/concrete-channel.js.map +1 -0
  379. package/dist/lib/confirmation-required.d.ts +3 -12
  380. package/dist/lib/confirmation-required.d.ts.map +1 -1
  381. package/dist/lib/confirmation-required.js +9 -8
  382. package/dist/lib/confirmation-required.js.map +1 -1
  383. package/dist/lib/connect.d.ts +9 -0
  384. package/dist/lib/connect.d.ts.map +1 -1
  385. package/dist/lib/connect.js +27 -0
  386. package/dist/lib/connect.js.map +1 -1
  387. package/dist/lib/control.d.ts +42 -12
  388. package/dist/lib/control.d.ts.map +1 -1
  389. package/dist/lib/control.js +130 -31
  390. package/dist/lib/control.js.map +1 -1
  391. package/dist/lib/controller-restore.d.ts.map +1 -1
  392. package/dist/lib/controller-restore.js +12 -7
  393. package/dist/lib/controller-restore.js.map +1 -1
  394. package/dist/lib/credential-authority.d.ts.map +1 -1
  395. package/dist/lib/credential-authority.js +3 -0
  396. package/dist/lib/credential-authority.js.map +1 -1
  397. package/dist/lib/credential-exports.d.ts +17 -0
  398. package/dist/lib/credential-exports.d.ts.map +1 -0
  399. package/dist/lib/credential-exports.js +21 -0
  400. package/dist/lib/credential-exports.js.map +1 -0
  401. package/dist/lib/debug-flag.d.ts +4 -0
  402. package/dist/lib/debug-flag.d.ts.map +1 -0
  403. package/dist/lib/debug-flag.js +7 -0
  404. package/dist/lib/debug-flag.js.map +1 -0
  405. package/dist/lib/default-persona.d.ts +2 -0
  406. package/dist/lib/default-persona.d.ts.map +1 -1
  407. package/dist/lib/default-persona.js +2 -0
  408. package/dist/lib/default-persona.js.map +1 -1
  409. package/dist/lib/delivery-proc.d.ts +1 -1
  410. package/dist/lib/delivery-proc.d.ts.map +1 -1
  411. package/dist/lib/delivery-proc.js +5 -4
  412. package/dist/lib/delivery-proc.js.map +1 -1
  413. package/dist/lib/delivery-responder.d.ts +7 -3
  414. package/dist/lib/delivery-responder.d.ts.map +1 -1
  415. package/dist/lib/delivery-responder.js +8 -4
  416. package/dist/lib/delivery-responder.js.map +1 -1
  417. package/dist/lib/denied-write.d.ts +8 -0
  418. package/dist/lib/denied-write.d.ts.map +1 -0
  419. package/dist/lib/denied-write.js +24 -0
  420. package/dist/lib/denied-write.js.map +1 -0
  421. package/dist/lib/endpoint-capability-gates.js +2 -2
  422. package/dist/lib/endpoint-capability-gates.js.map +1 -1
  423. package/dist/lib/flag-value-refusal.d.ts +8 -0
  424. package/dist/lib/flag-value-refusal.d.ts.map +1 -0
  425. package/dist/lib/flag-value-refusal.js +10 -0
  426. package/dist/lib/flag-value-refusal.js.map +1 -0
  427. package/dist/lib/install-umask.d.ts +5 -0
  428. package/dist/lib/install-umask.d.ts.map +1 -1
  429. package/dist/lib/install-umask.js +25 -0
  430. package/dist/lib/install-umask.js.map +1 -1
  431. package/dist/lib/interrupt-notice.d.ts +23 -1
  432. package/dist/lib/interrupt-notice.d.ts.map +1 -1
  433. package/dist/lib/interrupt-notice.js +27 -6
  434. package/dist/lib/interrupt-notice.js.map +1 -1
  435. package/dist/lib/interrupt-report.d.ts +7 -0
  436. package/dist/lib/interrupt-report.d.ts.map +1 -0
  437. package/dist/lib/interrupt-report.js +24 -0
  438. package/dist/lib/interrupt-report.js.map +1 -0
  439. package/dist/lib/isolated-broker.d.ts +1 -1
  440. package/dist/lib/isolated-broker.d.ts.map +1 -1
  441. package/dist/lib/isolated-broker.js +17 -8
  442. package/dist/lib/isolated-broker.js.map +1 -1
  443. package/dist/lib/legacy-start.d.ts +8 -6
  444. package/dist/lib/legacy-start.d.ts.map +1 -1
  445. package/dist/lib/legacy-start.js +36 -36
  446. package/dist/lib/legacy-start.js.map +1 -1
  447. package/dist/lib/manager-choice.d.ts +45 -4
  448. package/dist/lib/manager-choice.d.ts.map +1 -1
  449. package/dist/lib/manager-choice.js +214 -24
  450. package/dist/lib/manager-choice.js.map +1 -1
  451. package/dist/lib/manager-proc.d.ts.map +1 -1
  452. package/dist/lib/manager-proc.js +7 -6
  453. package/dist/lib/manager-proc.js.map +1 -1
  454. package/dist/lib/manifest/index.d.ts +5 -1
  455. package/dist/lib/manifest/index.d.ts.map +1 -1
  456. package/dist/lib/manifest/index.js +50 -5
  457. package/dist/lib/manifest/index.js.map +1 -1
  458. package/dist/lib/manifest/preflight.d.ts +4 -0
  459. package/dist/lib/manifest/preflight.d.ts.map +1 -1
  460. package/dist/lib/manifest/preflight.js +18 -1
  461. package/dist/lib/manifest/preflight.js.map +1 -1
  462. package/dist/lib/manifest/resolve.d.ts +8 -0
  463. package/dist/lib/manifest/resolve.d.ts.map +1 -1
  464. package/dist/lib/manifest/resolve.js +104 -11
  465. package/dist/lib/manifest/resolve.js.map +1 -1
  466. package/dist/lib/missing-flags.js +1 -1
  467. package/dist/lib/missing-flags.js.map +1 -1
  468. package/dist/lib/nats-bin.d.ts +28 -5
  469. package/dist/lib/nats-bin.d.ts.map +1 -1
  470. package/dist/lib/nats-bin.js +85 -7
  471. package/dist/lib/nats-bin.js.map +1 -1
  472. package/dist/lib/nearest-word.d.ts +14 -0
  473. package/dist/lib/nearest-word.d.ts.map +1 -0
  474. package/dist/lib/nearest-word.js +76 -0
  475. package/dist/lib/nearest-word.js.map +1 -0
  476. package/dist/lib/no-expiry-record.d.ts +8 -0
  477. package/dist/lib/no-expiry-record.d.ts.map +1 -0
  478. package/dist/lib/no-expiry-record.js +27 -0
  479. package/dist/lib/no-expiry-record.js.map +1 -0
  480. package/dist/lib/paths.d.ts +31 -0
  481. package/dist/lib/paths.d.ts.map +1 -1
  482. package/dist/lib/paths.js +92 -2
  483. package/dist/lib/paths.js.map +1 -1
  484. package/dist/lib/persona-files.d.ts +29 -6
  485. package/dist/lib/persona-files.d.ts.map +1 -1
  486. package/dist/lib/persona-files.js +179 -36
  487. package/dist/lib/persona-files.js.map +1 -1
  488. package/dist/lib/personas.d.ts +18 -1
  489. package/dist/lib/personas.d.ts.map +1 -1
  490. package/dist/lib/personas.js +65 -6
  491. package/dist/lib/personas.js.map +1 -1
  492. package/dist/lib/prompts.d.ts +7 -1
  493. package/dist/lib/prompts.d.ts.map +1 -1
  494. package/dist/lib/prompts.js +43 -3
  495. package/dist/lib/prompts.js.map +1 -1
  496. package/dist/lib/registry-errors.d.ts +2 -1
  497. package/dist/lib/registry-errors.d.ts.map +1 -1
  498. package/dist/lib/registry-errors.js +6 -2
  499. package/dist/lib/registry-errors.js.map +1 -1
  500. package/dist/lib/reset-space-plan.d.ts +2 -0
  501. package/dist/lib/reset-space-plan.d.ts.map +1 -1
  502. package/dist/lib/reset-space-plan.js +1 -1
  503. package/dist/lib/reset-space-plan.js.map +1 -1
  504. package/dist/lib/restore.d.ts +45 -3
  505. package/dist/lib/restore.d.ts.map +1 -1
  506. package/dist/lib/restore.js +248 -35
  507. package/dist/lib/restore.js.map +1 -1
  508. package/dist/lib/rolled-back-runs.d.ts +36 -0
  509. package/dist/lib/rolled-back-runs.d.ts.map +1 -0
  510. package/dist/lib/rolled-back-runs.js +96 -0
  511. package/dist/lib/rolled-back-runs.js.map +1 -0
  512. package/dist/lib/service-definitions.d.ts +16 -3
  513. package/dist/lib/service-definitions.d.ts.map +1 -1
  514. package/dist/lib/service-definitions.js +99 -27
  515. package/dist/lib/service-definitions.js.map +1 -1
  516. package/dist/lib/service-instances.d.ts +13 -1
  517. package/dist/lib/service-instances.d.ts.map +1 -1
  518. package/dist/lib/service-instances.js +56 -12
  519. package/dist/lib/service-instances.js.map +1 -1
  520. package/dist/lib/service-presets.d.ts.map +1 -1
  521. package/dist/lib/service-presets.js +16 -0
  522. package/dist/lib/service-presets.js.map +1 -1
  523. package/dist/lib/service-process.d.ts +51 -8
  524. package/dist/lib/service-process.d.ts.map +1 -1
  525. package/dist/lib/service-process.js +385 -48
  526. package/dist/lib/service-process.js.map +1 -1
  527. package/dist/lib/space-streams.d.ts +18 -0
  528. package/dist/lib/space-streams.d.ts.map +1 -0
  529. package/dist/lib/space-streams.js +35 -0
  530. package/dist/lib/space-streams.js.map +1 -0
  531. package/dist/lib/spawn-defaults.d.ts +25 -1
  532. package/dist/lib/spawn-defaults.d.ts.map +1 -1
  533. package/dist/lib/spawn-defaults.js +37 -1
  534. package/dist/lib/spawn-defaults.js.map +1 -1
  535. package/dist/lib/stack-journal.d.ts +157 -14
  536. package/dist/lib/stack-journal.d.ts.map +1 -1
  537. package/dist/lib/stack-journal.js +406 -49
  538. package/dist/lib/stack-journal.js.map +1 -1
  539. package/dist/lib/stack-listeners.d.ts +17 -0
  540. package/dist/lib/stack-listeners.d.ts.map +1 -0
  541. package/dist/lib/stack-listeners.js +54 -0
  542. package/dist/lib/stack-listeners.js.map +1 -0
  543. package/dist/lib/stack-members.d.ts +13 -0
  544. package/dist/lib/stack-members.d.ts.map +1 -0
  545. package/dist/lib/stack-members.js +24 -0
  546. package/dist/lib/stack-members.js.map +1 -0
  547. package/dist/lib/stack-resume.d.ts.map +1 -1
  548. package/dist/lib/stack-resume.js +5 -2
  549. package/dist/lib/stack-resume.js.map +1 -1
  550. package/dist/lib/stack-runs.d.ts +34 -0
  551. package/dist/lib/stack-runs.d.ts.map +1 -0
  552. package/dist/lib/stack-runs.js +75 -0
  553. package/dist/lib/stack-runs.js.map +1 -0
  554. package/dist/lib/status.d.ts +11 -0
  555. package/dist/lib/status.d.ts.map +1 -1
  556. package/dist/lib/status.js +4 -5
  557. package/dist/lib/status.js.map +1 -1
  558. package/dist/lib/stdout-owner.d.ts +12 -3
  559. package/dist/lib/stdout-owner.d.ts.map +1 -1
  560. package/dist/lib/stdout-owner.js +33 -5
  561. package/dist/lib/stdout-owner.js.map +1 -1
  562. package/dist/lib/store-dir.d.ts +68 -4
  563. package/dist/lib/store-dir.d.ts.map +1 -1
  564. package/dist/lib/store-dir.js +253 -17
  565. package/dist/lib/store-dir.js.map +1 -1
  566. package/dist/lib/team-additive-attempt.d.ts +1 -1
  567. package/dist/lib/team-channel-removal.d.ts.map +1 -1
  568. package/dist/lib/team-channel-removal.js +4 -0
  569. package/dist/lib/team-channel-removal.js.map +1 -1
  570. package/dist/lib/team-deploy-inspection.d.ts +13 -0
  571. package/dist/lib/team-deploy-inspection.d.ts.map +1 -1
  572. package/dist/lib/team-deploy-inspection.js +12 -0
  573. package/dist/lib/team-deploy-inspection.js.map +1 -1
  574. package/dist/lib/team-text.d.ts +6 -0
  575. package/dist/lib/team-text.d.ts.map +1 -0
  576. package/dist/lib/team-text.js +36 -0
  577. package/dist/lib/team-text.js.map +1 -0
  578. package/dist/lib/transient.d.ts +14 -8
  579. package/dist/lib/transient.d.ts.map +1 -1
  580. package/dist/lib/transient.js +72 -11
  581. package/dist/lib/transient.js.map +1 -1
  582. package/dist/lib/unusable-file.d.ts +13 -0
  583. package/dist/lib/unusable-file.d.ts.map +1 -0
  584. package/dist/lib/unusable-file.js +12 -0
  585. package/dist/lib/unusable-file.js.map +1 -0
  586. package/dist/lib/up-report.d.ts +6 -0
  587. package/dist/lib/up-report.d.ts.map +1 -1
  588. package/dist/lib/up-report.js +13 -0
  589. package/dist/lib/up-report.js.map +1 -1
  590. package/dist/lib/verdict.d.ts +14 -0
  591. package/dist/lib/verdict.d.ts.map +1 -0
  592. package/dist/lib/verdict.js +15 -0
  593. package/dist/lib/verdict.js.map +1 -0
  594. package/dist/managed-handoff.d.ts +11 -6
  595. package/dist/managed-handoff.d.ts.map +1 -1
  596. package/dist/managed-handoff.js +27 -18
  597. package/dist/managed-handoff.js.map +1 -1
  598. package/dist/render.d.ts +5 -2
  599. package/dist/render.d.ts.map +1 -1
  600. package/dist/render.js +44 -10
  601. package/dist/render.js.map +1 -1
  602. package/dist/telemetry.d.ts +4 -3
  603. package/dist/telemetry.d.ts.map +1 -1
  604. package/dist/telemetry.js +14 -6
  605. package/dist/telemetry.js.map +1 -1
  606. package/dist/ui.d.ts +3 -2
  607. package/dist/ui.d.ts.map +1 -1
  608. package/dist/ui.js +6 -4
  609. package/dist/ui.js.map +1 -1
  610. package/dist/view/mesh-view.d.ts.map +1 -1
  611. package/dist/view/mesh-view.js +4 -1
  612. package/dist/view/mesh-view.js.map +1 -1
  613. package/dist/watch-data.d.ts +9 -1
  614. package/dist/watch-data.d.ts.map +1 -1
  615. package/dist/watch-data.js +17 -3
  616. package/dist/watch-data.js.map +1 -1
  617. package/dist/watch-json.js +4 -3
  618. package/dist/watch-json.js.map +1 -1
  619. package/package.json +5 -5
@@ -10,20 +10,26 @@
10
10
  import { randomUUID } from "node:crypto";
11
11
  import { existsSync, lstatSync, realpathSync } from "node:fs";
12
12
  import { homedir } from "node:os";
13
- import { join, resolve } from "node:path";
13
+ import { isIP } from "node:net";
14
+ import { basename, join, resolve } from "node:path";
14
15
  import { JetStreamApiCodes, JetStreamApiError } from "@nats-io/jetstream";
15
16
  import { awaitDeadDeliveryLease, deliveryLeaseHolderFor, isJetStreamMissing, isReachable, LEASE_TTL_MS, mintCreds, newIdentity } from "@cotal-ai/core";
16
- import { CommandFailure, accountInventory, authDir, canonicalRoot, deliveryCredsKey, findMesh, findPreparedSpace, getCurrent, getSpaceAuth, hasUserAuthState, homeCotalDir, isCommandFailure, loadMeshes, localMeshesForRoot, presentationOf, readMaintenanceJournal, renderReport, resolveNativeServiceTarget, resolveOnPath, stackHomeRemedy, stackRunsUnderOtherHome, terminalWidth, workspaceSecretStore, writeResult, } from "@cotal-ai/workspace";
17
+ import { CommandFailure, accountInventory, authDir, canonicalRoot, deliveryCredsKey, findMesh, findPreparedSpace, keepsRegistration, getCurrent, getSpaceAuth, hasUserAuthState, homeCotalDir, isCommandFailure, loadMeshes, localMeshesForRoot, presentationOf, readMaintenanceJournal, renderReport, resolveNativeServiceTarget, resolveOnPath, rotateSystemCreds, SPACE_NAME_MAX, spaceNameTooLong, stackHomeRemedy, stackRunsUnderOtherHome, terminalWidth, workspaceSecretStore, writeResult, MIN_FILE_STORE, unparsableDaemonCreds, loopbackListeners, readProcessCommand, resolveMeshTarget, processStopped, } from "@cotal-ai/workspace";
17
18
  import { liveMeshProcesses } from "./clean.js";
18
- import { brokerListenAddress } from "../lib/broker-service.js";
19
+ import { addressHolder, brokerListenAddress, listenerBindError } from "../lib/broker-service.js";
20
+ import { brokerStoreWrite, jetStreamDisabled, jetStreamDisabledRefusal, readStoredBytes, storeDamageNotice, storeFull } from "../lib/broker-store-health.js";
21
+ import { shellWord } from "../lib/endpoint-errors.js";
19
22
  import { seedDefaultPersona } from "../lib/default-persona.js";
20
- import { serviceDefinitionStore, validateServiceDefinition } from "../lib/service-definitions.js";
21
- import { instanceProjection, observeServiceProcess, serviceInstances } from "../lib/service-instances.js";
22
- import { prepareProcessService, removeStoppedInstanceRecords, settleExitedInstances, startProcessService } from "../lib/service-process.js";
23
+ import { definitionListeners, exposedPlaintext, listenerRow } from "../lib/stack-listeners.js";
24
+ import { definitionRootMatch, serviceDefinitionStore, validateServiceDefinition } from "../lib/service-definitions.js";
25
+ import { instanceProjection, observeServiceProcess, serviceInstances, serviceInstanceStore, serviceRecordsWriteProblem } from "../lib/service-instances.js";
26
+ import { prepareKernelServiceStop, prepareProcessService, readServiceLog, removeStoppedInstanceRecords, settleExitedInstances, startProcessService, stopProcessService } from "../lib/service-process.js";
23
27
  import { listLedgerFiles } from "../lib/manifest/ledger.js";
24
28
  import { listAdditiveTeamAttempts, retainedAdditiveTeamAttempts } from "../lib/team-additive-attempt.js";
25
29
  import { freshTeamAttemptSettled, listFreshTeamAttempts, listFreshTeamSummaries } from "../lib/team-fresh.js";
26
- import { foreignLocalProcesses, newStackOperation, readStackJournal, settleRetainedStackStops, settleStackOperation, stackDefinitionsAt, stackMaintenanceFence, stackNeverStarted, stackOperationUnsettled, stackSettlementNotice, STACK_ADAPTER, STACK_DEFINITION, STACK_ROLES, stackRoleApplies, withSettledMembers, writeStackJournal } from "../lib/stack-journal.js";
30
+ import { foreignLocalProcesses, newStackOperation, readStackJournal, runningStackRoles, serviceHeldRecords, settleRetainedStackStops, settleStackOperation, STACK_ADAPTER, STACK_DEFINITION, STACK_ROLES, stackDefinitionsAt, stackMaintenanceFence, stackNeverStarted, stackOperationUnsettled, stackRoleApplies, stackSettlementNotice, withSettledMembers, writeStackJournal } from "../lib/stack-journal.js";
31
+ import { natsServerLabel } from "../lib/nats-bin.js";
32
+ import { missingStoreWarning, sharedStoreAtStart, sharedStoreWarning } from "../lib/store-dir.js";
27
33
  import { assertUserStackTransport, confirmUserAuthEndpoints, preflightUserStack, provisionalUserAuth, userLoginRequired, userLoginState, userRegistrationIncomplete } from "./stack-user-auth.js";
28
34
  /** Pin a named store that must already exist as a real directory, refusing a missing path, a
29
35
  * non-directory and a symlink. The pin and its rechecks narrow the window in which another local
@@ -60,20 +66,69 @@ export function recheckExistingStore(pin, target) {
60
66
  if (!stat || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev.toString() !== pin.dev || stat.ino.toString() !== pin.ino || stat.birthtimeNs.toString() !== pin.birthtimeNs)
61
67
  throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the named broker store disappeared, was replaced or became a link after it was checked; no store was created and the broker was not started", { target: { ...target, storeDir: pin.named } });
62
68
  }
63
- /** Inputs that name a legacy-only startup refuse on the controller route. They are not dropped. */
69
+ /** Inputs that name a legacy-only startup refuse on the controller route. They are not dropped. A
70
+ * recorded stack takes `rotate-sys` on a stopped start; a first start refuses it, because it mints
71
+ * the space's system account new. */
64
72
  const CONTROLLER_UNSUPPORTED = ["file", "dry-run", "restore", "restore-only", "accept-missing-source", "accept-stale-checkpoint", "rotate-sys", "exchange-public-port", "exchange-public-url", "exchange-trusted-proxy", "advertised-server", "agent-provisioning-url", "tls-cert", "tls-key"];
73
+ /** The inputs that ask for a TLS broker, which the controller stack does not serve: the certificate
74
+ * pair, and a `--server` that names a `tls://` address. */
75
+ const TLS_INPUTS = ["tls-cert", "tls-key", "server tls://"];
76
+ const namesTlsServer = (values) => typeof values.server === "string" && /^tls:\/\//i.test(values.server);
77
+ /** A `--server` broker URL as `up` records and compares it: the scheme in lower case, with no bare
78
+ * trailing `/`. Any other value comes back as given, for the address checks to refuse. */
79
+ export function canonicalServer(server) {
80
+ let url;
81
+ try {
82
+ url = new URL(server);
83
+ }
84
+ catch {
85
+ return server;
86
+ }
87
+ if ((url.protocol !== "nats:" && url.protocol !== "tls:") || url.username || url.password || url.search || url.hash || (url.pathname !== "" && url.pathname !== "/") || server.includes(","))
88
+ return server;
89
+ return `${url.protocol}//${url.host}`;
90
+ }
91
+ /** Whether an `up` invocation asks for a TLS broker. */
92
+ export function requestsTls(values) {
93
+ return values["tls-cert"] !== undefined || values["tls-key"] !== undefined || namesTlsServer(values);
94
+ }
95
+ /** Of those, the ones `up -f <cotal.yaml>` takes on a prepared root. */
96
+ const MANIFEST_ROUTE = ["dry-run", ...TLS_INPUTS];
97
+ /** The refusal of startup options the controller stack has no route for, before anything starts.
98
+ * A prepared root that has not run a stack yet is also offered the manifest route. */
99
+ function controllerUnsupported(root, options, prepared) {
100
+ const flags = options.map((name) => `--${name}`);
101
+ const named = flags.length === 1 ? flags[0] : `${flags.slice(0, -1).join(", ")} and ${flags.at(-1)}`;
102
+ const manifest = prepared && options.every((name) => MANIFEST_ROUTE.includes(name));
103
+ const rotation = prepared && options.includes("rotate-sys") ? "; a first start mints the space's $SYS creds, so there is nothing to rotate" : "";
104
+ return new CommandFailure("refused", "UNSUPPORTED", `${prepared ? "this root is prepared for a controller-owned stack" : "this root's stack is owned by the service controller"}, which has no route for ${named}; nothing was started through the legacy launcher`, {
105
+ target: { root, options },
106
+ remedy: manifest && options.some((name) => TLS_INPUTS.includes(name))
107
+ ? `run cotal up without ${named} to serve plaintext, or serve TLS from a manifest whose broker.servers names a tls:// address, with cotal up -f <cotal.yaml> --tls-cert <cert.pem> --tls-key <key.pem>`
108
+ : manifest ? `run cotal up without ${named}, or start the space from a manifest with cotal up -f <cotal.yaml>, which takes ${flags.length === 1 ? "it" : "them"}` : `run cotal up without ${named}${rotation}`,
109
+ });
110
+ }
65
111
  /** Any account record, readable or not, means the root carries static trust an open stack would bypass. */
66
112
  function holdsBrokerAccount(root) {
67
113
  const inventory = accountInventory(authDir(root));
68
114
  return inventory.spaces.length > 0 || inventory.corrupt.length > 0;
69
115
  }
116
+ const MODE_NAME = { auth: "static auth", open: "open", user: "user auth" };
117
+ /** The next step when an explicit mode is not the one a root's first whole-stack `up` recorded.
118
+ * Nothing converts a root's mode: `reset`, `clean` and `space forget` keep the stack journal that
119
+ * records it. So the step keeps that mode, or starts the requested one in another folder. */
120
+ function pinnedModeRemedy(recorded, requested) {
121
+ const flag = requested === "open" ? " --open" : requested === "user" ? " --user-auth" : "";
122
+ return `run bare cotal up to keep ${MODE_NAME[recorded]} here, or for ${MODE_NAME[requested]} run cotal space create <space>, then cotal up${flag}, in another folder`;
123
+ }
70
124
  /** The mode an invocation explicitly asks for, or none for a bare `up`. */
71
125
  export function requestedStackMode(values) {
72
126
  return values["user-auth"] === true ? "user" : values.open === true ? "open" : undefined;
73
127
  }
74
128
  /** A root takes the controller route when it already has a stack journal, or when it is a fresh,
75
- * prepared root with nothing legacy, maintenance or team-owned retained under it and the
76
- * invocation names only controller-supported inputs. A static-auth request needs an `up`
129
+ * prepared root with nothing legacy, maintenance or team-owned retained under it. On either, an
130
+ * input the controller has no route for refuses `UNSUPPORTED`. A recorded stack that launched a
131
+ * member keeps its auth mode. A static-auth request needs an `up`
77
132
  * registration in auth mode or none. An `--open` request needs an open registration or none, and
78
133
  * a root that holds no broker account. A prepared user-auth root uses the same controller with
79
134
  * its native auth service. Anything else keeps the retained path. */
@@ -81,19 +136,22 @@ export function controllerStackApplies(root, space, values) {
81
136
  const canonical = canonicalRoot(root);
82
137
  const recorded = readStackJournal(canonical);
83
138
  const requested = requestedStackMode(values);
84
- const unsupportedNow = (name) => values[name] !== undefined && values[name] !== false && CONTROLLER_UNSUPPORTED.includes(name);
139
+ const unsupported = CONTROLLER_UNSUPPORTED.filter((name) => values[name] !== undefined && values[name] !== false);
140
+ if (namesTlsServer(values))
141
+ unsupported.push("server tls://");
85
142
  if (recorded) {
86
- const unsupported = CONTROLLER_UNSUPPORTED.filter(unsupportedNow);
87
- if (unsupported.length)
88
- throw new CommandFailure("refused", "UNSUPPORTED", "this root's stack is owned by the service controller; the requested startup option has no controller-owned route and was not applied through the legacy launcher", { target: { root: canonical, options: unsupported } });
143
+ const refused = unsupported.filter((name) => name !== "rotate-sys");
144
+ if (refused.length)
145
+ throw controllerUnsupported(canonical, refused, false);
146
+ // A stack that never launched a member pins no mode; its next up plans a first start.
147
+ if (stackNeverStarted(recorded.journal))
148
+ return true;
89
149
  if (requested !== undefined && requested !== recorded.journal.mode)
90
- throw new CommandFailure("refused", "CONFLICT", `this root's controller stack is pinned to ${recorded.journal.mode === "open" ? "open" : recorded.journal.mode === "user" ? "user auth" : "static auth"}; the requested mode does not convert it`, { target: { root: canonical, recorded: recorded.journal.mode, requested }, remedy: "run bare cotal up to keep the recorded mode" });
150
+ throw new CommandFailure("refused", "CONFLICT", `this root's controller stack is pinned to ${MODE_NAME[recorded.journal.mode]}; the requested mode does not convert it`, { target: { root: canonical, recorded: recorded.journal.mode, requested }, remedy: pinnedModeRemedy(recorded.journal.mode, requested) });
91
151
  if (values.idp !== undefined && recorded.journal.mode !== "user")
92
152
  throw new CommandFailure("refused", "USAGE_INVALID", "--idp belongs to a user-auth stack", { target: { root: canonical } });
93
153
  return true;
94
154
  }
95
- if (CONTROLLER_UNSUPPORTED.some(unsupportedNow))
96
- return false;
97
155
  const wanted = requested ?? "auth";
98
156
  if (canonical === canonicalRoot(homedir()) || wanted !== "user" && hasUserAuthState(canonical, space, { readOnly: true }))
99
157
  return false;
@@ -105,12 +163,21 @@ export function controllerStackApplies(root, space, values) {
105
163
  // Only a space prepared at this very root qualifies. An absent prepared record is not a root: an
106
164
  // empty path would canonicalize to the working directory and admit an unprepared legacy folder.
107
165
  const prepared = findPreparedSpace(space);
108
- if (!registered && (!prepared || canonicalRoot(prepared.root) !== canonical))
166
+ const preparedHere = prepared !== undefined && canonicalRoot(prepared.root) === canonical;
167
+ if (!registered && !preparedHere)
168
+ return false;
169
+ // A legacy `down` keeps the registration of a space named after its folder, and the retained
170
+ // launcher that wrote it starts it again.
171
+ if (registered && !preparedHere && keepsRegistration(registered))
109
172
  return false;
110
173
  if (readMaintenanceJournal(canonical))
111
174
  return false;
112
175
  if (existsSync(join(canonical, ".cotal", "nats.pid")) || liveMeshProcesses(canonical, space).length)
113
176
  return false;
177
+ // A prepared root never falls through to the legacy launcher, so an option the controller stack
178
+ // has no route for refuses here as it does on a root whose stack the controller owns.
179
+ if (unsupported.length)
180
+ throw controllerUnsupported(canonical, unsupported, true);
114
181
  return true;
115
182
  }
116
183
  /** Returns a settled active restore of the recorded stack that was admitted, for the result to name. */
@@ -122,6 +189,14 @@ function stackPreflight(root, space, recorded, ownAttempt) {
122
189
  if (maintenance.fenced)
123
190
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "this root retains a maintenance or recovery attempt; the controller stack did not substitute an ordinary startup", { target: { root, space } });
124
191
  const legacy = foreignLocalProcesses(root, space);
192
+ // A service of this space started at this root, such as a `manager` preset, writes its own record
193
+ // here. It is named with the stop `down` names for it; the stack still neither adopts nor replaces it.
194
+ const held = legacy.length && !existsSync(join(root, ".cotal", "nats.pid")) ? serviceHeldRecords(root, space) : [];
195
+ if (held.length && held.length === legacy.length)
196
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `${held.map((row) => `the ${row.definition} service of this space runs this root's ${row.record.name} (pid ${row.record.pid}, instance ${row.instanceId})`).join("; ")}, outside the controller stack, which neither adopts nor replaces it`, {
197
+ target: { root, space, processes: legacy, services: held.map((row) => ({ definition: row.definition, instanceId: row.instanceId })) },
198
+ remedy: `stop ${held.length === 1 ? "it" : "each"} with ${held.map((row) => `\`cotal svc stop ${row.definition} --instance ${row.instanceId} --space ${space} --yes\``).join(", ")}, then run \`cotal up\` again`,
199
+ });
125
200
  if (legacy.length || existsSync(join(root, ".cotal", "nats.pid")))
126
201
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "legacy pidfile-owned processes or records remain under this root; the controller stack neither adopts nor replaces them", { target: { root, space, processes: legacy } });
127
202
  if (localMeshesForRoot(root).some((mesh) => mesh.space !== space))
@@ -137,8 +212,18 @@ function stackPreflight(root, space, recorded, ownAttempt) {
137
212
  throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "team records under this root could not be read; no empty team state was inferred", { target: { root, space } });
138
213
  }
139
214
  const settled = new Map(summaries.valid.map((summary) => [summary.deploymentId, summary]));
140
- if (ledgers.valid.length || ledgers.refused.length || retainedAdditiveTeamAttempts(additive).length || additive.refused.length || boots.refused.length || summaries.refused.length || boots.valid.some((attempt) => attempt.deploymentId !== ownAttempt && !freshTeamAttemptSettled(attempt, settled.get(attempt.deploymentId))))
141
- throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "team deployments or unsettled boot records remain under this root; the controller stack did not adopt their resources", { target: { root, space } });
215
+ // A channel-only deployment that returned onto this recorded stack stays with it across a stop: its
216
+ // cards are in this broker's store, so starting the stack again adopts nothing and its records stay
217
+ // as they are. Any other retained deployment still blocks.
218
+ const carried = (attempt) => recorded !== undefined && attempt.requestedAgents.length === 0 && additive.returned.some((row) => row.deploymentId === attempt.deploymentId)
219
+ && attempt.space === recorded.space && canonicalRoot(attempt.root) === canonicalRoot(root) && attempt.server === recorded.server && attempt.authMode === recorded.mode;
220
+ const retained = retainedAdditiveTeamAttempts(additive).filter((attempt) => !carried(attempt));
221
+ const unsettledBoots = boots.valid.filter((attempt) => attempt.deploymentId !== ownAttempt && !freshTeamAttemptSettled(attempt, settled.get(attempt.deploymentId)));
222
+ if (ledgers.valid.length || ledgers.refused.length || retained.length || additive.refused.length || boots.refused.length || summaries.refused.length || unsettledBoots.length) {
223
+ const ids = [...new Set([...retained.map((attempt) => attempt.deploymentId), ...ledgers.valid.map(({ ledger }) => ledger.runId), ...unsettledBoots.map((attempt) => attempt.deploymentId)])];
224
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "team deployments or unsettled boot records remain under this root; the controller stack did not adopt their resources", { target: { root, space, deployments: ids },
225
+ remedy: ids.length ? `inspect each with ${ids.map((id) => `cotal team show ${id}`).join(", ")}; nothing was started` : `list the records with cotal team in ${root}; nothing was started` });
226
+ }
142
227
  return maintenance.admittedRestore;
143
228
  }
144
229
  /** The broker binary that preparation already selected, canonicalized to its file. A bare PATH name
@@ -188,12 +273,12 @@ function ensureDefinition(space, role, input, root, replace) {
188
273
  function adapterDefinition(space, adapter, options, timeoutMs) {
189
274
  return { schemaVersion: 1, space, launch: { type: "adapter", adapter, options }, readiness: { type: "adapter", timeoutMs } };
190
275
  }
191
- function membersView(journal, title) {
276
+ function membersView(journal, title, executable, streamsRecreated = false) {
192
277
  // A role the stack's mode never plans (auth on a static or open stack, delivery on an open one)
193
278
  // is not a member of it; it stays in the journal and JSON only.
194
279
  const members = journal.members.filter((member) => stackRoleApplies(journal.mode, member.role));
195
280
  return { sections: [{ title, blocks: [
196
- { kind: "fields", rows: [["Space", journal.space], ["Root", journal.root], ["Broker", journal.server], ["Mode", journal.mode === "open" ? "open, no authentication" : journal.mode === "user" ? "user auth" : "static auth"], ["Operation", `${journal.operation.kind} ${journal.operation.phase}`], ...(journal.mode === "user" ? [["Registration", userRegistrationIncomplete(journal.space) ? "incomplete: no confirmed auth-service endpoint" : "auth-service endpoint confirmed by its provider"]] : [])] },
281
+ { kind: "fields", rows: [["Space", journal.space], ["Root", journal.root], ["Broker", journal.server], ["Mode", journal.mode === "open" ? "open, no authentication" : journal.mode === "user" ? "user auth" : "static auth"], ["Operation", `${journal.operation.kind} ${journal.operation.phase}`], ...(executable ? [["Broker executable", natsServerLabel(executable)]] : []), ...(streamsRecreated ? [["Space streams", "created again, empty, on the running broker"]] : []), ...(journal.mode === "user" ? [["Registration", userRegistrationIncomplete(journal.space) ? "incomplete: no confirmed auth-service endpoint" : "auth-service endpoint confirmed by its provider"]] : [])] },
197
282
  { kind: "table", columns: [{ key: "role", label: "Member" }, { key: "definition", label: "Definition" }, { key: "instance", label: "Full instance" }, { key: "state", label: "Result" }], rows: members.map((member) => ({ role: member.role, definition: member.definition, instance: member.instanceId ?? "not allocated", state: { text: member.state.replaceAll("-", " "), tone: ["started", "reused", "stopped", "already-stopped"].includes(member.state) ? "ok" : ["refused", "failed"].includes(member.state) ? "failed" : "waiting" } })) },
198
283
  { kind: "lines", lines: [journal.mode === "open"
199
284
  ? "Open stack: no authentication, no delivery member and no delivery credential. Each member is one exact service-controller instance. Broker readiness means its own process reported its listener; manager readiness is the child's own local receipt, not an attributed endpoint response. This is not agent or task readiness, and a partial start is not rolled back."
@@ -202,17 +287,63 @@ function membersView(journal, title) {
202
287
  : "Each member is one exact service-controller instance. Broker readiness means its own process reported its listener; delivery readiness is its process startup receipt; manager readiness is its attributed native endpoint. This is not agent or task readiness, and a partial start is not rolled back."] },
203
288
  ] }] };
204
289
  }
290
+ /** The warning a start gives for daemon credentials the NATS client cannot parse. `up` mints only a
291
+ * missing one and the manager re-signs only one that holds its key, so it names the step that
292
+ * replaces it. */
293
+ export function unparsableDaemonCredsNotice(kinds) {
294
+ const them = kinds.length === 1 ? "it" : "them";
295
+ return `${kinds.join(" and ")} cannot be parsed, so the delivery daemon runs without ${them} and the manager cannot re-sign ${them}; stop the stack with \`cotal down\`, then run \`cotal doctor auth --fix\`, which mints ${them} again`;
296
+ }
297
+ /** The listeners the stack's running broker and manager opened, from their saved definitions. Null
298
+ * when the broker's configuration could not be read, so no list is given rather than a short one. */
299
+ function stackListeners(journal) {
300
+ const store = serviceDefinitionStore(journal.space), listeners = [];
301
+ for (const member of journal.members) {
302
+ if (member.role !== "broker" && member.role !== "manager" || member.state !== "started" && member.state !== "reused")
303
+ continue;
304
+ const definition = store.read(member.definition);
305
+ const found = definition && definitionListeners(definition);
306
+ if (!found)
307
+ return null;
308
+ listeners.push(...found);
309
+ }
310
+ return listeners;
311
+ }
312
+ /** The selection a start finds: one that names a registered or prepared space, else none. */
313
+ function usableSelection() {
314
+ const current = getCurrent();
315
+ return current && (findMesh(current) || findPreparedSpace(current)) ? current : undefined;
316
+ }
317
+ /** What `up` says when it selects the space it started, because nothing usable was selected. */
318
+ export function selectedOnUp(space) {
319
+ return `selected "${space}": a command without --space targets it, except in another space's project folder`;
320
+ }
321
+ /** What `up` says when another selected space stays selected. */
322
+ export function keptOnUp(space, kept) {
323
+ return `"${space}" up; "${kept}" stays selected for commands run outside this folder - \`cotal use ${space}\` to switch`;
324
+ }
205
325
  /** `cotal up`'s controller route: start, seed the default persona into the root, then write its
206
- * own receipt. The stack is up by then, so a persona that cannot be written is a warning. */
326
+ * own receipt, which names the saved services it does not start. The stack is up by then, so a
327
+ * persona that cannot be written, or saved services that cannot be listed, is a warning. */
207
328
  export async function stackUp(request, native) {
208
- const { journal, changed, allReused, admittedRestore, settled } = await startControllerStack(request, native);
329
+ const before = usableSelection();
330
+ const { journal, changed, allReused, admittedRestore, settled, brokerExecutable, streamsRecreated, rotation, storeShared, storeMissing } = await startControllerStack(request, native);
209
331
  const { root, space, server, mode } = journal;
210
332
  const managed = journal.members.some((row) => row.role === "manager" && (row.state === "started" || row.state === "reused"));
211
- // The start keeps another selected space; the receipt says so, as a legacy `up` does.
212
- const current = getCurrent();
213
- const keptCurrent = current && current !== space && (findMesh(current) || findPreparedSpace(current)) ? current : undefined;
333
+ // The receipt says when the start selected its space, and when another space stays selected.
334
+ const current = usableSelection();
335
+ const keptCurrent = current !== space ? current : undefined;
336
+ const selected = current === space && before !== space;
214
337
  const written = [];
215
338
  const warnings = settled ? [{ code: "OPERATION_SETTLED", target: { root, space, operation: settled.operation.id }, message: stackSettlementNotice(settled) }] : [];
339
+ if (storeMissing)
340
+ warnings.push({ code: "STORE_MISSING", target: { root, space, storeDir: storeMissing }, message: missingStoreWarning(storeMissing) });
341
+ if (storeShared)
342
+ warnings.push({ code: "STORE_SHARED", target: { root, space, storeDir: storeShared.path, otherSpaces: storeShared.tenants }, message: sharedStoreWarning(storeShared.path, storeShared.tenants) });
343
+ // Damage the broker found while it restored its stored files is logged by now.
344
+ const damage = brokerStoreWrite(root, space);
345
+ if (damage.state === "damaged")
346
+ warnings.push({ code: "STORE_DAMAGE_LOGGED", target: { root, space, brokerLog: damage.log }, message: storeDamageNotice(damage) });
216
347
  try {
217
348
  const persona = seedDefaultPersona(root);
218
349
  if (persona)
@@ -221,23 +352,148 @@ export async function stackUp(request, native) {
221
352
  catch (error) {
222
353
  warnings.push({ code: "PERSONA_NOT_WRITTEN", target: { root, space }, message: `the default persona was not written in ${root}: ${error.message}` });
223
354
  }
224
- writeResult(request.presentation, { command: "up", target: { root, space, server }, result: { kind: "controller-stack-up", root, space, server, mode, operation: journal.operation, members: journal.members, changed, foreground: request.foreground, admittedRestore: admittedRestore ?? null, settledOperation: settled ?? null, written }, warnings, ...(allReused && written.length === 0 ? { noOp: true } : {}) }, (result) => {
225
- const members = membersView({ ...journal, members: result.members }, allReused ? "Controller stack already running" : "Controller stack started");
226
- const view = result.written.length ? { ...members, sections: [...members.sections, { blocks: [{ kind: "fields", rows: result.written.map((w) => ["wrote", `${w.what}: ${w.path}`]) }] }] } : members;
355
+ if (mode !== "open") {
356
+ const unparsable = await unparsableDaemonCreds(root, space);
357
+ if (unparsable.length)
358
+ warnings.push({ code: "DAEMON_CREDENTIAL_UNPARSABLE", target: { root, space, credentials: unparsable }, message: unparsableDaemonCredsNotice(unparsable) });
359
+ }
360
+ // The receipt names each saved service up does not start, and which of them a space forgotten
361
+ // under this name left from another root, as `cotal service` marks them inherited.
362
+ const stackDefinitions = new Set(Object.values(STACK_DEFINITION));
363
+ let savedServices = [], inheritedServices = [];
364
+ try {
365
+ const rows = serviceDefinitionStore(space).list().filter((row) => !stackDefinitions.has(row.name));
366
+ savedServices = rows.map((row) => row.name);
367
+ inheritedServices = rows.filter((row) => definitionRootMatch(row.record.value, canonicalRoot(root)) === "inherited").map((row) => row.name);
368
+ }
369
+ catch (error) {
370
+ warnings.push({ code: "SAVED_SERVICES_NOT_READ", target: { root, space }, message: `the saved services of ${space} could not be listed: ${error.message}` });
371
+ }
372
+ writeResult(request.presentation, { command: "up", target: { root, space, server }, result: { kind: "controller-stack-up", root, space, server, mode, operation: journal.operation, members: journal.members, changed, foreground: request.foreground, admittedRestore: admittedRestore ?? null, settledOperation: settled ?? null, brokerExecutable: brokerExecutable ?? null, streamsRecreated: streamsRecreated === true, rotatedSystemAccount: rotation ?? null, listeners: stackListeners(journal), written, savedServices, inheritedServices, selection: { current: current ?? null, changed: current === space && before !== space } }, warnings, ...(allReused && written.length === 0 && !streamsRecreated ? { noOp: true } : {}) }, (result) => {
373
+ const members = membersView({ ...journal, members: result.members }, allReused ? "Controller stack already running" : "Controller stack started", result.brokerExecutable, result.streamsRecreated);
374
+ const exposed = result.listeners && exposedPlaintext(result.listeners);
375
+ const listening = [{ title: "Listeners", blocks: [
376
+ result.listeners ? { kind: "fields", rows: result.listeners.map(listenerRow) } : { kind: "lines", lines: ["The broker's configuration could not be read, so its listeners are not listed."] },
377
+ ...(exposed ? [{ kind: "lines", lines: [{ text: exposed, tone: "waiting" }] }] : []),
378
+ ] }];
379
+ const view = { ...members, sections: [...members.sections, ...listening, ...(result.written.length ? [{ blocks: [{ kind: "fields", rows: result.written.map((w) => ["wrote", `${w.what}: ${w.path}`]) }] }] : [])] };
380
+ // `down` stops only the stack of the folder it runs in, so from another folder the Next says where.
381
+ const elsewhere = request.invokedRoot !== undefined && request.invokedRoot !== canonicalRoot(root);
227
382
  const next = request.foreground ? [] : [{ title: "Next", blocks: [{ kind: "commands", items: [
228
383
  // A bare spawn targets the selected space, which this up does not change when one is set.
229
- managed ? { command: `cotal spawn --space ${space}`, description: "Launch your default agent" } : { command: "cotal up", description: "Add the manager to this stack" },
230
- { command: "cotal down", description: "Stop every recorded member" },
384
+ managed ? { command: `cotal spawn --space ${space}`, description: "Launch your default agent" } : { command: elsewhere ? `cotal up --root ${root}` : "cotal up", description: "Add the manager to this stack" },
385
+ { command: "cotal down", description: elsewhere ? `Stop every recorded member; run it from ${root}` : "Stop every recorded member" },
231
386
  ] }] }];
232
- const kept = keptCurrent ? [{ blocks: [{ kind: "lines", lines: [{ text: `"${space}" up; current is still "${keptCurrent}" - \`cotal use ${space}\` to switch`, tone: "hint" }] }] }] : [];
233
- return { ...view, sections: [...view.sections, ...(admittedRestore ? [{ title: "Retained restore journal", blocks: [{ kind: "lines", lines: [`Active restore ${admittedRestore} stays in this root's maintenance journal. It was read and not changed.`] }] }] : []), ...kept, ...next] };
387
+ const selection = keptCurrent ? keptOnUp(space, keptCurrent) : selected ? selectedOnUp(space) : undefined;
388
+ const kept = selection ? [{ blocks: [{ kind: "lines", lines: [{ text: selection, tone: "hint" }] }] }] : [];
389
+ const saved = result.savedServices.length ? [{ blocks: [{ kind: "lines", lines: [
390
+ { text: `saved services up does not start: ${result.savedServices.join(", ")}`, tone: "hint" },
391
+ ...(result.inheritedServices.length ? [{ text: ` ${result.inheritedServices.join(", ")} came from a space forgotten under the name ${space} in another folder and ${result.inheritedServices.length === 1 ? "does" : "do"} not start here; \`cotal service remove <name> --space ${space} --yes\` forgets one`, tone: "hint" }] : []),
392
+ { text: ` \`cotal service show <name> --space ${space}\` shows what one runs`, tone: "hint" },
393
+ ] }] }] : [];
394
+ const rotated = result.rotatedSystemAccount ? [{ title: "System account rotated", blocks: [
395
+ { kind: "fields", rows: [["Generation", String(result.rotatedSystemAccount.generation)], ["$SYS creds valid to", result.rotatedSystemAccount.expiresAt?.slice(0, 10) ?? "no expiry"]] },
396
+ { kind: "lines", lines: ["membership-observer.creds and connection-evictor.creds were minted against the new system account, and the broker started on a configuration rendered from it. The data account, every agent credential and the JetStream store are unchanged. Old $SYS creds are refused by any broker that loads this configuration."] },
397
+ ] }] : [];
398
+ return { ...view, sections: [...view.sections, ...rotated, ...(admittedRestore ? [{ title: "Retained restore journal", blocks: [{ kind: "lines", lines: [`Active restore ${admittedRestore} stays in this root's maintenance journal. It was read and not changed.`] }] }] : []), ...saved, ...kept, ...next] };
234
399
  });
235
400
  }
401
+ /** The refusal of an up whose running broker disabled JetStream after a store write failure: no
402
+ * stream check or later member start reaches it. Undefined for an error already classified. */
403
+ function reusedWithoutJetStream(caught, brokerReused, root, space) {
404
+ if (!brokerReused || isCommandFailure(caught) && caught.outcome !== "unknown")
405
+ return undefined;
406
+ const disabled = jetStreamDisabled(root, space);
407
+ if (!disabled)
408
+ return undefined;
409
+ const manager = serviceInstances(space, STACK_DEFINITION.manager).map((row) => row.record.value).find((value) => observeServiceProcess(value) === "running");
410
+ return jetStreamDisabledRefusal(disabled, root, space, "up cannot check the space's streams on it", "its running members were left as they are", { root, space }, manager?.process?.pid);
411
+ }
412
+ /** What holds a stopped stack's recorded broker address, as bare up's own bind check finds it, with
413
+ * the listening processes of this account named. Undefined while the address is free, could not be
414
+ * checked, or this stack's broker runs there. */
415
+ async function recordedAddressHeld(space, server) {
416
+ const brokerRows = serviceInstances(space, STACK_DEFINITION.broker);
417
+ if (brokerRows.length === 1 && observeServiceProcess(brokerRows[0].record.value) === "running")
418
+ return undefined;
419
+ const bindError = await listenerBindError(server);
420
+ if (bindError === undefined || bindError === "timeout" || bindError.code !== "EADDRINUSE")
421
+ return undefined;
422
+ const { host, port } = brokerListenAddress(server);
423
+ const held = addressHolder("that address", host, port);
424
+ const holders = loopbackListeners(server).map((pid) => {
425
+ const command = readProcessCommand(pid);
426
+ return command.kind === "command" ? `${pid} (${basename(command.command.split(" ")[0])})` : String(pid);
427
+ });
428
+ return holders.length ? { says: `${held.says}, where process ${holders.join(", ")} of this account listens`, frees: held.frees } : held;
429
+ }
430
+ /** The broker's store over its recorded cap, read over an observer credential after a member failed
431
+ * to start. Every write is refused until there is room, a delivery daemon's lease included.
432
+ * Undefined while the store is under its cap, with no cap recorded, or when it cannot be read. */
433
+ async function storeFullAfterStart(root, space) {
434
+ let used;
435
+ try {
436
+ used = await readStoredBytes(resolveMeshTarget(root, { space, readOnly: true }), "up-diagnosis");
437
+ }
438
+ catch {
439
+ used = undefined;
440
+ }
441
+ return used === undefined ? undefined : storeFull(root, space, used);
442
+ }
443
+ /** The two ways out of a full store for an up whose member could not start: making room purges the
444
+ * space's channel history, and raising the cap keeps it but needs the broker restarted, so the
445
+ * manager's own process is ended first where it runs, as a full store refuses its stop. */
446
+ function fullStoreUpRemedy(root, space) {
447
+ const pid = serviceInstances(space, STACK_DEFINITION.manager).map((row) => row.record.value).find((value) => observeServiceProcess(value) === "running")?.process?.pid;
448
+ return `from ${root}, make room with cotal history clear --yes, which purges all of this space's channel history, then run cotal up again; to keep that history, ${pid !== undefined ? `end the manager on this host with kill -TERM ${pid}, which stops its agents by its default policy, then ` : ""}run cotal down --yes and cotal up --max-file-store <bytes> with a larger cap`;
449
+ }
450
+ /** The running broker of an unregistered space: what an up stopped before registration leaves. */
451
+ function strandedBroker(space) {
452
+ if (findMesh(space))
453
+ return undefined;
454
+ const rows = serviceInstances(space, STACK_DEFINITION.broker);
455
+ return rows.length === 1 && observeServiceProcess(rows[0].record.value) === "running" ? rows[0].record.value : undefined;
456
+ }
457
+ /** What a detached up interrupted by a signal left: the members that run, and the command that
458
+ * finishes the start or stops them. An up given `--no-manager` names `cotal up --no-manager`, since
459
+ * bare `up` adds the manager. */
460
+ export function stackUpInterruptNotice(root, space, noManager = false) {
461
+ const up = `cotal up${noManager ? " --no-manager" : ""}`;
462
+ const stranded = strandedBroker(space);
463
+ if (stranded)
464
+ return `Interrupted before the space was registered; its broker keeps running as pid ${stranded.process?.pid}. Run cotal down --yes, then ${up}.`;
465
+ const running = runningStackRoles(space);
466
+ return running.length
467
+ ? `Interrupted while starting the stack in ${root}; ${running.join(", ")} ${running.length === 1 ? "keeps" : "keep"} running. Run ${up} to finish the start, or cotal down --yes to stop ${running.length === 1 ? "it" : "them"}.`
468
+ : `Interrupted before any member of the stack in ${root} started. Run ${up} to start it.`;
469
+ }
470
+ /** Whether a broker bound to `host` is reached at `server`'s address: a wildcard bind is reached at
471
+ * any address, and any other host must name that address. */
472
+ export function bindReaches(host, server) {
473
+ if (host === "0.0.0.0" || host === "::" || host === "[::]")
474
+ return true;
475
+ try {
476
+ return new URL(`nats://${isIP(host) === 6 ? `[${host}]` : host}:1`).hostname === new URL(server).hostname;
477
+ }
478
+ catch {
479
+ return false;
480
+ }
481
+ }
236
482
  /** Start the recorded stack and return its domain result without writing any receipt. */
237
483
  export async function startControllerStack(request, native) {
238
484
  const root = canonicalRoot(request.root), space = request.space;
239
485
  if (request.transport.kind !== "plaintext" && request.transport.kind !== "tls-required")
240
486
  throw new CommandFailure("refused", "UNSUPPORTED", "unknown broker transport");
487
+ // A space an earlier release prepared under a longer name refuses here, before its journal or any
488
+ // member's file is written, instead of failing on the first file name that does not fit.
489
+ const tooLong = spaceNameTooLong(space);
490
+ if (tooLong)
491
+ throw new CommandFailure("refused", "USAGE_INVALID", `${tooLong}; nothing was started or written`, { target: { root, space }, remedy: `forget it with cotal space forget ${space}, then create one with a name of at most ${SPACE_NAME_MAX} characters with cotal space create <name>` });
492
+ // Each member's start is recorded under the space's service records. A folder there this account
493
+ // cannot write refuses here, naming it, instead of an unknown outcome after a member started.
494
+ const unwritable = serviceRecordsWriteProblem(space, ["definitions", "instances"]);
495
+ if (unwritable)
496
+ throw new CommandFailure("refused", "PERMISSION_DENIED", `this account cannot write ${unwritable}, where up records the stack's services; nothing was started or written`, { target: { root, space, path: unwritable }, remedy: `make it writable with chmod u+w ${unwritable}, then run cotal up again` });
241
497
  const recorded = readStackJournal(root);
242
498
  if (request.expectPriorDown && (!recorded || recorded.sha256 !== request.expectPriorDown.journalSha256 || recorded.journal.operation.id !== request.expectPriorDown.operationId))
243
499
  throw new CommandFailure("refused", "CONFLICT", "the stopped stack changed after the team boot checked it; nothing was started", { target: { root, space, expected: request.expectPriorDown.operationId } });
@@ -248,14 +504,33 @@ export async function startControllerStack(request, native) {
248
504
  const previous = unstarted ? undefined : recorded;
249
505
  // A stopped stack's broker is prepared again from its own recorded inputs. An explicit request for
250
506
  // a different store, cap or bind host refuses; none is replaced by a default.
251
- const recordedBroker = previous?.journal.broker;
507
+ const recordedInputs = previous?.journal.broker;
508
+ // The broker binds its recorded host, or 127.0.0.1 when none was recorded. A bind that does not
509
+ // serve the recorded address starts a broker its clients never reach, so it pins nothing: while
510
+ // the broker is stopped, an explicit --host that serves the recorded address replaces it, and any
511
+ // other up refuses before anything starts and names that step.
512
+ const recordedBind = recordedInputs ? recordedInputs.host ?? "127.0.0.1" : undefined;
513
+ const strayHost = recordedBind !== undefined && !bindReaches(recordedBind, previous.journal.server) ? recordedBind : undefined;
514
+ if (strayHost !== undefined) {
515
+ const brokerRuns = serviceInstances(space, STACK_DEFINITION.broker).some((row) => observeServiceProcess(row.record.value) === "running");
516
+ if (request.host === undefined || !bindReaches(request.host, previous.journal.server) || brokerRuns)
517
+ throw new CommandFailure("refused", "CONFLICT", `this stack's broker binds ${strayHost}${recordedInputs.host === undefined ? ", as no bind host was recorded," : ","} which does not serve its recorded address ${previous.journal.server}, so its clients cannot reach it; nothing was started`, {
518
+ target: { root, space, recorded: recordedInputs },
519
+ remedy: `${brokerRuns ? `stop its broker with cotal down --yes from ${root}, then ` : ""}run cotal up --host ${new URL(previous.journal.server).hostname} from ${root}`,
520
+ });
521
+ }
522
+ // The cap is fixed while the broker runs. A stopped broker starts again with an explicit new cap,
523
+ // which replaces the recorded one, as after a cap too small for the space's streams.
524
+ const newCap = recordedInputs !== undefined && request.maxFileStore !== undefined && request.maxFileStore !== recordedInputs.maxFileStore;
525
+ const capReplaced = newCap && !serviceInstances(space, STACK_DEFINITION.broker).some((row) => observeServiceProcess(row.record.value) === "running");
526
+ const recordedBroker = recordedInputs && { ...recordedInputs, ...(strayHost !== undefined ? { host: request.host } : {}), ...(capReplaced ? { maxFileStore: request.maxFileStore } : {}) };
252
527
  const changedInputs = recordedBroker ? [
253
528
  request.storeDir !== undefined && resolve(request.storeDir) !== recordedBroker.storeDir ? `--store-dir ${resolve(request.storeDir)} (recorded: ${recordedBroker.storeDir})` : undefined,
254
529
  request.maxFileStore !== undefined && request.maxFileStore !== recordedBroker.maxFileStore ? `--max-file-store ${request.maxFileStore} (recorded: ${recordedBroker.maxFileStore ?? "none"})` : undefined,
255
530
  request.host !== undefined && request.host !== recordedBroker.host ? `--host ${request.host} (recorded: ${recordedBroker.host ?? "none"})` : undefined,
256
531
  ].filter((input) => input !== undefined) : [];
257
532
  if (changedInputs.length)
258
- throw new CommandFailure("refused", "CONFLICT", `${changedInputs.join(", ")} ${changedInputs.length === 1 ? "differs" : "differ"} from this stack's recorded broker inputs; nothing was prepared`, { target: { root, space, recorded: recordedBroker }, remedy: `run bare cotal up from ${root} to start it with its recorded inputs` });
533
+ throw new CommandFailure("refused", "CONFLICT", `${changedInputs.join(", ")} ${changedInputs.length === 1 ? "differs" : "differ"} from this stack's recorded broker inputs; nothing was prepared`, { target: { root, space, recorded: recordedBroker }, remedy: `run bare cotal up from ${root} to start it with its recorded inputs${newCap ? `; a new --max-file-store applies once the broker is stopped with cotal down --yes` : ""}` });
259
534
  // A journal written before broker inputs were recorded cannot tell which store, cap or bind host
260
535
  // its stopped broker used: `cotal down` removed the registration that held them, and broker
261
536
  // preparation would otherwise fall back to the default `.cotal/nats` store with no cap. Such a
@@ -272,10 +547,15 @@ export async function startControllerStack(request, native) {
272
547
  const brokerStore = recordedBroker?.storeDir ?? request.storeDir ?? unstarted?.broker?.storeDir;
273
548
  const brokerCap = recordedBroker ? recordedBroker.maxFileStore : request.maxFileStore ?? unstarted?.broker?.maxFileStore;
274
549
  const brokerHost = recordedBroker ? recordedBroker.host : request.host ?? unstarted?.broker?.host;
550
+ // The manager's session ceiling is kept by its saved definition, so a bare up starts it with the
551
+ // ceiling an earlier up set rather than the default. An explicit --max-sessions replaces it.
552
+ const savedManager = serviceDefinitionStore(space).read(STACK_DEFINITION.manager)?.record.value.launch;
553
+ const savedSessions = savedManager?.type === "adapter" && savedManager.options.root === root ? savedManager.options["max-sessions"] : undefined;
554
+ const maxSessions = request.maxSessions ?? (typeof savedSessions === "number" ? savedSessions : undefined);
275
555
  // The mode is pinned by the first whole-stack up. A conflicting explicit request refuses here,
276
556
  // before any preflight write, preparation or launch.
277
557
  if (previous && request.mode !== undefined && request.mode !== previous.journal.mode)
278
- throw new CommandFailure("refused", "CONFLICT", "this root's controller stack is pinned to another auth mode; a running or stopped stack is not converted", { target: { root, space, recorded: previous.journal.mode, requested: request.mode }, remedy: "run bare cotal up to keep the recorded mode" });
558
+ throw new CommandFailure("refused", "CONFLICT", "this root's controller stack is pinned to another auth mode; a running or stopped stack is not converted", { target: { root, space, recorded: previous.journal.mode, requested: request.mode }, remedy: pinnedModeRemedy(previous.journal.mode, request.mode) });
279
559
  const mode = previous?.journal.mode ?? request.mode ?? "auth";
280
560
  if (mode === "open" && holdsBrokerAccount(root))
281
561
  throw new CommandFailure("refused", "CONFLICT", "this root holds a broker account; an open stack does not bypass its recorded authorization", { target: { root, space } });
@@ -289,8 +569,12 @@ export async function startControllerStack(request, native) {
289
569
  const recordedTarget = { root, space, recorded: { space: previous?.journal.space, server: previous?.journal.server }, requested: { space, server: request.server } };
290
570
  if (previous && previous.journal.space !== space)
291
571
  throw new CommandFailure("refused", "CONFLICT", `this root's controller stack is recorded for space ${previous.journal.space}, and this up asked for ${space}; it was not rebound`, { target: recordedTarget, remedy: `run bare cotal up from ${root} to start ${previous.journal.space}` });
292
- if (previous && previous.journal.server !== request.server)
293
- throw new CommandFailure("refused", "CONFLICT", `this root's controller stack is recorded at ${previous.journal.server}, and this up asked for ${request.server}; a recorded stack is not moved to another address`, { target: recordedTarget, remedy: `run bare cotal up from ${root} to start it at ${previous.journal.server}` });
572
+ // No command moves a stack that ran to another address. While another program holds the recorded
573
+ // one, bare up refuses too, so the refusal names that holder rather than sending the operator there.
574
+ if (previous && canonicalServer(previous.journal.server) !== canonicalServer(request.server)) {
575
+ const held = await recordedAddressHeld(space, previous.journal.server);
576
+ throw new CommandFailure("refused", "CONFLICT", `this root's controller stack is recorded at ${previous.journal.server}, and this up asked for ${request.server}; a recorded stack is not moved to another address${held ? `, and ${held.says}` : ""}`, { target: recordedTarget, remedy: held ? `${held.frees}, then run bare cotal up from ${root}; no command moves a stack that ran to another address, so it starts only at ${previous.journal.server}` : `run bare cotal up from ${root} to start it at ${previous.journal.server}` });
577
+ }
294
578
  // The broker service's own address rules run before anything is written, so an address it would
295
579
  // refuse never becomes this root's recorded broker address.
296
580
  brokerListenAddress(request.server);
@@ -301,7 +585,24 @@ export async function startControllerStack(request, native) {
301
585
  if (registration && (registration.origin !== "up" || canonicalRoot(registration.root) !== root || registration.server !== (previous?.journal.server ?? request.server)))
302
586
  throw new CommandFailure("refused", "CONFLICT", "the space is registered to another root, broker address or external origin; nothing was prepared or started", { target: { root, space }, remedy: `inspect it with cotal space show ${space}` });
303
587
  if (!registration && (!preparedSpace || canonicalRoot(preparedSpace.root) !== root))
304
- throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the space has no prepared or locally started registration at this root; nothing was prepared or started", { target: { root, space }, remedy: `prepare it with cotal space create ${space} --root ${root}, then run cotal up` });
588
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the space has no prepared or locally started registration at this root; nothing was prepared or started", { target: { root, space }, remedy: `prepare it with cotal space create ${space} --root ${shellWord(root)}, then run cotal up` });
589
+ // A store folder belongs to one space. A --store-dir no record of this stack names refuses while
590
+ // another space uses it; the recorded or default store starts, and the receipt warns.
591
+ const storePath = brokerStore !== undefined ? resolve(brokerStore) : join(root, ".cotal", "nats");
592
+ const storeTenants = sharedStoreAtStart(storePath, space, recordedBroker !== undefined || legacyStopped || request.storeDir === undefined);
593
+ const storeMissing = recordedBroker !== undefined && !existsSync(storePath);
594
+ // An up stopped after its broker served and before it registered the space leaves a broker whose
595
+ // stream setup and registration only that up's own preparation could finish, and trust is never
596
+ // prepared again under a running broker. This start refuses before any write and names the stop.
597
+ const stranded = registration ? undefined : strandedBroker(space);
598
+ if (stranded)
599
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `the stack's broker runs as pid ${stranded.process?.pid}, but the cotal up that started it stopped before it registered the space, so this up cannot finish that start; nothing was changed`, { target: { root, space, broker: stranded.instanceId, pid: stranded.process?.pid }, remedy: "stop that broker with cotal down --yes, then run cotal up again" });
600
+ // A broker stopped by a signal accepts connections and never answers, so every step through it would
601
+ // wait out its budget, and its readiness check would record a listener that serves nothing. This
602
+ // start refuses before any write and names the signal that resumes it.
603
+ const brokerPid = serviceInstances(space, STACK_DEFINITION.broker).map((row) => row.record.value).find((value) => observeServiceProcess(value) === "running")?.process?.pid;
604
+ if (brokerPid !== undefined && processStopped(brokerPid))
605
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `the stack's broker, pid ${brokerPid}, is stopped, so it accepts connections at ${previous?.journal.server ?? request.server} and never answers; nothing was started or written`, { target: { root, space, pid: brokerPid }, remedy: `resume it with kill -CONT ${brokerPid} and run cotal up again` });
305
606
  // An earlier up or down that never recorded its outcome is settled from its members' process
306
607
  // evidence under the held maintenance lock. Only a preserve or resume can remain unsettled here.
307
608
  // A member stop an earlier down could not confirm in time is settled from its own receipt first.
@@ -316,6 +617,18 @@ export async function startControllerStack(request, native) {
316
617
  if (running.length)
317
618
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "--no-manager cannot keep an already-running controller manager; no member was started or stopped", { target: { root, space, instances: running.map((row) => row.name) }, remedy: `stop the recorded manager with cotal service stop ${STACK_DEFINITION.manager} --space ${space} --yes before requesting --no-manager` });
318
619
  }
620
+ // A rotation is a stopped, fresh boot. A member that still runs would keep the retired system
621
+ // account, so every member must be stopped before anything is rotated or started.
622
+ if (request.rotateSys) {
623
+ if (mode === "open")
624
+ throw new CommandFailure("refused", "UNSUPPORTED", "an open stack has no system account or $SYS credentials to rotate; nothing was started", { target: { root, space }, remedy: `run bare cotal up from ${root} to start it` });
625
+ const running = STACK_ROLES.flatMap((role) => serviceInstances(space, STACK_DEFINITION[role])).filter((row) => observeServiceProcess(row.record.value) === "running");
626
+ if (running.length)
627
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "this stack has running members, and a running broker keeps serving the retired system account; nothing was rotated or started", { target: { root, space, instances: running.map((row) => row.name) }, remedy: "stop the stack with cotal down --yes, then run cotal up --rotate-sys" });
628
+ const trust = await getSpaceAuth(workspaceSecretStore(root), space);
629
+ if (!trust?.operator.seed)
630
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", trust ? "this root holds the space's trust without the broker operator seed, so it cannot rotate the system account; nothing was started" : "this stack has no system account yet, so nothing was rotated or started", { target: { root, space }, remedy: trust ? "run the rotation where the broker trust record lives" : `run bare cotal up from ${root}; a first start mints the $SYS creds` });
631
+ }
319
632
  // Check provider inputs before preparation or a journal write. A supplied IdP is always checked,
320
633
  // including a live refresh; only an unpinned first enable probes JWKS. Preparation checks again.
321
634
  if (mode === "user") {
@@ -372,9 +685,13 @@ export async function startControllerStack(request, native) {
372
685
  // never to the next planned one.
373
686
  let failedRole;
374
687
  let failedStage;
688
+ let startedBroker;
689
+ let brokerExecutable;
690
+ let streamsRecreated = false;
375
691
  let launch;
376
692
  // Only a broker this call starts gets the space's streams created.
377
693
  let brokerReused = false;
694
+ let rotation;
378
695
  try {
379
696
  // Broker. Trust and configuration are prepared only when this broker is not already serving
380
697
  // under its own recorded instance, never as an adapter planning step.
@@ -395,8 +712,34 @@ export async function startControllerStack(request, native) {
395
712
  : `${stopHolder}, then run bare cotal up from ${root}; this stack keeps its recorded address`,
396
713
  });
397
714
  }
715
+ // A program that holds the address without answering NATS, such as a web server, is refused here
716
+ // too, before any broker instance is recorded, so a first start names another address.
717
+ const bindError = brokerRunning ? undefined : await listenerBindError(server);
718
+ if (bindError !== undefined && bindError !== "timeout" && bindError.code === "EADDRINUSE") {
719
+ const { host, port } = brokerListenAddress(server), address = new URL(server);
720
+ const { says, frees } = addressHolder("the stack's broker address", host, port);
721
+ throw new CommandFailure("refused", "CONFLICT", `${says} (bind failed: address already in use); no broker was launched`, {
722
+ target: { root, space, server, bindError: bindError.code },
723
+ remedy: previous === undefined
724
+ ? `start this stack at another address with cotal up --server ${address.protocol}//${address.hostname}:<port> from ${root}, or ${frees} and run cotal up again`
725
+ : `${frees}, then run bare cotal up from ${root}; this stack keeps its recorded address`,
726
+ });
727
+ }
398
728
  let prepared;
399
729
  if (!brokerRunning) {
730
+ if (request.rotateSys) {
731
+ // Rotated here, after the address check, so no broker can still serve the retired account.
732
+ // Preparation then renders the broker configuration from the rotated trust record.
733
+ failedRole = "broker";
734
+ try {
735
+ const rotated = await rotateSystemCreds(root, space);
736
+ rotation = { generation: rotated.gen, expiresAt: rotated.expiresAt ? new Date(rotated.expiresAt * 1000).toISOString() : null };
737
+ }
738
+ catch (error) {
739
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", `the system account rotation did not finish: ${error.message}`, { target: { root, space } });
740
+ }
741
+ failedRole = undefined;
742
+ }
400
743
  prepared = await native.prepareBroker({ transport: request.transport, server, space, open: mode === "open", ...(mode === "user" ? { userAuth: request.idp !== undefined ? { idpUrl: request.idp } : {} } : {}), ...(brokerHost ? { host: brokerHost } : {}), ...(brokerStore ? { storeDir: brokerStore } : {}), ...(storePin ? { existingStore: storePin } : {}), ...(brokerCap !== undefined ? { maxFileStore: brokerCap } : {}), ...(request.manifest ? { seed: request.manifest.seed } : request.channels ? { channels: request.channels } : {}) });
401
744
  if (canonicalRoot(prepared.root) !== root || prepared.space !== space || prepared.server !== server || (prepared.setup === undefined) !== (mode === "open") || (prepared.user === undefined) !== (mode !== "user"))
402
745
  throw new CommandFailure("refused", "CONFLICT", "the prepared broker configuration names another root, space, address or auth mode; the stack did not continue");
@@ -413,12 +756,15 @@ export async function startControllerStack(request, native) {
413
756
  const savedOptions = savedBroker?.record.value.launch.type === "adapter" ? savedBroker.record.value.launch.options : undefined;
414
757
  if (!prepared && !savedOptions)
415
758
  throw new CommandFailure("refused", "CONFLICT", "a broker instance runs without its saved stack definition; it was not adopted", { target: { space, definition: STACK_DEFINITION.broker } });
416
- const brokerOptions = prepared ? { root, config: prepared.confPath, binary: canonicalBinary(prepared.bin), server } : { ...savedOptions };
759
+ if (prepared)
760
+ brokerExecutable = { path: canonicalBinary(prepared.bin), source: prepared.source, version: prepared.version };
761
+ const brokerOptions = prepared && brokerExecutable ? { root, config: prepared.confPath, binary: brokerExecutable.path, server } : { ...savedOptions };
417
762
  const broker = ensureDefinition(space, "broker", adapterDefinition(space, STACK_ADAPTER.broker, brokerOptions, 30000), root, replace("broker"));
418
763
  if (storePin)
419
764
  recheckExistingStore(storePin, { root, space });
420
- await start("broker", broker);
765
+ const brokerInstance = await start("broker", broker);
421
766
  if (prepared) {
767
+ startedBroker = { definition: broker, id: brokerInstance.name };
422
768
  // The broker's own stream and registry setup, on the native space path, after it serves.
423
769
  failedRole = "broker";
424
770
  failedStage = "broker-streams";
@@ -427,10 +773,18 @@ export async function startControllerStack(request, native) {
427
773
  // A user registration is recorded here, before its auth service exists, because the native
428
774
  // auth-service child resolves a registered user target. It carries only the prepared trust
429
775
  // pins and stays incomplete until that child's own readiness is confirmed below.
430
- native.recordMesh({ space, server, root, mode, tlsRequired: prepared.transport.kind === "tls-required", storeDir: prepared.storeDir, ...(prepared.user ? { userAuth: provisionalUserAuth(prepared.user) } : {}), ...(request.maxSessions !== undefined ? { maxSessions: request.maxSessions } : {}), ...(brokerHost ? { attachHost: brokerHost } : {}), ...(brokerCap !== undefined ? { maxFileStore: brokerCap } : {}) });
776
+ native.recordMesh({ space, server, root, mode, tlsRequired: prepared.transport.kind === "tls-required", storeDir: prepared.storeDir, ...(prepared.user ? { userAuth: provisionalUserAuth(prepared.user) } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(brokerHost ? { attachHost: brokerHost } : {}), ...(brokerCap !== undefined ? { maxFileStore: brokerCap } : {}) });
431
777
  failedStage = undefined;
432
778
  failedRole = undefined;
433
779
  }
780
+ else if (mode !== "user") {
781
+ // `cotal space delete` removes the streams from a broker that keeps running; it has no user-auth
782
+ // route. When every one is gone they are created again here, as a broker start would, and a
783
+ // partial loss is left alone.
784
+ failedRole = "broker";
785
+ streamsRecreated = await native.recreateDeletedStreams({ root, space, server, mode, ...(request.manifest ? { seed: request.manifest.seed } : request.channels ? { channels: request.channels } : {}) });
786
+ failedRole = undefined;
787
+ }
434
788
  // Auth service, user stacks only. Its native preparation came from this broker preparation, so
435
789
  // a stopped auth service under an already-running broker is not started from guessed material.
436
790
  if (mode === "user") {
@@ -443,7 +797,7 @@ export async function startControllerStack(request, native) {
443
797
  if (prepared?.user) {
444
798
  failedRole = "auth";
445
799
  const confirmed = await confirmUserAuthEndpoints(prepared.user, space, instance);
446
- native.recordMesh({ space, server, root, mode, tlsRequired: prepared.transport.kind === "tls-required", storeDir: prepared.storeDir, userAuth: confirmed, ...(request.maxSessions !== undefined ? { maxSessions: request.maxSessions } : {}), ...(brokerHost ? { attachHost: brokerHost } : {}), ...(brokerCap !== undefined ? { maxFileStore: brokerCap } : {}) });
800
+ native.recordMesh({ space, server, root, mode, tlsRequired: prepared.transport.kind === "tls-required", storeDir: prepared.storeDir, userAuth: confirmed, ...(maxSessions !== undefined ? { maxSessions } : {}), ...(brokerHost ? { attachHost: brokerHost } : {}), ...(brokerCap !== undefined ? { maxFileStore: brokerCap } : {}) });
447
801
  failedRole = undefined;
448
802
  }
449
803
  }
@@ -492,8 +846,8 @@ export async function startControllerStack(request, native) {
492
846
  const options = { root, runtime: request.runtime, server };
493
847
  if (prepared?.setup?.wsPort !== undefined)
494
848
  options["ws-port"] = prepared.setup.wsPort;
495
- if (request.maxSessions !== undefined)
496
- options["max-sessions"] = request.maxSessions;
849
+ if (maxSessions !== undefined)
850
+ options["max-sessions"] = maxSessions;
497
851
  if (brokerHost)
498
852
  options["console-host"] = brokerHost;
499
853
  if (request.manifest) {
@@ -515,11 +869,38 @@ export async function startControllerStack(request, native) {
515
869
  settle("completed");
516
870
  }
517
871
  catch (caught) {
518
- // `cotal space delete` removes the streams from a broker that keeps running, and a reused broker
519
- // gets none back, so the stack has to restart for its broker start to create them.
872
+ // A reused broker that lost some of the space's streams, but not all of them as `cotal space delete`
873
+ // leaves it, gets none back here; a broker start creates the missing ones.
520
874
  const error = brokerReused && isJetStreamMissing(caught, JetStreamApiCodes.StreamNotFound)
521
- ? new CommandFailure("refused", "TARGET_NOT_FOUND", "the running broker no longer holds this space's streams, as after cotal space delete, and up creates them only when it starts the broker", { remedy: "restart the stack with cotal down --yes, then cotal up, which creates them again, empty" })
522
- : caught;
875
+ ? new CommandFailure("refused", "TARGET_NOT_FOUND", "the running broker is missing some of this space's streams, and up creates them on a running broker only when every one is gone, as after cotal space delete", { remedy: "restart the stack with cotal down --yes, then cotal up, which creates the missing ones" })
876
+ : reusedWithoutJetStream(caught, brokerReused, root, space) ?? caught;
877
+ // A broker this call started that could not create the space's streams serves no stack, and a
878
+ // later up would reuse it and fail the same way. It is stopped again here, so the next up starts
879
+ // a fresh broker, and the run is a failure whose cause its log names.
880
+ const unserved = failedStage === "broker-streams" && startedBroker ? await stopUnservedBroker(space, startedBroker.definition, startedBroker.id) : undefined;
881
+ if (unserved) {
882
+ mark("broker", { state: "stopped", code: "OPERATION_FAILED" });
883
+ for (const row of journal.members.filter((member) => member.state === "planned"))
884
+ mark(row.role, { state: "not-attempted" });
885
+ settle("failed");
886
+ const nativeCause = error instanceof JetStreamApiError && Number.isSafeInteger(error.code) ? { code: String(error.code) } : undefined;
887
+ // JetStream answers 10047, insufficient storage resources, when the file store cannot hold a
888
+ // stream's reservation; the broker logs nothing about it.
889
+ const noStorage = error instanceof JetStreamApiError && error.code === 10047;
890
+ const storeRemedy = `with at least ${MIN_FILE_STORE} bytes, the least the space's streams start on, plus room for messages`;
891
+ throw new CommandFailure("failed", "OPERATION_FAILED", `the broker this command started could not create the space's streams${unserved.outOfFiles ? ", because it ran out of open files" : noStorage ? `, because its JetStream file store${brokerCap !== undefined ? ` cap (--max-file-store ${brokerCap})` : ""} has too little room for them` : ""}, so it was stopped again; nothing of the stack runs`, {
892
+ target: { root, space, operation: journal.operation.id, members: journal.members, ...(unserved.log ? { brokerLog: unserved.log } : {}) },
893
+ changed: [instanceProjection(unserved.stopped)],
894
+ ...(nativeCause ? { native: nativeCause } : {}),
895
+ remedy: unserved.outOfFiles
896
+ ? `raise the open-file limit (ulimit -n) of the shell that runs cotal up, then run cotal up again from ${root}`
897
+ : noStorage
898
+ ? brokerCap !== undefined
899
+ ? `run cotal up --max-file-store <bytes> from ${root} ${storeRemedy}`
900
+ : `free space on the filesystem that holds ${brokerStore ?? join(root, ".cotal", "nats")}, or run cotal up --max-file-store <bytes> from ${root} ${storeRemedy}`
901
+ : `fix what the broker's log${unserved.log ? ` at ${unserved.log}` : ""} names, then run cotal up again from ${root}`,
902
+ });
903
+ }
523
904
  const failure = isCommandFailure(error) ? error : undefined;
524
905
  const uncertain = failure === undefined || failure.outcome === "unknown";
525
906
  const pending = failedRole ? journal.members.find((row) => row.role === failedRole) : journal.members.find((row) => row.state === "planned");
@@ -535,8 +916,16 @@ export async function startControllerStack(request, native) {
535
916
  ? { code: String(error.code), ...(Number.isSafeInteger(error.status) && error.status >= 400 && error.status < 600 ? { detail: { status: error.status } } : {}) }
536
917
  : undefined;
537
918
  // The member's own sentence and remedy are what a reader can act on, such as a busy broker port.
538
- const cause = pending && failure ? ` (${pending.role}: ${failure.message})` : "";
539
- throw new CommandFailure(outcome, uncertain ? "OPERATION_UNKNOWN" : changed.length ? "OPERATION_PARTIAL" : failure.code, `the controller stack did not start every planned member${cause}; started members were kept and nothing was retried`, { target: { root, space, operation: journal.operation.id, members: journal.members, ...(failedStage ? { stage: failedStage } : {}) }, changed, ...(nativeCause ? { native: nativeCause } : {}), remedy: !uncertain && failure?.remedy ? failure.remedy : `inspect the stack's members with cotal service --space ${space} before another cotal up; a later bare cotal down stops only the recorded members` });
919
+ // A member that could not connect to a broker which ran out of open files names only that; the
920
+ // broker's log names the cause, and a running broker keeps the limit it started with.
921
+ const starved = pending && failure && pending.role !== "broker" ? brokerOutOfFilesLog(space) : undefined;
922
+ // A member that writes to the store, as delivery writes its lease, cannot start while the store
923
+ // is over its cap: the broker refuses that write as every other until there is room.
924
+ const full = pending && failure && pending.role !== "broker" && starved === undefined ? await storeFullAfterStart(root, space) : undefined;
925
+ const cause = pending && failure ? ` (${pending.role}: ${failure.message}${starved !== undefined ? `; the broker's log${starved ? ` at ${starved}` : ""} records that it ran out of open files` : full ? `; the broker's JetStream store ${full.path} is full at its --max-file-store cap of ${full.cap} bytes, so it refuses every write` : ""})` : "";
926
+ // A refusal or failure with no member started or reused leaves nothing of the stack running.
927
+ const none = !uncertain && !journal.members.some((row) => row.state === "started" || row.state === "reused");
928
+ throw new CommandFailure(outcome, uncertain ? "OPERATION_UNKNOWN" : changed.length ? "OPERATION_PARTIAL" : failure.code, none ? `the controller stack started no member${cause}; nothing was retried` : `the controller stack did not start every planned member${cause}; started members were kept and nothing was retried`, { target: { root, space, operation: journal.operation.id, members: journal.members, ...(failedStage ? { stage: failedStage } : {}) }, changed, ...(nativeCause ? { native: nativeCause } : {}), remedy: starved !== undefined ? `stop the stack with cotal down --yes from ${root}, raise the open-file limit (ulimit -n) of the shell that runs cotal up, then run cotal up there again` : full ? fullStoreUpRemedy(root, space) : !uncertain && failure?.remedy ? failure.remedy : `inspect the stack's members with cotal service --space ${shellWord(space)} before another cotal up; a later bare cotal down stops only the recorded members` });
540
929
  }
541
930
  if (loginBlock) {
542
931
  mark("manager", { state: "not-attempted", code: "AUTH_REQUIRED" });
@@ -553,15 +942,53 @@ export async function startControllerStack(request, native) {
553
942
  : "the user stack's other members were already running and were reused; the manager was not attempted because no signed-in, granted login exists. This is not whole-stack readiness", { target: detail, changed, native: { code: "AUTH_REQUIRED", outcome: "refused", detail: loginBlock.message }, ...(loginBlock.remedy ? { remedy: loginBlock.remedy } : {}) });
554
943
  }
555
944
  const allReused = journal.members.every((row) => row.state === "reused" || row.state === "not-attempted");
556
- return { journal, changed, allReused, ...(launch ? { launch } : {}), ...(admittedRestore ? { admittedRestore } : {}), ...(settled ? { settled } : {}) };
945
+ return { journal, changed, allReused, ...(storeTenants.length ? { storeShared: { path: storePath, tenants: storeTenants } } : {}), ...(storeMissing && !brokerReused ? { storeMissing: storePath } : {}), ...(launch ? { launch } : {}), ...(admittedRestore ? { admittedRestore } : {}), ...(settled ? { settled } : {}), ...(brokerExecutable ? { brokerExecutable } : {}), ...(streamsRecreated ? { streamsRecreated: true } : {}), ...(rotation ? { rotation } : {}) };
946
+ }
947
+ /** Stop a broker this call started, through its exact kernel stop, and read whether its log says it
948
+ * ran out of open files. A stop that does not confirm returns nothing, so the caller reports the
949
+ * run as unknown and names the inspection step instead. */
950
+ async function stopUnservedBroker(space, definition, id) {
951
+ try {
952
+ const current = serviceInstanceStore(space).read(id);
953
+ if (!current)
954
+ return undefined;
955
+ const plan = await prepareKernelServiceStop(definition, current);
956
+ const { instance } = await stopProcessService(definition, current, undefined, undefined, { plan });
957
+ if (observeServiceProcess(instance.record.value) === "running")
958
+ return undefined;
959
+ const log = readServiceLog(space, id, 200);
960
+ return { stopped: instance, log: log.path, outOfFiles: log.lines.some((line) => /too many open files/i.test(line)) };
961
+ }
962
+ catch {
963
+ return undefined;
964
+ }
965
+ }
966
+ /** This space's broker log when its tail records that the broker ran out of open files, or null when
967
+ * that log has no path. Undefined when it records no such thing or cannot be read. */
968
+ function brokerOutOfFilesLog(space) {
969
+ try {
970
+ const rows = serviceInstances(space, STACK_DEFINITION.broker);
971
+ if (rows.length !== 1)
972
+ return undefined;
973
+ const log = readServiceLog(space, rows[0].name, 200);
974
+ return log.lines.some((line) => /too many open files/i.test(line)) ? log.path : undefined;
975
+ }
976
+ catch {
977
+ return undefined;
978
+ }
557
979
  }
558
980
  /** The member table and evidence text a caller embeds in its own receipt. */
559
981
  export function stackMembersView(journal, title) {
560
982
  return membersView(journal, title);
561
983
  }
562
- export function stackUpForegroundNotice(presentation, space) {
984
+ /** The notice a foreground `up` prints before it blocks. With `takeover`, the stack already runs, started
985
+ * by a background `up` or a foreground one that has exited, and this terminal takes its lifetime over. */
986
+ export function stackUpForegroundNotice(presentation, space, takeover = false) {
563
987
  if (presentation === "json")
564
988
  return;
565
- console.log(renderReport({ space, sections: [{ title: "Foreground stack lifetime", blocks: [{ kind: "lines", lines: ["This terminal holds the stack's lifetime. Ctrl-C or SIGTERM runs the same guarded whole-stack stop as bare cotal down, including its manager impact review. Terminal loss or an external kill is not a confirmed stop."] }] }] }, presentation, terminalWidth(process.stdout)));
989
+ const holds = takeover
990
+ ? "This stack is already running, and this terminal now takes over its lifetime. Ctrl-C or SIGTERM here stops the whole stack, though another command started it, with the same guarded whole-stack stop as bare cotal down, including its manager impact review."
991
+ : "This terminal holds the stack's lifetime. Ctrl-C or SIGTERM runs the same guarded whole-stack stop as bare cotal down, including its manager impact review.";
992
+ console.log(renderReport({ space, sections: [{ title: "Foreground stack lifetime", blocks: [{ kind: "lines", lines: [`${holds} Terminal loss or an external kill is not a confirmed stop.`] }] }] }, presentation, terminalWidth(process.stdout)));
566
993
  }
567
994
  //# sourceMappingURL=stack-up.js.map