@cotal-ai/cli 0.90.1 → 0.92.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 (775) hide show
  1. package/dist/chat/chat-view.d.ts +17 -0
  2. package/dist/chat/chat-view.d.ts.map +1 -0
  3. package/dist/chat/chat-view.js +179 -0
  4. package/dist/chat/chat-view.js.map +1 -0
  5. package/dist/chat/controller.d.ts +20 -0
  6. package/dist/chat/controller.d.ts.map +1 -0
  7. package/dist/chat/controller.js +132 -0
  8. package/dist/chat/controller.js.map +1 -0
  9. package/dist/chat/engine.d.ts +110 -0
  10. package/dist/chat/engine.d.ts.map +1 -0
  11. package/dist/chat/engine.js +224 -0
  12. package/dist/chat/engine.js.map +1 -0
  13. package/dist/chat/frontend.d.ts +35 -0
  14. package/dist/chat/frontend.d.ts.map +1 -0
  15. package/dist/chat/frontend.js +166 -0
  16. package/dist/chat/frontend.js.map +1 -0
  17. package/dist/chat/native-session.d.ts +93 -0
  18. package/dist/chat/native-session.d.ts.map +1 -0
  19. package/dist/chat/native-session.js +389 -0
  20. package/dist/chat/native-session.js.map +1 -0
  21. package/dist/chat/open-session.d.ts +8 -0
  22. package/dist/chat/open-session.d.ts.map +1 -0
  23. package/dist/chat/open-session.js +120 -0
  24. package/dist/chat/open-session.js.map +1 -0
  25. package/dist/chat/picker.d.ts +35 -0
  26. package/dist/chat/picker.d.ts.map +1 -0
  27. package/dist/chat/picker.js +99 -0
  28. package/dist/chat/picker.js.map +1 -0
  29. package/dist/chat/plain.d.ts +15 -0
  30. package/dist/chat/plain.d.ts.map +1 -0
  31. package/dist/chat/plain.js +249 -0
  32. package/dist/chat/plain.js.map +1 -0
  33. package/dist/chat/session.d.ts +222 -0
  34. package/dist/chat/session.d.ts.map +1 -0
  35. package/dist/chat/session.js +2 -0
  36. package/dist/chat/session.js.map +1 -0
  37. package/dist/chat/static-session.d.ts +61 -0
  38. package/dist/chat/static-session.d.ts.map +1 -0
  39. package/dist/chat/static-session.js +212 -0
  40. package/dist/chat/static-session.js.map +1 -0
  41. package/dist/chat/stdio-io.d.ts +35 -0
  42. package/dist/chat/stdio-io.d.ts.map +1 -0
  43. package/dist/chat/stdio-io.js +176 -0
  44. package/dist/chat/stdio-io.js.map +1 -0
  45. package/dist/chat/stdio.d.ts +173 -0
  46. package/dist/chat/stdio.d.ts.map +1 -0
  47. package/dist/chat/stdio.js +401 -0
  48. package/dist/chat/stdio.js.map +1 -0
  49. package/dist/chat/user-session.d.ts +21 -0
  50. package/dist/chat/user-session.d.ts.map +1 -0
  51. package/dist/chat/user-session.js +180 -0
  52. package/dist/chat/user-session.js.map +1 -0
  53. package/dist/chat/view.d.ts +217 -0
  54. package/dist/chat/view.d.ts.map +1 -0
  55. package/dist/chat/view.js +433 -0
  56. package/dist/chat/view.js.map +1 -0
  57. package/dist/command.d.ts +11 -3
  58. package/dist/command.d.ts.map +1 -1
  59. package/dist/command.js +395 -147
  60. package/dist/command.js.map +1 -1
  61. package/dist/commands/agents.d.ts +103 -11
  62. package/dist/commands/agents.d.ts.map +1 -1
  63. package/dist/commands/agents.js +506 -251
  64. package/dist/commands/agents.js.map +1 -1
  65. package/dist/commands/app-identity.d.ts.map +1 -1
  66. package/dist/commands/app-identity.js +10 -1
  67. package/dist/commands/app-identity.js.map +1 -1
  68. package/dist/commands/backup-maintenance.d.ts +4 -0
  69. package/dist/commands/backup-maintenance.d.ts.map +1 -0
  70. package/dist/commands/backup-maintenance.js +93 -0
  71. package/dist/commands/backup-maintenance.js.map +1 -0
  72. package/dist/commands/backup-read.d.ts +4 -0
  73. package/dist/commands/backup-read.d.ts.map +1 -0
  74. package/dist/commands/backup-read.js +30 -0
  75. package/dist/commands/backup-read.js.map +1 -0
  76. package/dist/commands/backup-restore.d.ts +7 -0
  77. package/dist/commands/backup-restore.d.ts.map +1 -0
  78. package/dist/commands/backup-restore.js +78 -0
  79. package/dist/commands/backup-restore.js.map +1 -0
  80. package/dist/commands/backup.d.ts +2 -1
  81. package/dist/commands/backup.d.ts.map +1 -1
  82. package/dist/commands/backup.js +123 -32
  83. package/dist/commands/backup.js.map +1 -1
  84. package/dist/commands/channel-members.d.ts +8 -0
  85. package/dist/commands/channel-members.d.ts.map +1 -0
  86. package/dist/commands/channel-members.js +144 -0
  87. package/dist/commands/channel-members.js.map +1 -0
  88. package/dist/commands/channels.d.ts +75 -22
  89. package/dist/commands/channels.d.ts.map +1 -1
  90. package/dist/commands/channels.js +181 -100
  91. package/dist/commands/channels.js.map +1 -1
  92. package/dist/commands/chat.d.ts +109 -0
  93. package/dist/commands/chat.d.ts.map +1 -0
  94. package/dist/commands/chat.js +227 -0
  95. package/dist/commands/chat.js.map +1 -0
  96. package/dist/commands/clean.d.ts +43 -1
  97. package/dist/commands/clean.d.ts.map +1 -1
  98. package/dist/commands/clean.js +90 -47
  99. package/dist/commands/clean.js.map +1 -1
  100. package/dist/commands/completion.d.ts +39 -1
  101. package/dist/commands/completion.d.ts.map +1 -1
  102. package/dist/commands/completion.js +211 -87
  103. package/dist/commands/completion.js.map +1 -1
  104. package/dist/commands/config.d.ts +33 -0
  105. package/dist/commands/config.d.ts.map +1 -0
  106. package/dist/commands/config.js +159 -0
  107. package/dist/commands/config.js.map +1 -0
  108. package/dist/commands/console.d.ts.map +1 -1
  109. package/dist/commands/console.js +25 -7
  110. package/dist/commands/console.js.map +1 -1
  111. package/dist/commands/describe.d.ts +63 -31
  112. package/dist/commands/describe.d.ts.map +1 -1
  113. package/dist/commands/describe.js +270 -136
  114. package/dist/commands/describe.js.map +1 -1
  115. package/dist/commands/doctor.d.ts +11 -6
  116. package/dist/commands/doctor.d.ts.map +1 -1
  117. package/dist/commands/doctor.js +195 -288
  118. package/dist/commands/doctor.js.map +1 -1
  119. package/dist/commands/down-services.d.ts +29 -0
  120. package/dist/commands/down-services.d.ts.map +1 -0
  121. package/dist/commands/down-services.js +129 -0
  122. package/dist/commands/down-services.js.map +1 -0
  123. package/dist/commands/down.d.ts +37 -11
  124. package/dist/commands/down.d.ts.map +1 -1
  125. package/dist/commands/down.js +384 -117
  126. package/dist/commands/down.js.map +1 -1
  127. package/dist/commands/endpoint-authoring.d.ts +6 -0
  128. package/dist/commands/endpoint-authoring.d.ts.map +1 -0
  129. package/dist/commands/endpoint-authoring.js +130 -0
  130. package/dist/commands/endpoint-authoring.js.map +1 -0
  131. package/dist/commands/endpoint-deregister.d.ts +5 -0
  132. package/dist/commands/endpoint-deregister.d.ts.map +1 -0
  133. package/dist/commands/endpoint-deregister.js +70 -0
  134. package/dist/commands/endpoint-deregister.js.map +1 -0
  135. package/dist/commands/endpoint.d.ts +118 -0
  136. package/dist/commands/endpoint.d.ts.map +1 -0
  137. package/dist/commands/endpoint.js +177 -0
  138. package/dist/commands/endpoint.js.map +1 -0
  139. package/dist/commands/endpoints.d.ts +27 -1
  140. package/dist/commands/endpoints.d.ts.map +1 -1
  141. package/dist/commands/endpoints.js +42 -30
  142. package/dist/commands/endpoints.js.map +1 -1
  143. package/dist/commands/ext.d.ts +38 -1
  144. package/dist/commands/ext.d.ts.map +1 -1
  145. package/dist/commands/ext.js +84 -49
  146. package/dist/commands/ext.js.map +1 -1
  147. package/dist/commands/feedback.d.ts +58 -1
  148. package/dist/commands/feedback.d.ts.map +1 -1
  149. package/dist/commands/feedback.js +119 -47
  150. package/dist/commands/feedback.js.map +1 -1
  151. package/dist/commands/help.d.ts +20 -0
  152. package/dist/commands/help.d.ts.map +1 -0
  153. package/dist/commands/help.js +52 -0
  154. package/dist/commands/help.js.map +1 -0
  155. package/dist/commands/history-clear.d.ts +14 -0
  156. package/dist/commands/history-clear.d.ts.map +1 -0
  157. package/dist/commands/history-clear.js +74 -0
  158. package/dist/commands/history-clear.js.map +1 -0
  159. package/dist/commands/history.d.ts +146 -4
  160. package/dist/commands/history.d.ts.map +1 -1
  161. package/dist/commands/history.js +437 -19
  162. package/dist/commands/history.js.map +1 -1
  163. package/dist/commands/join.d.ts.map +1 -1
  164. package/dist/commands/join.js +7 -3
  165. package/dist/commands/join.js.map +1 -1
  166. package/dist/commands/meshes-add.d.ts +3 -0
  167. package/dist/commands/meshes-add.d.ts.map +1 -1
  168. package/dist/commands/meshes-add.js +41 -34
  169. package/dist/commands/meshes-add.js.map +1 -1
  170. package/dist/commands/meshes-wizard.js +3 -3
  171. package/dist/commands/meshes-wizard.js.map +1 -1
  172. package/dist/commands/mint-endpoint-caller.d.ts +5 -0
  173. package/dist/commands/mint-endpoint-caller.d.ts.map +1 -0
  174. package/dist/commands/mint-endpoint-caller.js +130 -0
  175. package/dist/commands/mint-endpoint-caller.js.map +1 -0
  176. package/dist/commands/mint.d.ts +2 -37
  177. package/dist/commands/mint.d.ts.map +1 -1
  178. package/dist/commands/mint.js +142 -325
  179. package/dist/commands/mint.js.map +1 -1
  180. package/dist/commands/models.d.ts +30 -8
  181. package/dist/commands/models.d.ts.map +1 -1
  182. package/dist/commands/models.js +72 -41
  183. package/dist/commands/models.js.map +1 -1
  184. package/dist/commands/persona-remote.d.ts +5 -0
  185. package/dist/commands/persona-remote.d.ts.map +1 -0
  186. package/dist/commands/persona-remote.js +237 -0
  187. package/dist/commands/persona-remote.js.map +1 -0
  188. package/dist/commands/persona.d.ts +91 -0
  189. package/dist/commands/persona.d.ts.map +1 -0
  190. package/dist/commands/persona.js +200 -0
  191. package/dist/commands/persona.js.map +1 -0
  192. package/dist/commands/personas.d.ts.map +1 -1
  193. package/dist/commands/personas.js +16 -59
  194. package/dist/commands/personas.js.map +1 -1
  195. package/dist/commands/reset-space-apply.d.ts +5 -0
  196. package/dist/commands/reset-space-apply.d.ts.map +1 -0
  197. package/dist/commands/reset-space-apply.js +127 -0
  198. package/dist/commands/reset-space-apply.js.map +1 -0
  199. package/dist/commands/reset-store-apply.d.ts +35 -0
  200. package/dist/commands/reset-store-apply.d.ts.map +1 -0
  201. package/dist/commands/reset-store-apply.js +216 -0
  202. package/dist/commands/reset-store-apply.js.map +1 -0
  203. package/dist/commands/reset.d.ts +26 -0
  204. package/dist/commands/reset.d.ts.map +1 -0
  205. package/dist/commands/reset.js +155 -0
  206. package/dist/commands/reset.js.map +1 -0
  207. package/dist/commands/runtimes.d.ts +26 -1
  208. package/dist/commands/runtimes.d.ts.map +1 -1
  209. package/dist/commands/runtimes.js +68 -32
  210. package/dist/commands/runtimes.js.map +1 -1
  211. package/dist/commands/send.d.ts +91 -6
  212. package/dist/commands/send.d.ts.map +1 -1
  213. package/dist/commands/send.js +180 -106
  214. package/dist/commands/send.js.map +1 -1
  215. package/dist/commands/service-actions.d.ts +6 -0
  216. package/dist/commands/service-actions.d.ts.map +1 -0
  217. package/dist/commands/service-actions.js +413 -0
  218. package/dist/commands/service-actions.js.map +1 -0
  219. package/dist/commands/service-log-follow.d.ts +5 -0
  220. package/dist/commands/service-log-follow.d.ts.map +1 -0
  221. package/dist/commands/service-log-follow.js +107 -0
  222. package/dist/commands/service-log-follow.js.map +1 -0
  223. package/dist/commands/service-registry.d.ts +67 -0
  224. package/dist/commands/service-registry.d.ts.map +1 -0
  225. package/dist/commands/service-registry.js +275 -0
  226. package/dist/commands/service-registry.js.map +1 -0
  227. package/dist/commands/service-set-stop.d.ts +6 -0
  228. package/dist/commands/service-set-stop.d.ts.map +1 -0
  229. package/dist/commands/service-set-stop.js +164 -0
  230. package/dist/commands/service-set-stop.js.map +1 -0
  231. package/dist/commands/service-unit-entry.d.ts +5 -0
  232. package/dist/commands/service-unit-entry.d.ts.map +1 -0
  233. package/dist/commands/service-unit-entry.js +113 -0
  234. package/dist/commands/service-unit-entry.js.map +1 -0
  235. package/dist/commands/setup-start.d.ts +21 -0
  236. package/dist/commands/setup-start.d.ts.map +1 -0
  237. package/dist/commands/setup-start.js +95 -0
  238. package/dist/commands/setup-start.js.map +1 -0
  239. package/dist/commands/setup.d.ts +86 -100
  240. package/dist/commands/setup.d.ts.map +1 -1
  241. package/dist/commands/setup.js +766 -487
  242. package/dist/commands/setup.js.map +1 -1
  243. package/dist/commands/space-delete.d.ts +3 -0
  244. package/dist/commands/space-delete.d.ts.map +1 -0
  245. package/dist/commands/space-delete.js +386 -0
  246. package/dist/commands/space-delete.js.map +1 -0
  247. package/dist/commands/space-registration.d.ts +92 -0
  248. package/dist/commands/space-registration.d.ts.map +1 -0
  249. package/dist/commands/space-registration.js +394 -0
  250. package/dist/commands/space-registration.js.map +1 -0
  251. package/dist/commands/space.d.ts +128 -0
  252. package/dist/commands/space.d.ts.map +1 -0
  253. package/dist/commands/space.js +230 -0
  254. package/dist/commands/space.js.map +1 -0
  255. package/dist/commands/spawn-manifest.d.ts.map +1 -1
  256. package/dist/commands/spawn-manifest.js +2 -2
  257. package/dist/commands/spawn-manifest.js.map +1 -1
  258. package/dist/commands/spawn-preview.d.ts +9 -0
  259. package/dist/commands/spawn-preview.d.ts.map +1 -0
  260. package/dist/commands/spawn-preview.js +68 -0
  261. package/dist/commands/spawn-preview.js.map +1 -0
  262. package/dist/commands/spawn.d.ts +81 -21
  263. package/dist/commands/spawn.d.ts.map +1 -1
  264. package/dist/commands/spawn.js +254 -107
  265. package/dist/commands/spawn.js.map +1 -1
  266. package/dist/commands/stack-down.d.ts +20 -0
  267. package/dist/commands/stack-down.d.ts.map +1 -0
  268. package/dist/commands/stack-down.js +313 -0
  269. package/dist/commands/stack-down.js.map +1 -0
  270. package/dist/commands/stack-up.d.ts +154 -0
  271. package/dist/commands/stack-up.d.ts.map +1 -0
  272. package/dist/commands/stack-up.js +498 -0
  273. package/dist/commands/stack-up.js.map +1 -0
  274. package/dist/commands/stack-user-auth.d.ts +52 -0
  275. package/dist/commands/stack-user-auth.d.ts.map +1 -0
  276. package/dist/commands/stack-user-auth.js +128 -0
  277. package/dist/commands/stack-user-auth.js.map +1 -0
  278. package/dist/commands/status.d.ts +244 -5
  279. package/dist/commands/status.d.ts.map +1 -1
  280. package/dist/commands/status.js +1044 -407
  281. package/dist/commands/status.js.map +1 -1
  282. package/dist/commands/sync.d.ts +23 -0
  283. package/dist/commands/sync.d.ts.map +1 -1
  284. package/dist/commands/sync.js +69 -17
  285. package/dist/commands/sync.js.map +1 -1
  286. package/dist/commands/team-agent-apply.d.ts +5 -0
  287. package/dist/commands/team-agent-apply.d.ts.map +1 -0
  288. package/dist/commands/team-agent-apply.js +204 -0
  289. package/dist/commands/team-agent-apply.js.map +1 -0
  290. package/dist/commands/team-agent-remove.d.ts +87 -0
  291. package/dist/commands/team-agent-remove.d.ts.map +1 -0
  292. package/dist/commands/team-agent-remove.js +348 -0
  293. package/dist/commands/team-agent-remove.js.map +1 -0
  294. package/dist/commands/team-boot-controller.d.ts +11 -0
  295. package/dist/commands/team-boot-controller.d.ts.map +1 -0
  296. package/dist/commands/team-boot-controller.js +176 -0
  297. package/dist/commands/team-boot-controller.js.map +1 -0
  298. package/dist/commands/team-channel-remove.d.ts +167 -0
  299. package/dist/commands/team-channel-remove.d.ts.map +1 -0
  300. package/dist/commands/team-channel-remove.js +486 -0
  301. package/dist/commands/team-channel-remove.js.map +1 -0
  302. package/dist/commands/team-deploy-apply.d.ts +11 -0
  303. package/dist/commands/team-deploy-apply.d.ts.map +1 -0
  304. package/dist/commands/team-deploy-apply.js +320 -0
  305. package/dist/commands/team-deploy-apply.js.map +1 -0
  306. package/dist/commands/team-mixed-remove.d.ts +8 -0
  307. package/dist/commands/team-mixed-remove.d.ts.map +1 -0
  308. package/dist/commands/team-mixed-remove.js +207 -0
  309. package/dist/commands/team-mixed-remove.js.map +1 -0
  310. package/dist/commands/team.d.ts +51 -0
  311. package/dist/commands/team.d.ts.map +1 -0
  312. package/dist/commands/team.js +728 -0
  313. package/dist/commands/team.js.map +1 -0
  314. package/dist/commands/topology.d.ts +4 -0
  315. package/dist/commands/topology.d.ts.map +1 -1
  316. package/dist/commands/topology.js +8 -0
  317. package/dist/commands/topology.js.map +1 -1
  318. package/dist/commands/up.d.ts +146 -6
  319. package/dist/commands/up.d.ts.map +1 -1
  320. package/dist/commands/up.js +1123 -131
  321. package/dist/commands/up.js.map +1 -1
  322. package/dist/commands/update.d.ts +13 -0
  323. package/dist/commands/update.d.ts.map +1 -1
  324. package/dist/commands/update.js +90 -22
  325. package/dist/commands/update.js.map +1 -1
  326. package/dist/commands/use.d.ts +16 -3
  327. package/dist/commands/use.d.ts.map +1 -1
  328. package/dist/commands/use.js +45 -19
  329. package/dist/commands/use.js.map +1 -1
  330. package/dist/commands/watch.d.ts +37 -0
  331. package/dist/commands/watch.d.ts.map +1 -0
  332. package/dist/commands/watch.js +106 -0
  333. package/dist/commands/watch.js.map +1 -0
  334. package/dist/commands/who.d.ts +79 -0
  335. package/dist/commands/who.d.ts.map +1 -0
  336. package/dist/commands/who.js +193 -0
  337. package/dist/commands/who.js.map +1 -0
  338. package/dist/commands/whoami.d.ts +56 -0
  339. package/dist/commands/whoami.d.ts.map +1 -0
  340. package/dist/commands/whoami.js +106 -0
  341. package/dist/commands/whoami.js.map +1 -0
  342. package/dist/console/app.d.ts.map +1 -1
  343. package/dist/console/app.js +8 -4
  344. package/dist/console/app.js.map +1 -1
  345. package/dist/console/commands.d.ts.map +1 -1
  346. package/dist/console/commands.js +12 -6
  347. package/dist/console/commands.js.map +1 -1
  348. package/dist/exec-endpoint/definition.d.ts +15 -0
  349. package/dist/exec-endpoint/definition.d.ts.map +1 -0
  350. package/dist/exec-endpoint/definition.js +56 -0
  351. package/dist/exec-endpoint/definition.js.map +1 -0
  352. package/dist/exec-endpoint/handler.d.ts +13 -0
  353. package/dist/exec-endpoint/handler.d.ts.map +1 -0
  354. package/dist/exec-endpoint/handler.js +155 -0
  355. package/dist/exec-endpoint/handler.js.map +1 -0
  356. package/dist/exec-endpoint/registration.d.ts +34 -0
  357. package/dist/exec-endpoint/registration.d.ts.map +1 -0
  358. package/dist/exec-endpoint/registration.js +148 -0
  359. package/dist/exec-endpoint/registration.js.map +1 -0
  360. package/dist/exec-endpoint/serve.d.ts +8 -0
  361. package/dist/exec-endpoint/serve.d.ts.map +1 -0
  362. package/dist/exec-endpoint/serve.js +159 -0
  363. package/dist/exec-endpoint/serve.js.map +1 -0
  364. package/dist/exec-endpoint/service-adapter.d.ts +6 -0
  365. package/dist/exec-endpoint/service-adapter.d.ts.map +1 -0
  366. package/dist/exec-endpoint/service-adapter.js +110 -0
  367. package/dist/exec-endpoint/service-adapter.js.map +1 -0
  368. package/dist/ext-loader.d.ts +10 -0
  369. package/dist/ext-loader.d.ts.map +1 -1
  370. package/dist/ext-loader.js +61 -13
  371. package/dist/ext-loader.js.map +1 -1
  372. package/dist/help.d.ts +18 -0
  373. package/dist/help.d.ts.map +1 -0
  374. package/dist/help.js +256 -0
  375. package/dist/help.js.map +1 -0
  376. package/dist/index.d.ts +3 -0
  377. package/dist/index.d.ts.map +1 -1
  378. package/dist/index.js +446 -119
  379. package/dist/index.js.map +1 -1
  380. package/dist/lib/assist.d.ts.map +1 -1
  381. package/dist/lib/assist.js +3 -2
  382. package/dist/lib/assist.js.map +1 -1
  383. package/dist/lib/attach-client.d.ts +7 -6
  384. package/dist/lib/attach-client.d.ts.map +1 -1
  385. package/dist/lib/attach-client.js +14 -15
  386. package/dist/lib/attach-client.js.map +1 -1
  387. package/dist/lib/auth-proc.d.ts +3 -3
  388. package/dist/lib/auth-proc.d.ts.map +1 -1
  389. package/dist/lib/auth-proc.js +8 -8
  390. package/dist/lib/auth-proc.js.map +1 -1
  391. package/dist/lib/backup-artifact.d.ts +41 -1
  392. package/dist/lib/backup-artifact.d.ts.map +1 -1
  393. package/dist/lib/backup-artifact.js +96 -22
  394. package/dist/lib/backup-artifact.js.map +1 -1
  395. package/dist/lib/broker-service.d.ts +19 -0
  396. package/dist/lib/broker-service.d.ts.map +1 -0
  397. package/dist/lib/broker-service.js +369 -0
  398. package/dist/lib/broker-service.js.map +1 -0
  399. package/dist/lib/cancel.js +1 -1
  400. package/dist/lib/cancel.js.map +1 -1
  401. package/dist/lib/choose-target.d.ts +10 -0
  402. package/dist/lib/choose-target.d.ts.map +1 -0
  403. package/dist/lib/choose-target.js +42 -0
  404. package/dist/lib/choose-target.js.map +1 -0
  405. package/dist/lib/command-path.d.ts +13 -0
  406. package/dist/lib/command-path.d.ts.map +1 -0
  407. package/dist/lib/command-path.js +40 -0
  408. package/dist/lib/command-path.js.map +1 -0
  409. package/dist/lib/completion-install.d.ts +29 -0
  410. package/dist/lib/completion-install.d.ts.map +1 -0
  411. package/dist/lib/completion-install.js +369 -0
  412. package/dist/lib/completion-install.js.map +1 -0
  413. package/dist/lib/completion-scripts.d.ts +4 -0
  414. package/dist/lib/completion-scripts.d.ts.map +1 -0
  415. package/dist/lib/completion-scripts.js +15 -0
  416. package/dist/lib/completion-scripts.js.map +1 -0
  417. package/dist/lib/completion.d.ts.map +1 -1
  418. package/dist/lib/completion.js +4 -1
  419. package/dist/lib/completion.js.map +1 -1
  420. package/dist/lib/confirmation-required.d.ts +13 -0
  421. package/dist/lib/confirmation-required.d.ts.map +1 -0
  422. package/dist/lib/confirmation-required.js +10 -0
  423. package/dist/lib/confirmation-required.js.map +1 -0
  424. package/dist/lib/control.d.ts +65 -6
  425. package/dist/lib/control.d.ts.map +1 -1
  426. package/dist/lib/control.js +121 -27
  427. package/dist/lib/control.js.map +1 -1
  428. package/dist/lib/controller-preserve.d.ts +12 -0
  429. package/dist/lib/controller-preserve.d.ts.map +1 -0
  430. package/dist/lib/controller-preserve.js +373 -0
  431. package/dist/lib/controller-preserve.js.map +1 -0
  432. package/dist/lib/controller-restore.d.ts +38 -0
  433. package/dist/lib/controller-restore.d.ts.map +1 -0
  434. package/dist/lib/controller-restore.js +205 -0
  435. package/dist/lib/controller-restore.js.map +1 -0
  436. package/dist/lib/controller-resume.d.ts +92 -0
  437. package/dist/lib/controller-resume.d.ts.map +1 -0
  438. package/dist/lib/controller-resume.js +300 -0
  439. package/dist/lib/controller-resume.js.map +1 -0
  440. package/dist/lib/credential-authority.d.ts +17 -0
  441. package/dist/lib/credential-authority.d.ts.map +1 -0
  442. package/dist/lib/credential-authority.js +29 -0
  443. package/dist/lib/credential-authority.js.map +1 -0
  444. package/dist/lib/default-persona.d.ts +38 -0
  445. package/dist/lib/default-persona.d.ts.map +1 -0
  446. package/dist/lib/default-persona.js +85 -0
  447. package/dist/lib/default-persona.js.map +1 -0
  448. package/dist/lib/delivery-proc.d.ts +9 -9
  449. package/dist/lib/delivery-proc.d.ts.map +1 -1
  450. package/dist/lib/delivery-proc.js +44 -23
  451. package/dist/lib/delivery-proc.js.map +1 -1
  452. package/dist/lib/endpoint-capability-gates.d.ts +10 -0
  453. package/dist/lib/endpoint-capability-gates.d.ts.map +1 -0
  454. package/dist/lib/endpoint-capability-gates.js +70 -0
  455. package/dist/lib/endpoint-capability-gates.js.map +1 -0
  456. package/dist/lib/endpoint-client.d.ts +23 -0
  457. package/dist/lib/endpoint-client.d.ts.map +1 -0
  458. package/dist/lib/endpoint-client.js +46 -0
  459. package/dist/lib/endpoint-client.js.map +1 -0
  460. package/dist/lib/endpoint-errors.d.ts +20 -0
  461. package/dist/lib/endpoint-errors.d.ts.map +1 -0
  462. package/dist/lib/endpoint-errors.js +46 -0
  463. package/dist/lib/endpoint-errors.js.map +1 -0
  464. package/dist/lib/endpoint-goal.d.ts +19 -0
  465. package/dist/lib/endpoint-goal.d.ts.map +1 -0
  466. package/dist/lib/endpoint-goal.js +31 -0
  467. package/dist/lib/endpoint-goal.js.map +1 -0
  468. package/dist/lib/endpoint-inventory.d.ts +30 -0
  469. package/dist/lib/endpoint-inventory.d.ts.map +1 -0
  470. package/dist/lib/endpoint-inventory.js +79 -0
  471. package/dist/lib/endpoint-inventory.js.map +1 -0
  472. package/dist/lib/endpoint-references.d.ts +22 -0
  473. package/dist/lib/endpoint-references.d.ts.map +1 -0
  474. package/dist/lib/endpoint-references.js +44 -0
  475. package/dist/lib/endpoint-references.js.map +1 -0
  476. package/dist/lib/endpoint-scatter.d.ts +57 -0
  477. package/dist/lib/endpoint-scatter.d.ts.map +1 -0
  478. package/dist/lib/endpoint-scatter.js +75 -0
  479. package/dist/lib/endpoint-scatter.js.map +1 -0
  480. package/dist/lib/endpoint-selection.d.ts +35 -0
  481. package/dist/lib/endpoint-selection.d.ts.map +1 -0
  482. package/dist/lib/endpoint-selection.js +80 -0
  483. package/dist/lib/endpoint-selection.js.map +1 -0
  484. package/dist/lib/install-umask.d.ts +6 -0
  485. package/dist/lib/install-umask.d.ts.map +1 -0
  486. package/dist/lib/install-umask.js +15 -0
  487. package/dist/lib/install-umask.js.map +1 -0
  488. package/dist/lib/isolated-broker.d.ts.map +1 -1
  489. package/dist/lib/isolated-broker.js +9 -5
  490. package/dist/lib/isolated-broker.js.map +1 -1
  491. package/dist/lib/local-process-stop.d.ts.map +1 -1
  492. package/dist/lib/local-process-stop.js +7 -1
  493. package/dist/lib/local-process-stop.js.map +1 -1
  494. package/dist/lib/manager-proc.d.ts +11 -5
  495. package/dist/lib/manager-proc.d.ts.map +1 -1
  496. package/dist/lib/manager-proc.js +12 -17
  497. package/dist/lib/manager-proc.js.map +1 -1
  498. package/dist/lib/manifest/apply.d.ts +4 -1
  499. package/dist/lib/manifest/apply.d.ts.map +1 -1
  500. package/dist/lib/manifest/apply.js +1 -1
  501. package/dist/lib/manifest/apply.js.map +1 -1
  502. package/dist/lib/manifest/ledger.d.ts +3 -1
  503. package/dist/lib/manifest/ledger.d.ts.map +1 -1
  504. package/dist/lib/manifest/ledger.js +16 -3
  505. package/dist/lib/manifest/ledger.js.map +1 -1
  506. package/dist/lib/manifest/schema.d.ts +1 -117
  507. package/dist/lib/manifest/schema.d.ts.map +1 -1
  508. package/dist/lib/manifest/schema.js +1 -95
  509. package/dist/lib/manifest/schema.js.map +1 -1
  510. package/dist/lib/offline-recipient.d.ts +5 -0
  511. package/dist/lib/offline-recipient.d.ts.map +1 -0
  512. package/dist/lib/offline-recipient.js +7 -0
  513. package/dist/lib/offline-recipient.js.map +1 -0
  514. package/dist/lib/onboard.js +3 -3
  515. package/dist/lib/onboard.js.map +1 -1
  516. package/dist/lib/persona-files.d.ts +29 -0
  517. package/dist/lib/persona-files.d.ts.map +1 -0
  518. package/dist/lib/persona-files.js +154 -0
  519. package/dist/lib/persona-files.js.map +1 -0
  520. package/dist/lib/personas.d.ts +3 -0
  521. package/dist/lib/personas.d.ts.map +1 -1
  522. package/dist/lib/personas.js +14 -2
  523. package/dist/lib/personas.js.map +1 -1
  524. package/dist/lib/prompts.d.ts +16 -0
  525. package/dist/lib/prompts.d.ts.map +1 -0
  526. package/dist/lib/prompts.js +35 -0
  527. package/dist/lib/prompts.js.map +1 -0
  528. package/dist/lib/protected-records.d.ts +2 -0
  529. package/dist/lib/protected-records.d.ts.map +1 -0
  530. package/dist/lib/protected-records.js +3 -0
  531. package/dist/lib/protected-records.js.map +1 -0
  532. package/dist/lib/registry-errors.d.ts +4 -0
  533. package/dist/lib/registry-errors.d.ts.map +1 -0
  534. package/dist/lib/registry-errors.js +6 -0
  535. package/dist/lib/registry-errors.js.map +1 -0
  536. package/dist/lib/reset-space-plan.d.ts +36 -0
  537. package/dist/lib/reset-space-plan.d.ts.map +1 -0
  538. package/dist/lib/reset-space-plan.js +202 -0
  539. package/dist/lib/reset-space-plan.js.map +1 -0
  540. package/dist/lib/restore.d.ts +13 -1
  541. package/dist/lib/restore.d.ts.map +1 -1
  542. package/dist/lib/restore.js +73 -11
  543. package/dist/lib/restore.js.map +1 -1
  544. package/dist/lib/seat-resume.d.ts +4 -1
  545. package/dist/lib/seat-resume.d.ts.map +1 -1
  546. package/dist/lib/seat-resume.js +7 -4
  547. package/dist/lib/seat-resume.js.map +1 -1
  548. package/dist/lib/service-adapters.d.ts +32 -0
  549. package/dist/lib/service-adapters.d.ts.map +1 -0
  550. package/dist/lib/service-adapters.js +55 -0
  551. package/dist/lib/service-adapters.js.map +1 -0
  552. package/dist/lib/service-census.d.ts +73 -0
  553. package/dist/lib/service-census.d.ts.map +1 -0
  554. package/dist/lib/service-census.js +42 -0
  555. package/dist/lib/service-census.js.map +1 -0
  556. package/dist/lib/service-definitions.d.ts +49 -0
  557. package/dist/lib/service-definitions.d.ts.map +1 -0
  558. package/dist/lib/service-definitions.js +61 -0
  559. package/dist/lib/service-definitions.js.map +1 -0
  560. package/dist/lib/service-install-intent.d.ts +48 -0
  561. package/dist/lib/service-install-intent.d.ts.map +1 -0
  562. package/dist/lib/service-install-intent.js +95 -0
  563. package/dist/lib/service-install-intent.js.map +1 -0
  564. package/dist/lib/service-instances.d.ts +143 -0
  565. package/dist/lib/service-instances.d.ts.map +1 -0
  566. package/dist/lib/service-instances.js +193 -0
  567. package/dist/lib/service-instances.js.map +1 -0
  568. package/dist/lib/service-journal.d.ts +38 -0
  569. package/dist/lib/service-journal.d.ts.map +1 -0
  570. package/dist/lib/service-journal.js +210 -0
  571. package/dist/lib/service-journal.js.map +1 -0
  572. package/dist/lib/service-launchd-plan.d.ts +21 -0
  573. package/dist/lib/service-launchd-plan.d.ts.map +1 -0
  574. package/dist/lib/service-launchd-plan.js +69 -0
  575. package/dist/lib/service-launchd-plan.js.map +1 -0
  576. package/dist/lib/service-launchd-unit.d.ts +20 -0
  577. package/dist/lib/service-launchd-unit.d.ts.map +1 -0
  578. package/dist/lib/service-launchd-unit.js +66 -0
  579. package/dist/lib/service-launchd-unit.js.map +1 -0
  580. package/dist/lib/service-presets.d.ts +17 -0
  581. package/dist/lib/service-presets.d.ts.map +1 -0
  582. package/dist/lib/service-presets.js +139 -0
  583. package/dist/lib/service-presets.js.map +1 -0
  584. package/dist/lib/service-private-seed.d.ts +7 -0
  585. package/dist/lib/service-private-seed.d.ts.map +1 -0
  586. package/dist/lib/service-private-seed.js +64 -0
  587. package/dist/lib/service-private-seed.js.map +1 -0
  588. package/dist/lib/service-private-tree.d.ts +6 -0
  589. package/dist/lib/service-private-tree.d.ts.map +1 -0
  590. package/dist/lib/service-private-tree.js +100 -0
  591. package/dist/lib/service-private-tree.js.map +1 -0
  592. package/dist/lib/service-process.d.ts +146 -0
  593. package/dist/lib/service-process.d.ts.map +1 -0
  594. package/dist/lib/service-process.js +862 -0
  595. package/dist/lib/service-process.js.map +1 -0
  596. package/dist/lib/service-stopped-allocation.d.ts +6 -0
  597. package/dist/lib/service-stopped-allocation.d.ts.map +1 -0
  598. package/dist/lib/service-stopped-allocation.js +42 -0
  599. package/dist/lib/service-stopped-allocation.js.map +1 -0
  600. package/dist/lib/service-supervision.d.ts +59 -0
  601. package/dist/lib/service-supervision.d.ts.map +1 -0
  602. package/dist/lib/service-supervision.js +71 -0
  603. package/dist/lib/service-supervision.js.map +1 -0
  604. package/dist/lib/service-systemd-attempt-read.d.ts +40 -0
  605. package/dist/lib/service-systemd-attempt-read.d.ts.map +1 -0
  606. package/dist/lib/service-systemd-attempt-read.js +80 -0
  607. package/dist/lib/service-systemd-attempt-read.js.map +1 -0
  608. package/dist/lib/service-systemd-control.d.ts +38 -0
  609. package/dist/lib/service-systemd-control.d.ts.map +1 -0
  610. package/dist/lib/service-systemd-control.js +141 -0
  611. package/dist/lib/service-systemd-control.js.map +1 -0
  612. package/dist/lib/service-systemd-files.d.ts +8 -0
  613. package/dist/lib/service-systemd-files.d.ts.map +1 -0
  614. package/dist/lib/service-systemd-files.js +63 -0
  615. package/dist/lib/service-systemd-files.js.map +1 -0
  616. package/dist/lib/service-systemd-install.d.ts +17 -0
  617. package/dist/lib/service-systemd-install.d.ts.map +1 -0
  618. package/dist/lib/service-systemd-install.js +146 -0
  619. package/dist/lib/service-systemd-install.js.map +1 -0
  620. package/dist/lib/service-systemd-plan.d.ts +28 -0
  621. package/dist/lib/service-systemd-plan.d.ts.map +1 -0
  622. package/dist/lib/service-systemd-plan.js +56 -0
  623. package/dist/lib/service-systemd-plan.js.map +1 -0
  624. package/dist/lib/service-systemd-reseed.d.ts +16 -0
  625. package/dist/lib/service-systemd-reseed.d.ts.map +1 -0
  626. package/dist/lib/service-systemd-reseed.js +106 -0
  627. package/dist/lib/service-systemd-reseed.js.map +1 -0
  628. package/dist/lib/service-systemd-uninstall-plan.d.ts +29 -0
  629. package/dist/lib/service-systemd-uninstall-plan.d.ts.map +1 -0
  630. package/dist/lib/service-systemd-uninstall-plan.js +56 -0
  631. package/dist/lib/service-systemd-uninstall-plan.js.map +1 -0
  632. package/dist/lib/service-systemd-uninstall.d.ts +17 -0
  633. package/dist/lib/service-systemd-uninstall.d.ts.map +1 -0
  634. package/dist/lib/service-systemd-uninstall.js +106 -0
  635. package/dist/lib/service-systemd-uninstall.js.map +1 -0
  636. package/dist/lib/service-systemd-unit.d.ts +28 -0
  637. package/dist/lib/service-systemd-unit.d.ts.map +1 -0
  638. package/dist/lib/service-systemd-unit.js +73 -0
  639. package/dist/lib/service-systemd-unit.js.map +1 -0
  640. package/dist/lib/service-systemd.d.ts +49 -0
  641. package/dist/lib/service-systemd.d.ts.map +1 -0
  642. package/dist/lib/service-systemd.js +134 -0
  643. package/dist/lib/service-systemd.js.map +1 -0
  644. package/dist/lib/service-uninstall-intent.d.ts +38 -0
  645. package/dist/lib/service-uninstall-intent.d.ts.map +1 -0
  646. package/dist/lib/service-uninstall-intent.js +74 -0
  647. package/dist/lib/service-uninstall-intent.js.map +1 -0
  648. package/dist/lib/service-unit-action.d.ts +24 -0
  649. package/dist/lib/service-unit-action.d.ts.map +1 -0
  650. package/dist/lib/service-unit-action.js +61 -0
  651. package/dist/lib/service-unit-action.js.map +1 -0
  652. package/dist/lib/setup-log.d.ts +5 -4
  653. package/dist/lib/setup-log.d.ts.map +1 -1
  654. package/dist/lib/setup-log.js +18 -9
  655. package/dist/lib/setup-log.js.map +1 -1
  656. package/dist/lib/shown-time.d.ts +5 -0
  657. package/dist/lib/shown-time.d.ts.map +1 -0
  658. package/dist/lib/shown-time.js +9 -0
  659. package/dist/lib/shown-time.js.map +1 -0
  660. package/dist/lib/space-schema-inspection.d.ts +73 -0
  661. package/dist/lib/space-schema-inspection.d.ts.map +1 -0
  662. package/dist/lib/space-schema-inspection.js +118 -0
  663. package/dist/lib/space-schema-inspection.js.map +1 -0
  664. package/dist/lib/space-schema-report.d.ts +82 -0
  665. package/dist/lib/space-schema-report.d.ts.map +1 -0
  666. package/dist/lib/space-schema-report.js +109 -0
  667. package/dist/lib/space-schema-report.js.map +1 -0
  668. package/dist/lib/spawn-defaults.d.ts +14 -0
  669. package/dist/lib/spawn-defaults.d.ts.map +1 -0
  670. package/dist/lib/spawn-defaults.js +20 -0
  671. package/dist/lib/spawn-defaults.js.map +1 -0
  672. package/dist/lib/stack-journal.d.ts +166 -0
  673. package/dist/lib/stack-journal.d.ts.map +1 -0
  674. package/dist/lib/stack-journal.js +421 -0
  675. package/dist/lib/stack-journal.js.map +1 -0
  676. package/dist/lib/stack-resume.d.ts +35 -0
  677. package/dist/lib/stack-resume.d.ts.map +1 -0
  678. package/dist/lib/stack-resume.js +123 -0
  679. package/dist/lib/stack-resume.js.map +1 -0
  680. package/dist/lib/status.d.ts +19 -20
  681. package/dist/lib/status.d.ts.map +1 -1
  682. package/dist/lib/status.js +41 -40
  683. package/dist/lib/status.js.map +1 -1
  684. package/dist/lib/stdout-owner.d.ts +17 -0
  685. package/dist/lib/stdout-owner.d.ts.map +1 -0
  686. package/dist/lib/stdout-owner.js +44 -0
  687. package/dist/lib/stdout-owner.js.map +1 -0
  688. package/dist/lib/steps.d.ts.map +1 -1
  689. package/dist/lib/steps.js +3 -2
  690. package/dist/lib/steps.js.map +1 -1
  691. package/dist/lib/systemd-supervision.d.ts +11 -4
  692. package/dist/lib/systemd-supervision.d.ts.map +1 -1
  693. package/dist/lib/systemd-supervision.js +19 -8
  694. package/dist/lib/systemd-supervision.js.map +1 -1
  695. package/dist/lib/team-additive-attempt.d.ts +286 -0
  696. package/dist/lib/team-additive-attempt.d.ts.map +1 -0
  697. package/dist/lib/team-additive-attempt.js +387 -0
  698. package/dist/lib/team-additive-attempt.js.map +1 -0
  699. package/dist/lib/team-additive-native.d.ts +17 -0
  700. package/dist/lib/team-additive-native.d.ts.map +1 -0
  701. package/dist/lib/team-additive-native.js +29 -0
  702. package/dist/lib/team-additive-native.js.map +1 -0
  703. package/dist/lib/team-agent-removal.d.ts +104 -0
  704. package/dist/lib/team-agent-removal.d.ts.map +1 -0
  705. package/dist/lib/team-agent-removal.js +121 -0
  706. package/dist/lib/team-agent-removal.js.map +1 -0
  707. package/dist/lib/team-channel-removal.d.ts +220 -0
  708. package/dist/lib/team-channel-removal.d.ts.map +1 -0
  709. package/dist/lib/team-channel-removal.js +258 -0
  710. package/dist/lib/team-channel-removal.js.map +1 -0
  711. package/dist/lib/team-deploy-inspection.d.ts +59 -0
  712. package/dist/lib/team-deploy-inspection.d.ts.map +1 -0
  713. package/dist/lib/team-deploy-inspection.js +177 -0
  714. package/dist/lib/team-deploy-inspection.js.map +1 -0
  715. package/dist/lib/team-fresh.d.ts +73 -0
  716. package/dist/lib/team-fresh.d.ts.map +1 -0
  717. package/dist/lib/team-fresh.js +207 -0
  718. package/dist/lib/team-fresh.js.map +1 -0
  719. package/dist/lib/team-removal-reconcile.d.ts +118 -0
  720. package/dist/lib/team-removal-reconcile.d.ts.map +1 -0
  721. package/dist/lib/team-removal-reconcile.js +90 -0
  722. package/dist/lib/team-removal-reconcile.js.map +1 -0
  723. package/dist/lib/team-removal-record.d.ts +7 -0
  724. package/dist/lib/team-removal-record.d.ts.map +1 -0
  725. package/dist/lib/team-removal-record.js +46 -0
  726. package/dist/lib/team-removal-record.js.map +1 -0
  727. package/dist/lib/team-retained.d.ts +33 -0
  728. package/dist/lib/team-retained.d.ts.map +1 -0
  729. package/dist/lib/team-retained.js +55 -0
  730. package/dist/lib/team-retained.js.map +1 -0
  731. package/dist/lib/theme.d.ts.map +1 -1
  732. package/dist/lib/theme.js +9 -8
  733. package/dist/lib/theme.js.map +1 -1
  734. package/dist/lib/transient.d.ts +14 -9
  735. package/dist/lib/transient.d.ts.map +1 -1
  736. package/dist/lib/transient.js +25 -18
  737. package/dist/lib/transient.js.map +1 -1
  738. package/dist/lib/up-report.d.ts +3 -0
  739. package/dist/lib/up-report.d.ts.map +1 -1
  740. package/dist/lib/up-report.js +4 -1
  741. package/dist/lib/up-report.js.map +1 -1
  742. package/dist/lib/version.d.ts +8 -2
  743. package/dist/lib/version.d.ts.map +1 -1
  744. package/dist/lib/version.js +16 -9
  745. package/dist/lib/version.js.map +1 -1
  746. package/dist/managed-handoff.d.ts +3 -0
  747. package/dist/managed-handoff.d.ts.map +1 -1
  748. package/dist/managed-handoff.js +5 -0
  749. package/dist/managed-handoff.js.map +1 -1
  750. package/dist/seed/paths.d.ts +1 -1
  751. package/dist/seed/paths.js +1 -1
  752. package/dist/seed/reconcile.d.ts.map +1 -1
  753. package/dist/seed/reconcile.js +19 -3
  754. package/dist/seed/reconcile.js.map +1 -1
  755. package/dist/ui.d.ts +10 -2
  756. package/dist/ui.d.ts.map +1 -1
  757. package/dist/ui.js +28 -6
  758. package/dist/ui.js.map +1 -1
  759. package/dist/watch-data.d.ts +15 -0
  760. package/dist/watch-data.d.ts.map +1 -0
  761. package/dist/watch-data.js +66 -0
  762. package/dist/watch-data.js.map +1 -0
  763. package/dist/watch-json.d.ts +5 -0
  764. package/dist/watch-json.d.ts.map +1 -0
  765. package/dist/watch-json.js +132 -0
  766. package/dist/watch-json.js.map +1 -0
  767. package/dist/watch-view.d.ts +8 -0
  768. package/dist/watch-view.d.ts.map +1 -0
  769. package/dist/watch-view.js +65 -0
  770. package/dist/watch-view.js.map +1 -0
  771. package/package.json +8 -5
  772. package/dist/commands/service.d.ts +0 -17
  773. package/dist/commands/service.d.ts.map +0 -1
  774. package/dist/commands/service.js +0 -589
  775. package/dist/commands/service.js.map +0 -1
@@ -1,14 +1,14 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { createConnection, createServer } from "node:net";
4
- import { hostname } from "node:os";
5
- import { mkdirSync, writeFileSync, readFileSync, existsSync, openSync, statSync, readSync, closeSync, lstatSync, realpathSync, readdirSync, } from "node:fs";
6
- import { dirname, join, resolve } from "node:path";
7
- import { isReachable, DEFAULT_SERVER, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, reconcileSpaceTtls, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, seedChannelRegistry, ensureDefaultDeliveryClass, LEASE_TTL_MS, mkSecretDir, writeSecretFile, } from "@cotal-ai/core";
4
+ import { homedir, hostname } from "node:os";
5
+ import { mkdirSync, readFileSync, existsSync, openSync, fstatSync, statSync, readSync, closeSync, lstatSync, realpathSync, readdirSync, } from "node:fs";
6
+ import { dirname, isAbsolute, join, resolve } from "node:path";
7
+ import { isReachable, DEFAULT_SERVER, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, reconcileSpaceTtls, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, seedChannelRegistry, ensureDefaultDeliveryClass, LEASE_TTL_MS, mkSecretDir, openPrivateAppend, realDirNoSymlink, writeSecretFile, } from "@cotal-ai/core";
8
8
  import { connect } from "@nats-io/transport-node";
9
9
  import { jetstreamManager, StorageType } from "@nats-io/jetstream";
10
10
  import { Kvm } from "@nats-io/kv";
11
- import { assertSingleSpaceBroker, assertUserAuthInfo, authDir, getSoleSpaceAuth, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, clearCurrent, findMesh, getCurrent, loadMeshes, localMeshesForRoot, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, parsePositiveIntegerFlag, recordMesh, meshesForRoot, removeMesh, rotateSystemCreds, setCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, readMaintenanceResumeDocument, seatCheckpointDir, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, sameStoreIdentity, readBrokerPolicy, writeBrokerPolicy, removePidPair, writePidPair, isLoopbackHost, connectUserControlOrThrow, userViewAuth, } from "@cotal-ai/workspace";
11
+ import { CommandFailure, commandFailureReport, isCommandFailure, jsonFlag, plainFlag, renderReport, terminalWidth, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, canonicalRoot, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, oneLine, presentationOf, writeResult, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, parsePositiveIntegerFlag, recordMesh, meshesForRoot, removeMesh, rotateSystemCreds, setCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, readMaintenanceResumeDocument, seatCheckpointDir, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, writeBrokerPolicy, removePidPair, writePidPair, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, } from "@cotal-ai/workspace";
12
12
  import { ensureAuthService, resolveAuthProvider, stopAuthService } from "../lib/auth-proc.js";
13
13
  import { resolveSpace } from "../lib/status.js";
14
14
  import { c } from "../ui.js";
@@ -16,27 +16,57 @@ import { admitAndRestoreSeatCheckpoints } from "../lib/seat-resume.js";
16
16
  import { resolveNatsServer } from "../lib/nats-bin.js";
17
17
  import { cotalPath, cotalRoot } from "../lib/paths.js";
18
18
  import { renderDetachedSummary } from "../lib/up-report.js";
19
- import { detachedSystemdSupervisionWarning } from "../lib/systemd-supervision.js";
19
+ import { seedDefaultPersona } from "../lib/default-persona.js";
20
+ import { upSystemdSupervisionWarning } from "../lib/systemd-supervision.js";
20
21
  import { deliveryStoppedByDown, deliveryUp, ensureControlPlane, ensureDelivery, stopDelivery } from "../lib/delivery-proc.js";
21
22
  import { RESPONDER_UNBOUND_CONSEQUENCE } from "../lib/delivery-responder.js";
22
23
  import { displayCmd } from "../lib/self-exec.js";
23
24
  import { clearManagerArtifacts, liveManagerWouldApplyMaxSessions, managerHasDeliveryMarker, managerLogDisplayPath, managerRecordState, managerUp, stopManager } from "../lib/manager-proc.js";
24
25
  import { loadManifest } from "../lib/manifest/index.js";
25
26
  import { buildLaunchSpec, genRunId, manifestToChannels, preflightConnectors, writeLaunchSpec } from "../lib/manifest/apply.js";
27
+ import { listLedgerFiles } from "../lib/manifest/ledger.js";
28
+ import { freshTeamAttemptSettled, listFreshTeamAttempts, listFreshTeamSummaries, writeFreshTeamAttempt, writeFreshTeamSummary } from "../lib/team-fresh.js";
29
+ import { listAdditiveTeamAttempts, retainedAdditiveTeamAttempts } from "../lib/team-additive-attempt.js";
26
30
  import { renderUpPlan, renderInherited, renderWarnings } from "../lib/manifest/render.js";
27
31
  import { idpUrlProblem, serverUrlProblems } from "../lib/manifest/resolve.js";
28
- import { failManifest } from "./topology.js";
32
+ import { failManifest, refuseManifestSpaceMismatch } from "./topology.js";
33
+ import { liveMeshProcesses } from "./clean.js";
34
+ import { controllerStackApplies, recheckExistingStore, requestedStackMode, stackUp, stackUpForegroundNotice } from "./stack-up.js";
35
+ import { assertUserStackTransport, preflightUserStack } from "./stack-user-auth.js";
36
+ import { stackDown } from "./stack-down.js";
37
+ import { assertControllerCoupling, assertControllerMembersLive, assertControllerResumeEligible, beginControllerResume, bindControllerBroker, controllerAttemptBrokerInstance, currentControllerAttempt, managerResumeAttempt, relaunchCommittedManager, settleControllerResume, startControllerMember, startControllerMembers, } from "../lib/controller-resume.js";
38
+ import { removeRetiredBrokerInstance } from "../lib/controller-restore.js";
39
+ import { acquireStackOperationLock, admittedStackRestore, readStackJournal, refuseControllerCut } from "../lib/stack-journal.js";
40
+ import { serviceInstances } from "../lib/service-instances.js";
41
+ import { serviceSupervisorStore } from "../lib/service-supervision.js";
42
+ import { serviceInstallIntents } from "../lib/service-install-intent.js";
43
+ import { serviceUninstallIntents } from "../lib/service-uninstall-intent.js";
44
+ import { serviceUnitActionStore } from "../lib/service-unit-action.js";
29
45
  import { extensionNames, preflightRuntime } from "../ext-loader.js";
30
46
  import { completingFlagValue } from "../lib/completion.js";
47
+ import { metadataPositionals } from "../lib/command-path.js";
31
48
  import { askManager } from "../lib/control.js";
32
- import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, prepareRestore, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, replacePreparedDeadRestoreListener, } from "../lib/restore.js";
49
+ import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, prepareRestore, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, replacePreparedDeadRestoreListener, } from "../lib/restore.js";
33
50
  const pendingRestores = new Map();
51
+ const restoreSinks = new Map();
52
+ /** Run the guarded `up --restore` startup and return its result instead of printing it. The
53
+ * restore inputs and fences are exactly `up --restore`'s; this adds no route, flag or authority. */
54
+ export async function startRestore(values) {
55
+ let returned;
56
+ await up({ values: { ...values }, positionals: [], raw: [] }, undefined, false, (result) => { returned = result; });
57
+ if (!returned) {
58
+ const root = cotalRoot(), held = heldRestoreAttempt(root);
59
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the guarded restore returned without its activation result; the journal records its state and no step was repeated", { target: { root, ...(held ? { attemptId: held.attemptId, journalState: held.journalState } : {}) }, remedy: held?.remedy ?? "this root's maintenance journal names no restore attempt; check it with cotal status" });
60
+ }
61
+ return returned;
62
+ }
34
63
  const pendingOrdinaryResumes = new Map();
35
64
  /** `cotal up` flags — colocated with the command (like `spawnFlags`) so its completion can read them. */
36
65
  export const upFlags = [
37
66
  { name: "server", type: "string", value: "<url>", description: "listen URL override" },
38
67
  { name: "host", type: "string", value: "<host>", description: "bind host override (an IP/hostname, not a URL; the URL is --server)" },
39
68
  { name: "space", type: "string", value: "<s>", description: "space name (default: the folder's)" },
69
+ { name: "root", type: "string", value: "<dir>", description: "use this existing prepared local root instead of the current folder" },
40
70
  { name: "store-dir", type: "string", value: "<dir>", description: "JetStream store directory" },
41
71
  { name: "max-file-store", type: "string", value: "<bytes>", description: "JetStream file storage cap in bytes (default: nats-server's dynamic cap). Fixed at broker start; recorded and kept across `down --preserve-state`" },
42
72
  { name: "channels", type: "string", value: "<path>", description: "channel-registry seed file (JSON; default .cotal/channels.json)" },
@@ -55,47 +85,312 @@ export const upFlags = [
55
85
  { name: "advertised-server", type: "string", value: "<url>", description: "with --exchange-public-port: the broker address the public bundle advertises - what participants dial (default: --server)" },
56
86
  { name: "agent-provisioning-url", type: "string", value: "<https://…>", description: "with --exchange-public-port: the deployment's remote agent-provisioning endpoint the public bundle advertises" },
57
87
  { name: "rotate-sys", type: "boolean", description: "renew the expired/expiring $SYS creds by rotating the system account (agents, data and creds survive; needs a stopped mesh)" },
58
- { name: "detach", type: "boolean", description: "run in the background (stop with `cotal down`)" },
88
+ { name: "detach", type: "boolean", description: "run in the background (the default; stop with cotal down)" },
89
+ { name: "foreground", type: "boolean", description: "keep a non-manifest native stack in this terminal; -f currently refuses" },
59
90
  { name: "runtime", type: "string", value: "<name>", description: "agent runtime for the mesh manager (default pty; extension runtimes are explicit-only, see `cotal runtimes`); with -f overrides the manifest's runtime" },
60
91
  { name: "max-sessions", type: "string", value: "<n>", description: "live-session ceiling for the mesh manager (default 64; one session per console pane, so size for agents × panes). Recorded and reused by later manager launches" },
61
92
  { name: "no-manager", type: "boolean", description: "broker-only boot: start the broker and, in auth mode, the delivery daemon, and no local manager (refuses on a mesh whose manager is live)" },
62
93
  { name: "file", type: "string", short: "f", value: "<cotal.yaml>", description: "launch a whole mesh from a manifest" },
63
94
  { name: "dry-run", type: "boolean", description: "with -f: print the plan, mutate nothing" },
95
+ { ...jsonFlag, description: "controller-owned stack only: one structured receipt on stdout" },
96
+ { ...plainFlag, description: "controller-owned stack only: plain line-oriented receipt" },
64
97
  ];
65
98
  /** Completion for `cotal up` — `--runtime <TAB>` offers `pty` + installed runtime providers (the same
66
99
  * offline source `spawn` uses; a <TAB> never imports or probes). Run `cotal runtimes` to also see the
67
- * official ones that aren't installed yet. Any other position falls back to the command's flags, the
68
- * same set the dispatcher offers for a command with no hook — the hook only ADDS runtime values. */
100
+ * official ones that aren't installed yet. Declared flags are offered only while options remain open. */
69
101
  export function upComplete(argv) {
102
+ if (metadataPositionals({ flags: upFlags }, argv, { completing: true }).optionsEnded)
103
+ return { items: [], directive: "nofiles" };
70
104
  const flag = completingFlagValue(argv, upFlags);
71
105
  if (flag?.name === "runtime")
72
106
  return { items: ["pty", ...extensionNames("runtime")].filter((v, i, a) => a.indexOf(v) === i).map((value) => ({ value })), directive: "nofiles" };
73
107
  if (flag?.name === "restore-only")
74
108
  return { items: [{ value: "registry" }], directive: "nofiles" };
75
- if (flag?.name === "restore")
109
+ if (flag && ["root", "restore", "file", "channels", "tls-cert", "tls-key", "store-dir"].includes(flag.name))
76
110
  return { items: [], directive: "default" };
111
+ if (flag)
112
+ return { items: [], directive: "nofiles" };
77
113
  const items = upFlags.map((f) => ({ value: `--${f.name}`, description: f.description }));
78
114
  return { items, directive: items.length ? "nofiles" : "default" };
79
115
  }
116
+ /** Launch intent is checked by the kernel before seed or effect preparation. A recovery
117
+ * re-entry supplies its recorded mode explicitly rather than inheriting the new public default. */
118
+ export function validateUpArguments(args) {
119
+ presentationOf(args.values);
120
+ if (args.values["user-auth"] === true && args.values.open === true)
121
+ throw new CommandFailure("refused", "USAGE_INVALID", "--user-auth and --open contradict - a user-auth space cannot run unauthenticated", { remedy: "drop --open for user auth, or drop --user-auth for an open space" });
122
+ if (args.values.idp !== undefined && args.values["user-auth"] !== true && !args.values.file)
123
+ throw new CommandFailure("refused", "USAGE_INVALID", '--idp is for user-auth spaces; pair it with --user-auth, or set broker.auth: "user" in a manifest', { remedy: "use --user-auth --idp <auth base URL>, without --open" });
124
+ if (args.values["no-manager"] === true && args.values.runtime !== undefined)
125
+ throw new CommandFailure("refused", "USAGE_INVALID", "--no-manager cannot be combined with --runtime because no manager starts", { remedy: "drop --runtime, or drop --no-manager to select a manager runtime" });
126
+ if (args.values["no-manager"] === true && args.values["max-sessions"] !== undefined)
127
+ throw new CommandFailure("refused", "USAGE_INVALID", "--no-manager cannot be combined with --max-sessions because no manager starts", { remedy: "drop --max-sessions, or drop --no-manager to set the manager session ceiling" });
128
+ if (args.values.foreground === true && args.values.detach === true)
129
+ throw new CommandFailure("refused", "USAGE_INVALID", "choose --foreground or --detach, not both");
130
+ // A manifest boot checks its own `--server` override against `broker.servers`.
131
+ const serverProblem = args.values.server !== undefined && !args.values.file ? upServerProblem(String(args.values.server)) : undefined;
132
+ if (serverProblem)
133
+ throw new CommandFailure("refused", "USAGE_INVALID", `${serverProblem}; nothing was started or written`, { remedy: "pass the address the local broker listens on, for example --server nats://127.0.0.1:4222" });
134
+ if (args.values.file !== undefined && args.values.foreground === true)
135
+ throw new CommandFailure("refused", "UNSUPPORTED", "manifest boot has no native foreground custody path; a detached broker was not substituted for the requested terminal-bound lifetime");
136
+ if (args.values.foreground === true && (args.values.json === true || args.values.plain === true))
137
+ throw new CommandFailure("refused", "USAGE_INVALID", "foreground up keeps native terminal custody and cannot produce a finite JSON or plain receipt");
138
+ // Flag values and combinations are usage, so they refuse here, before any effect. The run keeps
139
+ // its own checks for maintenance re-entries, which do not pass through this validation.
140
+ parsePositiveIntegerFlag("--max-sessions", args.values["max-sessions"]);
141
+ parsePositiveIntegerFlag("--max-file-store", args.values["max-file-store"]);
142
+ const restoreOnly = args.values["restore-only"];
143
+ if (restoreOnly !== undefined && restoreOnly !== "registry")
144
+ throw new CommandFailure("refused", "USAGE_INVALID", `--restore-only takes registry (got ${JSON.stringify(restoreOnly)})`);
145
+ if (!args.values.restore && (restoreOnly !== undefined || args.values["accept-missing-source"] === true))
146
+ throw new CommandFailure("refused", "USAGE_INVALID", "--restore-only and --accept-missing-source require --restore <dir>");
147
+ if (args.values.restore && (args.values.file !== undefined || args.values.channels !== undefined))
148
+ throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --file/-f or --channels");
149
+ if (args.values.restore && args.values["rotate-sys"] === true)
150
+ throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --rotate-sys", { remedy: "restore the space and verify it first, then rotate: cotal down, then cotal up --rotate-sys" });
151
+ if (args.values.root !== undefined)
152
+ preparedUpRoot(String(args.values.root));
153
+ else {
154
+ const inheritedRoot = inheritedMachineHomeRoot();
155
+ if (inheritedRoot && !(args.values.file && args.values["dry-run"] === true))
156
+ throw new CommandFailure("refused", "CONFLICT", "this folder inherits the machine's home .cotal; up did not start a stack in that home root", { target: { root: process.cwd(), inheritedRoot }, remedy: "prepare this folder with cotal space create <space> --root ., then use cotal up --root .; to start the home stack, run up from home itself" });
157
+ }
158
+ if (args.values.restore !== undefined)
159
+ refuseControllerCut(args.values.root !== undefined ? preparedUpRoot(String(args.values.root)) : cotalRoot(), "up --restore");
160
+ }
161
+ /** Why `--server` cannot be the address a local broker listens on, or undefined when it can. Both
162
+ * launch routes need one nats:// or tls:// URL with a host and a TCP port, and without this check
163
+ * a typo reached their first write. The message never repeats the value, which may carry a
164
+ * credential. */
165
+ function upServerProblem(server) {
166
+ let url;
167
+ try {
168
+ url = new URL(server);
169
+ }
170
+ catch {
171
+ return "--server is not a URL";
172
+ }
173
+ if (url.protocol !== "nats:" && url.protocol !== "tls:")
174
+ return "--server must be a nats:// or tls:// URL";
175
+ if (url.username || url.password)
176
+ return "--server must not embed credentials";
177
+ if (url.search || url.hash || (url.pathname && url.pathname !== "/") || server.includes(","))
178
+ return "--server must be one broker URL without a path, query or fragment";
179
+ if (!url.hostname)
180
+ return "--server names no host";
181
+ if (url.port === "0")
182
+ return "--server needs a TCP port from 1 to 65535";
183
+ return undefined;
184
+ }
185
+ function inheritedMachineHomeRoot() {
186
+ const root = cotalRoot();
187
+ const machineHome = canonicalRoot(root) === canonicalRoot(homedir()) || canonicalRoot(join(root, ".cotal")) === canonicalRoot(homeCotalDir());
188
+ return machineHome && canonicalRoot(process.cwd()) !== canonicalRoot(root) ? root : undefined;
189
+ }
190
+ /** An explicit root is an existing local workspace, not a hint to find another ancestor or
191
+ * create trust in an arbitrary directory. Validation runs before the dispatcher seeds extensions. */
192
+ export function preparedUpRoot(value) {
193
+ if (!value)
194
+ throw new CommandFailure("refused", "USAGE_INVALID", "--root needs an existing prepared project directory; an empty value is not the current folder");
195
+ let root;
196
+ try {
197
+ root = realpathSync(resolve(value));
198
+ if (!statSync(root).isDirectory())
199
+ throw new Error("not a directory");
200
+ const cotal = lstatSync(join(root, ".cotal"));
201
+ if (!cotal.isDirectory() || cotal.isSymbolicLink())
202
+ throw new Error("not a private project directory");
203
+ }
204
+ catch {
205
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "--root must name an existing prepared local project with its own .cotal directory; no ancestor or other space was selected", { target: { root: resolve(value) }, remedy: "prepare it with cotal space create <space> --root <dir>, then retry with that root" });
206
+ }
207
+ if (canonicalRoot(root) === canonicalRoot(homedir()) || canonicalRoot(join(root, ".cotal")) === canonicalRoot(homeCotalDir()))
208
+ throw new CommandFailure("refused", "CONFLICT", "--root names the machine's home store, not a prepared project; no stack was started there", { target: { root }, remedy: "prepare the space in a project folder with cotal space create <space> --root <dir>" });
209
+ return root;
210
+ }
211
+ /** The fresh team entry refuses retained custody before `up -f` can write a launch spec,
212
+ * regenerate trust or stop a leftover manager. Only a recorded local root is eligible. */
213
+ function assertFreshTeamBootOwnership(root, space, mode, own) {
214
+ const current = findMesh(space), prepared = findPreparedSpace(space);
215
+ if (!current && !prepared)
216
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "fresh team boot needs a prepared local space; no checkout or machine-home root was guessed", { target: { root, space } });
217
+ if (current && (current.origin !== "up" || canonicalRoot(current.root) !== canonicalRoot(root)) || prepared && canonicalRoot(prepared.root) !== canonicalRoot(root))
218
+ throw new CommandFailure("refused", "CONFLICT", "the selected space is externally registered or its prepared root moved; no fresh local boot was started", { target: { root, space } });
219
+ if (current && mode && current.mode !== mode)
220
+ throw new CommandFailure("refused", "CONFLICT", "the requested fresh boot changes the locally recorded authentication mode; no trust was replaced", { target: { root, space, recordedMode: current.mode, requestedMode: mode } });
221
+ assertSingleSpaceBroker(authDir(root), "team boot");
222
+ const accounts = listSpaceAccounts(authDir(root));
223
+ if (mode === "open" && accounts.length)
224
+ throw new CommandFailure("refused", "CONFLICT", "the selected root retains a broker account; an open team boot did not bypass its recorded authorization", { target: { root, space } });
225
+ if (accounts.some((hosted) => hosted !== space))
226
+ throw new CommandFailure("refused", "CONFLICT", "the local broker root retains another space's account; team boot did not reassign that trust", { target: { root, space } });
227
+ const userSpaces = userAuthSpacesOnDisk(authDir(root));
228
+ if (mode === "user" && (userSpaces.some((hosted) => hosted !== space) || (accounts.includes(space) && !userSpaces.includes(space))))
229
+ throw new CommandFailure("refused", "CONFLICT", "the selected root holds another user-auth space or static trust without matching user-auth state; team boot did not convert its identity", { target: { root, space } });
230
+ if (mode && mode !== "user" && userSpaces.length)
231
+ throw new CommandFailure("refused", "CONFLICT", "this root retains user-auth state; a static or open team boot did not re-mode its identity", { target: { root, space } });
232
+ if (localMeshesForRoot(root).some((entry) => entry.space !== space))
233
+ throw new CommandFailure("refused", "CONFLICT", "another locally registered space uses this broker root; fresh team boot did not reuse or replace its stack", { target: { root, space } });
234
+ if (readMaintenanceJournal(root))
235
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "this root retains a recovery or maintenance attempt; team boot cannot substitute an ordinary startup", { target: { root, space } });
236
+ const manager = managerRecordState(undefined, undefined, space, root);
237
+ if (manager.state !== "absent")
238
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "a manager record remains, including when its process appears dead; team boot will not stop or overwrite it", { target: { root, space, state: manager.state, path: manager.path }, remedy: "inspect the recorded manager and reconcile its own lifecycle before a fresh team boot" });
239
+ const processes = liveMeshProcesses(root, space);
240
+ if (processes.length)
241
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "a local component may still own this stack; team boot did not replace it", { target: { root, space, processes } });
242
+ const instances = serviceInstances(space), supervisors = serviceSupervisorStore(space).list();
243
+ if (instances.length || supervisors.length)
244
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "service-controller instances or supervisor receipts remain for this space; their ownership was not replaced by fresh team boot", { target: { root, space, instances: instances.map((row) => row.name), supervisors: supervisors.map((row) => row.name) }, remedy: "inspect each service instance and its native supervisor before booting the whole stack" });
245
+ const actions = serviceUnitActionStore(space).list();
246
+ if (actions.some((row) => row.name !== row.record.value.instanceId))
247
+ throw new CommandFailure("refused", "SCHEMA_INVALID", "a retained native action filename differs from its full instance ID; no fresh boot ownership was inferred", { target: { root, space } });
248
+ const attempts = [
249
+ ...serviceInstallIntents(space).map((row) => ({ kind: "install", instanceId: row.name, attemptId: row.record.value.attemptId })),
250
+ ...serviceUninstallIntents(space).map((row) => ({ kind: "uninstall", instanceId: row.name, attemptId: row.record.value.attemptId })),
251
+ ...actions.map((row) => ({ kind: "unit-action", instanceId: row.name, attemptId: row.record.value.attemptId })),
252
+ ];
253
+ if (attempts.length)
254
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "native service attempts remain for this space; a submitted step may have changed state, so fresh team boot did not replace their custody", { target: { root, space, attempts }, remedy: "inspect and reconcile each retained attempt on its original service instance before fresh boot" });
255
+ let ledgers;
256
+ try {
257
+ ledgers = listLedgerFiles(root, { requireReadable: true });
258
+ }
259
+ catch {
260
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the root's additive ledger directory could not be inspected; no absence of prior owned resources was inferred", { target: { root, space } });
261
+ }
262
+ if (ledgers.valid.length || ledgers.refused.length)
263
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "additive ownership ledgers or unreadable ledger records remain under this root; fresh team boot did not adopt or erase them", { target: { root, space, deploymentIds: ledgers.valid.map(({ ledger }) => ledger.runId), unreadable: ledgers.refused.map(({ path }) => path) }, remedy: "inspect and finish each additive deployment's own lifecycle before a fresh team boot" });
264
+ let additiveAttempts;
265
+ try {
266
+ additiveAttempts = listAdditiveTeamAttempts(root);
267
+ }
268
+ catch {
269
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the root's additive attempt inventory could not be read; fresh boot did not assume it was empty", { target: { root, space } });
270
+ }
271
+ if (retainedAdditiveTeamAttempts(additiveAttempts).length || additiveAttempts.refused.length)
272
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "an additive deployment attempt remains under this root; its native outcome was not adopted as whole-stack ownership", { target: { root, space, deploymentIds: retainedAdditiveTeamAttempts(additiveAttempts).map((attempt) => attempt.deploymentId), unreadable: additiveAttempts.refused.map(({ path }) => path) } });
273
+ let bootAttempts, summaries;
274
+ try {
275
+ bootAttempts = listFreshTeamAttempts(root);
276
+ summaries = listFreshTeamSummaries(root);
277
+ }
278
+ catch {
279
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "fresh boot attempt or summary records could not be read; no earlier startup was assumed settled", { target: { root, space } });
280
+ }
281
+ const byId = new Map(summaries.valid.map((summary) => [summary.deploymentId, summary]));
282
+ const ownAttempt = own && bootAttempts.valid.find((attempt) => attempt.deploymentId === own.deploymentId);
283
+ if (own && (!ownAttempt || ownAttempt.space !== space || ownAttempt.root !== root || ownAttempt.server !== own.server || ownAttempt.manifestPath !== own.manifestPath || ownAttempt.authMode !== mode || byId.has(own.deploymentId)))
284
+ throw new CommandFailure("refused", "CONFLICT", "this fresh boot's own intent changed or acquired a summary during preparation; no launch spec was written", { target: { root, space, deploymentId: own.deploymentId } });
285
+ const unsettled = bootAttempts.valid.filter((attempt) => attempt.deploymentId !== own?.deploymentId && !freshTeamAttemptSettled(attempt, byId.get(attempt.deploymentId)));
286
+ if (bootAttempts.refused.length || summaries.refused.length || unsettled.length)
287
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "a prior fresh boot attempt lacks a matching readable summary, or an attempt/summary is unreadable; its outcome was not treated as absent", { target: { root, space, unsettledIds: unsettled.map((attempt) => attempt.deploymentId), unreadable: [...bootAttempts.refused, ...summaries.refused].map(({ path }) => path) }, remedy: "inspect each full boot attempt and its original listener before another fresh start; do not retry an unknown boot" });
288
+ }
289
+ /** Foreground controller stack: the terminal holds the stack's lifetime until SIGINT or SIGTERM,
290
+ * which runs the same guarded whole-stack stop as bare `down`, acknowledged by the signal. A failed
291
+ * or unknown stop is reported with its retained members; nothing is force-killed. */
292
+ export function holdForegroundStack(root) {
293
+ return new Promise((resolveHold) => {
294
+ // The hold ends on its own when another command completes a whole-stack stop or preserve of this
295
+ // root: a later operation recorded as completed is that evidence. Any other later operation,
296
+ // such as a refresh, keeps the hold. The poll also keeps Node alive, which a pending promise and
297
+ // signal listeners alone do not.
298
+ const recorded = () => { try {
299
+ return readStackJournal(root)?.journal.operation;
300
+ }
301
+ catch {
302
+ return undefined;
303
+ } };
304
+ const held = recorded()?.id;
305
+ let stopping = false;
306
+ const lifetime = setInterval(() => {
307
+ const operation = recorded();
308
+ if (stopping || !operation || operation.id === held || operation.phase !== "completed" || operation.kind !== "down" && operation.kind !== "preserve")
309
+ return;
310
+ stopping = true;
311
+ process.off("SIGINT", interrupt);
312
+ process.off("SIGTERM", terminate);
313
+ clearInterval(lifetime);
314
+ process.stderr.write(`${renderReport({ sections: [{ title: "Foreground stack released", blocks: [{ kind: "lines", lines: [`Another command completed a ${operation.kind === "down" ? "stop" : "preserve"} of this stack (operation ${operation.id}). This terminal no longer holds it.`] }] }] }, "rich", terminalWidth(process.stderr))}\n`);
315
+ resolveHold();
316
+ }, 1000);
317
+ const stop = (signal) => {
318
+ if (stopping)
319
+ return;
320
+ stopping = true;
321
+ process.off("SIGINT", interrupt);
322
+ process.off("SIGTERM", terminate);
323
+ clearInterval(lifetime);
324
+ void stackDown(root, { yes: true }).catch((error) => {
325
+ process.stderr.write(`${renderReport(commandFailureReport(isCommandFailure(error) ? error : new CommandFailure("unknown", "OPERATION_UNKNOWN", "the foreground stack stop did not confirm its outcome; its members were retained")), "rich", terminalWidth(process.stderr))}\n`);
326
+ }).finally(() => { process.exitCode = signal === "SIGINT" ? 130 : 143; resolveHold(); });
327
+ };
328
+ const interrupt = () => stop("SIGINT");
329
+ const terminate = () => stop("SIGTERM");
330
+ process.on("SIGINT", interrupt);
331
+ process.on("SIGTERM", terminate);
332
+ });
333
+ }
334
+ /** The registered `up` command. When a background run is the main process of a systemd unit, it
335
+ * names that unit and the `--foreground` remedy once startup returns: controller stack, retained
336
+ * launcher, refresh and restore alike. It never changes the run's mode. Internal callers of
337
+ * {@link up} print nothing. */
338
+ export async function upCommand(args) {
339
+ await up(args);
340
+ const warning = upSystemdSupervisionWarning(args.values);
341
+ if (warning)
342
+ console.error(c.yellow(warning));
343
+ }
80
344
  /** `inheritedLock` is the root maintenance lock a recovery re-entry hands down (see the re-entry
81
345
  * below). Ownership transfers with it: this call releases it at its own release point. */
82
- export async function up(args, inheritedLock) {
83
- if (!inheritedLock)
84
- return await runUp(args);
85
- // A re-entry owns the inherited lock from the moment it is called, but `runUp` only adopts it
86
- // part-way in — an early refusal (an unusable `--runtime`, say) throws before that. Release it
87
- // here in exactly that case, so a refused re-entry never leaves the root locked for the reaper.
346
+ export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink) {
347
+ // A re-entry owns its inherited lock even if mode validation refuses before runUp adopts it.
88
348
  let adopted = false;
89
349
  try {
90
- return await runUp(args, inheritedLock, () => { adopted = true; });
350
+ validateUpArguments(args);
351
+ const root = args.values.root === undefined ? undefined : preparedUpRoot(String(args.values.root));
352
+ const previousCwd = process.cwd();
353
+ // Path flags still mean paths relative to the invoking directory, not the selected root.
354
+ // The recursive restore/resume re-entries inherit absolute paths and the same absolute root.
355
+ const paths = root ? Object.fromEntries(["file", "restore", "channels", "tls-cert", "tls-key", "store-dir"].filter((key) => typeof args.values[key] === "string" && args.values[key] !== "").map((key) => [key, resolve(String(args.values[key]))])) : {};
356
+ const invocation = { ...args, values: { ...args.values, ...paths, ...(root ? { root } : {}), detach: args.values.foreground !== true } };
357
+ if (root) {
358
+ try {
359
+ process.chdir(root);
360
+ }
361
+ catch {
362
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the prepared --root became inaccessible before startup; no alternate directory was selected", { target: { root } });
363
+ }
364
+ // A root replaced with an inherited/symlinked store between validation and the effect
365
+ // must refuse. No implicit walk toward ~/.cotal is permitted for explicit targeting.
366
+ try {
367
+ const record = lstatSync(join(root, ".cotal"));
368
+ if (!record.isDirectory() || record.isSymbolicLink() || canonicalRoot(cotalRoot()) !== canonicalRoot(root))
369
+ throw new Error("changed root");
370
+ }
371
+ catch {
372
+ process.chdir(previousCwd);
373
+ throw new CommandFailure("refused", "CONFLICT", "the selected --root changed before startup; no inherited workspace was used", { target: { root } });
374
+ }
375
+ }
376
+ try {
377
+ return await runUp(invocation, inheritedLock, () => { adopted = true; }, freshTeamBoot, restoreSink);
378
+ }
379
+ finally {
380
+ if (root)
381
+ process.chdir(previousCwd);
382
+ }
91
383
  }
92
384
  finally {
93
- if (!adopted)
385
+ if (inheritedLock && !adopted)
94
386
  releaseMaintenanceLock(inheritedLock);
95
387
  }
96
388
  }
97
- async function runUp(args, inheritedLock, onAdopt) {
389
+ const NO_MANAGER_DURING_RECOVERY = "--no-manager is refused while this root has a maintenance attempt to recover - a resume needs a manager to commit the preserved inventory; recover it (`cotal up` alone) or roll it back first";
390
+ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restoreSink) {
98
391
  const values = args.values;
392
+ if (freshTeamBoot && (!values.file || values.restore || values.__restoreAttempt || values.__ordinaryResumeAttempt || values["rotate-sys"] || values["no-manager"]))
393
+ throw new CommandFailure("refused", "USAGE_INVALID", "fresh team boot accepts one manifest and its selected lifetime, not a restore, rotation or manager-free override");
99
394
  if (values.restore) {
100
395
  if (values.file || values.channels)
101
396
  throw new Error("--restore cannot be combined with --file/-f or --channels");
@@ -109,8 +404,29 @@ async function runUp(args, inheritedLock, onAdopt) {
109
404
  // A restore rewrites the shared store and the trust root under it, from an artifact that names
110
405
  // one space (see `cotal backup`) - it cannot leave the root's other tenants standing.
111
406
  assertSingleSpaceBroker(authDir(cotalRoot()), "cotal up --restore");
112
- const prepared = await prepareRestore(cotalRoot(), values);
407
+ // A `backup restore` owns stdout for its receipt, so its seat admission lines go to stderr.
408
+ const prepared = await prepareRestore(cotalRoot(), values, restoreSink ? (line) => console.error(line) : undefined);
113
409
  pendingRestores.set(prepared.attemptId, prepared);
410
+ const committed = readMaintenanceJournal(prepared.root);
411
+ if (committed && cutController(committed.cut)) {
412
+ // A controller restore continues through its recorded members. A member
413
+ // that cannot start holds the attempt at commit intent for bare `cotal up` to continue; it is
414
+ // not marked degraded, because a degraded attempt starts nothing.
415
+ const lock = acquireMaintenanceLock(prepared.root);
416
+ let foreground;
417
+ try {
418
+ foreground = await resumeControllerStack(lock, prepared.root, values, restoreSink);
419
+ }
420
+ finally {
421
+ pendingRestores.delete(prepared.attemptId);
422
+ releaseMaintenanceLock(lock);
423
+ }
424
+ if (foreground)
425
+ await holdForegroundStack(prepared.root);
426
+ return;
427
+ }
428
+ if (restoreSink)
429
+ restoreSinks.set(prepared.attemptId, restoreSink);
114
430
  const next = {
115
431
  ...values,
116
432
  restore: undefined,
@@ -129,6 +445,7 @@ async function runUp(args, inheritedLock, onAdopt) {
129
445
  }
130
446
  catch (error) {
131
447
  pendingRestores.delete(prepared.attemptId);
448
+ restoreSinks.delete(prepared.attemptId);
132
449
  // The one journal writer deliberately NOT handed a lock, and the reason is structural rather
133
450
  // than stylistic: no lock is held in this frame either way. This invocation returns just below
134
451
  // without ever reaching the `startupLock` acquire, and the re-entry that did hold one released
@@ -137,8 +454,13 @@ async function runUp(args, inheritedLock, onAdopt) {
137
454
  markPreparedRestoreDegraded(prepared.root, prepared.attemptId, error.message);
138
455
  throw error;
139
456
  }
457
+ restoreSinks.delete(prepared.attemptId);
140
458
  return;
141
459
  }
460
+ // A result sink belongs to the explicit restore entry above, never to a recovery, resume or
461
+ // ordinary start. Any other arrival with one is a caller bug, refused rather than ignored.
462
+ if (restoreSink)
463
+ throw new Error("a restore result sink requires --restore <dir>");
142
464
  if (values["restore-only"] || values["accept-missing-source"])
143
465
  throw new Error("--restore-only and --accept-missing-source require --restore <dir>");
144
466
  // MAINTENANCE RE-ENTRY. `--restore` is refused with `--rotate-sys` above, but that guard only sees
@@ -164,9 +486,35 @@ async function runUp(args, inheritedLock, onAdopt) {
164
486
  throw new Error("--rotate-sys is refused while this root has a maintenance attempt to recover - finish or roll back that attempt (`cotal up` alone recovers it), then `cotal down` and `cotal up --rotate-sys`");
165
487
  // Raised here for the stronger reason the journal itself carries: a pending maintenance attempt
166
488
  // means the store is mid-recovery, and a broker-only boot over it is wrong with or without the
167
- // manager half. The manager half is why the FLAG specifically cannot apply.
168
- if (values["no-manager"] && readMaintenanceJournal(root))
169
- throw new Error("--no-manager is refused while this root has a maintenance attempt to recover - a resume needs a manager to commit the preserved inventory; recover it (`cotal up` alone) or roll it back first");
489
+ // manager half. The manager half is why the FLAG specifically cannot apply. A settled active
490
+ // restore of this root's own controller stack has nothing left to commit; it takes the
491
+ // controller stack route below, which applies --no-manager as an ordinary start does.
492
+ if (values["no-manager"] && readMaintenanceJournal(root) && !admittedStackRestore(root))
493
+ throw new Error(NO_MANAGER_DURING_RECOVERY);
494
+ // Refuse first-enable IdP failures and explicit pin conflicts before even recovery's lock
495
+ // creates its layout. Existing recovery keeps its own recorded startup and trust checks.
496
+ const stackSpace = values.space ?? folderSpace();
497
+ recordOperationSpace(stackSpace);
498
+ if (!readMaintenanceJournal(root) && controllerStackApplies(root, stackSpace, values)) {
499
+ const recordedStack = readStackJournal(root);
500
+ if ((recordedStack?.journal.mode ?? requestedStackMode(values)) === "user" && (!recordedStack || values.idp !== undefined)) {
501
+ const server = values.server ?? recordedStack?.journal.server ?? localMeshesForRoot(root).find((m) => m.space === stackSpace)?.server ?? (values.host ? reconcileHostAndServer(values.host, undefined) : DEFAULT_SERVER);
502
+ const transport = resolveTransport(values, undefined, root, { persist: false, quiet: true });
503
+ assertUserStackTransport(server, transport.kind === "tls-required");
504
+ await preflightUserStack(root, stackSpace, values.idp);
505
+ }
506
+ }
507
+ // A runtime with no installed provider refuses here, before the lock creates its layout and
508
+ // before any member starts. The manager member resolves the same name through the same
509
+ // installed-extension lookup when it boots, so this check and the manager cannot disagree.
510
+ if (values.runtime) {
511
+ try {
512
+ await preflightRuntime(values.runtime);
513
+ }
514
+ catch (error) {
515
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "the requested runtime did not pass preflight; nothing was started", { target: { root, space: stackSpace, runtime: values.runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
516
+ }
517
+ }
170
518
  const lock = acquireMaintenanceLock(root);
171
519
  let pending;
172
520
  let recoveredRestore;
@@ -186,7 +534,25 @@ async function runUp(args, inheritedLock, onAdopt) {
186
534
  throw new Error(`cotal up is refused: restore attempt ${attempt} owners cannot be proven dead; inspect the recorded coordinator, watchdog, and broker processes before recovery`);
187
535
  throw new Error(`cotal up is refused: stale restore attempt ${attempt} holds the store; roll it back with \`cotal clean restore-attempt --attempt ${attempt} --force\`, or recover it with \`cotal up --restore\``);
188
536
  }
189
- if (journal && (journal.state === "commit-intent" || journal.state === "manager-committed" || journal.state === "degraded")) {
537
+ const controllerCut = journal ? cutController(journal.cut) : undefined;
538
+ if (journal && controllerCut && journal.state !== "cut-intent" && journal.state !== "cut-committed" && journal.state !== "resume-retired") {
539
+ // A controller cut resumes or restores only through its recorded members. A settled active
540
+ // restore of this stack no longer fences it, as legacy bare down admits it, so it falls
541
+ // through to the controller stack route below. The lock is released before a
542
+ // foreground stack holds this terminal. `--no-manager` is rechecked here, under the lock.
543
+ if (!admittedStackRestore(root)) {
544
+ if (values["no-manager"])
545
+ throw new Error(NO_MANAGER_DURING_RECOVERY);
546
+ const foreground = await resumeControllerStack(lock, root, values);
547
+ // Released here, once, so the foreground hold below does not keep the maintenance lock.
548
+ handedOff = true;
549
+ releaseMaintenanceLock(lock);
550
+ if (foreground)
551
+ await holdForegroundStack(root);
552
+ return;
553
+ }
554
+ }
555
+ else if (journal && (journal.state === "commit-intent" || journal.state === "manager-committed" || journal.state === "degraded")) {
190
556
  recoveredRestore = rehydratePreparedRestore(root, journal);
191
557
  pendingRestores.set(recoveredRestore.attemptId, recoveredRestore);
192
558
  }
@@ -358,6 +724,7 @@ async function runUp(args, inheritedLock, onAdopt) {
358
724
  "store-dir": recoveredRestore.targetPath,
359
725
  runtime: recoveredRestore.runtime,
360
726
  detach: recoveredRestore.detached,
727
+ foreground: !recoveredRestore.detached,
361
728
  open: recoveredRestore.mode === "open",
362
729
  "user-auth": recoveredRestore.mode === "user",
363
730
  },
@@ -384,6 +751,7 @@ async function runUp(args, inheritedLock, onAdopt) {
384
751
  "max-file-store": pending.maxFileStore === undefined ? undefined : String(pending.maxFileStore),
385
752
  runtime: pending.runtime,
386
753
  detach: pending.detached,
754
+ foreground: !pending.detached,
387
755
  open: pending.mode === "open",
388
756
  "user-auth": pending.mode === "user",
389
757
  },
@@ -402,24 +770,11 @@ async function runUp(args, inheritedLock, onAdopt) {
402
770
  }
403
771
  }
404
772
  const wantUser = Boolean(values["user-auth"]);
405
- // The auth-mode flags contradict each other loudly, never silently (a user-auth space quietly
406
- // started open would run agents on the wrong identity plane — the exact failure per-user-auth
407
- // exists to prevent).
408
- if (wantUser && values.open) {
409
- throw new Error("--user-auth and --open contradict - a user-auth space cannot run unauthenticated");
410
- }
411
- if (values.idp && !wantUser && !values.file) {
412
- throw new Error('--idp is for user-auth spaces; pair it with --user-auth, or set broker.auth: "user" in a manifest');
413
- }
414
773
  // BROKER-ONLY MODE (#1417). `--no-manager` names what it omits, and the two manager-shaping flags
415
774
  // are refused beside it rather than silently dropped: a runtime selected or a ceiling recorded for
416
775
  // a manager that will never start is a misunderstanding, and dropping it quietly is the exact
417
776
  // silent-no-op shape this repo refuses everywhere else.
418
777
  const noManager = Boolean(values["no-manager"]);
419
- if (noManager && values.runtime)
420
- throw new Error("--no-manager cannot be combined with --runtime - no manager starts, so there is no runtime to select; drop --runtime, or drop --no-manager");
421
- if (noManager && values["max-sessions"])
422
- throw new Error("--no-manager cannot be combined with --max-sessions - no manager starts, so there is no session ceiling to set; drop --max-sessions, or drop --no-manager");
423
778
  const publicExchange = publicExchangeArgs(values, wantUser);
424
779
  const maxSessions = parsePositiveIntegerFlag("--max-sessions", values["max-sessions"]);
425
780
  const maxFileStore = parsePositiveIntegerFlag("--max-file-store", values["max-file-store"]);
@@ -445,11 +800,13 @@ async function runUp(args, inheritedLock, onAdopt) {
445
800
  // Dry-run must not pin (mkdir is a mutation). Validation still uses whatever root is visible;
446
801
  // persistence is already suppressed below.
447
802
  if (!values["dry-run"]) {
448
- const spaceForRoot = values.space ?? resolveSpace(process.cwd());
803
+ const spaceForRoot = values.space ?? folderSpace();
449
804
  if (values.file) {
450
805
  try {
451
806
  const prepared = loadManifest(resolve(values.file));
452
- ensureRootForSpace(values.space ?? prepared.manifest.space);
807
+ // A --space that names another space is refused by the -f path below, before anything is written.
808
+ if (values.space === undefined || values.space === prepared.manifest.space)
809
+ ensureRootForSpace(prepared.manifest.space);
453
810
  }
454
811
  catch {
455
812
  // Manifest errors are reported by the -f path with the same load; do not double-print.
@@ -491,15 +848,43 @@ async function runUp(args, inheritedLock, onAdopt) {
491
848
  // (S5). Decide and validate early so every branch sees the transport; write only after a
492
849
  // matching listener is started and proved (`commitTransportPolicy`), never on a refuse path.
493
850
  // `quiet` suppresses the serving/inheriting lines until that commit (or a dry-run announce).
494
- const meshRoot = cotalRoot();
851
+ // An unprepared manifest preview reads no home policy: applying from this folder would first
852
+ // require its own project root, while dry-run must write nothing to create one.
853
+ const previewRoot = values.file && values["dry-run"] && !values.root && inheritedMachineHomeRoot() ? process.cwd() : undefined;
854
+ const meshRoot = previewRoot ?? cotalRoot();
495
855
  const transport = resolveTransport(values, undefined, meshRoot, {
496
856
  persist: false,
497
857
  quiet: true,
498
858
  });
859
+ // CONTROLLER-OWNED STACK. A root whose stack the service controller owns, or a fresh prepared
860
+ // static-auth, open or user-auth root with nothing legacy retained, starts as exact controller members instead
861
+ // of the pidfile launcher. The decision is made once here; neither route falls back to the other.
862
+ if (!values.file && controllerStackApplies(meshRoot, values.space ?? folderSpace(), values)) {
863
+ const stackSpace = values.space ?? folderSpace();
864
+ recordOperationSpace(stackSpace);
865
+ const stackServer = values.server ?? readStackJournal(meshRoot)?.journal.server ?? localMeshesForRoot(meshRoot).find((m) => m.space === stackSpace)?.server ?? (values.host ? reconcileHostAndServer(values.host, undefined) : DEFAULT_SERVER);
866
+ const stackMode = requestedStackMode(values);
867
+ const presentation = presentationOf(values);
868
+ const stackLock = acquireStackOperationLock(meshRoot);
869
+ const native = controllerStackNative();
870
+ try {
871
+ if (values.foreground && presentation !== "json")
872
+ stackUpForegroundNotice(presentation, stackSpace);
873
+ await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, ...(stackMode ? { mode: stackMode } : {}), ...(values.idp ? { idp: values.idp } : {}), ...(values.host ? { host: values.host } : {}), ...(values["store-dir"] ? { storeDir: values["store-dir"] } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), foreground: values.foreground === true, presentation }, native);
874
+ }
875
+ finally {
876
+ releaseMaintenanceLock(stackLock);
877
+ }
878
+ if (values.foreground)
879
+ await holdForegroundStack(meshRoot);
880
+ return;
881
+ }
882
+ if (values.json || values.plain)
883
+ throw new CommandFailure("refused", "UNSUPPORTED", "this startup uses the retained native launcher, which has no structured or plain receipt; nothing was started", { target: { root: meshRoot }, remedy: "use a fresh prepared root with static auth, --open, or plain-loopback --user-auth for the controller-owned stack, or omit --json/--plain" });
499
884
  // `up -f cotal.yaml` is a distinct path: bring up a FRESH mesh described by a manifest (broker +
500
- // channels + booted agents). It owns the whole space; deploying onto a RUNNING mesh is `spawn -f`.
885
+ // channels + booted agents). It owns the whole space; the additive team deploy route is separate.
501
886
  // CLI flags override the manifest (flag > manifest > default) so the same file runs at a different
502
- // port / runtime / space / auth without editing it.
887
+ // port / runtime / auth without editing it. Its space is its target: `--space` may only repeat it.
503
888
  if (values.file) {
504
889
  if (values["dry-run"]) {
505
890
  await upManifest(values.file, {
@@ -508,6 +893,7 @@ async function runUp(args, inheritedLock, onAdopt) {
508
893
  server: values.server,
509
894
  host: values.host,
510
895
  space: values.space,
896
+ root: values.root,
511
897
  runtime: values.runtime,
512
898
  open: values.open,
513
899
  userAuth: wantUser,
@@ -516,17 +902,27 @@ async function runUp(args, inheritedLock, onAdopt) {
516
902
  maxSessions,
517
903
  noManager,
518
904
  });
905
+ if (previewRoot)
906
+ console.log(c.yellow("! this preview used the invoking folder, not the inherited home store; before applying, prepare it with `cotal space create <space> --root .`"));
519
907
  return;
520
908
  }
521
909
  const lock = acquireMaintenanceLock(cotalRoot());
522
910
  try {
911
+ if (freshTeamBoot) {
912
+ if (!values.space)
913
+ throw new CommandFailure("refused", "USAGE_INVALID", "fresh team boot needs the manifest's exact selected space");
914
+ assertFreshTeamBootOwnership(cotalRoot(), values.space);
915
+ }
523
916
  assertOrdinaryUpAllowed(cotalRoot());
524
917
  await upManifest(values.file, {
525
918
  transport,
526
919
  dryRun: Boolean(values["dry-run"]),
920
+ freshTeamBoot,
921
+ presentation: freshTeamBoot ? presentationOf(values) : undefined,
527
922
  server: values.server,
528
923
  host: values.host,
529
924
  space: values.space,
925
+ root: values.root,
530
926
  runtime: values.runtime,
531
927
  open: values.open,
532
928
  userAuth: wantUser,
@@ -587,7 +983,7 @@ async function runUp(args, inheritedLock, onAdopt) {
587
983
  // Without --server the default URL only seeds a first boot. A first boot that found it taken ran
588
984
  // on a free port, which this root's record keeps; a re-run must start from that URL, or every
589
985
  // lookup below misses its own mesh and the space claim refuses it (#3889).
590
- const recordedSpace = values.space ?? resolveSpace(process.cwd());
986
+ const recordedSpace = values.space ?? folderSpace();
591
987
  const implicitServer = localMeshesForRoot(cotalRoot()).find((m) => m.space === recordedSpace)?.server ?? DEFAULT_SERVER;
592
988
  let server = values.server ?? implicitServer;
593
989
  const host = values.host ?? "127.0.0.1";
@@ -606,7 +1002,7 @@ async function runUp(args, inheritedLock, onAdopt) {
606
1002
  // here is reused as `listenerReachable` further down instead of probing twice.
607
1003
  let repairProbe;
608
1004
  if (!resumeAttempt) {
609
- const repairSpace = values.space ?? resolveSpace(process.cwd());
1005
+ const repairSpace = values.space ?? folderSpace();
610
1006
  const repairRoot = cotalRoot();
611
1007
  const heldForRepair = loadMeshes().find((m) => m.origin !== "manual" && m.origin !== "catalog" && m.server === server && m.root === repairRoot && m.space === repairSpace);
612
1008
  if (heldForRepair) {
@@ -669,7 +1065,7 @@ async function runUp(args, inheritedLock, onAdopt) {
669
1065
  if (resumeAttempt && listenerReachable)
670
1066
  throw new Error(`resume attempt ${resumeAttempt} refuses the unproven occupied listener at ${server}`);
671
1067
  if (listenerReachable) {
672
- const space = values.space ?? resolveSpace(process.cwd());
1068
+ const space = values.space ?? folderSpace();
673
1069
  const root = cotalRoot();
674
1070
  // A broker is already on this port. Same root means "this project is already up" unless the
675
1071
  // operator explicitly asked for a second space in the same `.cotal/` root (unsupported today: pid,
@@ -743,12 +1139,14 @@ async function runUp(args, inheritedLock, onAdopt) {
743
1139
  // `--no-manager` on a refresh whose manager is LIVE is the same class of refusal: this branch
744
1140
  // starts nothing, so the flag cannot apply, and silently keeping the manager would answer a
745
1141
  // broker-only ask with a full stack while silently stopping it would kill agents this command
746
- // was never asked to touch. Same shape as `--runtime`/`--max-sessions` above: refuse, name the
747
- // exact remedy. A refresh of a mesh whose manager is NOT live simply proceeds broker-only.
1142
+ // was never asked to touch. Same shape as `--runtime`/`--max-sessions` above: refuse and name the
1143
+ // remedy. This launcher's stack has no manager-only stop, so the remedy is the whole-stack stop
1144
+ // and a broker-only start. A refresh of a mesh whose manager is NOT live simply proceeds
1145
+ // broker-only.
748
1146
  if (noManager) {
749
1147
  const live = managerRecordState(undefined, undefined, held.space);
750
1148
  if (live.state === "alive") {
751
- console.error(c.red(`✗ mesh "${held.space}" is already running at ${server} with a live manager - \`cotal up --no-manager\` will not keep or stop one; \`cotal down manager\` first, then \`cotal up --no-manager\``));
1149
+ console.error(c.red(`✗ mesh "${held.space}" is already running at ${server} with a live manager - \`cotal up --no-manager\` will not keep or stop one, and this stack has no command that stops only its manager; \`cotal down\` stops the whole stack, then \`cotal up --no-manager --space ${held.space}\` starts it broker-only`));
752
1150
  process.exit(1);
753
1151
  }
754
1152
  }
@@ -885,6 +1283,7 @@ async function runUp(args, inheritedLock, onAdopt) {
885
1283
  // `recordOurMesh` carries everything else (`tlsRequired`, the recorded host and session
886
1284
  // ceiling, the store) from the record as it stands at write time, not from `held`.
887
1285
  recordOurMesh({ space: held.space, server, root, mode: held.mode, ...(userAuth ? { userAuth } : {}), ...(values.host ? { attachHost: values.host } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ts: new Date().toISOString() }, "refresh");
1286
+ seedPersonaAfterUp(root);
888
1287
  return;
889
1288
  }
890
1289
  const who = held ? `mesh "${held.space}" (${held.root})` : "a broker not started here";
@@ -923,6 +1322,8 @@ async function runUp(args, inheritedLock, onAdopt) {
923
1322
  verify: async () => { await verifySpawnedOrdinaryListener(ordinaryAttempt); },
924
1323
  } : undefined;
925
1324
  if (values.detach) {
1325
+ // A `backup restore` owns its own receipt: the native launcher's progress lines stay off stdout.
1326
+ const quietRestore = restored !== undefined && restoreSinks.has(restored.attemptId);
926
1327
  const { pid, source, authService, controlPlane, delivery, manager } = await startMeshDetached({
927
1328
  transport,
928
1329
  server,
@@ -942,15 +1343,15 @@ async function runUp(args, inheritedLock, onAdopt) {
942
1343
  maxSessions,
943
1344
  noManager,
944
1345
  resumeAttempt,
945
- resumeCommitToken: restored?.managerCommit?.durableCommitToken ?? ordinaryAttempt?.managerCommit?.durableCommitToken,
1346
+ resumeCommit: commitTokenHandoff(cotalRoot(), (restored?.managerCommit ?? ordinaryAttempt?.managerCommit) !== undefined, startupLock),
946
1347
  boundListener,
1348
+ ...(quietRestore ? { quietBoot: true } : {}),
947
1349
  });
948
1350
  // Transport policy is committed inside startMeshDetached before delivery launch (S5+S9).
949
- console.log(c.dim(`Started nats-server (${source}).`));
950
- console.log(c.green(renderDetachedSummary({ pid, delivery, authService: wantUser && authService, manager })));
951
- const supervisionWarning = detachedSystemdSupervisionWarning();
952
- if (supervisionWarning)
953
- console.error(c.yellow(supervisionWarning));
1351
+ if (!quietRestore) {
1352
+ console.log(c.dim(`Started nats-server (${source}).`));
1353
+ console.log(c.green(renderDetachedSummary({ pid, delivery, authService: wantUser && authService, manager, machineHome: canonicalRoot(cotalRoot()) === canonicalRoot(homedir()), ...(values.root ? { root: cotalRoot() } : {}) })));
1354
+ }
954
1355
  if (restored && process.env.COTAL_SMOKE_FAIL_AFTER_RESTORE_LISTENER_READY === "1")
955
1356
  throw new Error("smoke-injected failure after restore listener readiness");
956
1357
  // A user mesh whose auth service never became ready, or a mesh whose control plane is degraded,
@@ -959,10 +1360,16 @@ async function runUp(args, inheritedLock, onAdopt) {
959
1360
  if (!authService || !controlPlane)
960
1361
  process.exitCode = 1;
961
1362
  await completeResumeActivation(resumeAttempt, controlPlane && authService, !authService ? "normal listener started but the user-auth service is unavailable" : "normal listener started but the control plane is degraded", server, startupLock);
1363
+ if (restored)
1364
+ restoreSinks.get(restored.attemptId)?.({
1365
+ attemptId: restored.attemptId, space: restored.space, root: restored.root, server: restored.server, mode: restored.mode,
1366
+ selection: restored.selection, targetPath: restored.targetPath, runtime: restored.runtime, brokerPid: pid,
1367
+ delivery, authService, controlPlane, manager,
1368
+ });
962
1369
  return;
963
1370
  }
964
1371
  const useAuth = !values.open;
965
- const space = values.space ?? resolveSpace(process.cwd());
1372
+ const space = values.space ?? folderSpace();
966
1373
  ensureRootForSpace(space); // may pin the cwd as this space's root — before any cotalPath use
967
1374
  refuseOpenOverUserState(Boolean(values.open), space);
968
1375
  const storeDir = values["store-dir"] ? resolve(values["store-dir"]) : cotalPath("nats");
@@ -975,7 +1382,9 @@ async function runUp(args, inheritedLock, onAdopt) {
975
1382
  if (!sameStoreIdentity(readStoreIdentity(storeDir), resumeJournal.source))
976
1383
  throw new Error(`resume store ${storeDir} no longer matches the preserved source identity; refusing to open JetStream over it`);
977
1384
  }
978
- mkdirSync(storeDir, { recursive: true });
1385
+ // Owner-private regardless of umask: a recursive create also makes a missing `.cotal`, which every
1386
+ // later protection check walks as an ancestor.
1387
+ mkdirSync(storeDir, { recursive: true, mode: 0o700 });
979
1388
  await claimSpace(space, server, cotalRoot());
980
1389
  const seedFile = loadChannelsFile(values.channels);
981
1390
  // Decided above the branch; the dial host is only settled here (a port collision may have moved
@@ -996,7 +1405,10 @@ async function runUp(args, inheritedLock, onAdopt) {
996
1405
  console.log(c.dim(`Starting nats-server (JetStream, ${useAuth ? "JWT auth" : "OPEN/no-auth"}, ${source}) - store: ${storeDir}, bind: ${host}`));
997
1406
  console.log(c.dim("Press Ctrl-C to stop.\n"));
998
1407
  const listenerStartedAt = new Date().toISOString();
999
- const child = spawn(bin, natsArgs, { stdio: "inherit" });
1408
+ // A terminal sends Ctrl-C to the whole foreground process group. Keep the broker outside it
1409
+ // on POSIX so only this owner receives the interrupt and can finish manager-first teardown
1410
+ // before signalling the broker. Keep the child referenced and its output in this terminal.
1411
+ const child = spawn(bin, natsArgs, { stdio: "inherit", detached: process.platform !== "win32" });
1000
1412
  let activationFinished = !resumeAttempt;
1001
1413
  await recordSpawnedListener(child, listenerStartedAt, boundListener);
1002
1414
  releaseStartupLock();
@@ -1017,8 +1429,8 @@ async function runUp(args, inheritedLock, onAdopt) {
1017
1429
  // the refusal is printed with the reap route and the latch is released, so the stack keeps running
1018
1430
  // in the foreground; the operator ends it with `cotal down --with-agents` from another terminal,
1019
1431
  // and the broker-exit handler below already ends `up` when the broker goes.
1020
- // stopDelivery and stopAuthService are the stops `cotal down delivery` and `cotal down auth`
1021
- // perform (reservation, SIGKILL escalation); the rest of the teardown must run even if one fails —
1432
+ // stopDelivery and stopAuthService are the stops bare `cotal down` performs for those daemons
1433
+ // (reservation, SIGKILL escalation); the rest of the teardown must run even if one fails —
1022
1434
  // the failure is logged, never swallowed silently. Teardown is AWAITED before the broker is
1023
1435
  // signalled, so it never races a broker that is already going away.
1024
1436
  let stopping = false;
@@ -1102,7 +1514,7 @@ async function runUp(args, inheritedLock, onAdopt) {
1102
1514
  // it cannot reach the broker, and a starved host makes a running broker look unreachable, so it can
1103
1515
  // end while this broker serves on. Nothing else brings it back, and every static retirement then
1104
1516
  // fails on the ctl.delivery-admin rail and holds its name until an operator re-runs `cotal up`. A
1105
- // clean exit or SIGTERM/SIGINT is a deliberate stop (`cotal down delivery`) and stays stopped, and so
1517
+ // clean exit or SIGTERM/SIGINT is a deliberate stop (`cotal down`) and stays stopped, and so
1106
1518
  // is the SIGKILL `down` escalates to when a starved daemon outlives its grace, also when either ends a
1107
1519
  // replacement this loop is still waiting on: that attempt then fails, and retrying it would undo the
1108
1520
  // stop. A failed attempt waits out the lease TTL, the longest a dead holder's lease blocks its
@@ -1155,7 +1567,7 @@ async function runUp(args, inheritedLock, onAdopt) {
1155
1567
  maxFileStore,
1156
1568
  publicExchange,
1157
1569
  resumeAttempt,
1158
- resumeCommitToken: restored?.managerCommit?.durableCommitToken ?? ordinaryAttempt?.managerCommit?.durableCommitToken,
1570
+ resumeCommit: commitTokenHandoff(cotalRoot(), (restored?.managerCommit ?? ordinaryAttempt?.managerCommit) !== undefined, startupLock),
1159
1571
  runtime: values.runtime,
1160
1572
  noManager,
1161
1573
  onDeliveryExit,
@@ -1433,6 +1845,163 @@ function provePreparedRestoreListener(prepared) {
1433
1845
  return journal.restore.target;
1434
1846
  }, { path: prepared.targetPath, changed: "target identity changed" });
1435
1847
  }
1848
+ /** Bare `up`, `up --restore` and `backup restore` on a controller cut: at
1849
+ * `ready`, eligibility and the resume intent; before manager commitment, each member started or
1850
+ * adopted by the journal's own start rows, the broker's listener proof bound to its started
1851
+ * instance, then the manager; after commitment, only the manager relaunched once its exit is
1852
+ * receipted; then the shared same-principal activation. A re-entry continues the recorded attempt;
1853
+ * nothing here launches the legacy pidfile stack. A degraded attempt starts nothing and holds on any
1854
+ * member that is not live. Returns whether the caller should hold the stack's lifetime in the
1855
+ * foreground, which it does after releasing the lock. */
1856
+ async function resumeControllerStack(lock, root, values, restoreSink) {
1857
+ let journal = readMaintenanceJournal(root);
1858
+ const cut = cutController(journal.cut);
1859
+ const space = journal.space;
1860
+ const inventory = readMaintenanceResumeDocument(root, journal.resume).inventory;
1861
+ const agents = inventory.agents ?? [];
1862
+ // A restore's inputs were checked and journaled by `prepareRestore`; a resume takes them from the cut.
1863
+ if (!("restore" in journal)) {
1864
+ if (values.server !== undefined && values.server !== journal.cut.launch.server)
1865
+ throw new CommandFailure("refused", "USAGE_INVALID", "a controller resume takes its broker address from the cut; --server is refused", { target: { root, space } });
1866
+ if (values["store-dir"] !== undefined || values["max-file-store"] !== undefined)
1867
+ throw new CommandFailure("refused", "USAGE_INVALID", "a controller resume takes its store and cap from the cut; --store-dir and --max-file-store are refused", { target: { root, space } });
1868
+ const runtimes = [...new Set(agents.map((agent) => agent.launch?.runtime).filter((value) => typeof value === "string"))];
1869
+ if (runtimes.length > 1 || (values.runtime !== undefined && runtimes[0] !== undefined && values.runtime !== runtimes[0]))
1870
+ throw new CommandFailure("refused", "USAGE_INVALID", "--runtime must equal the preserved inventory's runtime; a controller resume does not change it", { target: { root, space } });
1871
+ if (journal.state === "ready") {
1872
+ const stops = journal.cutCompletion.controllerStops ?? [];
1873
+ assertControllerCoupling(root, cut, journal.cut.launch.server, journal.source.path);
1874
+ assertStoreIdentity(journal.source);
1875
+ assertControllerResumeEligible(space, cut, stops, cut.brokerDefinitionRevision);
1876
+ const attemptId = `resume-${randomUUID()}`;
1877
+ const staleConsent = admitAndRestoreSeatCheckpoints(root, space, journal.cut.attemptId, values, inventory);
1878
+ const serverNonce = randomUUID().replaceAll("-", "");
1879
+ beginControllerResume(lock, attemptId, {
1880
+ server: journal.cut.launch.server, storeDir: journal.source.path,
1881
+ ...(typeof journal.cut.launch.maxFileStore === "number" ? { maxFileStore: journal.cut.launch.maxFileStore } : {}),
1882
+ runtime: runtimes[0] ?? "pty", detached: !values.foreground, serverName: `${attemptId}-${serverNonce}`, serverNonce,
1883
+ ...(staleConsent.length ? { acceptedStaleCheckpoints: staleConsent.map((seat) => ({ ...seat })) } : {}),
1884
+ });
1885
+ journal = readMaintenanceJournal(root);
1886
+ }
1887
+ }
1888
+ const attempt = currentControllerAttempt(root);
1889
+ const { attemptId } = attempt;
1890
+ assertControllerCoupling(root, cut, journal.cut.launch.server, journal.source.path, { stackOperationId: attempt.stackOperationId, attemptId });
1891
+ const restoring = "restore" in journal;
1892
+ const launch = ("ordinaryResume" in journal ? journal.ordinaryResume.launch : journal.launch);
1893
+ try {
1894
+ if (journal.state === "resume-intent" || journal.state === "commit-intent") {
1895
+ await startControllerMembers(lock, root, space, launch.serverName);
1896
+ const brokerInfo = await readNatsInfo(launch.server);
1897
+ if (brokerInfo.server_name !== launch.serverName)
1898
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the resumed broker reports another server name than this attempt recorded; nothing further was started", { target: { root, space } });
1899
+ bindControllerBroker(lock, root, space, launch);
1900
+ await startControllerMember(lock, root, space, "manager", managerResumeAttempt(root));
1901
+ }
1902
+ else if (journal.state === "resume-committed" || journal.state === "manager-committed") {
1903
+ assertControllerMembersLive(root, space, "manager");
1904
+ await relaunchCommittedManager(lock, root, space);
1905
+ }
1906
+ else if (journal.state !== "active") {
1907
+ assertControllerMembersLive(root, space);
1908
+ }
1909
+ }
1910
+ catch (error) {
1911
+ settleControllerResume(root, isCommandFailure(error) && error.outcome === "refused" ? "refused" : "unknown");
1912
+ throw error;
1913
+ }
1914
+ // Read before activation: a new broker instance replaces the cut's retired record, which is
1915
+ // removed once the attempt is active.
1916
+ const broker = controllerAttemptBrokerInstance(root, space);
1917
+ const stops = journal.cutCompletion.controllerStops ?? [];
1918
+ const retireBroker = attempt.brokerRequired ? () => removeRetiredBrokerInstance(space, cut, stops) : undefined;
1919
+ journal = readMaintenanceJournal(root);
1920
+ let targetPath = journal.source.path;
1921
+ try {
1922
+ if (restoring) {
1923
+ const record = journal;
1924
+ const prepared = pendingRestores.get(attemptId) ?? rehydratePreparedRestore(root, record);
1925
+ if (record.listenerProof)
1926
+ prepared.listenerProof = record.listenerProof;
1927
+ pendingRestores.set(attemptId, prepared);
1928
+ targetPath = record.restore.target.path;
1929
+ if (record.state === "active") {
1930
+ pendingRestores.delete(attemptId);
1931
+ retireActiveRestoreBroker(root, attemptId, retireBroker, lock);
1932
+ }
1933
+ else {
1934
+ await completeResumeActivation(attemptId, true, "controller stack restored", launch.server, lock, retireBroker);
1935
+ }
1936
+ }
1937
+ else {
1938
+ pendingOrdinaryResumes.set(attemptId, {
1939
+ root, attemptId, space, mode: journal.mode, server: launch.server, storeDir: journal.source.path,
1940
+ ...(launch.maxFileStore !== undefined ? { maxFileStore: launch.maxFileStore } : {}),
1941
+ runtime: launch.runtime, detached: launch.detached, inventory,
1942
+ journalState: journal.state,
1943
+ ...(journal.state === "resume-committed" ? { managerCommit: journal.managerCommit } : {}),
1944
+ serverName: launch.serverName, serverNonce: launch.serverNonce,
1945
+ });
1946
+ await completeResumeActivation(attemptId, true, "controller stack resumed", launch.server, lock, retireBroker);
1947
+ }
1948
+ }
1949
+ catch (error) {
1950
+ settleControllerResume(root, "unknown");
1951
+ throw error;
1952
+ }
1953
+ settleControllerResume(root, "completed", { ...(attempt.brokerRequired ? { brokerInstanceId: broker.instanceId } : {}), ...(restoring ? { storeDir: targetPath } : {}) });
1954
+ if (restoring) {
1955
+ const restored = readMaintenanceJournal(root);
1956
+ const has = (role) => cut.members.some((member) => member.role === role);
1957
+ const result = {
1958
+ attemptId, space, root, server: launch.server, mode: restored.mode, selection: restored.launch.restoreOnly === "registry" ? "registry" : "full",
1959
+ targetPath, runtime: launch.runtime, brokerPid: broker.pid, delivery: has("delivery"), authService: has("auth"), controlPlane: true, manager: true,
1960
+ };
1961
+ if (restoreSink)
1962
+ restoreSink(result);
1963
+ else
1964
+ writeResult(presentationOf(values), { command: "up", target: { root, space, server: launch.server }, result: { kind: "controller-stack-restore", root, space, server: launch.server, attemptId, targetPath, selection: result.selection, retiredBrokerRemoved: attempt.brokerRequired } }, (row) => ({ sections: [{ title: "Controller stack restored", blocks: [
1965
+ { kind: "fields", rows: [["Space", row.space], ["Root", row.root], ["Broker", row.server], ["Attempt", row.attemptId], ["Store", row.targetPath], ["Selection", row.selection]] },
1966
+ { kind: "lines", lines: ["Each recorded member was started or adopted for this attempt, and the retained agents were resumed under the same principals. The restore journal stays active until its fallback is cleaned up. This is not agent or task readiness."] },
1967
+ ] }] }));
1968
+ return values.foreground === true && !restoreSink;
1969
+ }
1970
+ writeResult(presentationOf(values), { command: "up", target: { root, space, server: launch.server }, result: { kind: "controller-stack-resume", root, space, server: launch.server, attemptId, seatResume: agents.length ? "requested" : "not-requested" } }, (row) => ({ sections: [{ title: "Controller stack resumed", blocks: [
1971
+ { kind: "fields", rows: [["Space", row.space], ["Root", row.root], ["Broker", row.server], ["Attempt", row.attemptId], ["Retained agents", row.seatResume]] },
1972
+ { kind: "lines", lines: ["Each recorded member was started or adopted from its own recorded instance, and the retained agents were resumed under the same principals. This is not agent or task readiness."] },
1973
+ ] }] }));
1974
+ return values.foreground === true;
1975
+ }
1976
+ /** An active controller restore whose attempt started a new broker removes the cut's retired record
1977
+ * here; a mismatch degrades the restore with its reason and removes nothing. */
1978
+ function retireActiveRestoreBroker(root, attemptId, retireBroker, heldLock) {
1979
+ if (!retireBroker)
1980
+ return;
1981
+ try {
1982
+ retireBroker();
1983
+ }
1984
+ catch (error) {
1985
+ markPreparedRestoreDegraded(root, attemptId, error instanceof Error ? error.message : String(error), heldLock);
1986
+ throw error;
1987
+ }
1988
+ }
1989
+ /** Hand a manager-committed attempt's commit token to the next manager as a protected file. The
1990
+ * token is read from the journal under the maintenance lock and never travels on argv. An attempt
1991
+ * with no manager commit has nothing to hand off. */
1992
+ function commitTokenHandoff(root, committed, heldLock) {
1993
+ if (!committed)
1994
+ return undefined;
1995
+ const lock = heldLock ?? acquireMaintenanceLock(root);
1996
+ try {
1997
+ sweepTokenHandoff(lock);
1998
+ return writeTokenHandoff(lock);
1999
+ }
2000
+ finally {
2001
+ if (!heldLock)
2002
+ releaseMaintenanceLock(lock);
2003
+ }
2004
+ }
1436
2005
  function bindSpawnedOrdinaryResumeListener(pending, pid, startedAt, heldLock) {
1437
2006
  if (!Number.isInteger(pid) || pid <= 0)
1438
2007
  throw new Error("resume listener spawn returned no pid");
@@ -1499,7 +2068,7 @@ async function resumeProvenOrdinaryListener(pending, heldLock) {
1499
2068
  attachHost: adoptAttachHost,
1500
2069
  maxSessions: adoptMaxSessions,
1501
2070
  resumeAttempt: pending.attemptId,
1502
- resumeCommitToken: pending.managerCommit?.durableCommitToken,
2071
+ resumeCommit: commitTokenHandoff(pending.root, pending.managerCommit !== undefined, heldLock),
1503
2072
  });
1504
2073
  await completeResumeActivation(pending.attemptId, controlPlane !== undefined && svc.ok, !svc.ok ? "adopted resume listener has no user-auth service" : "adopted resume listener has a degraded control plane", pending.server, heldLock);
1505
2074
  }
@@ -1545,11 +2114,11 @@ async function resumeProvenRestoreListener(prepared, heldLock) {
1545
2114
  attachHost: restoreAttachHost,
1546
2115
  maxSessions: restoreMaxSessions,
1547
2116
  resumeAttempt: prepared.attemptId,
1548
- resumeCommitToken: prepared.managerCommit?.durableCommitToken,
2117
+ resumeCommit: commitTokenHandoff(prepared.root, prepared.managerCommit !== undefined, heldLock),
1549
2118
  });
1550
2119
  await completeResumeActivation(prepared.attemptId, controlPlane !== undefined && svc.ok, !svc.ok ? "proven restore listener has no user-auth service" : "proven restore listener has a degraded control plane", prepared.server, heldLock);
1551
2120
  }
1552
- async function completeResumeActivation(attemptId, healthy, reason, server, heldLock) {
2121
+ async function completeResumeActivation(attemptId, healthy, reason, server, heldLock, retireBroker) {
1553
2122
  if (!attemptId)
1554
2123
  return;
1555
2124
  const ordinary = pendingOrdinaryResumes.get(attemptId);
@@ -1722,8 +2291,13 @@ async function completeResumeActivation(attemptId, healthy, reason, server, held
1722
2291
  if (process.env.COTAL_SMOKE_EXIT_AFTER_RESUME_FINALIZE === "1")
1723
2292
  process.exit(91);
1724
2293
  if (ordinary) {
2294
+ // A controller resume that started a new broker removes the cut's retired record before the
2295
+ // journal is retired; a mismatch leaves the committed attempt to recover forward.
2296
+ retireBroker?.();
1725
2297
  const lock = heldLock ?? acquireMaintenanceLock(ordinary.root);
1726
2298
  try {
2299
+ // The finalized manager has read or abandoned its handoff file; settle it before retirement.
2300
+ settleTokenHandoff(lock);
1727
2301
  retireOrdinaryResume(lock, finalizeEvidence);
1728
2302
  consumeRetiredMaintenance(lock);
1729
2303
  }
@@ -1738,6 +2312,7 @@ async function completeResumeActivation(attemptId, healthy, reason, server, held
1738
2312
  markPreparedRestoreActive(restored, finalizeEvidence, heldLock);
1739
2313
  restored.cleanupStage();
1740
2314
  pendingRestores.delete(attemptId);
2315
+ retireActiveRestoreBroker(restored.root, attemptId, retireBroker, heldLock);
1741
2316
  }
1742
2317
  }
1743
2318
  /** Validate + assemble the auth-service daemon's public-exchange argv from `up`'s flags. The three
@@ -1771,7 +2346,7 @@ function publicExchangeArgs(v, wantUser) {
1771
2346
  * service down", never fall back to static semantics) — plus `ok`, so the exiting `up` surfaces
1772
2347
  * (detach / manifest / refresh-heal) turn a dead identity plane into a NON-ZERO exit: automation
1773
2348
  * must not read "user mesh up" from a mesh whose every user connect will be denied. */
1774
- async function startUserAuthService(space, server, setup, publicExchange) {
2349
+ async function startUserAuthService(space, server, setup, publicExchange, quietBoot = false) {
1775
2350
  if (!setup?.prepared || !setup.stateDir)
1776
2351
  return { ok: true };
1777
2352
  try {
@@ -1782,7 +2357,8 @@ async function startUserAuthService(space, server, setup, publicExchange) {
1782
2357
  const base = typeof raw.publicUrl === "string" ? raw.publicUrl : String(raw.url);
1783
2358
  const endpoints = { url: base, ...(typeof raw.publicUrl === "string" ? { managerAuthorityUrl: `${base.replace(/\/$/, "")}/manager-service-authority` } : {}) };
1784
2359
  const info = assertUserAuthInfo({ ...setup.prepared.publicAuth, endpoints });
1785
- console.log(c.green("✓ user-auth service up") + c.dim(` - sign in with: cotal login --idp ${info.idp.url}`));
2360
+ if (!quietBoot)
2361
+ console.log(c.green("✓ user-auth service up") + c.dim(` - sign in with: cotal login --idp ${info.idp.url}`));
1786
2362
  return { userAuth: info, ok: true };
1787
2363
  }
1788
2364
  catch (e) {
@@ -1790,43 +2366,178 @@ async function startUserAuthService(space, server, setup, publicExchange) {
1790
2366
  return { userAuth: assertUserAuthInfo(setup.prepared.publicAuth), ok: false };
1791
2367
  }
1792
2368
  }
2369
+ /** The fresh boot's read-only preparation, shared by the controller team boot. It runs the same
2370
+ * manifest load, override, mode agreement, ownership, bind, runtime, reachability and connector
2371
+ * refusals as the retained `upManifest` fresh path, in the same order, and writes nothing. */
2372
+ export async function prepareFreshTeamBoot(file, opts) {
2373
+ const flags = { ...opts, dryRun: false, freshTeamBoot: true };
2374
+ let prepared;
2375
+ try {
2376
+ prepared = loadManifest(resolve(file));
2377
+ }
2378
+ catch {
2379
+ throw new CommandFailure("refused", "SCHEMA_INVALID", "the fresh boot manifest changed or could not be resolved before startup; no broker was started", { target: { path: resolve(file), space: opts.space } });
2380
+ }
2381
+ if (opts.space !== prepared.manifest.space)
2382
+ throw new CommandFailure("refused", "CONFLICT", "the fresh boot manifest no longer names the selected space; no broker was started", { target: { selectedSpace: opts.space, declaredSpace: prepared.manifest.space } });
2383
+ const declared = prepared.manifest.broker?.auth;
2384
+ if (opts.open && declared === "user")
2385
+ throw new CommandFailure("refused", "CONFLICT", "--open contradicts this manifest's user-auth mode; no trust or broker was changed", { target: { space: opts.space } });
2386
+ if (opts.userAuth && declared !== "user")
2387
+ throw new CommandFailure("refused", "CONFLICT", "--user-auth contradicts this manifest's declared auth mode; no trust or broker was changed", { target: { space: opts.space } });
2388
+ if (opts.idp && declared !== "user")
2389
+ throw new CommandFailure("refused", "CONFLICT", "--idp needs this manifest's user-auth mode; no trust or broker was changed", { target: { space: opts.space } });
2390
+ const idpProblem = opts.idp === undefined ? undefined : idpUrlProblem(opts.idp, "--idp");
2391
+ if (idpProblem)
2392
+ throw new CommandFailure("refused", "SCHEMA_INVALID", idpProblem, { target: { space: opts.space } });
2393
+ const serverProblems = opts.server === undefined ? [] : serverUrlProblems(opts.server, "--server");
2394
+ if (serverProblems.length)
2395
+ throw new CommandFailure("refused", "SCHEMA_INVALID", serverProblems.join("; "), { target: { space: opts.space } });
2396
+ const eff = applyUpOverrides(prepared, flags);
2397
+ const m = eff.manifest;
2398
+ const host = m.broker?.host ?? "127.0.0.1";
2399
+ const server = m.broker?.host ? reconcileHostAndServer(m.broker.host, m.broker?.servers, "broker.host", "broker.servers") : (m.broker?.servers ?? DEFAULT_SERVER);
2400
+ const open = m.broker?.auth === false;
2401
+ const mode = open ? "open" : m.broker?.auth === "user" ? "user" : "auth";
2402
+ const runtime = m.runtime ?? "pty";
2403
+ if (open && (m.defaults?.deliveryClass === "durable" || m.channels.some((channel) => channel.deliveryClass === "durable")))
2404
+ throw new CommandFailure("refused", "UNSUPPORTED", "this open manifest explicitly requests durable channel delivery, but the open broker has no delivery daemon; no channel metadata or broker was written", { target: { space: m.space }, remedy: "use static/user authentication for durable delivery, or declare live delivery for an open mesh" });
2405
+ const other = loadMeshes().filter((row) => row.space !== m.space && row.server === server);
2406
+ if (other.length)
2407
+ throw new CommandFailure("refused", "CONFLICT", "another local registration names this exact broker address; fresh team boot did not create a listener over its recorded target", { target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable", otherSpaces: other.map((row) => row.space) } });
2408
+ assertFreshTeamBootOwnership(cotalRoot(), m.space, mode);
2409
+ await assertFreshTeamBindAvailable(server, host, m.space);
2410
+ try {
2411
+ await preflightRuntime(runtime);
2412
+ }
2413
+ catch (error) {
2414
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "the requested runtime did not pass preflight; no fresh boot intent or broker was started", { target: { space: m.space, runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
2415
+ }
2416
+ if (await isReachable(server))
2417
+ throw new CommandFailure("refused", "CONFLICT", "the selected address already has a broker; fresh boot did not adopt it or start a competing listener", { target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable" } });
2418
+ const conn = await preflightConnectors(prepared);
2419
+ if (conn)
2420
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "connector preflight failed before the fresh boot intent; no native effect was requested", { target: { space: m.space }, remedy: conn });
2421
+ return { root: canonicalRoot(cotalRoot()), space: m.space, server, host: m.broker?.host, mode, idp: m.broker?.idp, runtime, manifestPath: resolve(file), prepared: eff, transport: assertServesDialHost(opts.transport, new URL(server).hostname), maxSessions: opts.maxSessions };
2422
+ }
2423
+ /** A team boot that resumes one exact stopped controller stack whose manager was never attempted.
2424
+ * The same manifest load, agreement, durable-on-open, runtime, reachability and connector refusals
2425
+ * as {@link prepareFreshTeamBoot}, without the fresh zero-instance ownership gate: that gate is
2426
+ * replaced by the stopped-stack eligibility the caller binds under its lock. The manifest may not
2427
+ * move the recorded broker: its server must equal the recorded one, and a declared bind host must
2428
+ * equal the recorded host. Writes nothing. */
2429
+ export async function prepareResumeTeamBoot(file, opts) {
2430
+ let prepared;
2431
+ try {
2432
+ prepared = loadManifest(resolve(file));
2433
+ }
2434
+ catch {
2435
+ throw new CommandFailure("refused", "SCHEMA_INVALID", "the team manifest changed or could not be resolved before startup; nothing was resumed", { target: { path: resolve(file), space: opts.space } });
2436
+ }
2437
+ if (opts.space !== prepared.manifest.space)
2438
+ throw new CommandFailure("refused", "CONFLICT", "the team manifest no longer names the selected space; nothing was resumed", { target: { selectedSpace: opts.space, declaredSpace: prepared.manifest.space } });
2439
+ const eff = applyUpOverrides(prepared, { transport: opts.transport, dryRun: false, freshTeamBoot: true });
2440
+ const m = eff.manifest;
2441
+ const server = m.broker?.host ? reconcileHostAndServer(m.broker.host, m.broker?.servers, "broker.host", "broker.servers") : (m.broker?.servers ?? DEFAULT_SERVER);
2442
+ const open = m.broker?.auth === false;
2443
+ const mode = open ? "open" : m.broker?.auth === "user" ? "user" : "auth";
2444
+ const runtime = m.runtime ?? "pty";
2445
+ if (server !== opts.recorded.server || mode !== opts.recorded.mode || (m.broker?.host !== undefined && m.broker.host !== opts.recorded.host))
2446
+ throw new CommandFailure("refused", "CONFLICT", "the manifest's broker address, bind host or auth mode differs from the recorded stopped stack; nothing was resumed", { target: { space: m.space, recorded: opts.recorded, declared: { server: brokerAddressForDisplay(server) ?? "not displayable", host: m.broker?.host ?? null, mode } } });
2447
+ if (open && (m.defaults?.deliveryClass === "durable" || m.channels.some((channel) => channel.deliveryClass === "durable")))
2448
+ throw new CommandFailure("refused", "UNSUPPORTED", "this open manifest explicitly requests durable channel delivery, but the open broker has no delivery daemon; nothing was resumed", { target: { space: m.space } });
2449
+ const other = loadMeshes().filter((row) => row.space !== m.space && row.server === server);
2450
+ if (other.length)
2451
+ throw new CommandFailure("refused", "CONFLICT", "another local registration names this exact broker address; the stopped stack was not resumed over it", { target: { space: m.space, otherSpaces: other.map((row) => row.space) } });
2452
+ try {
2453
+ await preflightRuntime(runtime);
2454
+ }
2455
+ catch (error) {
2456
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "the requested runtime did not pass preflight; nothing was resumed", { target: { space: m.space, runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
2457
+ }
2458
+ if (await isReachable(server))
2459
+ throw new CommandFailure("refused", "CONFLICT", "the recorded broker address already answers; the stopped stack was not resumed over it", { target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable" } });
2460
+ const conn = await preflightConnectors(prepared);
2461
+ if (conn)
2462
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "connector preflight failed; nothing was resumed", { target: { space: m.space }, remedy: conn });
2463
+ return { root: canonicalRoot(cotalRoot()), space: m.space, server, host: opts.recorded.host, mode, idp: m.broker?.idp, runtime, manifestPath: resolve(file), prepared: eff, transport: assertServesDialHost(opts.transport, new URL(server).hostname), maxSessions: undefined };
2464
+ }
2465
+ /** The recorded broker transport of a prepared root, decided without persisting anything: a team
2466
+ * boot names no TLS flags, so it inherits the root's recorded policy exactly as a bare `up` does. */
2467
+ export function recordedBrokerTransport(root) {
2468
+ return resolveTransport({}, undefined, root, { persist: false, quiet: true });
2469
+ }
2470
+ /** Recheck, under the fresh boot's own lock, the ownership and bind refusals that a concurrent
2471
+ * writer could have invalidated after {@link prepareFreshTeamBoot}. */
2472
+ export async function recheckFreshTeamBoot(plan, own) {
2473
+ assertFreshTeamBootOwnership(plan.root, plan.space, plan.mode, own ? { deploymentId: own.deploymentId, server: plan.server, manifestPath: plan.manifestPath } : undefined);
2474
+ await assertFreshTeamBindAvailable(plan.server, plan.host ?? "127.0.0.1", plan.space);
2475
+ }
2476
+ /** The native callbacks a controller stack start uses, shared by `cotal up` and a controller team
2477
+ * boot so both prepare, seed and record through the same native path. */
2478
+ export function controllerStackNative() {
2479
+ return {
2480
+ prepareBroker: async (opts) => {
2481
+ const prepared = await prepareBrokerStart({ transport: opts.transport, server: opts.server, space: opts.space, ...(opts.open ? { open: true } : {}), ...(opts.userAuth ? { userAuth: opts.userAuth } : {}), ...(opts.host ? { host: opts.host } : {}), ...(opts.storeDir ? { storeDir: opts.storeDir } : {}), ...(opts.existingStore ? { existingStore: opts.existingStore } : {}), ...(opts.maxFileStore !== undefined ? { maxFileStore: opts.maxFileStore } : {}), ...(opts.seed !== undefined ? { seed: opts.seed } : opts.channels ? { channels: opts.channels } : {}), quietBoot: true });
2482
+ return { root: prepared.root, server: prepared.server, space: prepared.space, storeDir: prepared.storeDir, transport: prepared.transport, ...(prepared.setup ? { setup: { creds: prepared.setup.creds, wsPort: prepared.setup.wsPort } } : {}), ...(prepared.setup?.prepared && prepared.setup.stateDir ? { user: { prepared: prepared.setup.prepared, stateDir: prepared.setup.stateDir } } : {}), confPath: prepared.confPath, bin: prepared.bin, seedFile: prepared.seedFile };
2483
+ },
2484
+ initializeStreams: (server, space, setup, seedFile) => postStart(server, space, setup, seedFile),
2485
+ recordMesh: (entry) => recordOurMesh({ ...entry, ts: new Date().toISOString() }, "started", true),
2486
+ commitTransport: (root, chosen) => commitTransportPolicy(root, chosen, true),
2487
+ };
2488
+ }
1793
2489
  /** `cotal up -f cotal.yaml` — bring up a FRESH mesh from a manifest (broker + channels + booted
1794
2490
  * agents). `up -f` is a broker-CREATION command: `broker.servers` is the bind address for the NEW
1795
2491
  * local broker, never a connect target. A broker already reachable there (local OR remote) means
1796
- * "deploy onto it" — refuse and redirect to `spawn -f`; an unbindable/remote address makes the
1797
- * broker fail to start (no silent local fallback). It owns the whole space, so `cotal down` tears it
1798
- * down and no ownership ledger is needed (that's `spawn -f`). */
2492
+ * fresh boot refusal; an unbindable/remote address makes the broker fail to start (no silent
2493
+ * local fallback). It owns the whole space, so `cotal down` tears it down without an additive
2494
+ * ownership ledger. */
1799
2495
  async function upManifest(file, opts) {
1800
2496
  let prepared;
1801
2497
  try {
1802
2498
  prepared = loadManifest(resolve(file));
1803
2499
  }
1804
2500
  catch (e) {
2501
+ if (opts.freshTeamBoot)
2502
+ throw new CommandFailure("refused", "SCHEMA_INVALID", "the fresh boot manifest changed or could not be resolved before startup; no broker was started", { target: { path: resolve(file), space: opts.space } });
1805
2503
  failManifest(e);
1806
2504
  }
2505
+ if (opts.freshTeamBoot && opts.space !== prepared.manifest.space)
2506
+ throw new CommandFailure("refused", "CONFLICT", "the fresh boot manifest no longer names the selected space; no broker was started", { target: { selectedSpace: opts.space, declaredSpace: prepared.manifest.space } });
2507
+ refuseManifestSpaceMismatch(prepared, opts.space);
1807
2508
  // The auth-mode sources (flags vs manifest) must AGREE — any mismatch names both sources and the
1808
2509
  // exact correction in one sentence (a no-fallback identity decision, never a bare enum error).
1809
2510
  const declared = prepared.manifest.broker?.auth;
1810
2511
  const declaredStr = declared === undefined ? '"static" (the unset default)' : JSON.stringify(declared);
1811
2512
  if (opts.open && declared === "user") {
2513
+ if (opts.freshTeamBoot)
2514
+ throw new CommandFailure("refused", "CONFLICT", "--open contradicts this manifest's user-auth mode; no trust or broker was changed", { target: { space: prepared.manifest.space } });
1812
2515
  console.error(c.red('✗ --open contradicts this manifest\'s broker.auth: "user" - a user-auth space cannot run unauthenticated. Drop --open, or change the manifest.'));
1813
2516
  process.exit(1);
1814
2517
  }
1815
2518
  if (opts.userAuth && declared !== "user") {
2519
+ if (opts.freshTeamBoot)
2520
+ throw new CommandFailure("refused", "CONFLICT", "--user-auth contradicts this manifest's declared auth mode; no trust or broker was changed", { target: { space: prepared.manifest.space } });
1816
2521
  console.error(c.red(`✗ --user-auth requires manifest broker.auth: "user" (this manifest's broker.auth is ${declaredStr}). Either set broker.auth: "user" in the manifest, or drop --user-auth.`));
1817
2522
  process.exit(1);
1818
2523
  }
1819
2524
  if (opts.idp && declared !== "user") {
2525
+ if (opts.freshTeamBoot)
2526
+ throw new CommandFailure("refused", "CONFLICT", "--idp needs this manifest's user-auth mode; no trust or broker was changed", { target: { space: prepared.manifest.space } });
1820
2527
  console.error(c.red(`✗ --idp is for user-auth spaces (this manifest's broker.auth is ${declaredStr}) - set broker.auth: "user" in the manifest, or drop --idp.`));
1821
2528
  process.exit(1);
1822
2529
  }
1823
2530
  const idpProblem = opts.idp === undefined ? undefined : idpUrlProblem(opts.idp, "--idp");
1824
2531
  if (idpProblem) {
2532
+ if (opts.freshTeamBoot)
2533
+ throw new CommandFailure("refused", "SCHEMA_INVALID", idpProblem, { target: { space: prepared.manifest.space } });
1825
2534
  console.error(c.red(`✗ ${idpProblem}`));
1826
2535
  process.exit(1);
1827
2536
  }
1828
2537
  const serverProblems = opts.server === undefined ? [] : serverUrlProblems(opts.server, "--server");
1829
2538
  if (serverProblems.length) {
2539
+ if (opts.freshTeamBoot)
2540
+ throw new CommandFailure("refused", "SCHEMA_INVALID", serverProblems.join("; "), { target: { space: prepared.manifest.space } });
1830
2541
  for (const problem of serverProblems)
1831
2542
  console.error(c.red(`✗ ${problem}`));
1832
2543
  process.exit(1);
@@ -1842,11 +2553,22 @@ async function upManifest(file, opts) {
1842
2553
  const open = m.broker?.auth === false; // default is auth
1843
2554
  const userAuth = m.broker?.auth === "user" ? { idpUrl: m.broker.idp } : undefined;
1844
2555
  const runtime = m.runtime ?? "pty";
2556
+ if (open && (m.defaults?.deliveryClass === "durable" || m.channels.some((channel) => channel.deliveryClass === "durable")))
2557
+ throw new CommandFailure("refused", "UNSUPPORTED", "this open manifest explicitly requests durable channel delivery, but the open broker has no delivery daemon; no channel metadata or broker was written", { target: { space: m.space, defaultDurable: m.defaults?.deliveryClass === "durable", channels: m.channels.filter((channel) => channel.deliveryClass === "durable").map((channel) => channel.name) }, remedy: "use static/user authentication for durable delivery, or declare live delivery for an open mesh" });
2558
+ if (opts.freshTeamBoot) {
2559
+ const other = loadMeshes().filter((row) => row.space !== m.space && row.server === server);
2560
+ if (other.length)
2561
+ throw new CommandFailure("refused", "CONFLICT", "another local registration names this exact broker address; fresh team boot did not create a listener over its recorded target", { target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable", otherSpaces: other.map((row) => row.space) }, remedy: "inspect both registrations and their native brokers; exact-address conflicts block creation, while no conflict does not prove exclusivity" });
2562
+ }
2563
+ if (opts.freshTeamBoot) {
2564
+ assertFreshTeamBootOwnership(cotalRoot(), m.space, open ? "open" : userAuth ? "user" : "auth");
2565
+ await assertFreshTeamBindAvailable(server, host, m.space);
2566
+ }
1845
2567
  // A manifest's agents are booted BY the manager `up -f` starts with the mesh, so `--no-manager`
1846
2568
  // against a manifest declaring agents asks for a boot that cannot deliver its own plan. Refused
1847
- // before the dry-run print and before anything boots, with the two workable spellings named.
2569
+ // before the dry-run print and before anything boots.
1848
2570
  if (opts.noManager && eff.agents.length)
1849
- throw new Error(`--no-manager cannot launch this manifest: it declares ${eff.agents.length} agent(s), and a manifest's agents are booted by its manager (which --no-manager omits). Deploy it from a manager host with \`cotal spawn -f\`, or drop --no-manager.`);
2571
+ throw new Error(`--no-manager cannot launch this manifest: it declares ${eff.agents.length} agent(s), and a manifest's agents are booted by its manager (which --no-manager omits). Drop --no-manager, or use a broker-only manifest with no agents.`);
1850
2572
  const effectiveNoManager = Boolean(opts.noManager);
1851
2573
  // The open-mesh refusal must be RE-STATED here, not only against the CLI `--open` flag: on this
1852
2574
  // path openness comes from the MANIFEST (`broker.auth: false`), which the flag-level guard cannot
@@ -1880,18 +2602,40 @@ async function upManifest(file, opts) {
1880
2602
  }
1881
2603
  // Preflight an extension runtime before starting the broker. The detached manager re-execs this
1882
2604
  // CLI and resolves the same installed package when `supervise --runtime <name>` starts.
1883
- await preflightRuntime(runtime);
1884
- // up -f never adopts a running broker. Reachable at the bind address ⇒ redirect to spawn -f.
2605
+ try {
2606
+ await preflightRuntime(runtime);
2607
+ }
2608
+ catch (error) {
2609
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `the requested runtime did not pass preflight; ${opts.freshTeamBoot ? "no fresh boot intent or broker was started" : "no broker was started"}`, { target: { space: m.space, runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
2610
+ }
2611
+ // up -f never adopts a running broker. The old spawn -f route is no longer a manifest deploy.
1885
2612
  if (await isReachable(server)) {
1886
- console.error(c.red(`✗ ${server} already has a broker - deploy this manifest onto it with \`cotal spawn -f ${file}\``));
2613
+ if (opts.freshTeamBoot)
2614
+ throw new CommandFailure("refused", "CONFLICT", "the selected address already has a broker; fresh boot did not adopt it or start a competing listener", { target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable" }, remedy: "inspect the existing broker and selected local records, or use another prepared address" });
2615
+ console.error(c.red(`✗ ${brokerAddressForDisplay(server) ?? "selected address"} already has a broker - a fresh boot will not adopt it. Stop the owned stack or select another address; team deploy supports only all-new channel cards, not agent apply.`));
1887
2616
  process.exit(1);
1888
2617
  }
1889
2618
  // Connectors + their required binaries must exist before any mutation (no fallback).
1890
2619
  const conn = await preflightConnectors(prepared);
1891
2620
  if (conn) {
2621
+ if (opts.freshTeamBoot)
2622
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "connector preflight failed before the fresh boot intent; no native effect was requested", { target: { space: m.space }, remedy: conn });
1892
2623
  console.error(c.red(`✗ connector preflight failed: ${conn}`));
1893
2624
  process.exit(1);
1894
2625
  }
2626
+ if (opts.freshTeamBoot) {
2627
+ assertFreshTeamBootOwnership(cotalRoot(), m.space, open ? "open" : userAuth ? "user" : "auth");
2628
+ await assertFreshTeamBindAvailable(server, host, m.space);
2629
+ }
2630
+ const deploymentId = genRunId();
2631
+ if (opts.freshTeamBoot) {
2632
+ try {
2633
+ writeFreshTeamAttempt(cotalRoot(), { schemaVersion: 1, kind: "fresh-team-attempt", deploymentId, space: m.space, root: cotalRoot(), server, authMode: open ? "open" : userAuth ? "user" : "auth", manifestPath: resolve(file), createdAt: new Date().toISOString() });
2634
+ }
2635
+ catch {
2636
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "fresh boot intent creation or its durability did not confirm; no trust preparation, launch spec or listener was requested", { target: { space: m.space, deploymentId, root: cotalRoot(), intentPath: join(cotalRoot(), ".cotal", `team-boot-attempt-${deploymentId}.json`) }, remedy: "inspect the exact intent path before deciding whether any further boot can be attempted" });
2637
+ }
2638
+ }
1895
2639
  // USER-AUTH manifest: the agents run under the LOGGED-IN operator's owner, and the launch spec
1896
2640
  // (consumed by the manager at boot) must carry it — so resolve it NOW. On a fresh mesh the
1897
2641
  // derivation material doesn't exist yet; ensure it just-in-time (authSetup + prepareServer are
@@ -1900,14 +2644,16 @@ async function upManifest(file, opts) {
1900
2644
  let owner;
1901
2645
  if (userAuth) {
1902
2646
  try {
1903
- mkdirSync(cotalPath("nats"), { recursive: true });
2647
+ mkdirSync(cotalPath("nats"), { recursive: true, mode: 0o700 });
1904
2648
  // NO `rotateSys` here on purpose: this is an owner-derivation pre-resolve that runs BEFORE the
1905
2649
  // real boot, and the boot below carries the flag. Rotating in both would burn two generations
1906
2650
  // per `up -f --rotate-sys` and retire the account the first pass just minted creds against.
1907
- const setup = await authSetup(cotalPath("nats"), server, m.space, host, userAuth, assertServesDialHost(opts.transport, new URL(server).hostname));
2651
+ const setup = await authSetup(cotalPath("nats"), server, m.space, host, userAuth, assertServesDialHost(opts.transport, new URL(server).hostname), false, undefined, opts.freshTeamBoot);
1908
2652
  owner = await resolveAuthProvider().ownerForLogin({ store: workspaceSecretStore(cotalRoot()), dir: setup.stateDir, space: m.space });
1909
2653
  }
1910
2654
  catch (e) {
2655
+ if (opts.freshTeamBoot)
2656
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the fresh user-auth owner preparation did not confirm; trust or provider state may have changed, but no launch spec or listener was requested", { target: { space: m.space, deploymentId, root: cotalRoot() }, remedy: "inspect the retained boot intent, trust state and login before deciding another action; do not repeat an uncertain preparation" });
1911
2657
  console.error(c.red(`✗ ${e.message}`));
1912
2658
  process.exit(1);
1913
2659
  }
@@ -1918,27 +2664,95 @@ async function upManifest(file, opts) {
1918
2664
  // the lease — the loser refuses, so either the agents never boot or the incumbent is orphaned
1919
2665
  // behind an overwritten pid file. The manager materializes each transient persona and mints creds
1920
2666
  // from the resolved policy — never re-reading a file for authority.
1921
- const specPath = writeLaunchSpec(cotalRoot(), buildLaunchSpec(eff, genRunId(), owner));
1922
- // A leftover detached manager (its broker is gone — the reachability check above proved nothing
1923
- // lives at this address) would win the fresh mesh's lease and the launch manager would refuse.
1924
- // Stop it, so the manager started below WITH the launch spec is THE manager.
1925
- await stopManager(m.space);
1926
- clearManagerArtifacts(m.space);
2667
+ if (opts.freshTeamBoot) {
2668
+ assertFreshTeamBootOwnership(cotalRoot(), m.space, open ? "open" : userAuth ? "user" : "auth", { deploymentId, server, manifestPath: resolve(file) });
2669
+ try {
2670
+ await assertFreshTeamBindAvailable(server, host, m.space);
2671
+ }
2672
+ catch {
2673
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the fresh boot's bind address was not confirmed after owner preparation; no launch spec or listener was requested, but its retained intent and any prepared trust were not discarded", { target: { space: m.space, deploymentId, server: brokerAddressForDisplay(server) ?? "not displayable" }, remedy: "inspect the exact retained intent, trust state and address before deciding another boot; this bind probe does not reserve the listener" });
2674
+ }
2675
+ }
2676
+ let specPath;
2677
+ try {
2678
+ specPath = writeLaunchSpec(cotalRoot(), buildLaunchSpec(eff, deploymentId, owner));
2679
+ }
2680
+ catch (error) {
2681
+ if (opts.freshTeamBoot)
2682
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the fresh boot intent was recorded, but launch-spec creation did not confirm its outcome; no broker launch was attempted and the intent remains for inspection", { target: { space: m.space, deploymentId, root: cotalRoot() }, remedy: "inspect the original intent and launch-spec path before another boot; no effect was retried" });
2683
+ throw error;
2684
+ }
2685
+ // Ordinary up can reconcile a leftover manager. Fresh team boot must not signal one: its
2686
+ // stricter prewrite gate required no manager record at all, and a later contender wins
2687
+ // neither stop authority nor permission to replace it.
2688
+ if (!opts.freshTeamBoot) {
2689
+ await stopManager(m.space);
2690
+ clearManagerArtifacts(m.space);
2691
+ }
1927
2692
  let pid;
1928
2693
  let controlPlane = false;
1929
2694
  let authService = true;
2695
+ let deliveryResponderBound = null;
1930
2696
  try {
1931
2697
  // `m.broker?.host`, not the defaulted `host`: same reason as the flag path — only a host the
1932
2698
  // manifest actually declared is an exposure decision worth persisting.
1933
- ({ pid, controlPlane, authService } = await startMeshDetached({ transport: opts.transport, server, space: m.space, open, userAuth, rotateSys: opts.rotateSys, host: m.broker?.host, seed: manifestToChannels(eff), runtime, launch: specPath, maxSessions: opts.maxSessions, noManager: effectiveNoManager }));
2699
+ ({ pid, controlPlane, authService, deliveryResponderBound } = await startMeshDetached({ transport: opts.transport, server, space: m.space, open, userAuth, rotateSys: opts.rotateSys, host: m.broker?.host, seed: manifestToChannels(eff), runtime, launch: specPath, maxSessions: opts.maxSessions, noManager: effectiveNoManager, quietBoot: opts.freshTeamBoot }));
1934
2700
  }
1935
2701
  catch (e) {
2702
+ if (opts.freshTeamBoot)
2703
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the fresh broker startup did not confirm completion after its launch spec was written; the listener or control plane may have changed state and the boot was not retried", { target: { space: m.space, deploymentId, launchSpec: specPath }, changed: [{ kind: "launch-spec-written", path: specPath }], remedy: "inspect this exact run and the recorded local listener, manager and auth state before another boot" });
1936
2704
  console.error(c.red(`✗ ${e.message}`));
1937
2705
  process.exit(1);
1938
2706
  }
1939
2707
  // Transport committed inside startMeshDetached before delivery (S5+S9).
2708
+ let summaryRecorded = false;
2709
+ try {
2710
+ writeFreshTeamSummary(cotalRoot(), {
2711
+ schemaVersion: 1, kind: "fresh-team-summary", deploymentId, space: m.space,
2712
+ root: cotalRoot(), server, authMode: open ? "open" : userAuth ? "user" : "auth", brokerPid: pid, manifestPath: resolve(file),
2713
+ requestedAgents: eff.agents.map((agent) => agent.name),
2714
+ declaredChannels: m.channels.map((channel) => channel.name),
2715
+ recordedAt: new Date().toISOString(), managerRequested: !effectiveNoManager,
2716
+ controlPlaneReturned: controlPlane, authServiceReturned: authService, deliveryResponderBound,
2717
+ agentReadiness: "not-checked",
2718
+ });
2719
+ summaryRecorded = true;
2720
+ }
2721
+ catch {
2722
+ console.error(c.yellow(`! the native fresh boot returned but its local team summary could not be recorded (run ${deploymentId}); do not repeat the boot just to recreate the summary`));
2723
+ }
2724
+ if (opts.freshTeamBoot) {
2725
+ if (!authService || !controlPlane || !summaryRecorded || (!open && deliveryResponderBound !== true))
2726
+ throw new CommandFailure("partial", "OPERATION_PARTIAL", "the fresh broker started, but its control plane, auth service, delivery responder or local deployment summary did not confirm readiness; the same boot was not retried", { target: { space: m.space, deploymentId, brokerPid: pid, launchSpec: specPath }, changed: [{ kind: "broker-started", pid, server: brokerAddressForDisplay(server) ?? "not displayable" }, { kind: "launch-spec-written", path: specPath }, ...(summaryRecorded ? [{ kind: "fresh-summary-recorded", deploymentId }] : [])], remedy: "inspect this exact run, the local broker and manager, and any retained summary before deciding another action" });
2727
+ const inheritedAccess = eff.agents.flatMap((agent) => {
2728
+ const access = agent.inherited;
2729
+ return access.capabilities.length || access.subscribe.length || access.allowSubscribe.length || access.allowPublish.length
2730
+ ? [{ agent: agent.name, persona: agent.persona ?? null, capabilities: access.capabilities, subscribe: access.subscribe, allowSubscribe: access.allowSubscribe, allowPublish: access.allowPublish }]
2731
+ : [];
2732
+ });
2733
+ let currentSelection = null;
2734
+ let selectionChecked = false;
2735
+ try {
2736
+ currentSelection = getCurrent() ?? null;
2737
+ selectionChecked = true;
2738
+ }
2739
+ catch { /* The returned broker receipt remains usable without a current-default read. */ }
2740
+ const result = { kind: "fresh-team-boot", space: m.space, root: cotalRoot(), deploymentId, server: brokerAddressForDisplay(server) ?? "not displayable", brokerPid: pid, manifestPath: resolve(file), runtime, currentSelection, selectionChecked,
2741
+ mode: open ? "open" : userAuth ? "user-auth" : "static-auth", controlPlaneReturned: controlPlane, authServiceReturned: authService, deliveryResponderBound, summaryRecorded,
2742
+ requestedAgents: eff.agents.map((agent) => ({ name: agent.name, application: agent.agentType, role: agent.role ?? null })),
2743
+ declaredChannels: m.channels.map((channel) => ({ name: channel.name, deliveryClass: channel.deliveryClass ?? null, replay: channel.replay ?? null, replayWindow: channel.replayWindow ?? null })), inheritedAccess, agentReadiness: "not-checked" };
2744
+ writeResult(opts.presentation ?? "rich", { command: "team boot", target: { space: m.space, root: cotalRoot(), deploymentId }, result, completeness: "partial", warnings: [...eff.warnings.map((warning) => ({ code: "MANIFEST_WARNING", target: { agent: warning.agent }, message: warning.message })), ...(!selectionChecked ? [{ code: "CURRENT_SELECTION_UNAVAILABLE", target: { space: m.space }, message: "The current default space could not be read after boot; no default was inferred." }] : [])] }, (data) => ({ sections: [
2745
+ { title: "Fresh team broker returned", blocks: [{ kind: "fields", rows: [["Space", data.space], ["Deployment", data.deploymentId], ["Root", data.root], ["Broker", data.server], ["Broker PID", String(data.brokerPid)], ["Manifest", data.manifestPath], ["Auth mode", data.mode], ["Runtime request", data.runtime], ["Current default", data.selectionChecked ? data.currentSelection ?? "none selected" : "not checked"], ["Control-plane ensure", "returned"], ["Delivery responder", data.deliveryResponderBound === null ? "not required" : "bound when boot returned"], ["Membership material", "not checked by this receipt"], ["Auth service", data.mode === "user-auth" ? "returned at boot" : "not required"], ["Launch summary", "recorded"], ["Agent readiness", "not checked"]] }, { kind: "lines", lines: ["The manager was requested as part of boot; this receipt does not establish agent joins, current broker health or whole-stack stop authority."] }] },
2746
+ { title: "Requested topology", blocks: [data.requestedAgents.length ? { kind: "table", columns: [{ key: "name", label: "Agent" }, { key: "application", label: "Application" }, { key: "role", label: "Role" }], rows: data.requestedAgents.slice(0, 100).map((agent) => ({ ...agent, role: agent.role ?? "none" })) } : { kind: "lines", lines: ["No agents requested."] }, data.declaredChannels.length ? { kind: "table", columns: [{ key: "name", label: "Channel" }, { key: "delivery", label: "Declared delivery" }, { key: "replay", label: "Declared replay" }, { key: "window", label: "Declared window" }], rows: data.declaredChannels.slice(0, 100).map((channel) => ({ name: `#${channel.name}`, delivery: channel.deliveryClass ?? "not declared", replay: channel.replay === null ? "not declared" : channel.replay ? "on" : "off", window: channel.replayWindow ?? "not declared" })) } : { kind: "lines", lines: ["No channels declared."] }, ...((data.requestedAgents.length > 100 || data.declaredChannels.length > 100) ? [{ kind: "lines", lines: ["Showing at most 100 declared agents and channels; the saved summary retains all names."] }] : [])] },
2747
+ ...(data.inheritedAccess.length ? [{ title: "Persona-inherited access", blocks: [{ kind: "table", columns: [{ key: "agent", label: "Agent" }, { key: "persona", label: "Persona" }, { key: "scope", label: "Outside manifest channels" }], rows: data.inheritedAccess.slice(0, 100).map((row) => ({ agent: row.agent, persona: row.persona ?? "none", scope: [row.capabilities.length ? `capabilities ${row.capabilities.join(",")}` : "", row.subscribe.length ? `subscribe ${row.subscribe.join(",")}` : "", row.allowSubscribe.length ? `read ${row.allowSubscribe.join(",")}` : "", row.allowPublish.length ? `post ${row.allowPublish.join(",")}` : ""].filter(Boolean).join(" · ") })) }, { kind: "lines", lines: [...(data.inheritedAccess.length > 100 ? ["Additional inherited scopes are not shown in this terminal view."] : []), "These scopes came from referenced personas and are not limited to channels declared by this manifest."] }] }] : []),
2748
+ { title: "Next", blocks: [{ kind: "commands", items: [{ command: `cotal team show ${data.deploymentId}`, description: "Read this local launch summary" }, { command: `cotal watch --space ${data.space}`, description: "Observe the selected mesh" }, { command: `cotal down --space ${data.space} --dry-run`, description: "Inspect local stop records without stopping the stack" }] }] },
2749
+ ] }));
2750
+ return;
2751
+ }
1940
2752
  console.log(c.green(`✓ mesh "${m.space}" up at ${server}`) + c.dim(` (broker pid ${pid})`));
1941
2753
  console.log(c.dim(` seeded ${m.channels.length} channel(s): ${m.channels.map((ch) => "#" + ch.name).join(", ")}`));
2754
+ if (summaryRecorded)
2755
+ console.log(c.dim(` fresh deployment ${deploymentId} recorded; cotal team show ${deploymentId} reads its launch summary, not live ownership`));
1942
2756
  // Never claim a launch the control plane can't deliver: the manager carries the launch spec, so a
1943
2757
  // degraded control plane (announced above) means the agents are NOT coming up.
1944
2758
  if (effectiveNoManager) {
@@ -1959,11 +2773,12 @@ async function upManifest(file, opts) {
1959
2773
  console.log("\n" + inherited);
1960
2774
  if (eff.warnings.length)
1961
2775
  console.log("\n" + renderWarnings(eff.warnings));
1962
- console.log(c.dim(`\nWatch: \`cotal web\` (browser dashboard) or \`cotal console --space ${m.space}\` (terminal) · Tear down: \`cotal down\``));
2776
+ const downRoute = opts.root ? `from ${oneLine(cotalRoot())}, run \`cotal down\`` : "`cotal down`";
2777
+ console.log(c.dim(`\nWatch: \`cotal watch --space ${m.space}\` (terminal) · Dashboard: configure the explicit web service preset separately · Tear down: ${downRoute}`));
1963
2778
  // A declared-user-auth manifest whose auth service never became ready, or a degraded control
1964
2779
  // plane: the mesh is up + recorded, but this launch did not deliver what it declared — exit
1965
2780
  // non-zero so CI/wrappers don't read success (the consequence line printed at the failure above).
1966
- if (!authService || !controlPlane)
2781
+ if (!authService || !controlPlane || !summaryRecorded)
1967
2782
  process.exitCode = 1;
1968
2783
  }
1969
2784
  /** Return a copy of the prepared manifest with CLI overrides applied to broker/space/runtime, so the
@@ -1984,7 +2799,6 @@ function applyUpOverrides(prepared, o) {
1984
2799
  manifest: {
1985
2800
  ...m,
1986
2801
  broker: Object.keys(broker).length ? broker : undefined,
1987
- space: o.space ?? m.space,
1988
2802
  runtime: o.runtime ?? m.runtime,
1989
2803
  },
1990
2804
  };
@@ -2120,7 +2934,7 @@ async function serveReadyListener(l) {
2120
2934
  // USER MODE: the auth service comes up FIRST among the daemons — until its callout answers,
2121
2935
  // every user-mode connect to this broker is denied, so `up` must not report a usable user mesh
2122
2936
  // (nor let agents race it) on a half-started auth plane.
2123
- const svc = await startUserAuthService(space, server, setup, l.publicExchange);
2937
+ const svc = await startUserAuthService(space, server, setup, l.publicExchange, l.quietBoot);
2124
2938
  // Record BEFORE the control plane comes up: the manager's fail-closed mode detection requires
2125
2939
  // an authoritative registry entry (marker-without-registry is a refused start, not a guess),
2126
2940
  // so the record must exist by the time it boots. A manager/delivery failure after this leaves
@@ -2148,11 +2962,11 @@ async function serveReadyListener(l) {
2148
2962
  ...(l.maxFileStore !== undefined ? { maxFileStore: l.maxFileStore } : {}),
2149
2963
  storeDir: l.storeDir,
2150
2964
  ts: new Date().toISOString(),
2151
- }, "started");
2965
+ }, "started", l.quietBoot);
2152
2966
  // Commit the policy only for a listener that is up and recorded (S5), and before the control
2153
2967
  // plane (S9). startDeliveryWithBroker is HANDED the transport decision, so it does not depend on
2154
2968
  // the file at all.
2155
- commitTransportPolicy(cotalRoot(), transport);
2969
+ commitTransportPolicy(cotalRoot(), transport, l.quietBoot);
2156
2970
  // The delivery daemon self-gates on `.cotal/auth`, so an open mesh has none. Class-2 credential
2157
2971
  // renewal is NOT wired here: the MANAGER is the renewal owner (it is resident in every mesh mode,
2158
2972
  // where a foreground `up` process is not).
@@ -2167,22 +2981,17 @@ async function serveReadyListener(l) {
2167
2981
  maxSessions,
2168
2982
  noManager: l.noManager,
2169
2983
  resumeAttempt: l.resumeAttempt,
2170
- resumeCommitToken: l.resumeCommitToken,
2984
+ resumeCommit: l.resumeCommit,
2171
2985
  wsPort: setup?.wsPort, // P2 item 6: the console session client's broker ws port
2172
2986
  });
2987
+ seedPersonaAfterUp(cotalRoot(), l.quietBoot);
2173
2988
  return { authService: svc.ok, controlPlane };
2174
2989
  }
2175
- /**
2176
- * Start a background nats-server (JetStream), wait until it's reachable, pre-create the
2177
- * space's streams, and leave it running detached (pid in `.cotal/nats.pid`). Used by
2178
- * `up --detach`. When `onLine` is given, boot output is tailed from the
2179
- * log file and forwarded — the child writes to the file (not a pipe), so it survives the
2180
- * parent exiting.
2181
- */
2182
- export async function startMeshDetached(
2183
- // The `= {}` default is gone with the optional transport: an options object that can be omitted
2184
- // entirely cannot carry a mandatory decision.
2185
- opts) {
2990
+ /** Prepare the existing broker's local trust, configuration and launch inputs without starting a
2991
+ * listener, auth service, delivery daemon or manager. This is an explicit mutating phase, not a
2992
+ * dry-run or service-adapter planning hook. Its returned setup includes private authority material
2993
+ * for the coordinating caller only; it must not be logged or serialized into a public receipt. */
2994
+ export async function prepareBrokerStart(opts) {
2186
2995
  const server = opts.server ?? DEFAULT_SERVER;
2187
2996
  const useAuth = !opts.open;
2188
2997
  // Belt on the one boot that both renders the broker config and can be reached by any caller: an
@@ -2190,31 +2999,70 @@ opts) {
2190
2999
  // rather than refused. Callers guard this too; this is the seam that cannot be bypassed.
2191
3000
  if (opts.rotateSys && !useAuth)
2192
3001
  throw new Error("startMeshDetached: --rotate-sys is for auth meshes; an open mesh has no system account or $SYS credentials to rotate");
2193
- const space = opts.space ?? resolveSpace(process.cwd());
3002
+ const space = opts.space ?? folderSpace();
2194
3003
  ensureRootForSpace(space); // may pin the cwd as this space's root — before any cotalPath use
2195
3004
  refuseOpenOverUserState(Boolean(opts.open), space);
3005
+ const root = cotalRoot();
2196
3006
  const storeDir = opts.storeDir ? resolve(opts.storeDir) : cotalPath("nats");
2197
- mkdirSync(storeDir, { recursive: true });
2198
- await claimSpace(space, server, cotalRoot());
3007
+ if (opts.existingStore) {
3008
+ if (opts.existingStore.named !== storeDir)
3009
+ throw new Error("prepareBrokerStart: the pinned existing store is not the store being prepared");
3010
+ recheckExistingStore(opts.existingStore, { space, storeDir });
3011
+ }
3012
+ else
3013
+ mkdirSync(storeDir, { recursive: true, mode: 0o700 });
3014
+ await claimSpace(space, server, root);
2199
3015
  const seedFile = opts.seed ?? loadChannelsFile(opts.channels);
2200
3016
  const host = opts.host ?? "127.0.0.1";
2201
3017
  // The transport arrives decided. The dial-host SAN is re-checked here because THIS is where the
2202
3018
  // effective server is finally known — a manifest may name a different host than the flags did, and
2203
3019
  // a certificate that is valid for one is not thereby valid for the other.
2204
3020
  const transport = assertServesDialHost(opts.transport, new URL(server).hostname);
2205
- const setup = useAuth ? await authSetup(storeDir, server, space, host, opts.userAuth, transport, opts.rotateSys, opts.maxFileStore) : undefined;
3021
+ const setup = useAuth ? await authSetup(storeDir, server, space, host, opts.userAuth, transport, opts.rotateSys, opts.maxFileStore, opts.quietBoot) : undefined;
2206
3022
  const port = Number(new URL(server).port) || 4222;
2207
3023
  // Same rule as the foreground path: every route to a listener names its transport (see
2208
3024
  // `writeOpenBrokerConf`). Detach must not be the mode where the fence quietly does not apply.
2209
3025
  const confPath = setup ? setup.confPath : writeOpenBrokerConf(storeDir, { port, host, transport, maxFileStore: opts.maxFileStore });
3026
+ // Trust preparation awaits; the pinned store is checked again before its config is handed back.
3027
+ if (opts.existingStore)
3028
+ recheckExistingStore(opts.existingStore, { space, storeDir });
2210
3029
  const args = [
2211
3030
  "-c", confPath,
2212
3031
  ...(opts.boundListener ? ["--name", opts.boundListener.serverName] : []),
2213
3032
  ];
2214
3033
  const { bin, source } = await resolveNatsServer();
3034
+ return { root, server, space, useAuth, storeDir, seedFile, host, transport, setup, confPath, args, bin, source };
3035
+ }
3036
+ /**
3037
+ * Open the detached broker's log with {@link openPrivateAppend}: created `0600` whatever the umask,
3038
+ * never through a symlink, and an earlier log this user owns set to `0600`. A symlink, a log another
3039
+ * user owns or a name that is not a regular file is refused and left unchanged.
3040
+ */
3041
+ export function openBrokerLog(path) {
3042
+ try {
3043
+ return openPrivateAppend(path);
3044
+ }
3045
+ catch (error) {
3046
+ if (error.code !== "EPERM")
3047
+ throw error;
3048
+ throw new CommandFailure("refused", "PERMISSION_DENIED", `no broker was started: ${error.message}`, { target: { path }, remedy: `remove ${path} or replace it with a regular file you own, then run cotal up again` });
3049
+ }
3050
+ }
3051
+ /**
3052
+ * Start a background nats-server (JetStream), wait until it's reachable, pre-create the
3053
+ * space's streams, and leave it running detached (pid in `.cotal/nats.pid`). Used by
3054
+ * `up --detach`. When `onLine` is given, boot output is tailed from the
3055
+ * log file and forwarded — the child writes to the file (not a pipe), so it survives the
3056
+ * parent exiting.
3057
+ */
3058
+ export async function startMeshDetached(
3059
+ // The `= {}` default is gone with the optional transport: an options object that can be omitted
3060
+ // entirely cannot carry a mandatory decision.
3061
+ opts) {
3062
+ const { server, space, useAuth, storeDir, seedFile, transport, setup, args, bin, source } = await prepareBrokerStart(opts);
2215
3063
  const logPath = cotalPath("nats.log");
2216
- const startOffset = existsSync(logPath) ? statSync(logPath).size : 0;
2217
- const fd = openSync(logPath, "a");
3064
+ const fd = openBrokerLog(logPath);
3065
+ const startOffset = fstatSync(fd).size;
2218
3066
  const listenerStartedAt = new Date().toISOString();
2219
3067
  const child = spawn(bin, args, { detached: true, stdio: ["ignore", fd, fd] });
2220
3068
  closeSync(fd);
@@ -2236,10 +3084,11 @@ opts) {
2236
3084
  maxFileStore: opts.maxFileStore,
2237
3085
  publicExchange: opts.publicExchange,
2238
3086
  resumeAttempt: opts.resumeAttempt,
2239
- resumeCommitToken: opts.resumeCommitToken,
3087
+ resumeCommit: opts.resumeCommit,
2240
3088
  runtime: opts.runtime,
2241
3089
  launch: opts.launch,
2242
3090
  noManager: opts.noManager,
3091
+ quietBoot: opts.quietBoot,
2243
3092
  });
2244
3093
  return {
2245
3094
  server,
@@ -2247,6 +3096,7 @@ opts) {
2247
3096
  source,
2248
3097
  controlPlane: controlPlane !== undefined,
2249
3098
  authService,
3099
+ deliveryResponderBound: useAuth ? controlPlane?.responderBound === true : null,
2250
3100
  delivery: useAuth && deliveryUp(space),
2251
3101
  manager: managerUp(space),
2252
3102
  };
@@ -2284,6 +3134,14 @@ function refuseOpenOverUserState(open, space) {
2284
3134
  function ensureRootForSpace(space) {
2285
3135
  const root = cotalRoot();
2286
3136
  const cwd = process.cwd();
3137
+ // A prepared space starts only in the root `cotal space create` gave it. Checked before the mkdir
3138
+ // below, so a refused start leaves nothing behind.
3139
+ const prepared = findPreparedSpace(space);
3140
+ if (prepared && canonicalRoot(prepared.root) !== canonicalRoot(root))
3141
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `space "${space}" is prepared in ${prepared.root}`, {
3142
+ target: { space, root: prepared.root },
3143
+ remedy: `start it with \`cotal up\` there, or \`cotal space forget ${space}\` to start it here`,
3144
+ });
2287
3145
  // What spaces does this root already host? Prefer auth material; fall back to a live MeshEntry
2288
3146
  // whose root is this directory (open meshes have no auth dir).
2289
3147
  const hosted = listSpaceAccounts(authDir(root));
@@ -2291,16 +3149,43 @@ function ensureRootForSpace(space) {
2291
3149
  return;
2292
3150
  const existing = hosted.length
2293
3151
  ? hosted
2294
- : [loadMeshes().find((m) => m.root === root || realpathSafe(m.root) === realpathSafe(root))?.space].filter((s) => !!s);
3152
+ : [loadMeshes().find((m) => m.root === root || realpathSafe(m.root) === realpathSafe(root))?.space ?? preparedSpaceAt(root)?.space].filter((s) => !!s);
2295
3153
  if (existing.length === 0 || existing.includes(space))
2296
3154
  return;
2297
3155
  const names = existing.map((s) => `"${s}"`).join(", ");
2298
3156
  if (root !== cwd) {
2299
- mkdirSync(join(cwd, ".cotal"), { recursive: true });
3157
+ mkdirSync(join(cwd, ".cotal"), { recursive: true, mode: 0o700 });
2300
3158
  console.log(c.dim(`nearest mesh root ${root} hosts ${names} - making this folder its own root for "${space}"`));
2301
3159
  return;
2302
3160
  }
2303
- throw new Error(`this folder is the root of ${names} (${root}/.cotal), so it can't also run "${space}" - drop \`--space\` to run ${existing.length === 1 ? names : "one of those"}, or start "${space}" from a different folder (it becomes that mesh's own root)`);
3161
+ throw new CommandFailure("refused", "CONFLICT", `this folder is the root of ${names} (${root}/.cotal), so it can't also run "${space}"`, {
3162
+ target: { space, root, hosted: existing },
3163
+ remedy: `${existing.length === 1 ? `run ${names} with \`cotal up --space ${existing[0]}\`` : "run one of those with `cotal up --space <name>`"}, or start "${space}" from a different folder (it becomes that mesh's own root)`,
3164
+ });
3165
+ }
3166
+ /** The space a `cotal up` that names none runs in this folder. The root's sole account names it
3167
+ * first, as {@link resolveSpace} does. An open mesh has no account, and its first start replaces
3168
+ * the prepared record with a registration, so the space this root's stack journal or its locally
3169
+ * started registration names comes next. Without it a second `up` in the same folder resolved the
3170
+ * default space and refused its own mesh. Several names there are refused, never picked. Then the
3171
+ * space prepared here, then the default.
3172
+ *
3173
+ * Only `up` asks this. `resolveSpace` also decides whether identity cleanup may attribute a root to
3174
+ * a space (`reset-space-plan.ts`) and, through `resolveRuntimeSpace`, which space a legacy `down`
3175
+ * removes credentials for; those keep their own answer. */
3176
+ function folderSpace() {
3177
+ const root = cotalRoot();
3178
+ if (soleSpaceOf(authDir(root)) === undefined) {
3179
+ const named = [...new Set([readStackJournal(root)?.journal.space, ...localMeshesForRoot(root).map((m) => m.space)])].filter((s) => s !== undefined);
3180
+ if (named.length > 1)
3181
+ throw new CommandFailure("refused", "CONFLICT", `this folder's stack and registrations name ${named.length} spaces (${named.map((s) => `"${s}"`).join(", ")}), so up cannot pick one`, {
3182
+ target: { root, spaces: named },
3183
+ remedy: "name the space to run with `--space`",
3184
+ });
3185
+ if (named.length === 1)
3186
+ return named[0];
3187
+ }
3188
+ return resolveSpace(process.cwd());
2304
3189
  }
2305
3190
  function realpathSafe(p) {
2306
3191
  try {
@@ -2338,27 +3223,77 @@ function manualClaimRemedy(space, server) {
2338
3223
  return `\`cotal supervise --space ${space} --server ${server}\` to run its control plane from here (and \`cotal deliver --space ${space} --server ${server}\` for the daemon)`;
2339
3224
  return `\`cotal meshes rm ${space}\` to drop that record first, or start this one under a different \`--space\``;
2340
3225
  }
3226
+ /** Where a prior holder's absolute root physically resolves, or undefined when it is proven gone: it
3227
+ * does not resolve (ENOENT, ENOTDIR) or resolves to something other than a directory. Any other
3228
+ * failure, such as EACCES, EPERM, EIO or ELOOP, proves nothing about the root or its journal, so the
3229
+ * name is kept and the refusal says why. No lexical spelling stands in for the physical path: under
3230
+ * an unreadable ancestor, `<root>/link/..` resolves lexically to `<root>` while it names another. */
3231
+ function priorRootPath(space, root) {
3232
+ let real;
3233
+ let kind;
3234
+ try {
3235
+ real = realpathSync.native(root);
3236
+ kind = statSync(real);
3237
+ }
3238
+ catch (e) {
3239
+ const code = e.code;
3240
+ if (code === "ENOENT" || code === "ENOTDIR")
3241
+ return undefined;
3242
+ throw new CommandFailure("refused", code === "EACCES" || code === "EPERM" ? "PERMISSION_DENIED" : "TARGET_UNAVAILABLE", `space "${space}" is registered to ${root}, which could not be resolved (${code ?? String(e)}) - \`cotal up\` did not take the name`, { target: { space, root }, remedy: `restore access to ${root} and run this again, or start this stack under a different \`--space\`` });
3243
+ }
3244
+ return kind.isDirectory() ? real : undefined;
3245
+ }
2341
3246
  /** A space name maps to one mesh in the registry (the key `--space`/`use`/`down` act on). Before
2342
3247
  * starting a broker, refuse to reuse a space already claimed by a DIFFERENT live mesh — a stale/dead
2343
- * holder is reclaimed. Re-`up`ping the same mesh (same server + root) is a refresh (port-reachable
3248
+ * holder is reclaimed, and said so when it was another root's, unless that root still holds a
3249
+ * maintenance journal. Re-`up`ping the same mesh (same server + root) is a refresh (port-reachable
2344
3250
  * path). NOTE: this is a best-effort sequential guard — two `cotal up --space X` racing from
2345
3251
  * different roots within the same instant can both pass the check before either records; that
2346
3252
  * concurrent case is out of scope (a single-operator CLI action), not synchronized with a lock. */
2347
3253
  export async function claimSpace(space, server, root) {
2348
3254
  const existing = findMesh(space);
2349
- if (!existing || (existing.server === server && existing.root === root))
3255
+ if (!existing)
2350
3256
  return;
3257
+ // A relative recorded root names no directory without a guess against the cwd, so it is never
3258
+ // taken as this root, compared with it or reclaimed. Its record stays until it is removed by hand.
3259
+ const relative = !isAbsolute(existing.root);
3260
+ if (!relative && existing.server === server && existing.root === root)
3261
+ return;
3262
+ // Every refusal below is made before the registry changes, so it is typed as refused with its own
3263
+ // remedy, and the controller and legacy routes both show the reason and exit 2.
3264
+ const target = { space, root: existing.root, server: existing.server };
2351
3265
  // An OPERATOR-REGISTERED holder is decided FIRST, before liveness, because liveness changes
2352
3266
  // nothing about it and the two outcomes would otherwise print the wrong remedy. It is never
2353
3267
  // reclaimed: unreachable is not proof the mesh is gone (the record describes a broker on another
2354
3268
  // machine), the reclaim runs BEFORE this launch starts anything, and `cotal down` — what the
2355
3269
  // liveness branch below would advise — cannot stop a mesh this machine does not run.
2356
3270
  if (existing.origin === "manual" || existing.origin === "catalog")
2357
- throw new Error(`space "${space}" is registered to a mesh at ${existing.server} (${existing.root}) - it is ${existing.origin === "catalog" ? "owned by a signed-in space catalog" : "registered by hand"}, so \`cotal up\` neither takes it over nor reclaims the name: ${existing.origin === "catalog" ? "use a different `--space`, or remove access at the IdP and run `cotal sync`" : manualClaimRemedy(space, existing.server)}`);
2358
- if (await isReachable(existing.server)) {
2359
- throw new Error(`space "${space}" is already in use by a mesh at ${existing.server} (${existing.root}) - pick a different \`--space\`, or \`cotal down\` it first`);
3271
+ throw new CommandFailure("refused", "CONFLICT", `space "${space}" is registered to a mesh at ${existing.server} (${existing.root}) - it is ${existing.origin === "catalog" ? "owned by a signed-in space catalog" : "registered by hand"}, so \`cotal up\` neither takes it over nor reclaims the name`, { target, remedy: existing.origin === "catalog" ? "use a different `--space`, or remove access at the IdP and run `cotal sync`" : manualClaimRemedy(space, existing.server) });
3272
+ if (relative)
3273
+ throw new CommandFailure("refused", "CONFLICT", `space "${space}" is registered to ${existing.root}, which is not an absolute path - \`cotal up\` did not take the name`, { target, remedy: `drop that record with \`cotal meshes rm ${space}\`, or start this stack under a different \`--space\`` });
3274
+ if (await isReachable(existing.server))
3275
+ throw new CommandFailure("refused", "CONFLICT", `space "${space}" is already in use by a mesh at ${existing.server} (${existing.root})`, { target, remedy: "pick a different `--space`, or `cotal down` it first" });
3276
+ // The recorded root is this root only where it physically resolves, so it is resolved before any
3277
+ // comparison, and one that cannot be resolved refuses. A dead holder at another root keeps its name
3278
+ // while that root holds a preserved cut or a restore: taking it would cut that root's recovery off
3279
+ // from its space. A journal that cannot be read keeps it too. A root proven gone or not a directory
3280
+ // has no journal to read; a readable root without one is reclaimed.
3281
+ const prior = priorRootPath(space, existing.root);
3282
+ const otherRoot = prior !== canonicalRoot(root);
3283
+ if (otherRoot && prior !== undefined) {
3284
+ let held;
3285
+ try {
3286
+ held = readMaintenanceJournal(existing.root)?.state;
3287
+ }
3288
+ catch {
3289
+ held = "unreadable";
3290
+ }
3291
+ if (held)
3292
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `space "${space}" is registered to ${existing.root}, whose maintenance journal holds a preserved cut or a restore (state ${held}) - \`cotal up\` did not take the name`, { target, remedy: `finish that attempt from ${existing.root}, or start this stack under a different \`--space\`` });
2360
3293
  }
2361
3294
  removeMesh(space); // the prior holder's broker is gone — reclaim the name
3295
+ if (otherRoot)
3296
+ console.error(`• space "${space}" was registered to ${existing.root}, whose broker at ${existing.server} is not running - this up takes the name over`);
2362
3297
  }
2363
3298
  /**
2364
3299
  * The manager attach/console BIND host for a launch into `space`.
@@ -2406,9 +3341,9 @@ export const recordOurMeshForTest = (m, provenance) => recordOurMesh(m, provenan
2406
3341
  * — i.e. the first mesh, OR when `current` dangles at a space that's no longer in the registry (a
2407
3342
  * ghost pointer is not a default). Never silently redirect a `current` that still resolves to a live
2408
3343
  * mesh; just say another is the default and how to switch. */
2409
- function recordOurMesh(m, provenance) {
3344
+ function recordOurMesh(m, provenance, quietBoot = false) {
2410
3345
  const cur = getCurrent();
2411
- const usableCurrent = cur && findMesh(cur) ? cur : undefined; // compute before recording m
3346
+ const usableCurrent = cur && (findMesh(cur) || findPreparedSpace(cur)) ? cur : undefined; // compute before recording m
2412
3347
  const prior = findMesh(m.space);
2413
3348
  const origin = provenance === "refresh" && (prior?.origin === "manual" || prior?.origin === "catalog") ? prior.origin : "up";
2414
3349
  // A REFRESH starts nothing: it concluded the mesh is up from reachability alone, so `m` holds only
@@ -2420,13 +3355,28 @@ function recordOurMesh(m, provenance) {
2420
3355
  if (provenance === "refresh" && !prior)
2421
3356
  throw new Error(`mesh "${m.space}" was removed from the registry while \`cotal up\` refreshed it - not re-recording it from an earlier read`);
2422
3357
  recordMesh(provenance === "refresh" ? { ...prior, ...m, origin } : { ...m, origin });
3358
+ removePreparedSpace(m.space); // started: the registration is its record now
2423
3359
  if (!usableCurrent) {
2424
3360
  setCurrent(m.space);
2425
3361
  return;
2426
3362
  }
2427
- if (usableCurrent !== m.space)
3363
+ if (usableCurrent !== m.space && !quietBoot)
2428
3364
  console.log(c.dim(`"${m.space}" up; current is still "${usableCurrent}" - \`cotal use ${m.space}\` to switch`));
2429
3365
  }
3366
+ /** Write the default persona into the root this `up` started or refreshed when it has none, and
3367
+ * say so. The mesh is already up, so a write that fails is reported and the start stands. */
3368
+ function seedPersonaAfterUp(root, quiet = false) {
3369
+ let written;
3370
+ try {
3371
+ written = seedDefaultPersona(root);
3372
+ }
3373
+ catch (e) {
3374
+ console.error(c.yellow(`! the default persona was not written in ${root}: ${e.message}`));
3375
+ return;
3376
+ }
3377
+ if (written && !quiet)
3378
+ console.log(c.dim(` wrote ${written.what}: ${written.path}`));
3379
+ }
2430
3380
  /** Poll a growing log file and forward newly-appended lines until `stopped()` is true. */
2431
3381
  function tailLines(path, from, onLine, stopped) {
2432
3382
  let offset = from;
@@ -2559,6 +3509,45 @@ function reconcileHostAndServer(host, explicitServer, source = "--host", urlSour
2559
3509
  }
2560
3510
  return explicitServer;
2561
3511
  }
3512
+ /** Bind the manifest's exact listener address before any team-boot write. Releasing this
3513
+ * socket is not a reservation: the real broker still owns the final bind verdict. */
3514
+ async function assertFreshTeamBindAvailable(server, host, space) {
3515
+ const url = new URL(server), port = Number(url.port || "4222");
3516
+ const displayServer = brokerAddressForDisplay(server) ?? "not displayable";
3517
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65535)
3518
+ throw new CommandFailure("refused", "USAGE_INVALID", "the fresh team broker needs a concrete TCP port before it can check its bind address", { target: { space } });
3519
+ await new Promise((resolve, reject) => {
3520
+ const socket = createServer(), controller = new AbortController();
3521
+ socket.unref();
3522
+ let settled = false;
3523
+ const finish = (error) => {
3524
+ if (settled)
3525
+ return;
3526
+ settled = true;
3527
+ clearTimeout(timer);
3528
+ if (error)
3529
+ reject(error);
3530
+ else
3531
+ resolve();
3532
+ };
3533
+ const timer = setTimeout(() => {
3534
+ controller.abort();
3535
+ finish(new CommandFailure("refused", "TARGET_UNAVAILABLE", "the local broker bind inspection did not complete within its deadline; no absence or startup eligibility was inferred", { target: { space, server: displayServer } }));
3536
+ }, 1500);
3537
+ socket.once("error", () => finish(new CommandFailure("refused", "TARGET_UNAVAILABLE", "the selected broker address cannot be bound as a new local listener; no existing or remote broker was adopted", { target: { space, server: displayServer }, remedy: "inspect this local bind address and any process already listening there" })));
3538
+ try {
3539
+ socket.listen({ port, host, signal: controller.signal }, () => {
3540
+ if (settled)
3541
+ return;
3542
+ socket.close((error) => finish(error ? new CommandFailure("failed", "OPERATION_FAILED", "the temporary bind inspection did not confirm closure; no broker was started", { target: { space, server: displayServer } }) : undefined));
3543
+ });
3544
+ }
3545
+ catch {
3546
+ controller.abort();
3547
+ finish(new CommandFailure("refused", "TARGET_UNAVAILABLE", "the selected broker bind address was rejected before startup; no other listener was chosen", { target: { space, server: displayServer } }));
3548
+ }
3549
+ });
3550
+ }
2562
3551
  async function serverWithFreePort(server, host) {
2563
3552
  const url = new URL(server);
2564
3553
  url.port = String(await freePort(host));
@@ -2695,12 +3684,13 @@ opts = {}) {
2695
3684
  writeBrokerPolicy(root, { version: 1, transport: validated });
2696
3685
  return validated;
2697
3686
  }
2698
- /** Persist + announce a transport that has been APPLIED (listener started and proved). */
2699
- function commitTransportPolicy(root, transport) {
3687
+ /** Persist a transport after its listener starts; a structured boot leaves stdout to its receipt. */
3688
+ function commitTransportPolicy(root, transport, quietBoot = false) {
2700
3689
  if (transport.kind !== "tls-required")
2701
3690
  return;
2702
3691
  writeBrokerPolicy(root, { version: 1, transport });
2703
- announceTransport(transport);
3692
+ if (!quietBoot)
3693
+ announceTransport(transport);
2704
3694
  }
2705
3695
  function announceTransport(transport) {
2706
3696
  if (transport.kind !== "tls-required")
@@ -2830,8 +3820,8 @@ function validateRecorded(transport, dialHost, opts = {}) {
2830
3820
  * does not state its transport.
2831
3821
  */
2832
3822
  function writeOpenBrokerConf(storeDir, opts) {
2833
- const confPath = resolve(storeDir, "..", "server-open.conf");
2834
- writeFileSync(confPath, openServerConfig({ port: opts.port, host: opts.host, storeDir, maxFileStore: opts.maxFileStore, transport: opts.transport }));
3823
+ const confPath = cotalPath("server-open.conf");
3824
+ writeSecretFile(confPath, openServerConfig({ port: opts.port, host: opts.host, storeDir, maxFileStore: opts.maxFileStore, transport: opts.transport }));
2835
3825
  return confPath;
2836
3826
  }
2837
3827
  /** Ensure the space's trust material exists, render a server config, and mint a privileged
@@ -2855,7 +3845,7 @@ async function authSetup(storeDir, server, space, host = "127.0.0.1", user,
2855
3845
  // operator's `--tls-cert` sat validated and unused. A default here cannot be right, because the
2856
3846
  // safe value and the common value are different values — every caller knows its transport, and
2857
3847
  // the one that does not is the one that must not compile.
2858
- transport, rotateSys = false, maxFileStore) {
3848
+ transport, rotateSys = false, maxFileStore, quietBoot = false) {
2859
3849
  const dir = authDir(cotalRoot()); // the broker config (server.conf) still lands under the FS auth dir
2860
3850
  const store = workspaceSecretStore(cotalRoot());
2861
3851
  let auth = await getSpaceAuth(store, space);
@@ -2898,7 +3888,7 @@ transport, rotateSys = false, maxFileStore) {
2898
3888
  console.log(c.dim(" NOTE: full backups taken before this rotation can no longer be restored (they are bound to the retired trust chain) - take a fresh `cotal backup` once the mesh is up."));
2899
3889
  }
2900
3890
  // The DATA half of the membership bundle, on EVERY path — see healMembershipDataCreds.
2901
- await healMembershipDataCreds(auth, cotalRoot(), space);
3891
+ await healMembershipDataCreds(auth, cotalRoot(), space, quietBoot);
2902
3892
  // The $SYS creds must be signed by the system account THIS boot is about to put in `server.conf`.
2903
3893
  // A rotation that committed the trust record and then died leaves them stale, unexpired, and
2904
3894
  // broker-dead and, crash-before-either-write, stale in a way that no comparison between the two
@@ -2964,7 +3954,9 @@ transport, rotateSys = false, maxFileStore) {
2964
3954
  : await resolveAuthProvider().preloadAccounts({ store, space: enabledSpace });
2965
3955
  extraAccounts.push(...accounts);
2966
3956
  }
2967
- writeFileSync(confPath, serverConfig(auth, spaces, { transport, port, storeDir, maxFileStore, host, wsPort, wsHost: host, extraAccounts }));
3957
+ // Owner-private regardless of umask, as `writeOpenBrokerConf` writes the open configuration: the
3958
+ // broker preset refuses a configuration that other local users can write.
3959
+ writeSecretFile(confPath, serverConfig(auth, spaces, { transport, port, storeDir, maxFileStore, host, wsPort, wsHost: host, extraAccounts }));
2968
3960
  // Ephemeral setup cred: used only to probe reachability, pre-create the space streams/buckets
2969
3961
  // (setupSpaceStreams) and seed the channel registry (seedChannelRegistry) — all within the
2970
3962
  // enumerated `provisioner` scope. No broad `manager` residual for the up path.
@@ -3046,7 +4038,7 @@ async function assertRootBrokerStopped(root) {
3046
4038
  * its own error text — advice that could not succeed. Healing here fixes both spellings at once:
3047
4039
  * the ordinary `up` repairs the data half with no rotation at all, and a rotation now repairs it
3048
4040
  * too, because this runs after both branches converge. */
3049
- async function healMembershipDataCreds(auth, root, space) {
4041
+ async function healMembershipDataCreds(auth, root, space, quietBoot = false) {
3050
4042
  try {
3051
4043
  const store = workspaceSecretStore(root);
3052
4044
  // THE RESOLVERS, not the bare kinds (P7 §2 rule 1). Both reads below are absent-means-MINT, which
@@ -3067,7 +4059,7 @@ async function healMembershipDataCreds(auth, root, space) {
3067
4059
  writeSecretFile(configPath, JSON.stringify({ accountId: auth.account.pub }));
3068
4060
  wrote.push(MEMBERSHIP_CONFIG_KIND);
3069
4061
  }
3070
- if (wrote.length)
4062
+ if (wrote.length && !quietBoot)
3071
4063
  console.log(c.dim(`• membership: provisioned ${wrote.join(" + ")} - the data-account half needs no system-account rotation`));
3072
4064
  }
3073
4065
  catch (e) {