@cotal-ai/cli 0.90.1 → 0.91.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 (759) 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 +19 -0
  6. package/dist/chat/controller.d.ts.map +1 -0
  7. package/dist/chat/controller.js +116 -0
  8. package/dist/chat/controller.js.map +1 -0
  9. package/dist/chat/engine.d.ts +108 -0
  10. package/dist/chat/engine.d.ts.map +1 -0
  11. package/dist/chat/engine.js +226 -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 +151 -0
  16. package/dist/chat/frontend.js.map +1 -0
  17. package/dist/chat/native-session.d.ts +71 -0
  18. package/dist/chat/native-session.d.ts.map +1 -0
  19. package/dist/chat/native-session.js +348 -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 +34 -0
  26. package/dist/chat/picker.d.ts.map +1 -0
  27. package/dist/chat/picker.js +97 -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 +242 -0
  32. package/dist/chat/plain.js.map +1 -0
  33. package/dist/chat/session.d.ts +217 -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 +34 -0
  42. package/dist/chat/stdio-io.d.ts.map +1 -0
  43. package/dist/chat/stdio-io.js +175 -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 +400 -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 +186 -0
  54. package/dist/chat/view.d.ts.map +1 -0
  55. package/dist/chat/view.js +386 -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 +392 -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 +501 -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 +92 -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 +27 -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 +81 -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 +102 -24
  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 +264 -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 +276 -115
  126. package/dist/commands/down.js.map +1 -1
  127. package/dist/commands/endpoint-authoring.d.ts +4 -0
  128. package/dist/commands/endpoint-authoring.d.ts.map +1 -0
  129. package/dist/commands/endpoint-authoring.js +125 -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 +73 -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 +443 -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 +140 -0
  198. package/dist/commands/reset-space-apply.js.map +1 -0
  199. package/dist/commands/reset-store-apply.d.ts +11 -0
  200. package/dist/commands/reset-store-apply.d.ts.map +1 -0
  201. package/dist/commands/reset-store-apply.js +154 -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 +143 -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 +405 -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 +106 -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 +161 -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 +341 -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 +388 -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 +78 -18
  263. package/dist/commands/spawn.d.ts.map +1 -1
  264. package/dist/commands/spawn.js +236 -96
  265. package/dist/commands/spawn.js.map +1 -1
  266. package/dist/commands/stack-down.d.ts +6 -0
  267. package/dist/commands/stack-down.d.ts.map +1 -0
  268. package/dist/commands/stack-down.js +206 -0
  269. package/dist/commands/stack-down.js.map +1 -0
  270. package/dist/commands/stack-up.d.ts +149 -0
  271. package/dist/commands/stack-up.d.ts.map +1 -0
  272. package/dist/commands/stack-up.js +459 -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 +232 -5
  279. package/dist/commands/status.d.ts.map +1 -1
  280. package/dist/commands/status.js +989 -406
  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 +727 -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 +144 -5
  319. package/dist/commands/up.d.ts.map +1 -1
  320. package/dist/commands/up.js +1015 -124
  321. package/dist/commands/up.js.map +1 -1
  322. package/dist/commands/update.d.ts +11 -0
  323. package/dist/commands/update.d.ts.map +1 -1
  324. package/dist/commands/update.js +72 -15
  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 +2 -0
  377. package/dist/index.d.ts.map +1 -1
  378. package/dist/index.js +444 -118
  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 +34 -1
  392. package/dist/lib/backup-artifact.d.ts.map +1 -1
  393. package/dist/lib/backup-artifact.js +67 -17
  394. package/dist/lib/backup-artifact.js.map +1 -1
  395. package/dist/lib/broker-service.d.ts +10 -0
  396. package/dist/lib/broker-service.d.ts.map +1 -0
  397. package/dist/lib/broker-service.js +329 -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/control.d.ts +65 -6
  421. package/dist/lib/control.d.ts.map +1 -1
  422. package/dist/lib/control.js +121 -27
  423. package/dist/lib/control.js.map +1 -1
  424. package/dist/lib/controller-preserve.d.ts +12 -0
  425. package/dist/lib/controller-preserve.d.ts.map +1 -0
  426. package/dist/lib/controller-preserve.js +373 -0
  427. package/dist/lib/controller-preserve.js.map +1 -0
  428. package/dist/lib/controller-restore.d.ts +38 -0
  429. package/dist/lib/controller-restore.d.ts.map +1 -0
  430. package/dist/lib/controller-restore.js +205 -0
  431. package/dist/lib/controller-restore.js.map +1 -0
  432. package/dist/lib/controller-resume.d.ts +92 -0
  433. package/dist/lib/controller-resume.d.ts.map +1 -0
  434. package/dist/lib/controller-resume.js +300 -0
  435. package/dist/lib/controller-resume.js.map +1 -0
  436. package/dist/lib/credential-authority.d.ts +17 -0
  437. package/dist/lib/credential-authority.d.ts.map +1 -0
  438. package/dist/lib/credential-authority.js +28 -0
  439. package/dist/lib/credential-authority.js.map +1 -0
  440. package/dist/lib/default-persona.d.ts +38 -0
  441. package/dist/lib/default-persona.d.ts.map +1 -0
  442. package/dist/lib/default-persona.js +85 -0
  443. package/dist/lib/default-persona.js.map +1 -0
  444. package/dist/lib/delivery-proc.d.ts +9 -9
  445. package/dist/lib/delivery-proc.d.ts.map +1 -1
  446. package/dist/lib/delivery-proc.js +9 -19
  447. package/dist/lib/delivery-proc.js.map +1 -1
  448. package/dist/lib/endpoint-capability-gates.d.ts +10 -0
  449. package/dist/lib/endpoint-capability-gates.d.ts.map +1 -0
  450. package/dist/lib/endpoint-capability-gates.js +70 -0
  451. package/dist/lib/endpoint-capability-gates.js.map +1 -0
  452. package/dist/lib/endpoint-client.d.ts +20 -0
  453. package/dist/lib/endpoint-client.d.ts.map +1 -0
  454. package/dist/lib/endpoint-client.js +42 -0
  455. package/dist/lib/endpoint-client.js.map +1 -0
  456. package/dist/lib/endpoint-errors.d.ts +11 -0
  457. package/dist/lib/endpoint-errors.d.ts.map +1 -0
  458. package/dist/lib/endpoint-errors.js +30 -0
  459. package/dist/lib/endpoint-errors.js.map +1 -0
  460. package/dist/lib/endpoint-goal.d.ts +19 -0
  461. package/dist/lib/endpoint-goal.d.ts.map +1 -0
  462. package/dist/lib/endpoint-goal.js +31 -0
  463. package/dist/lib/endpoint-goal.js.map +1 -0
  464. package/dist/lib/endpoint-inventory.d.ts +30 -0
  465. package/dist/lib/endpoint-inventory.d.ts.map +1 -0
  466. package/dist/lib/endpoint-inventory.js +79 -0
  467. package/dist/lib/endpoint-inventory.js.map +1 -0
  468. package/dist/lib/endpoint-references.d.ts +22 -0
  469. package/dist/lib/endpoint-references.d.ts.map +1 -0
  470. package/dist/lib/endpoint-references.js +44 -0
  471. package/dist/lib/endpoint-references.js.map +1 -0
  472. package/dist/lib/endpoint-scatter.d.ts +57 -0
  473. package/dist/lib/endpoint-scatter.d.ts.map +1 -0
  474. package/dist/lib/endpoint-scatter.js +75 -0
  475. package/dist/lib/endpoint-scatter.js.map +1 -0
  476. package/dist/lib/endpoint-selection.d.ts +35 -0
  477. package/dist/lib/endpoint-selection.d.ts.map +1 -0
  478. package/dist/lib/endpoint-selection.js +80 -0
  479. package/dist/lib/endpoint-selection.js.map +1 -0
  480. package/dist/lib/install-umask.d.ts +6 -0
  481. package/dist/lib/install-umask.d.ts.map +1 -0
  482. package/dist/lib/install-umask.js +15 -0
  483. package/dist/lib/install-umask.js.map +1 -0
  484. package/dist/lib/isolated-broker.d.ts.map +1 -1
  485. package/dist/lib/isolated-broker.js +9 -5
  486. package/dist/lib/isolated-broker.js.map +1 -1
  487. package/dist/lib/local-process-stop.d.ts.map +1 -1
  488. package/dist/lib/local-process-stop.js +7 -1
  489. package/dist/lib/local-process-stop.js.map +1 -1
  490. package/dist/lib/manager-proc.d.ts +11 -5
  491. package/dist/lib/manager-proc.d.ts.map +1 -1
  492. package/dist/lib/manager-proc.js +12 -17
  493. package/dist/lib/manager-proc.js.map +1 -1
  494. package/dist/lib/manifest/apply.d.ts +4 -1
  495. package/dist/lib/manifest/apply.d.ts.map +1 -1
  496. package/dist/lib/manifest/apply.js +1 -1
  497. package/dist/lib/manifest/apply.js.map +1 -1
  498. package/dist/lib/manifest/ledger.d.ts +3 -1
  499. package/dist/lib/manifest/ledger.d.ts.map +1 -1
  500. package/dist/lib/manifest/ledger.js +16 -3
  501. package/dist/lib/manifest/ledger.js.map +1 -1
  502. package/dist/lib/manifest/schema.d.ts +1 -117
  503. package/dist/lib/manifest/schema.d.ts.map +1 -1
  504. package/dist/lib/manifest/schema.js +1 -95
  505. package/dist/lib/manifest/schema.js.map +1 -1
  506. package/dist/lib/offline-recipient.d.ts +5 -0
  507. package/dist/lib/offline-recipient.d.ts.map +1 -0
  508. package/dist/lib/offline-recipient.js +7 -0
  509. package/dist/lib/offline-recipient.js.map +1 -0
  510. package/dist/lib/onboard.js +3 -3
  511. package/dist/lib/onboard.js.map +1 -1
  512. package/dist/lib/persona-files.d.ts +29 -0
  513. package/dist/lib/persona-files.d.ts.map +1 -0
  514. package/dist/lib/persona-files.js +154 -0
  515. package/dist/lib/persona-files.js.map +1 -0
  516. package/dist/lib/personas.d.ts +3 -0
  517. package/dist/lib/personas.d.ts.map +1 -1
  518. package/dist/lib/personas.js +14 -2
  519. package/dist/lib/personas.js.map +1 -1
  520. package/dist/lib/prompts.d.ts +16 -0
  521. package/dist/lib/prompts.d.ts.map +1 -0
  522. package/dist/lib/prompts.js +35 -0
  523. package/dist/lib/prompts.js.map +1 -0
  524. package/dist/lib/protected-records.d.ts +2 -0
  525. package/dist/lib/protected-records.d.ts.map +1 -0
  526. package/dist/lib/protected-records.js +3 -0
  527. package/dist/lib/protected-records.js.map +1 -0
  528. package/dist/lib/registry-errors.d.ts +4 -0
  529. package/dist/lib/registry-errors.d.ts.map +1 -0
  530. package/dist/lib/registry-errors.js +6 -0
  531. package/dist/lib/registry-errors.js.map +1 -0
  532. package/dist/lib/reset-space-plan.d.ts +36 -0
  533. package/dist/lib/reset-space-plan.d.ts.map +1 -0
  534. package/dist/lib/reset-space-plan.js +181 -0
  535. package/dist/lib/reset-space-plan.js.map +1 -0
  536. package/dist/lib/restore.d.ts +3 -1
  537. package/dist/lib/restore.d.ts.map +1 -1
  538. package/dist/lib/restore.js +38 -10
  539. package/dist/lib/restore.js.map +1 -1
  540. package/dist/lib/seat-resume.d.ts +4 -1
  541. package/dist/lib/seat-resume.d.ts.map +1 -1
  542. package/dist/lib/seat-resume.js +7 -4
  543. package/dist/lib/seat-resume.js.map +1 -1
  544. package/dist/lib/service-adapters.d.ts +32 -0
  545. package/dist/lib/service-adapters.d.ts.map +1 -0
  546. package/dist/lib/service-adapters.js +55 -0
  547. package/dist/lib/service-adapters.js.map +1 -0
  548. package/dist/lib/service-census.d.ts +73 -0
  549. package/dist/lib/service-census.d.ts.map +1 -0
  550. package/dist/lib/service-census.js +42 -0
  551. package/dist/lib/service-census.js.map +1 -0
  552. package/dist/lib/service-definitions.d.ts +49 -0
  553. package/dist/lib/service-definitions.d.ts.map +1 -0
  554. package/dist/lib/service-definitions.js +61 -0
  555. package/dist/lib/service-definitions.js.map +1 -0
  556. package/dist/lib/service-install-intent.d.ts +48 -0
  557. package/dist/lib/service-install-intent.d.ts.map +1 -0
  558. package/dist/lib/service-install-intent.js +95 -0
  559. package/dist/lib/service-install-intent.js.map +1 -0
  560. package/dist/lib/service-instances.d.ts +143 -0
  561. package/dist/lib/service-instances.d.ts.map +1 -0
  562. package/dist/lib/service-instances.js +193 -0
  563. package/dist/lib/service-instances.js.map +1 -0
  564. package/dist/lib/service-journal.d.ts +38 -0
  565. package/dist/lib/service-journal.d.ts.map +1 -0
  566. package/dist/lib/service-journal.js +210 -0
  567. package/dist/lib/service-journal.js.map +1 -0
  568. package/dist/lib/service-launchd-plan.d.ts +21 -0
  569. package/dist/lib/service-launchd-plan.d.ts.map +1 -0
  570. package/dist/lib/service-launchd-plan.js +69 -0
  571. package/dist/lib/service-launchd-plan.js.map +1 -0
  572. package/dist/lib/service-launchd-unit.d.ts +20 -0
  573. package/dist/lib/service-launchd-unit.d.ts.map +1 -0
  574. package/dist/lib/service-launchd-unit.js +66 -0
  575. package/dist/lib/service-launchd-unit.js.map +1 -0
  576. package/dist/lib/service-presets.d.ts +17 -0
  577. package/dist/lib/service-presets.d.ts.map +1 -0
  578. package/dist/lib/service-presets.js +138 -0
  579. package/dist/lib/service-presets.js.map +1 -0
  580. package/dist/lib/service-private-seed.d.ts +7 -0
  581. package/dist/lib/service-private-seed.d.ts.map +1 -0
  582. package/dist/lib/service-private-seed.js +64 -0
  583. package/dist/lib/service-private-seed.js.map +1 -0
  584. package/dist/lib/service-private-tree.d.ts +6 -0
  585. package/dist/lib/service-private-tree.d.ts.map +1 -0
  586. package/dist/lib/service-private-tree.js +100 -0
  587. package/dist/lib/service-private-tree.js.map +1 -0
  588. package/dist/lib/service-process.d.ts +121 -0
  589. package/dist/lib/service-process.d.ts.map +1 -0
  590. package/dist/lib/service-process.js +742 -0
  591. package/dist/lib/service-process.js.map +1 -0
  592. package/dist/lib/service-stopped-allocation.d.ts +6 -0
  593. package/dist/lib/service-stopped-allocation.d.ts.map +1 -0
  594. package/dist/lib/service-stopped-allocation.js +42 -0
  595. package/dist/lib/service-stopped-allocation.js.map +1 -0
  596. package/dist/lib/service-supervision.d.ts +59 -0
  597. package/dist/lib/service-supervision.d.ts.map +1 -0
  598. package/dist/lib/service-supervision.js +71 -0
  599. package/dist/lib/service-supervision.js.map +1 -0
  600. package/dist/lib/service-systemd-attempt-read.d.ts +40 -0
  601. package/dist/lib/service-systemd-attempt-read.d.ts.map +1 -0
  602. package/dist/lib/service-systemd-attempt-read.js +80 -0
  603. package/dist/lib/service-systemd-attempt-read.js.map +1 -0
  604. package/dist/lib/service-systemd-control.d.ts +38 -0
  605. package/dist/lib/service-systemd-control.d.ts.map +1 -0
  606. package/dist/lib/service-systemd-control.js +141 -0
  607. package/dist/lib/service-systemd-control.js.map +1 -0
  608. package/dist/lib/service-systemd-files.d.ts +8 -0
  609. package/dist/lib/service-systemd-files.d.ts.map +1 -0
  610. package/dist/lib/service-systemd-files.js +63 -0
  611. package/dist/lib/service-systemd-files.js.map +1 -0
  612. package/dist/lib/service-systemd-install.d.ts +17 -0
  613. package/dist/lib/service-systemd-install.d.ts.map +1 -0
  614. package/dist/lib/service-systemd-install.js +146 -0
  615. package/dist/lib/service-systemd-install.js.map +1 -0
  616. package/dist/lib/service-systemd-plan.d.ts +28 -0
  617. package/dist/lib/service-systemd-plan.d.ts.map +1 -0
  618. package/dist/lib/service-systemd-plan.js +56 -0
  619. package/dist/lib/service-systemd-plan.js.map +1 -0
  620. package/dist/lib/service-systemd-reseed.d.ts +16 -0
  621. package/dist/lib/service-systemd-reseed.d.ts.map +1 -0
  622. package/dist/lib/service-systemd-reseed.js +106 -0
  623. package/dist/lib/service-systemd-reseed.js.map +1 -0
  624. package/dist/lib/service-systemd-uninstall-plan.d.ts +29 -0
  625. package/dist/lib/service-systemd-uninstall-plan.d.ts.map +1 -0
  626. package/dist/lib/service-systemd-uninstall-plan.js +56 -0
  627. package/dist/lib/service-systemd-uninstall-plan.js.map +1 -0
  628. package/dist/lib/service-systemd-uninstall.d.ts +17 -0
  629. package/dist/lib/service-systemd-uninstall.d.ts.map +1 -0
  630. package/dist/lib/service-systemd-uninstall.js +106 -0
  631. package/dist/lib/service-systemd-uninstall.js.map +1 -0
  632. package/dist/lib/service-systemd-unit.d.ts +28 -0
  633. package/dist/lib/service-systemd-unit.d.ts.map +1 -0
  634. package/dist/lib/service-systemd-unit.js +73 -0
  635. package/dist/lib/service-systemd-unit.js.map +1 -0
  636. package/dist/lib/service-systemd.d.ts +49 -0
  637. package/dist/lib/service-systemd.d.ts.map +1 -0
  638. package/dist/lib/service-systemd.js +134 -0
  639. package/dist/lib/service-systemd.js.map +1 -0
  640. package/dist/lib/service-uninstall-intent.d.ts +38 -0
  641. package/dist/lib/service-uninstall-intent.d.ts.map +1 -0
  642. package/dist/lib/service-uninstall-intent.js +74 -0
  643. package/dist/lib/service-uninstall-intent.js.map +1 -0
  644. package/dist/lib/service-unit-action.d.ts +24 -0
  645. package/dist/lib/service-unit-action.d.ts.map +1 -0
  646. package/dist/lib/service-unit-action.js +61 -0
  647. package/dist/lib/service-unit-action.js.map +1 -0
  648. package/dist/lib/setup-log.d.ts +5 -4
  649. package/dist/lib/setup-log.d.ts.map +1 -1
  650. package/dist/lib/setup-log.js +18 -9
  651. package/dist/lib/setup-log.js.map +1 -1
  652. package/dist/lib/space-schema-inspection.d.ts +73 -0
  653. package/dist/lib/space-schema-inspection.d.ts.map +1 -0
  654. package/dist/lib/space-schema-inspection.js +118 -0
  655. package/dist/lib/space-schema-inspection.js.map +1 -0
  656. package/dist/lib/space-schema-report.d.ts +82 -0
  657. package/dist/lib/space-schema-report.d.ts.map +1 -0
  658. package/dist/lib/space-schema-report.js +109 -0
  659. package/dist/lib/space-schema-report.js.map +1 -0
  660. package/dist/lib/spawn-defaults.d.ts +14 -0
  661. package/dist/lib/spawn-defaults.d.ts.map +1 -0
  662. package/dist/lib/spawn-defaults.js +20 -0
  663. package/dist/lib/spawn-defaults.js.map +1 -0
  664. package/dist/lib/stack-journal.d.ts +92 -0
  665. package/dist/lib/stack-journal.d.ts.map +1 -0
  666. package/dist/lib/stack-journal.js +199 -0
  667. package/dist/lib/stack-journal.js.map +1 -0
  668. package/dist/lib/stack-resume.d.ts +35 -0
  669. package/dist/lib/stack-resume.d.ts.map +1 -0
  670. package/dist/lib/stack-resume.js +123 -0
  671. package/dist/lib/stack-resume.js.map +1 -0
  672. package/dist/lib/status.d.ts +19 -20
  673. package/dist/lib/status.d.ts.map +1 -1
  674. package/dist/lib/status.js +41 -40
  675. package/dist/lib/status.js.map +1 -1
  676. package/dist/lib/steps.d.ts.map +1 -1
  677. package/dist/lib/steps.js +3 -2
  678. package/dist/lib/steps.js.map +1 -1
  679. package/dist/lib/systemd-supervision.d.ts +11 -4
  680. package/dist/lib/systemd-supervision.d.ts.map +1 -1
  681. package/dist/lib/systemd-supervision.js +19 -8
  682. package/dist/lib/systemd-supervision.js.map +1 -1
  683. package/dist/lib/team-additive-attempt.d.ts +286 -0
  684. package/dist/lib/team-additive-attempt.d.ts.map +1 -0
  685. package/dist/lib/team-additive-attempt.js +387 -0
  686. package/dist/lib/team-additive-attempt.js.map +1 -0
  687. package/dist/lib/team-additive-native.d.ts +17 -0
  688. package/dist/lib/team-additive-native.d.ts.map +1 -0
  689. package/dist/lib/team-additive-native.js +29 -0
  690. package/dist/lib/team-additive-native.js.map +1 -0
  691. package/dist/lib/team-agent-removal.d.ts +104 -0
  692. package/dist/lib/team-agent-removal.d.ts.map +1 -0
  693. package/dist/lib/team-agent-removal.js +121 -0
  694. package/dist/lib/team-agent-removal.js.map +1 -0
  695. package/dist/lib/team-channel-removal.d.ts +220 -0
  696. package/dist/lib/team-channel-removal.d.ts.map +1 -0
  697. package/dist/lib/team-channel-removal.js +258 -0
  698. package/dist/lib/team-channel-removal.js.map +1 -0
  699. package/dist/lib/team-deploy-inspection.d.ts +59 -0
  700. package/dist/lib/team-deploy-inspection.d.ts.map +1 -0
  701. package/dist/lib/team-deploy-inspection.js +177 -0
  702. package/dist/lib/team-deploy-inspection.js.map +1 -0
  703. package/dist/lib/team-fresh.d.ts +73 -0
  704. package/dist/lib/team-fresh.d.ts.map +1 -0
  705. package/dist/lib/team-fresh.js +207 -0
  706. package/dist/lib/team-fresh.js.map +1 -0
  707. package/dist/lib/team-removal-reconcile.d.ts +118 -0
  708. package/dist/lib/team-removal-reconcile.d.ts.map +1 -0
  709. package/dist/lib/team-removal-reconcile.js +90 -0
  710. package/dist/lib/team-removal-reconcile.js.map +1 -0
  711. package/dist/lib/team-removal-record.d.ts +7 -0
  712. package/dist/lib/team-removal-record.d.ts.map +1 -0
  713. package/dist/lib/team-removal-record.js +46 -0
  714. package/dist/lib/team-removal-record.js.map +1 -0
  715. package/dist/lib/team-retained.d.ts +33 -0
  716. package/dist/lib/team-retained.d.ts.map +1 -0
  717. package/dist/lib/team-retained.js +55 -0
  718. package/dist/lib/team-retained.js.map +1 -0
  719. package/dist/lib/theme.d.ts.map +1 -1
  720. package/dist/lib/theme.js +9 -8
  721. package/dist/lib/theme.js.map +1 -1
  722. package/dist/lib/transient.d.ts +14 -9
  723. package/dist/lib/transient.d.ts.map +1 -1
  724. package/dist/lib/transient.js +25 -18
  725. package/dist/lib/transient.js.map +1 -1
  726. package/dist/lib/up-report.d.ts +1 -0
  727. package/dist/lib/up-report.d.ts.map +1 -1
  728. package/dist/lib/up-report.js +2 -1
  729. package/dist/lib/up-report.js.map +1 -1
  730. package/dist/lib/version.d.ts +8 -2
  731. package/dist/lib/version.d.ts.map +1 -1
  732. package/dist/lib/version.js +16 -9
  733. package/dist/lib/version.js.map +1 -1
  734. package/dist/seed/paths.d.ts +1 -1
  735. package/dist/seed/paths.js +1 -1
  736. package/dist/seed/reconcile.d.ts.map +1 -1
  737. package/dist/seed/reconcile.js +19 -3
  738. package/dist/seed/reconcile.js.map +1 -1
  739. package/dist/ui.d.ts +6 -0
  740. package/dist/ui.d.ts.map +1 -1
  741. package/dist/ui.js +12 -1
  742. package/dist/ui.js.map +1 -1
  743. package/dist/watch-data.d.ts +15 -0
  744. package/dist/watch-data.d.ts.map +1 -0
  745. package/dist/watch-data.js +66 -0
  746. package/dist/watch-data.js.map +1 -0
  747. package/dist/watch-json.d.ts +5 -0
  748. package/dist/watch-json.d.ts.map +1 -0
  749. package/dist/watch-json.js +131 -0
  750. package/dist/watch-json.js.map +1 -0
  751. package/dist/watch-view.d.ts +8 -0
  752. package/dist/watch-view.d.ts.map +1 -0
  753. package/dist/watch-view.js +65 -0
  754. package/dist/watch-view.js.map +1 -0
  755. package/package.json +8 -5
  756. package/dist/commands/service.d.ts +0 -17
  757. package/dist/commands/service.d.ts.map +0 -1
  758. package/dist/commands/service.js +0 -589
  759. 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";
4
+ import { homedir, hostname } from "node:os";
5
+ import { mkdirSync, readFileSync, existsSync, openSync, fstatSync, statSync, readSync, closeSync, lstatSync, realpathSync, readdirSync, } from "node:fs";
6
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";
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,55 @@ 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 { 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
49
  import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, 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
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the guarded restore returned without its activation result; the journal records its state and no step was repeated", { remedy: "inspect the root's maintenance journal; a stale attempt is recovered by `cotal backup recover <attempt-id>`" });
59
+ return returned;
60
+ }
34
61
  const pendingOrdinaryResumes = new Map();
35
62
  /** `cotal up` flags — colocated with the command (like `spawnFlags`) so its completion can read them. */
36
63
  export const upFlags = [
37
64
  { name: "server", type: "string", value: "<url>", description: "listen URL override" },
38
65
  { name: "host", type: "string", value: "<host>", description: "bind host override (an IP/hostname, not a URL; the URL is --server)" },
39
66
  { name: "space", type: "string", value: "<s>", description: "space name (default: the folder's)" },
67
+ { name: "root", type: "string", value: "<dir>", description: "use this existing prepared local root instead of the current folder" },
40
68
  { name: "store-dir", type: "string", value: "<dir>", description: "JetStream store directory" },
41
69
  { 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
70
  { name: "channels", type: "string", value: "<path>", description: "channel-registry seed file (JSON; default .cotal/channels.json)" },
@@ -55,47 +83,263 @@ export const upFlags = [
55
83
  { 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
84
  { 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
85
  { 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`)" },
86
+ { name: "detach", type: "boolean", description: "run in the background (the default; stop with cotal down)" },
87
+ { name: "foreground", type: "boolean", description: "keep a non-manifest native stack in this terminal; -f currently refuses" },
59
88
  { 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
89
  { 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
90
  { 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
91
  { name: "file", type: "string", short: "f", value: "<cotal.yaml>", description: "launch a whole mesh from a manifest" },
63
92
  { name: "dry-run", type: "boolean", description: "with -f: print the plan, mutate nothing" },
93
+ { ...jsonFlag, description: "controller-owned stack only: one structured receipt on stdout" },
94
+ { ...plainFlag, description: "controller-owned stack only: plain line-oriented receipt" },
64
95
  ];
65
96
  /** Completion for `cotal up` — `--runtime <TAB>` offers `pty` + installed runtime providers (the same
66
97
  * 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. */
98
+ * official ones that aren't installed yet. Declared flags are offered only while options remain open. */
69
99
  export function upComplete(argv) {
100
+ if (metadataPositionals({ flags: upFlags }, argv, { completing: true }).optionsEnded)
101
+ return { items: [], directive: "nofiles" };
70
102
  const flag = completingFlagValue(argv, upFlags);
71
103
  if (flag?.name === "runtime")
72
104
  return { items: ["pty", ...extensionNames("runtime")].filter((v, i, a) => a.indexOf(v) === i).map((value) => ({ value })), directive: "nofiles" };
73
105
  if (flag?.name === "restore-only")
74
106
  return { items: [{ value: "registry" }], directive: "nofiles" };
75
- if (flag?.name === "restore")
107
+ if (flag && ["root", "restore", "file", "channels", "tls-cert", "tls-key", "store-dir"].includes(flag.name))
76
108
  return { items: [], directive: "default" };
109
+ if (flag)
110
+ return { items: [], directive: "nofiles" };
77
111
  const items = upFlags.map((f) => ({ value: `--${f.name}`, description: f.description }));
78
112
  return { items, directive: items.length ? "nofiles" : "default" };
79
113
  }
114
+ /** Launch intent is checked by the kernel before seed or effect preparation. A recovery
115
+ * re-entry supplies its recorded mode explicitly rather than inheriting the new public default. */
116
+ export function validateUpArguments(args) {
117
+ presentationOf(args.values);
118
+ if (args.values["user-auth"] === true && args.values.open === true)
119
+ 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" });
120
+ if (args.values.idp !== undefined && args.values["user-auth"] !== true && !args.values.file)
121
+ 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" });
122
+ if (args.values["no-manager"] === true && args.values.runtime !== undefined)
123
+ 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" });
124
+ if (args.values["no-manager"] === true && args.values["max-sessions"] !== undefined)
125
+ 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" });
126
+ if (args.values.foreground === true && args.values.detach === true)
127
+ throw new CommandFailure("refused", "USAGE_INVALID", "choose --foreground or --detach, not both");
128
+ if (args.values.file !== undefined && args.values.foreground === true)
129
+ 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");
130
+ if (args.values.foreground === true && (args.values.json === true || args.values.plain === true))
131
+ throw new CommandFailure("refused", "USAGE_INVALID", "foreground up keeps native terminal custody and cannot produce a finite JSON or plain receipt");
132
+ // Flag values and combinations are usage, so they refuse here, before any effect. The run keeps
133
+ // its own checks for maintenance re-entries, which do not pass through this validation.
134
+ parsePositiveIntegerFlag("--max-sessions", args.values["max-sessions"]);
135
+ parsePositiveIntegerFlag("--max-file-store", args.values["max-file-store"]);
136
+ const restoreOnly = args.values["restore-only"];
137
+ if (restoreOnly !== undefined && restoreOnly !== "registry")
138
+ throw new CommandFailure("refused", "USAGE_INVALID", `--restore-only takes registry (got ${JSON.stringify(restoreOnly)})`);
139
+ if (!args.values.restore && (restoreOnly !== undefined || args.values["accept-missing-source"] === true))
140
+ throw new CommandFailure("refused", "USAGE_INVALID", "--restore-only and --accept-missing-source require --restore <dir>");
141
+ if (args.values.restore && (args.values.file !== undefined || args.values.channels !== undefined))
142
+ throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --file/-f or --channels");
143
+ if (args.values.restore && args.values["rotate-sys"] === true)
144
+ 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" });
145
+ if (args.values.root !== undefined)
146
+ preparedUpRoot(String(args.values.root));
147
+ else {
148
+ const inheritedRoot = inheritedMachineHomeRoot();
149
+ if (inheritedRoot && !(args.values.file && args.values["dry-run"] === true))
150
+ 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" });
151
+ }
152
+ if (args.values.restore !== undefined)
153
+ refuseControllerCut(args.values.root !== undefined ? preparedUpRoot(String(args.values.root)) : cotalRoot(), "up --restore");
154
+ }
155
+ function inheritedMachineHomeRoot() {
156
+ const root = cotalRoot();
157
+ const machineHome = canonicalRoot(root) === canonicalRoot(homedir()) || canonicalRoot(join(root, ".cotal")) === canonicalRoot(homeCotalDir());
158
+ return machineHome && canonicalRoot(process.cwd()) !== canonicalRoot(root) ? root : undefined;
159
+ }
160
+ /** An explicit root is an existing local workspace, not a hint to find another ancestor or
161
+ * create trust in an arbitrary directory. Validation runs before the dispatcher seeds extensions. */
162
+ export function preparedUpRoot(value) {
163
+ if (!value)
164
+ throw new CommandFailure("refused", "USAGE_INVALID", "--root needs an existing prepared project directory; an empty value is not the current folder");
165
+ let root;
166
+ try {
167
+ root = realpathSync(resolve(value));
168
+ if (!statSync(root).isDirectory())
169
+ throw new Error("not a directory");
170
+ const cotal = lstatSync(join(root, ".cotal"));
171
+ if (!cotal.isDirectory() || cotal.isSymbolicLink())
172
+ throw new Error("not a private project directory");
173
+ }
174
+ catch {
175
+ 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" });
176
+ }
177
+ if (canonicalRoot(root) === canonicalRoot(homedir()) || canonicalRoot(join(root, ".cotal")) === canonicalRoot(homeCotalDir()))
178
+ 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>" });
179
+ return root;
180
+ }
181
+ /** The fresh team entry refuses retained custody before `up -f` can write a launch spec,
182
+ * regenerate trust or stop a leftover manager. Only a recorded local root is eligible. */
183
+ function assertFreshTeamBootOwnership(root, space, mode, own) {
184
+ const current = findMesh(space), prepared = findPreparedSpace(space);
185
+ if (!current && !prepared)
186
+ 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 } });
187
+ if (current && (current.origin !== "up" || canonicalRoot(current.root) !== canonicalRoot(root)) || prepared && canonicalRoot(prepared.root) !== canonicalRoot(root))
188
+ 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 } });
189
+ if (current && mode && current.mode !== mode)
190
+ 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 } });
191
+ assertSingleSpaceBroker(authDir(root), "team boot");
192
+ const accounts = listSpaceAccounts(authDir(root));
193
+ if (mode === "open" && accounts.length)
194
+ 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 } });
195
+ if (accounts.some((hosted) => hosted !== space))
196
+ throw new CommandFailure("refused", "CONFLICT", "the local broker root retains another space's account; team boot did not reassign that trust", { target: { root, space } });
197
+ const userSpaces = userAuthSpacesOnDisk(authDir(root));
198
+ if (mode === "user" && (userSpaces.some((hosted) => hosted !== space) || (accounts.includes(space) && !userSpaces.includes(space))))
199
+ 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 } });
200
+ if (mode && mode !== "user" && userSpaces.length)
201
+ 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 } });
202
+ if (localMeshesForRoot(root).some((entry) => entry.space !== space))
203
+ 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 } });
204
+ if (readMaintenanceJournal(root))
205
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "this root retains a recovery or maintenance attempt; team boot cannot substitute an ordinary startup", { target: { root, space } });
206
+ const manager = managerRecordState(undefined, undefined, space, root);
207
+ if (manager.state !== "absent")
208
+ 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" });
209
+ const processes = liveMeshProcesses(root, space);
210
+ if (processes.length)
211
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "a local component may still own this stack; team boot did not replace it", { target: { root, space, processes } });
212
+ const instances = serviceInstances(space), supervisors = serviceSupervisorStore(space).list();
213
+ if (instances.length || supervisors.length)
214
+ 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" });
215
+ const actions = serviceUnitActionStore(space).list();
216
+ if (actions.some((row) => row.name !== row.record.value.instanceId))
217
+ 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 } });
218
+ const attempts = [
219
+ ...serviceInstallIntents(space).map((row) => ({ kind: "install", instanceId: row.name, attemptId: row.record.value.attemptId })),
220
+ ...serviceUninstallIntents(space).map((row) => ({ kind: "uninstall", instanceId: row.name, attemptId: row.record.value.attemptId })),
221
+ ...actions.map((row) => ({ kind: "unit-action", instanceId: row.name, attemptId: row.record.value.attemptId })),
222
+ ];
223
+ if (attempts.length)
224
+ 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" });
225
+ let ledgers;
226
+ try {
227
+ ledgers = listLedgerFiles(root, { requireReadable: true });
228
+ }
229
+ catch {
230
+ 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 } });
231
+ }
232
+ if (ledgers.valid.length || ledgers.refused.length)
233
+ 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" });
234
+ let additiveAttempts;
235
+ try {
236
+ additiveAttempts = listAdditiveTeamAttempts(root);
237
+ }
238
+ catch {
239
+ 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 } });
240
+ }
241
+ if (retainedAdditiveTeamAttempts(additiveAttempts).length || additiveAttempts.refused.length)
242
+ 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) } });
243
+ let bootAttempts, summaries;
244
+ try {
245
+ bootAttempts = listFreshTeamAttempts(root);
246
+ summaries = listFreshTeamSummaries(root);
247
+ }
248
+ catch {
249
+ 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 } });
250
+ }
251
+ const byId = new Map(summaries.valid.map((summary) => [summary.deploymentId, summary]));
252
+ const ownAttempt = own && bootAttempts.valid.find((attempt) => attempt.deploymentId === own.deploymentId);
253
+ if (own && (!ownAttempt || ownAttempt.space !== space || ownAttempt.root !== root || ownAttempt.server !== own.server || ownAttempt.manifestPath !== own.manifestPath || ownAttempt.authMode !== mode || byId.has(own.deploymentId)))
254
+ 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 } });
255
+ const unsettled = bootAttempts.valid.filter((attempt) => attempt.deploymentId !== own?.deploymentId && !freshTeamAttemptSettled(attempt, byId.get(attempt.deploymentId)));
256
+ if (bootAttempts.refused.length || summaries.refused.length || unsettled.length)
257
+ 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" });
258
+ }
259
+ /** Foreground controller stack: the terminal holds the stack's lifetime until SIGINT or SIGTERM,
260
+ * which runs the same guarded whole-stack stop as bare `down`, acknowledged by the signal. A failed
261
+ * or unknown stop is reported with its retained members; nothing is force-killed. */
262
+ export function holdForegroundStack(root) {
263
+ return new Promise((resolveHold) => {
264
+ // A pending promise and signal listeners do not keep Node alive after its last socket closes.
265
+ const lifetime = setInterval(() => { }, 60_000);
266
+ let stopping = false;
267
+ const stop = (signal) => {
268
+ if (stopping)
269
+ return;
270
+ stopping = true;
271
+ process.off("SIGINT", interrupt);
272
+ process.off("SIGTERM", terminate);
273
+ void stackDown(root, { yes: true }).catch((error) => {
274
+ 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`);
275
+ }).finally(() => { clearInterval(lifetime); process.exitCode = signal === "SIGINT" ? 130 : 143; resolveHold(); });
276
+ };
277
+ const interrupt = () => stop("SIGINT");
278
+ const terminate = () => stop("SIGTERM");
279
+ process.on("SIGINT", interrupt);
280
+ process.on("SIGTERM", terminate);
281
+ });
282
+ }
283
+ /** The registered `up` command. When a background run is the main process of a systemd unit, it
284
+ * names that unit and the `--foreground` remedy once startup returns: controller stack, retained
285
+ * launcher, refresh and restore alike. It never changes the run's mode. Internal callers of
286
+ * {@link up} print nothing. */
287
+ export async function upCommand(args) {
288
+ await up(args);
289
+ const warning = upSystemdSupervisionWarning(args.values);
290
+ if (warning)
291
+ console.error(c.yellow(warning));
292
+ }
80
293
  /** `inheritedLock` is the root maintenance lock a recovery re-entry hands down (see the re-entry
81
294
  * 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.
295
+ export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink) {
296
+ // A re-entry owns its inherited lock even if mode validation refuses before runUp adopts it.
88
297
  let adopted = false;
89
298
  try {
90
- return await runUp(args, inheritedLock, () => { adopted = true; });
299
+ validateUpArguments(args);
300
+ const root = args.values.root === undefined ? undefined : preparedUpRoot(String(args.values.root));
301
+ const previousCwd = process.cwd();
302
+ // Path flags still mean paths relative to the invoking directory, not the selected root.
303
+ // The recursive restore/resume re-entries inherit absolute paths and the same absolute root.
304
+ 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]))])) : {};
305
+ const invocation = { ...args, values: { ...args.values, ...paths, ...(root ? { root } : {}), detach: args.values.foreground !== true } };
306
+ if (root) {
307
+ try {
308
+ process.chdir(root);
309
+ }
310
+ catch {
311
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the prepared --root became inaccessible before startup; no alternate directory was selected", { target: { root } });
312
+ }
313
+ // A root replaced with an inherited/symlinked store between validation and the effect
314
+ // must refuse. No implicit walk toward ~/.cotal is permitted for explicit targeting.
315
+ try {
316
+ const record = lstatSync(join(root, ".cotal"));
317
+ if (!record.isDirectory() || record.isSymbolicLink() || canonicalRoot(cotalRoot()) !== canonicalRoot(root))
318
+ throw new Error("changed root");
319
+ }
320
+ catch {
321
+ process.chdir(previousCwd);
322
+ throw new CommandFailure("refused", "CONFLICT", "the selected --root changed before startup; no inherited workspace was used", { target: { root } });
323
+ }
324
+ }
325
+ try {
326
+ return await runUp(invocation, inheritedLock, () => { adopted = true; }, freshTeamBoot, restoreSink);
327
+ }
328
+ finally {
329
+ if (root)
330
+ process.chdir(previousCwd);
331
+ }
91
332
  }
92
333
  finally {
93
- if (!adopted)
334
+ if (inheritedLock && !adopted)
94
335
  releaseMaintenanceLock(inheritedLock);
95
336
  }
96
337
  }
97
- async function runUp(args, inheritedLock, onAdopt) {
338
+ 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";
339
+ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restoreSink) {
98
340
  const values = args.values;
341
+ if (freshTeamBoot && (!values.file || values.restore || values.__restoreAttempt || values.__ordinaryResumeAttempt || values["rotate-sys"] || values["no-manager"]))
342
+ 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
343
  if (values.restore) {
100
344
  if (values.file || values.channels)
101
345
  throw new Error("--restore cannot be combined with --file/-f or --channels");
@@ -109,8 +353,29 @@ async function runUp(args, inheritedLock, onAdopt) {
109
353
  // A restore rewrites the shared store and the trust root under it, from an artifact that names
110
354
  // one space (see `cotal backup`) - it cannot leave the root's other tenants standing.
111
355
  assertSingleSpaceBroker(authDir(cotalRoot()), "cotal up --restore");
112
- const prepared = await prepareRestore(cotalRoot(), values);
356
+ // A `backup restore` owns stdout for its receipt, so its seat admission lines go to stderr.
357
+ const prepared = await prepareRestore(cotalRoot(), values, restoreSink ? (line) => console.error(line) : undefined);
113
358
  pendingRestores.set(prepared.attemptId, prepared);
359
+ const committed = readMaintenanceJournal(prepared.root);
360
+ if (committed && cutController(committed.cut)) {
361
+ // A controller restore continues through its recorded members. A member
362
+ // that cannot start holds the attempt at commit intent for bare `cotal up` to continue; it is
363
+ // not marked degraded, because a degraded attempt starts nothing.
364
+ const lock = acquireMaintenanceLock(prepared.root);
365
+ let foreground;
366
+ try {
367
+ foreground = await resumeControllerStack(lock, prepared.root, values, restoreSink);
368
+ }
369
+ finally {
370
+ pendingRestores.delete(prepared.attemptId);
371
+ releaseMaintenanceLock(lock);
372
+ }
373
+ if (foreground)
374
+ await holdForegroundStack(prepared.root);
375
+ return;
376
+ }
377
+ if (restoreSink)
378
+ restoreSinks.set(prepared.attemptId, restoreSink);
114
379
  const next = {
115
380
  ...values,
116
381
  restore: undefined,
@@ -129,6 +394,7 @@ async function runUp(args, inheritedLock, onAdopt) {
129
394
  }
130
395
  catch (error) {
131
396
  pendingRestores.delete(prepared.attemptId);
397
+ restoreSinks.delete(prepared.attemptId);
132
398
  // The one journal writer deliberately NOT handed a lock, and the reason is structural rather
133
399
  // than stylistic: no lock is held in this frame either way. This invocation returns just below
134
400
  // without ever reaching the `startupLock` acquire, and the re-entry that did hold one released
@@ -137,8 +403,13 @@ async function runUp(args, inheritedLock, onAdopt) {
137
403
  markPreparedRestoreDegraded(prepared.root, prepared.attemptId, error.message);
138
404
  throw error;
139
405
  }
406
+ restoreSinks.delete(prepared.attemptId);
140
407
  return;
141
408
  }
409
+ // A result sink belongs to the explicit restore entry above, never to a recovery, resume or
410
+ // ordinary start. Any other arrival with one is a caller bug, refused rather than ignored.
411
+ if (restoreSink)
412
+ throw new Error("a restore result sink requires --restore <dir>");
142
413
  if (values["restore-only"] || values["accept-missing-source"])
143
414
  throw new Error("--restore-only and --accept-missing-source require --restore <dir>");
144
415
  // MAINTENANCE RE-ENTRY. `--restore` is refused with `--rotate-sys` above, but that guard only sees
@@ -164,9 +435,35 @@ async function runUp(args, inheritedLock, onAdopt) {
164
435
  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
436
  // Raised here for the stronger reason the journal itself carries: a pending maintenance attempt
166
437
  // 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");
438
+ // manager half. The manager half is why the FLAG specifically cannot apply. A settled active
439
+ // restore of this root's own controller stack has nothing left to commit; it takes the
440
+ // controller stack route below, which applies --no-manager as an ordinary start does.
441
+ if (values["no-manager"] && readMaintenanceJournal(root) && !admittedStackRestore(root))
442
+ throw new Error(NO_MANAGER_DURING_RECOVERY);
443
+ // Refuse first-enable IdP failures and explicit pin conflicts before even recovery's lock
444
+ // creates its layout. Existing recovery keeps its own recorded startup and trust checks.
445
+ const stackSpace = values.space ?? folderSpace();
446
+ recordOperationSpace(stackSpace);
447
+ if (!readMaintenanceJournal(root) && controllerStackApplies(root, stackSpace, values)) {
448
+ const recordedStack = readStackJournal(root);
449
+ if ((recordedStack?.journal.mode ?? requestedStackMode(values)) === "user" && (!recordedStack || values.idp !== undefined)) {
450
+ const server = values.server ?? recordedStack?.journal.server ?? localMeshesForRoot(root).find((m) => m.space === stackSpace)?.server ?? (values.host ? reconcileHostAndServer(values.host, undefined) : DEFAULT_SERVER);
451
+ const transport = resolveTransport(values, undefined, root, { persist: false, quiet: true });
452
+ assertUserStackTransport(server, transport.kind === "tls-required");
453
+ await preflightUserStack(root, stackSpace, values.idp);
454
+ }
455
+ }
456
+ // A runtime with no installed provider refuses here, before the lock creates its layout and
457
+ // before any member starts. The manager member resolves the same name through the same
458
+ // installed-extension lookup when it boots, so this check and the manager cannot disagree.
459
+ if (values.runtime) {
460
+ try {
461
+ await preflightRuntime(values.runtime);
462
+ }
463
+ catch (error) {
464
+ 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" });
465
+ }
466
+ }
170
467
  const lock = acquireMaintenanceLock(root);
171
468
  let pending;
172
469
  let recoveredRestore;
@@ -186,7 +483,25 @@ async function runUp(args, inheritedLock, onAdopt) {
186
483
  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
484
  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
485
  }
189
- if (journal && (journal.state === "commit-intent" || journal.state === "manager-committed" || journal.state === "degraded")) {
486
+ const controllerCut = journal ? cutController(journal.cut) : undefined;
487
+ if (journal && controllerCut && journal.state !== "cut-intent" && journal.state !== "cut-committed" && journal.state !== "resume-retired") {
488
+ // A controller cut resumes or restores only through its recorded members. A settled active
489
+ // restore of this stack no longer fences it, as legacy bare down admits it, so it falls
490
+ // through to the controller stack route below. The lock is released before a
491
+ // foreground stack holds this terminal. `--no-manager` is rechecked here, under the lock.
492
+ if (!admittedStackRestore(root)) {
493
+ if (values["no-manager"])
494
+ throw new Error(NO_MANAGER_DURING_RECOVERY);
495
+ const foreground = await resumeControllerStack(lock, root, values);
496
+ // Released here, once, so the foreground hold below does not keep the maintenance lock.
497
+ handedOff = true;
498
+ releaseMaintenanceLock(lock);
499
+ if (foreground)
500
+ await holdForegroundStack(root);
501
+ return;
502
+ }
503
+ }
504
+ else if (journal && (journal.state === "commit-intent" || journal.state === "manager-committed" || journal.state === "degraded")) {
190
505
  recoveredRestore = rehydratePreparedRestore(root, journal);
191
506
  pendingRestores.set(recoveredRestore.attemptId, recoveredRestore);
192
507
  }
@@ -358,6 +673,7 @@ async function runUp(args, inheritedLock, onAdopt) {
358
673
  "store-dir": recoveredRestore.targetPath,
359
674
  runtime: recoveredRestore.runtime,
360
675
  detach: recoveredRestore.detached,
676
+ foreground: !recoveredRestore.detached,
361
677
  open: recoveredRestore.mode === "open",
362
678
  "user-auth": recoveredRestore.mode === "user",
363
679
  },
@@ -384,6 +700,7 @@ async function runUp(args, inheritedLock, onAdopt) {
384
700
  "max-file-store": pending.maxFileStore === undefined ? undefined : String(pending.maxFileStore),
385
701
  runtime: pending.runtime,
386
702
  detach: pending.detached,
703
+ foreground: !pending.detached,
387
704
  open: pending.mode === "open",
388
705
  "user-auth": pending.mode === "user",
389
706
  },
@@ -402,24 +719,11 @@ async function runUp(args, inheritedLock, onAdopt) {
402
719
  }
403
720
  }
404
721
  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
722
  // BROKER-ONLY MODE (#1417). `--no-manager` names what it omits, and the two manager-shaping flags
415
723
  // are refused beside it rather than silently dropped: a runtime selected or a ceiling recorded for
416
724
  // a manager that will never start is a misunderstanding, and dropping it quietly is the exact
417
725
  // silent-no-op shape this repo refuses everywhere else.
418
726
  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
727
  const publicExchange = publicExchangeArgs(values, wantUser);
424
728
  const maxSessions = parsePositiveIntegerFlag("--max-sessions", values["max-sessions"]);
425
729
  const maxFileStore = parsePositiveIntegerFlag("--max-file-store", values["max-file-store"]);
@@ -445,11 +749,13 @@ async function runUp(args, inheritedLock, onAdopt) {
445
749
  // Dry-run must not pin (mkdir is a mutation). Validation still uses whatever root is visible;
446
750
  // persistence is already suppressed below.
447
751
  if (!values["dry-run"]) {
448
- const spaceForRoot = values.space ?? resolveSpace(process.cwd());
752
+ const spaceForRoot = values.space ?? folderSpace();
449
753
  if (values.file) {
450
754
  try {
451
755
  const prepared = loadManifest(resolve(values.file));
452
- ensureRootForSpace(values.space ?? prepared.manifest.space);
756
+ // A --space that names another space is refused by the -f path below, before anything is written.
757
+ if (values.space === undefined || values.space === prepared.manifest.space)
758
+ ensureRootForSpace(prepared.manifest.space);
453
759
  }
454
760
  catch {
455
761
  // Manifest errors are reported by the -f path with the same load; do not double-print.
@@ -491,15 +797,43 @@ async function runUp(args, inheritedLock, onAdopt) {
491
797
  // (S5). Decide and validate early so every branch sees the transport; write only after a
492
798
  // matching listener is started and proved (`commitTransportPolicy`), never on a refuse path.
493
799
  // `quiet` suppresses the serving/inheriting lines until that commit (or a dry-run announce).
494
- const meshRoot = cotalRoot();
800
+ // An unprepared manifest preview reads no home policy: applying from this folder would first
801
+ // require its own project root, while dry-run must write nothing to create one.
802
+ const previewRoot = values.file && values["dry-run"] && !values.root && inheritedMachineHomeRoot() ? process.cwd() : undefined;
803
+ const meshRoot = previewRoot ?? cotalRoot();
495
804
  const transport = resolveTransport(values, undefined, meshRoot, {
496
805
  persist: false,
497
806
  quiet: true,
498
807
  });
808
+ // CONTROLLER-OWNED STACK. A root whose stack the service controller owns, or a fresh prepared
809
+ // static-auth, open or user-auth root with nothing legacy retained, starts as exact controller members instead
810
+ // of the pidfile launcher. The decision is made once here; neither route falls back to the other.
811
+ if (!values.file && controllerStackApplies(meshRoot, values.space ?? folderSpace(), values)) {
812
+ const stackSpace = values.space ?? folderSpace();
813
+ recordOperationSpace(stackSpace);
814
+ const stackServer = values.server ?? readStackJournal(meshRoot)?.journal.server ?? localMeshesForRoot(meshRoot).find((m) => m.space === stackSpace)?.server ?? (values.host ? reconcileHostAndServer(values.host, undefined) : DEFAULT_SERVER);
815
+ const stackMode = requestedStackMode(values);
816
+ const presentation = presentationOf(values);
817
+ const stackLock = acquireMaintenanceLock(meshRoot);
818
+ const native = controllerStackNative();
819
+ try {
820
+ if (values.foreground && presentation !== "json")
821
+ stackUpForegroundNotice(presentation, stackSpace);
822
+ await stackUp({ 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);
823
+ }
824
+ finally {
825
+ releaseMaintenanceLock(stackLock);
826
+ }
827
+ if (values.foreground)
828
+ await holdForegroundStack(meshRoot);
829
+ return;
830
+ }
831
+ if (values.json || values.plain)
832
+ 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
833
  // `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`.
834
+ // channels + booted agents). It owns the whole space; the additive team deploy route is separate.
501
835
  // CLI flags override the manifest (flag > manifest > default) so the same file runs at a different
502
- // port / runtime / space / auth without editing it.
836
+ // port / runtime / auth without editing it. Its space is its target: `--space` may only repeat it.
503
837
  if (values.file) {
504
838
  if (values["dry-run"]) {
505
839
  await upManifest(values.file, {
@@ -508,6 +842,7 @@ async function runUp(args, inheritedLock, onAdopt) {
508
842
  server: values.server,
509
843
  host: values.host,
510
844
  space: values.space,
845
+ root: values.root,
511
846
  runtime: values.runtime,
512
847
  open: values.open,
513
848
  userAuth: wantUser,
@@ -516,17 +851,27 @@ async function runUp(args, inheritedLock, onAdopt) {
516
851
  maxSessions,
517
852
  noManager,
518
853
  });
854
+ if (previewRoot)
855
+ 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
856
  return;
520
857
  }
521
858
  const lock = acquireMaintenanceLock(cotalRoot());
522
859
  try {
860
+ if (freshTeamBoot) {
861
+ if (!values.space)
862
+ throw new CommandFailure("refused", "USAGE_INVALID", "fresh team boot needs the manifest's exact selected space");
863
+ assertFreshTeamBootOwnership(cotalRoot(), values.space);
864
+ }
523
865
  assertOrdinaryUpAllowed(cotalRoot());
524
866
  await upManifest(values.file, {
525
867
  transport,
526
868
  dryRun: Boolean(values["dry-run"]),
869
+ freshTeamBoot,
870
+ presentation: freshTeamBoot ? presentationOf(values) : undefined,
527
871
  server: values.server,
528
872
  host: values.host,
529
873
  space: values.space,
874
+ root: values.root,
530
875
  runtime: values.runtime,
531
876
  open: values.open,
532
877
  userAuth: wantUser,
@@ -587,7 +932,7 @@ async function runUp(args, inheritedLock, onAdopt) {
587
932
  // Without --server the default URL only seeds a first boot. A first boot that found it taken ran
588
933
  // on a free port, which this root's record keeps; a re-run must start from that URL, or every
589
934
  // lookup below misses its own mesh and the space claim refuses it (#3889).
590
- const recordedSpace = values.space ?? resolveSpace(process.cwd());
935
+ const recordedSpace = values.space ?? folderSpace();
591
936
  const implicitServer = localMeshesForRoot(cotalRoot()).find((m) => m.space === recordedSpace)?.server ?? DEFAULT_SERVER;
592
937
  let server = values.server ?? implicitServer;
593
938
  const host = values.host ?? "127.0.0.1";
@@ -606,7 +951,7 @@ async function runUp(args, inheritedLock, onAdopt) {
606
951
  // here is reused as `listenerReachable` further down instead of probing twice.
607
952
  let repairProbe;
608
953
  if (!resumeAttempt) {
609
- const repairSpace = values.space ?? resolveSpace(process.cwd());
954
+ const repairSpace = values.space ?? folderSpace();
610
955
  const repairRoot = cotalRoot();
611
956
  const heldForRepair = loadMeshes().find((m) => m.origin !== "manual" && m.origin !== "catalog" && m.server === server && m.root === repairRoot && m.space === repairSpace);
612
957
  if (heldForRepair) {
@@ -669,7 +1014,7 @@ async function runUp(args, inheritedLock, onAdopt) {
669
1014
  if (resumeAttempt && listenerReachable)
670
1015
  throw new Error(`resume attempt ${resumeAttempt} refuses the unproven occupied listener at ${server}`);
671
1016
  if (listenerReachable) {
672
- const space = values.space ?? resolveSpace(process.cwd());
1017
+ const space = values.space ?? folderSpace();
673
1018
  const root = cotalRoot();
674
1019
  // A broker is already on this port. Same root means "this project is already up" unless the
675
1020
  // operator explicitly asked for a second space in the same `.cotal/` root (unsupported today: pid,
@@ -743,12 +1088,14 @@ async function runUp(args, inheritedLock, onAdopt) {
743
1088
  // `--no-manager` on a refresh whose manager is LIVE is the same class of refusal: this branch
744
1089
  // starts nothing, so the flag cannot apply, and silently keeping the manager would answer a
745
1090
  // 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.
1091
+ // was never asked to touch. Same shape as `--runtime`/`--max-sessions` above: refuse and name the
1092
+ // remedy. This launcher's stack has no manager-only stop, so the remedy is the whole-stack stop
1093
+ // and a broker-only start. A refresh of a mesh whose manager is NOT live simply proceeds
1094
+ // broker-only.
748
1095
  if (noManager) {
749
1096
  const live = managerRecordState(undefined, undefined, held.space);
750
1097
  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\``));
1098
+ 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
1099
  process.exit(1);
753
1100
  }
754
1101
  }
@@ -885,6 +1232,7 @@ async function runUp(args, inheritedLock, onAdopt) {
885
1232
  // `recordOurMesh` carries everything else (`tlsRequired`, the recorded host and session
886
1233
  // ceiling, the store) from the record as it stands at write time, not from `held`.
887
1234
  recordOurMesh({ space: held.space, server, root, mode: held.mode, ...(userAuth ? { userAuth } : {}), ...(values.host ? { attachHost: values.host } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ts: new Date().toISOString() }, "refresh");
1235
+ seedPersonaAfterUp(root);
888
1236
  return;
889
1237
  }
890
1238
  const who = held ? `mesh "${held.space}" (${held.root})` : "a broker not started here";
@@ -923,6 +1271,8 @@ async function runUp(args, inheritedLock, onAdopt) {
923
1271
  verify: async () => { await verifySpawnedOrdinaryListener(ordinaryAttempt); },
924
1272
  } : undefined;
925
1273
  if (values.detach) {
1274
+ // A `backup restore` owns its own receipt: the native launcher's progress lines stay off stdout.
1275
+ const quietRestore = restored !== undefined && restoreSinks.has(restored.attemptId);
926
1276
  const { pid, source, authService, controlPlane, delivery, manager } = await startMeshDetached({
927
1277
  transport,
928
1278
  server,
@@ -942,15 +1292,15 @@ async function runUp(args, inheritedLock, onAdopt) {
942
1292
  maxSessions,
943
1293
  noManager,
944
1294
  resumeAttempt,
945
- resumeCommitToken: restored?.managerCommit?.durableCommitToken ?? ordinaryAttempt?.managerCommit?.durableCommitToken,
1295
+ resumeCommit: commitTokenHandoff(cotalRoot(), (restored?.managerCommit ?? ordinaryAttempt?.managerCommit) !== undefined, startupLock),
946
1296
  boundListener,
1297
+ ...(quietRestore ? { quietBoot: true } : {}),
947
1298
  });
948
1299
  // 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));
1300
+ if (!quietRestore) {
1301
+ console.log(c.dim(`Started nats-server (${source}).`));
1302
+ console.log(c.green(renderDetachedSummary({ pid, delivery, authService: wantUser && authService, manager, ...(values.root ? { root: cotalRoot() } : {}) })));
1303
+ }
954
1304
  if (restored && process.env.COTAL_SMOKE_FAIL_AFTER_RESTORE_LISTENER_READY === "1")
955
1305
  throw new Error("smoke-injected failure after restore listener readiness");
956
1306
  // A user mesh whose auth service never became ready, or a mesh whose control plane is degraded,
@@ -959,10 +1309,16 @@ async function runUp(args, inheritedLock, onAdopt) {
959
1309
  if (!authService || !controlPlane)
960
1310
  process.exitCode = 1;
961
1311
  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);
1312
+ if (restored)
1313
+ restoreSinks.get(restored.attemptId)?.({
1314
+ attemptId: restored.attemptId, space: restored.space, root: restored.root, server: restored.server, mode: restored.mode,
1315
+ selection: restored.selection, targetPath: restored.targetPath, runtime: restored.runtime, brokerPid: pid,
1316
+ delivery, authService, controlPlane, manager,
1317
+ });
962
1318
  return;
963
1319
  }
964
1320
  const useAuth = !values.open;
965
- const space = values.space ?? resolveSpace(process.cwd());
1321
+ const space = values.space ?? folderSpace();
966
1322
  ensureRootForSpace(space); // may pin the cwd as this space's root — before any cotalPath use
967
1323
  refuseOpenOverUserState(Boolean(values.open), space);
968
1324
  const storeDir = values["store-dir"] ? resolve(values["store-dir"]) : cotalPath("nats");
@@ -975,7 +1331,9 @@ async function runUp(args, inheritedLock, onAdopt) {
975
1331
  if (!sameStoreIdentity(readStoreIdentity(storeDir), resumeJournal.source))
976
1332
  throw new Error(`resume store ${storeDir} no longer matches the preserved source identity; refusing to open JetStream over it`);
977
1333
  }
978
- mkdirSync(storeDir, { recursive: true });
1334
+ // Owner-private regardless of umask: a recursive create also makes a missing `.cotal`, which every
1335
+ // later protection check walks as an ancestor.
1336
+ mkdirSync(storeDir, { recursive: true, mode: 0o700 });
979
1337
  await claimSpace(space, server, cotalRoot());
980
1338
  const seedFile = loadChannelsFile(values.channels);
981
1339
  // Decided above the branch; the dial host is only settled here (a port collision may have moved
@@ -996,7 +1354,10 @@ async function runUp(args, inheritedLock, onAdopt) {
996
1354
  console.log(c.dim(`Starting nats-server (JetStream, ${useAuth ? "JWT auth" : "OPEN/no-auth"}, ${source}) - store: ${storeDir}, bind: ${host}`));
997
1355
  console.log(c.dim("Press Ctrl-C to stop.\n"));
998
1356
  const listenerStartedAt = new Date().toISOString();
999
- const child = spawn(bin, natsArgs, { stdio: "inherit" });
1357
+ // A terminal sends Ctrl-C to the whole foreground process group. Keep the broker outside it
1358
+ // on POSIX so only this owner receives the interrupt and can finish manager-first teardown
1359
+ // before signalling the broker. Keep the child referenced and its output in this terminal.
1360
+ const child = spawn(bin, natsArgs, { stdio: "inherit", detached: process.platform !== "win32" });
1000
1361
  let activationFinished = !resumeAttempt;
1001
1362
  await recordSpawnedListener(child, listenerStartedAt, boundListener);
1002
1363
  releaseStartupLock();
@@ -1017,8 +1378,8 @@ async function runUp(args, inheritedLock, onAdopt) {
1017
1378
  // the refusal is printed with the reap route and the latch is released, so the stack keeps running
1018
1379
  // in the foreground; the operator ends it with `cotal down --with-agents` from another terminal,
1019
1380
  // 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 —
1381
+ // stopDelivery and stopAuthService are the stops bare `cotal down` performs for those daemons
1382
+ // (reservation, SIGKILL escalation); the rest of the teardown must run even if one fails —
1022
1383
  // the failure is logged, never swallowed silently. Teardown is AWAITED before the broker is
1023
1384
  // signalled, so it never races a broker that is already going away.
1024
1385
  let stopping = false;
@@ -1102,7 +1463,7 @@ async function runUp(args, inheritedLock, onAdopt) {
1102
1463
  // it cannot reach the broker, and a starved host makes a running broker look unreachable, so it can
1103
1464
  // end while this broker serves on. Nothing else brings it back, and every static retirement then
1104
1465
  // 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
1466
+ // clean exit or SIGTERM/SIGINT is a deliberate stop (`cotal down`) and stays stopped, and so
1106
1467
  // is the SIGKILL `down` escalates to when a starved daemon outlives its grace, also when either ends a
1107
1468
  // replacement this loop is still waiting on: that attempt then fails, and retrying it would undo the
1108
1469
  // stop. A failed attempt waits out the lease TTL, the longest a dead holder's lease blocks its
@@ -1155,7 +1516,7 @@ async function runUp(args, inheritedLock, onAdopt) {
1155
1516
  maxFileStore,
1156
1517
  publicExchange,
1157
1518
  resumeAttempt,
1158
- resumeCommitToken: restored?.managerCommit?.durableCommitToken ?? ordinaryAttempt?.managerCommit?.durableCommitToken,
1519
+ resumeCommit: commitTokenHandoff(cotalRoot(), (restored?.managerCommit ?? ordinaryAttempt?.managerCommit) !== undefined, startupLock),
1159
1520
  runtime: values.runtime,
1160
1521
  noManager,
1161
1522
  onDeliveryExit,
@@ -1433,6 +1794,163 @@ function provePreparedRestoreListener(prepared) {
1433
1794
  return journal.restore.target;
1434
1795
  }, { path: prepared.targetPath, changed: "target identity changed" });
1435
1796
  }
1797
+ /** Bare `up`, `up --restore` and `backup restore` on a controller cut: at
1798
+ * `ready`, eligibility and the resume intent; before manager commitment, each member started or
1799
+ * adopted by the journal's own start rows, the broker's listener proof bound to its started
1800
+ * instance, then the manager; after commitment, only the manager relaunched once its exit is
1801
+ * receipted; then the shared same-principal activation. A re-entry continues the recorded attempt;
1802
+ * nothing here launches the legacy pidfile stack. A degraded attempt starts nothing and holds on any
1803
+ * member that is not live. Returns whether the caller should hold the stack's lifetime in the
1804
+ * foreground, which it does after releasing the lock. */
1805
+ async function resumeControllerStack(lock, root, values, restoreSink) {
1806
+ let journal = readMaintenanceJournal(root);
1807
+ const cut = cutController(journal.cut);
1808
+ const space = journal.space;
1809
+ const inventory = readMaintenanceResumeDocument(root, journal.resume).inventory;
1810
+ const agents = inventory.agents ?? [];
1811
+ // A restore's inputs were checked and journaled by `prepareRestore`; a resume takes them from the cut.
1812
+ if (!("restore" in journal)) {
1813
+ if (values.server !== undefined && values.server !== journal.cut.launch.server)
1814
+ throw new CommandFailure("refused", "USAGE_INVALID", "a controller resume takes its broker address from the cut; --server is refused", { target: { root, space } });
1815
+ if (values["store-dir"] !== undefined || values["max-file-store"] !== undefined)
1816
+ 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 } });
1817
+ const runtimes = [...new Set(agents.map((agent) => agent.launch?.runtime).filter((value) => typeof value === "string"))];
1818
+ if (runtimes.length > 1 || (values.runtime !== undefined && runtimes[0] !== undefined && values.runtime !== runtimes[0]))
1819
+ throw new CommandFailure("refused", "USAGE_INVALID", "--runtime must equal the preserved inventory's runtime; a controller resume does not change it", { target: { root, space } });
1820
+ if (journal.state === "ready") {
1821
+ const stops = journal.cutCompletion.controllerStops ?? [];
1822
+ assertControllerCoupling(root, cut, journal.cut.launch.server, journal.source.path);
1823
+ assertStoreIdentity(journal.source);
1824
+ assertControllerResumeEligible(space, cut, stops, cut.brokerDefinitionRevision);
1825
+ const attemptId = `resume-${randomUUID()}`;
1826
+ const staleConsent = admitAndRestoreSeatCheckpoints(root, space, journal.cut.attemptId, values, inventory);
1827
+ const serverNonce = randomUUID().replaceAll("-", "");
1828
+ beginControllerResume(lock, attemptId, {
1829
+ server: journal.cut.launch.server, storeDir: journal.source.path,
1830
+ ...(typeof journal.cut.launch.maxFileStore === "number" ? { maxFileStore: journal.cut.launch.maxFileStore } : {}),
1831
+ runtime: runtimes[0] ?? "pty", detached: !values.foreground, serverName: `${attemptId}-${serverNonce}`, serverNonce,
1832
+ ...(staleConsent.length ? { acceptedStaleCheckpoints: staleConsent.map((seat) => ({ ...seat })) } : {}),
1833
+ });
1834
+ journal = readMaintenanceJournal(root);
1835
+ }
1836
+ }
1837
+ const attempt = currentControllerAttempt(root);
1838
+ const { attemptId } = attempt;
1839
+ assertControllerCoupling(root, cut, journal.cut.launch.server, journal.source.path, { stackOperationId: attempt.stackOperationId, attemptId });
1840
+ const restoring = "restore" in journal;
1841
+ const launch = ("ordinaryResume" in journal ? journal.ordinaryResume.launch : journal.launch);
1842
+ try {
1843
+ if (journal.state === "resume-intent" || journal.state === "commit-intent") {
1844
+ await startControllerMembers(lock, root, space, launch.serverName);
1845
+ const brokerInfo = await readNatsInfo(launch.server);
1846
+ if (brokerInfo.server_name !== launch.serverName)
1847
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the resumed broker reports another server name than this attempt recorded; nothing further was started", { target: { root, space } });
1848
+ bindControllerBroker(lock, root, space, launch);
1849
+ await startControllerMember(lock, root, space, "manager", managerResumeAttempt(root));
1850
+ }
1851
+ else if (journal.state === "resume-committed" || journal.state === "manager-committed") {
1852
+ assertControllerMembersLive(root, space, "manager");
1853
+ await relaunchCommittedManager(lock, root, space);
1854
+ }
1855
+ else if (journal.state !== "active") {
1856
+ assertControllerMembersLive(root, space);
1857
+ }
1858
+ }
1859
+ catch (error) {
1860
+ settleControllerResume(root, isCommandFailure(error) && error.outcome === "refused" ? "refused" : "unknown");
1861
+ throw error;
1862
+ }
1863
+ // Read before activation: a new broker instance replaces the cut's retired record, which is
1864
+ // removed once the attempt is active.
1865
+ const broker = controllerAttemptBrokerInstance(root, space);
1866
+ const stops = journal.cutCompletion.controllerStops ?? [];
1867
+ const retireBroker = attempt.brokerRequired ? () => removeRetiredBrokerInstance(space, cut, stops) : undefined;
1868
+ journal = readMaintenanceJournal(root);
1869
+ let targetPath = journal.source.path;
1870
+ try {
1871
+ if (restoring) {
1872
+ const record = journal;
1873
+ const prepared = pendingRestores.get(attemptId) ?? rehydratePreparedRestore(root, record);
1874
+ if (record.listenerProof)
1875
+ prepared.listenerProof = record.listenerProof;
1876
+ pendingRestores.set(attemptId, prepared);
1877
+ targetPath = record.restore.target.path;
1878
+ if (record.state === "active") {
1879
+ pendingRestores.delete(attemptId);
1880
+ retireActiveRestoreBroker(root, attemptId, retireBroker, lock);
1881
+ }
1882
+ else {
1883
+ await completeResumeActivation(attemptId, true, "controller stack restored", launch.server, lock, retireBroker);
1884
+ }
1885
+ }
1886
+ else {
1887
+ pendingOrdinaryResumes.set(attemptId, {
1888
+ root, attemptId, space, mode: journal.mode, server: launch.server, storeDir: journal.source.path,
1889
+ ...(launch.maxFileStore !== undefined ? { maxFileStore: launch.maxFileStore } : {}),
1890
+ runtime: launch.runtime, detached: launch.detached, inventory,
1891
+ journalState: journal.state,
1892
+ ...(journal.state === "resume-committed" ? { managerCommit: journal.managerCommit } : {}),
1893
+ serverName: launch.serverName, serverNonce: launch.serverNonce,
1894
+ });
1895
+ await completeResumeActivation(attemptId, true, "controller stack resumed", launch.server, lock, retireBroker);
1896
+ }
1897
+ }
1898
+ catch (error) {
1899
+ settleControllerResume(root, "unknown");
1900
+ throw error;
1901
+ }
1902
+ settleControllerResume(root, "completed", { ...(attempt.brokerRequired ? { brokerInstanceId: broker.instanceId } : {}), ...(restoring ? { storeDir: targetPath } : {}) });
1903
+ if (restoring) {
1904
+ const restored = readMaintenanceJournal(root);
1905
+ const has = (role) => cut.members.some((member) => member.role === role);
1906
+ const result = {
1907
+ attemptId, space, root, server: launch.server, mode: restored.mode, selection: restored.launch.restoreOnly === "registry" ? "registry" : "full",
1908
+ targetPath, runtime: launch.runtime, brokerPid: broker.pid, delivery: has("delivery"), authService: has("auth"), controlPlane: true, manager: true,
1909
+ };
1910
+ if (restoreSink)
1911
+ restoreSink(result);
1912
+ else
1913
+ 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: [
1914
+ { kind: "fields", rows: [["Space", row.space], ["Root", row.root], ["Broker", row.server], ["Attempt", row.attemptId], ["Store", row.targetPath], ["Selection", row.selection]] },
1915
+ { 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."] },
1916
+ ] }] }));
1917
+ return values.foreground === true && !restoreSink;
1918
+ }
1919
+ 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: [
1920
+ { kind: "fields", rows: [["Space", row.space], ["Root", row.root], ["Broker", row.server], ["Attempt", row.attemptId], ["Retained agents", row.seatResume]] },
1921
+ { 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."] },
1922
+ ] }] }));
1923
+ return values.foreground === true;
1924
+ }
1925
+ /** An active controller restore whose attempt started a new broker removes the cut's retired record
1926
+ * here; a mismatch degrades the restore with its reason and removes nothing. */
1927
+ function retireActiveRestoreBroker(root, attemptId, retireBroker, heldLock) {
1928
+ if (!retireBroker)
1929
+ return;
1930
+ try {
1931
+ retireBroker();
1932
+ }
1933
+ catch (error) {
1934
+ markPreparedRestoreDegraded(root, attemptId, error instanceof Error ? error.message : String(error), heldLock);
1935
+ throw error;
1936
+ }
1937
+ }
1938
+ /** Hand a manager-committed attempt's commit token to the next manager as a protected file. The
1939
+ * token is read from the journal under the maintenance lock and never travels on argv. An attempt
1940
+ * with no manager commit has nothing to hand off. */
1941
+ function commitTokenHandoff(root, committed, heldLock) {
1942
+ if (!committed)
1943
+ return undefined;
1944
+ const lock = heldLock ?? acquireMaintenanceLock(root);
1945
+ try {
1946
+ sweepTokenHandoff(lock);
1947
+ return writeTokenHandoff(lock);
1948
+ }
1949
+ finally {
1950
+ if (!heldLock)
1951
+ releaseMaintenanceLock(lock);
1952
+ }
1953
+ }
1436
1954
  function bindSpawnedOrdinaryResumeListener(pending, pid, startedAt, heldLock) {
1437
1955
  if (!Number.isInteger(pid) || pid <= 0)
1438
1956
  throw new Error("resume listener spawn returned no pid");
@@ -1499,7 +2017,7 @@ async function resumeProvenOrdinaryListener(pending, heldLock) {
1499
2017
  attachHost: adoptAttachHost,
1500
2018
  maxSessions: adoptMaxSessions,
1501
2019
  resumeAttempt: pending.attemptId,
1502
- resumeCommitToken: pending.managerCommit?.durableCommitToken,
2020
+ resumeCommit: commitTokenHandoff(pending.root, pending.managerCommit !== undefined, heldLock),
1503
2021
  });
1504
2022
  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
2023
  }
@@ -1545,11 +2063,11 @@ async function resumeProvenRestoreListener(prepared, heldLock) {
1545
2063
  attachHost: restoreAttachHost,
1546
2064
  maxSessions: restoreMaxSessions,
1547
2065
  resumeAttempt: prepared.attemptId,
1548
- resumeCommitToken: prepared.managerCommit?.durableCommitToken,
2066
+ resumeCommit: commitTokenHandoff(prepared.root, prepared.managerCommit !== undefined, heldLock),
1549
2067
  });
1550
2068
  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
2069
  }
1552
- async function completeResumeActivation(attemptId, healthy, reason, server, heldLock) {
2070
+ async function completeResumeActivation(attemptId, healthy, reason, server, heldLock, retireBroker) {
1553
2071
  if (!attemptId)
1554
2072
  return;
1555
2073
  const ordinary = pendingOrdinaryResumes.get(attemptId);
@@ -1722,8 +2240,13 @@ async function completeResumeActivation(attemptId, healthy, reason, server, held
1722
2240
  if (process.env.COTAL_SMOKE_EXIT_AFTER_RESUME_FINALIZE === "1")
1723
2241
  process.exit(91);
1724
2242
  if (ordinary) {
2243
+ // A controller resume that started a new broker removes the cut's retired record before the
2244
+ // journal is retired; a mismatch leaves the committed attempt to recover forward.
2245
+ retireBroker?.();
1725
2246
  const lock = heldLock ?? acquireMaintenanceLock(ordinary.root);
1726
2247
  try {
2248
+ // The finalized manager has read or abandoned its handoff file; settle it before retirement.
2249
+ settleTokenHandoff(lock);
1727
2250
  retireOrdinaryResume(lock, finalizeEvidence);
1728
2251
  consumeRetiredMaintenance(lock);
1729
2252
  }
@@ -1738,6 +2261,7 @@ async function completeResumeActivation(attemptId, healthy, reason, server, held
1738
2261
  markPreparedRestoreActive(restored, finalizeEvidence, heldLock);
1739
2262
  restored.cleanupStage();
1740
2263
  pendingRestores.delete(attemptId);
2264
+ retireActiveRestoreBroker(restored.root, attemptId, retireBroker, heldLock);
1741
2265
  }
1742
2266
  }
1743
2267
  /** Validate + assemble the auth-service daemon's public-exchange argv from `up`'s flags. The three
@@ -1771,7 +2295,7 @@ function publicExchangeArgs(v, wantUser) {
1771
2295
  * service down", never fall back to static semantics) — plus `ok`, so the exiting `up` surfaces
1772
2296
  * (detach / manifest / refresh-heal) turn a dead identity plane into a NON-ZERO exit: automation
1773
2297
  * must not read "user mesh up" from a mesh whose every user connect will be denied. */
1774
- async function startUserAuthService(space, server, setup, publicExchange) {
2298
+ async function startUserAuthService(space, server, setup, publicExchange, quietBoot = false) {
1775
2299
  if (!setup?.prepared || !setup.stateDir)
1776
2300
  return { ok: true };
1777
2301
  try {
@@ -1782,7 +2306,8 @@ async function startUserAuthService(space, server, setup, publicExchange) {
1782
2306
  const base = typeof raw.publicUrl === "string" ? raw.publicUrl : String(raw.url);
1783
2307
  const endpoints = { url: base, ...(typeof raw.publicUrl === "string" ? { managerAuthorityUrl: `${base.replace(/\/$/, "")}/manager-service-authority` } : {}) };
1784
2308
  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}`));
2309
+ if (!quietBoot)
2310
+ console.log(c.green("✓ user-auth service up") + c.dim(` - sign in with: cotal login --idp ${info.idp.url}`));
1786
2311
  return { userAuth: info, ok: true };
1787
2312
  }
1788
2313
  catch (e) {
@@ -1790,43 +2315,178 @@ async function startUserAuthService(space, server, setup, publicExchange) {
1790
2315
  return { userAuth: assertUserAuthInfo(setup.prepared.publicAuth), ok: false };
1791
2316
  }
1792
2317
  }
2318
+ /** The fresh boot's read-only preparation, shared by the controller team boot. It runs the same
2319
+ * manifest load, override, mode agreement, ownership, bind, runtime, reachability and connector
2320
+ * refusals as the retained `upManifest` fresh path, in the same order, and writes nothing. */
2321
+ export async function prepareFreshTeamBoot(file, opts) {
2322
+ const flags = { ...opts, dryRun: false, freshTeamBoot: true };
2323
+ let prepared;
2324
+ try {
2325
+ prepared = loadManifest(resolve(file));
2326
+ }
2327
+ catch {
2328
+ 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 } });
2329
+ }
2330
+ if (opts.space !== prepared.manifest.space)
2331
+ 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 } });
2332
+ const declared = prepared.manifest.broker?.auth;
2333
+ if (opts.open && declared === "user")
2334
+ throw new CommandFailure("refused", "CONFLICT", "--open contradicts this manifest's user-auth mode; no trust or broker was changed", { target: { space: opts.space } });
2335
+ if (opts.userAuth && declared !== "user")
2336
+ throw new CommandFailure("refused", "CONFLICT", "--user-auth contradicts this manifest's declared auth mode; no trust or broker was changed", { target: { space: opts.space } });
2337
+ if (opts.idp && declared !== "user")
2338
+ throw new CommandFailure("refused", "CONFLICT", "--idp needs this manifest's user-auth mode; no trust or broker was changed", { target: { space: opts.space } });
2339
+ const idpProblem = opts.idp === undefined ? undefined : idpUrlProblem(opts.idp, "--idp");
2340
+ if (idpProblem)
2341
+ throw new CommandFailure("refused", "SCHEMA_INVALID", idpProblem, { target: { space: opts.space } });
2342
+ const serverProblems = opts.server === undefined ? [] : serverUrlProblems(opts.server, "--server");
2343
+ if (serverProblems.length)
2344
+ throw new CommandFailure("refused", "SCHEMA_INVALID", serverProblems.join("; "), { target: { space: opts.space } });
2345
+ const eff = applyUpOverrides(prepared, flags);
2346
+ const m = eff.manifest;
2347
+ const host = m.broker?.host ?? "127.0.0.1";
2348
+ const server = m.broker?.host ? reconcileHostAndServer(m.broker.host, m.broker?.servers, "broker.host", "broker.servers") : (m.broker?.servers ?? DEFAULT_SERVER);
2349
+ const open = m.broker?.auth === false;
2350
+ const mode = open ? "open" : m.broker?.auth === "user" ? "user" : "auth";
2351
+ const runtime = m.runtime ?? "pty";
2352
+ if (open && (m.defaults?.deliveryClass === "durable" || m.channels.some((channel) => channel.deliveryClass === "durable")))
2353
+ 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" });
2354
+ const other = loadMeshes().filter((row) => row.space !== m.space && row.server === server);
2355
+ if (other.length)
2356
+ 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) } });
2357
+ assertFreshTeamBootOwnership(cotalRoot(), m.space, mode);
2358
+ await assertFreshTeamBindAvailable(server, host, m.space);
2359
+ try {
2360
+ await preflightRuntime(runtime);
2361
+ }
2362
+ catch (error) {
2363
+ 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" });
2364
+ }
2365
+ if (await isReachable(server))
2366
+ 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" } });
2367
+ const conn = await preflightConnectors(prepared);
2368
+ if (conn)
2369
+ 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 });
2370
+ 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 };
2371
+ }
2372
+ /** A team boot that resumes one exact stopped controller stack whose manager was never attempted.
2373
+ * The same manifest load, agreement, durable-on-open, runtime, reachability and connector refusals
2374
+ * as {@link prepareFreshTeamBoot}, without the fresh zero-instance ownership gate: that gate is
2375
+ * replaced by the stopped-stack eligibility the caller binds under its lock. The manifest may not
2376
+ * move the recorded broker: its server must equal the recorded one, and a declared bind host must
2377
+ * equal the recorded host. Writes nothing. */
2378
+ export async function prepareResumeTeamBoot(file, opts) {
2379
+ let prepared;
2380
+ try {
2381
+ prepared = loadManifest(resolve(file));
2382
+ }
2383
+ catch {
2384
+ 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 } });
2385
+ }
2386
+ if (opts.space !== prepared.manifest.space)
2387
+ 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 } });
2388
+ const eff = applyUpOverrides(prepared, { transport: opts.transport, dryRun: false, freshTeamBoot: true });
2389
+ const m = eff.manifest;
2390
+ const server = m.broker?.host ? reconcileHostAndServer(m.broker.host, m.broker?.servers, "broker.host", "broker.servers") : (m.broker?.servers ?? DEFAULT_SERVER);
2391
+ const open = m.broker?.auth === false;
2392
+ const mode = open ? "open" : m.broker?.auth === "user" ? "user" : "auth";
2393
+ const runtime = m.runtime ?? "pty";
2394
+ if (server !== opts.recorded.server || mode !== opts.recorded.mode || (m.broker?.host !== undefined && m.broker.host !== opts.recorded.host))
2395
+ 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 } } });
2396
+ if (open && (m.defaults?.deliveryClass === "durable" || m.channels.some((channel) => channel.deliveryClass === "durable")))
2397
+ 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 } });
2398
+ const other = loadMeshes().filter((row) => row.space !== m.space && row.server === server);
2399
+ if (other.length)
2400
+ 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) } });
2401
+ try {
2402
+ await preflightRuntime(runtime);
2403
+ }
2404
+ catch (error) {
2405
+ 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" });
2406
+ }
2407
+ if (await isReachable(server))
2408
+ 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" } });
2409
+ const conn = await preflightConnectors(prepared);
2410
+ if (conn)
2411
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "connector preflight failed; nothing was resumed", { target: { space: m.space }, remedy: conn });
2412
+ 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 };
2413
+ }
2414
+ /** The recorded broker transport of a prepared root, decided without persisting anything: a team
2415
+ * boot names no TLS flags, so it inherits the root's recorded policy exactly as a bare `up` does. */
2416
+ export function recordedBrokerTransport(root) {
2417
+ return resolveTransport({}, undefined, root, { persist: false, quiet: true });
2418
+ }
2419
+ /** Recheck, under the fresh boot's own lock, the ownership and bind refusals that a concurrent
2420
+ * writer could have invalidated after {@link prepareFreshTeamBoot}. */
2421
+ export async function recheckFreshTeamBoot(plan, own) {
2422
+ assertFreshTeamBootOwnership(plan.root, plan.space, plan.mode, own ? { deploymentId: own.deploymentId, server: plan.server, manifestPath: plan.manifestPath } : undefined);
2423
+ await assertFreshTeamBindAvailable(plan.server, plan.host ?? "127.0.0.1", plan.space);
2424
+ }
2425
+ /** The native callbacks a controller stack start uses, shared by `cotal up` and a controller team
2426
+ * boot so both prepare, seed and record through the same native path. */
2427
+ export function controllerStackNative() {
2428
+ return {
2429
+ prepareBroker: async (opts) => {
2430
+ 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 });
2431
+ 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 };
2432
+ },
2433
+ initializeStreams: (server, space, setup, seedFile) => postStart(server, space, setup, seedFile),
2434
+ recordMesh: (entry) => recordOurMesh({ ...entry, ts: new Date().toISOString() }, "started", true),
2435
+ commitTransport: (root, chosen) => commitTransportPolicy(root, chosen, true),
2436
+ };
2437
+ }
1793
2438
  /** `cotal up -f cotal.yaml` — bring up a FRESH mesh from a manifest (broker + channels + booted
1794
2439
  * agents). `up -f` is a broker-CREATION command: `broker.servers` is the bind address for the NEW
1795
2440
  * 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`). */
2441
+ * fresh boot refusal; an unbindable/remote address makes the broker fail to start (no silent
2442
+ * local fallback). It owns the whole space, so `cotal down` tears it down without an additive
2443
+ * ownership ledger. */
1799
2444
  async function upManifest(file, opts) {
1800
2445
  let prepared;
1801
2446
  try {
1802
2447
  prepared = loadManifest(resolve(file));
1803
2448
  }
1804
2449
  catch (e) {
2450
+ if (opts.freshTeamBoot)
2451
+ 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
2452
  failManifest(e);
1806
2453
  }
2454
+ if (opts.freshTeamBoot && opts.space !== prepared.manifest.space)
2455
+ 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 } });
2456
+ refuseManifestSpaceMismatch(prepared, opts.space);
1807
2457
  // The auth-mode sources (flags vs manifest) must AGREE — any mismatch names both sources and the
1808
2458
  // exact correction in one sentence (a no-fallback identity decision, never a bare enum error).
1809
2459
  const declared = prepared.manifest.broker?.auth;
1810
2460
  const declaredStr = declared === undefined ? '"static" (the unset default)' : JSON.stringify(declared);
1811
2461
  if (opts.open && declared === "user") {
2462
+ if (opts.freshTeamBoot)
2463
+ 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
2464
  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
2465
  process.exit(1);
1814
2466
  }
1815
2467
  if (opts.userAuth && declared !== "user") {
2468
+ if (opts.freshTeamBoot)
2469
+ 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
2470
  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
2471
  process.exit(1);
1818
2472
  }
1819
2473
  if (opts.idp && declared !== "user") {
2474
+ if (opts.freshTeamBoot)
2475
+ 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
2476
  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
2477
  process.exit(1);
1822
2478
  }
1823
2479
  const idpProblem = opts.idp === undefined ? undefined : idpUrlProblem(opts.idp, "--idp");
1824
2480
  if (idpProblem) {
2481
+ if (opts.freshTeamBoot)
2482
+ throw new CommandFailure("refused", "SCHEMA_INVALID", idpProblem, { target: { space: prepared.manifest.space } });
1825
2483
  console.error(c.red(`✗ ${idpProblem}`));
1826
2484
  process.exit(1);
1827
2485
  }
1828
2486
  const serverProblems = opts.server === undefined ? [] : serverUrlProblems(opts.server, "--server");
1829
2487
  if (serverProblems.length) {
2488
+ if (opts.freshTeamBoot)
2489
+ throw new CommandFailure("refused", "SCHEMA_INVALID", serverProblems.join("; "), { target: { space: prepared.manifest.space } });
1830
2490
  for (const problem of serverProblems)
1831
2491
  console.error(c.red(`✗ ${problem}`));
1832
2492
  process.exit(1);
@@ -1842,11 +2502,22 @@ async function upManifest(file, opts) {
1842
2502
  const open = m.broker?.auth === false; // default is auth
1843
2503
  const userAuth = m.broker?.auth === "user" ? { idpUrl: m.broker.idp } : undefined;
1844
2504
  const runtime = m.runtime ?? "pty";
2505
+ if (open && (m.defaults?.deliveryClass === "durable" || m.channels.some((channel) => channel.deliveryClass === "durable")))
2506
+ 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" });
2507
+ if (opts.freshTeamBoot) {
2508
+ const other = loadMeshes().filter((row) => row.space !== m.space && row.server === server);
2509
+ if (other.length)
2510
+ 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" });
2511
+ }
2512
+ if (opts.freshTeamBoot) {
2513
+ assertFreshTeamBootOwnership(cotalRoot(), m.space, open ? "open" : userAuth ? "user" : "auth");
2514
+ await assertFreshTeamBindAvailable(server, host, m.space);
2515
+ }
1845
2516
  // A manifest's agents are booted BY the manager `up -f` starts with the mesh, so `--no-manager`
1846
2517
  // 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.
2518
+ // before the dry-run print and before anything boots.
1848
2519
  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.`);
2520
+ 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
2521
  const effectiveNoManager = Boolean(opts.noManager);
1851
2522
  // The open-mesh refusal must be RE-STATED here, not only against the CLI `--open` flag: on this
1852
2523
  // path openness comes from the MANIFEST (`broker.auth: false`), which the flag-level guard cannot
@@ -1880,18 +2551,40 @@ async function upManifest(file, opts) {
1880
2551
  }
1881
2552
  // Preflight an extension runtime before starting the broker. The detached manager re-execs this
1882
2553
  // 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.
2554
+ try {
2555
+ await preflightRuntime(runtime);
2556
+ }
2557
+ catch (error) {
2558
+ 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" });
2559
+ }
2560
+ // up -f never adopts a running broker. The old spawn -f route is no longer a manifest deploy.
1885
2561
  if (await isReachable(server)) {
1886
- console.error(c.red(`✗ ${server} already has a broker - deploy this manifest onto it with \`cotal spawn -f ${file}\``));
2562
+ if (opts.freshTeamBoot)
2563
+ 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" });
2564
+ 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
2565
  process.exit(1);
1888
2566
  }
1889
2567
  // Connectors + their required binaries must exist before any mutation (no fallback).
1890
2568
  const conn = await preflightConnectors(prepared);
1891
2569
  if (conn) {
2570
+ if (opts.freshTeamBoot)
2571
+ 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
2572
  console.error(c.red(`✗ connector preflight failed: ${conn}`));
1893
2573
  process.exit(1);
1894
2574
  }
2575
+ if (opts.freshTeamBoot) {
2576
+ assertFreshTeamBootOwnership(cotalRoot(), m.space, open ? "open" : userAuth ? "user" : "auth");
2577
+ await assertFreshTeamBindAvailable(server, host, m.space);
2578
+ }
2579
+ const deploymentId = genRunId();
2580
+ if (opts.freshTeamBoot) {
2581
+ try {
2582
+ 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() });
2583
+ }
2584
+ catch {
2585
+ 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" });
2586
+ }
2587
+ }
1895
2588
  // USER-AUTH manifest: the agents run under the LOGGED-IN operator's owner, and the launch spec
1896
2589
  // (consumed by the manager at boot) must carry it — so resolve it NOW. On a fresh mesh the
1897
2590
  // derivation material doesn't exist yet; ensure it just-in-time (authSetup + prepareServer are
@@ -1900,14 +2593,16 @@ async function upManifest(file, opts) {
1900
2593
  let owner;
1901
2594
  if (userAuth) {
1902
2595
  try {
1903
- mkdirSync(cotalPath("nats"), { recursive: true });
2596
+ mkdirSync(cotalPath("nats"), { recursive: true, mode: 0o700 });
1904
2597
  // NO `rotateSys` here on purpose: this is an owner-derivation pre-resolve that runs BEFORE the
1905
2598
  // real boot, and the boot below carries the flag. Rotating in both would burn two generations
1906
2599
  // 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));
2600
+ const setup = await authSetup(cotalPath("nats"), server, m.space, host, userAuth, assertServesDialHost(opts.transport, new URL(server).hostname), false, undefined, opts.freshTeamBoot);
1908
2601
  owner = await resolveAuthProvider().ownerForLogin({ store: workspaceSecretStore(cotalRoot()), dir: setup.stateDir, space: m.space });
1909
2602
  }
1910
2603
  catch (e) {
2604
+ if (opts.freshTeamBoot)
2605
+ 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
2606
  console.error(c.red(`✗ ${e.message}`));
1912
2607
  process.exit(1);
1913
2608
  }
@@ -1918,27 +2613,95 @@ async function upManifest(file, opts) {
1918
2613
  // the lease — the loser refuses, so either the agents never boot or the incumbent is orphaned
1919
2614
  // behind an overwritten pid file. The manager materializes each transient persona and mints creds
1920
2615
  // 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);
2616
+ if (opts.freshTeamBoot) {
2617
+ assertFreshTeamBootOwnership(cotalRoot(), m.space, open ? "open" : userAuth ? "user" : "auth", { deploymentId, server, manifestPath: resolve(file) });
2618
+ try {
2619
+ await assertFreshTeamBindAvailable(server, host, m.space);
2620
+ }
2621
+ catch {
2622
+ 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" });
2623
+ }
2624
+ }
2625
+ let specPath;
2626
+ try {
2627
+ specPath = writeLaunchSpec(cotalRoot(), buildLaunchSpec(eff, deploymentId, owner));
2628
+ }
2629
+ catch (error) {
2630
+ if (opts.freshTeamBoot)
2631
+ 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" });
2632
+ throw error;
2633
+ }
2634
+ // Ordinary up can reconcile a leftover manager. Fresh team boot must not signal one: its
2635
+ // stricter prewrite gate required no manager record at all, and a later contender wins
2636
+ // neither stop authority nor permission to replace it.
2637
+ if (!opts.freshTeamBoot) {
2638
+ await stopManager(m.space);
2639
+ clearManagerArtifacts(m.space);
2640
+ }
1927
2641
  let pid;
1928
2642
  let controlPlane = false;
1929
2643
  let authService = true;
2644
+ let deliveryResponderBound = null;
1930
2645
  try {
1931
2646
  // `m.broker?.host`, not the defaulted `host`: same reason as the flag path — only a host the
1932
2647
  // 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 }));
2648
+ ({ 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
2649
  }
1935
2650
  catch (e) {
2651
+ if (opts.freshTeamBoot)
2652
+ 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
2653
  console.error(c.red(`✗ ${e.message}`));
1937
2654
  process.exit(1);
1938
2655
  }
1939
2656
  // Transport committed inside startMeshDetached before delivery (S5+S9).
2657
+ let summaryRecorded = false;
2658
+ try {
2659
+ writeFreshTeamSummary(cotalRoot(), {
2660
+ schemaVersion: 1, kind: "fresh-team-summary", deploymentId, space: m.space,
2661
+ root: cotalRoot(), server, authMode: open ? "open" : userAuth ? "user" : "auth", brokerPid: pid, manifestPath: resolve(file),
2662
+ requestedAgents: eff.agents.map((agent) => agent.name),
2663
+ declaredChannels: m.channels.map((channel) => channel.name),
2664
+ recordedAt: new Date().toISOString(), managerRequested: !effectiveNoManager,
2665
+ controlPlaneReturned: controlPlane, authServiceReturned: authService, deliveryResponderBound,
2666
+ agentReadiness: "not-checked",
2667
+ });
2668
+ summaryRecorded = true;
2669
+ }
2670
+ catch {
2671
+ 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`));
2672
+ }
2673
+ if (opts.freshTeamBoot) {
2674
+ if (!authService || !controlPlane || !summaryRecorded || (!open && deliveryResponderBound !== true))
2675
+ 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" });
2676
+ const inheritedAccess = eff.agents.flatMap((agent) => {
2677
+ const access = agent.inherited;
2678
+ return access.capabilities.length || access.subscribe.length || access.allowSubscribe.length || access.allowPublish.length
2679
+ ? [{ agent: agent.name, persona: agent.persona ?? null, capabilities: access.capabilities, subscribe: access.subscribe, allowSubscribe: access.allowSubscribe, allowPublish: access.allowPublish }]
2680
+ : [];
2681
+ });
2682
+ let currentSelection = null;
2683
+ let selectionChecked = false;
2684
+ try {
2685
+ currentSelection = getCurrent() ?? null;
2686
+ selectionChecked = true;
2687
+ }
2688
+ catch { /* The returned broker receipt remains usable without a current-default read. */ }
2689
+ 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,
2690
+ mode: open ? "open" : userAuth ? "user-auth" : "static-auth", controlPlaneReturned: controlPlane, authServiceReturned: authService, deliveryResponderBound, summaryRecorded,
2691
+ requestedAgents: eff.agents.map((agent) => ({ name: agent.name, application: agent.agentType, role: agent.role ?? null })),
2692
+ declaredChannels: m.channels.map((channel) => ({ name: channel.name, deliveryClass: channel.deliveryClass ?? null, replay: channel.replay ?? null, replayWindow: channel.replayWindow ?? null })), inheritedAccess, agentReadiness: "not-checked" };
2693
+ 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: [
2694
+ { 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."] }] },
2695
+ { 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."] }] : [])] },
2696
+ ...(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."] }] }] : []),
2697
+ { 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" }] }] },
2698
+ ] }));
2699
+ return;
2700
+ }
1940
2701
  console.log(c.green(`✓ mesh "${m.space}" up at ${server}`) + c.dim(` (broker pid ${pid})`));
1941
2702
  console.log(c.dim(` seeded ${m.channels.length} channel(s): ${m.channels.map((ch) => "#" + ch.name).join(", ")}`));
2703
+ if (summaryRecorded)
2704
+ console.log(c.dim(` fresh deployment ${deploymentId} recorded; cotal team show ${deploymentId} reads its launch summary, not live ownership`));
1942
2705
  // Never claim a launch the control plane can't deliver: the manager carries the launch spec, so a
1943
2706
  // degraded control plane (announced above) means the agents are NOT coming up.
1944
2707
  if (effectiveNoManager) {
@@ -1959,11 +2722,12 @@ async function upManifest(file, opts) {
1959
2722
  console.log("\n" + inherited);
1960
2723
  if (eff.warnings.length)
1961
2724
  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\``));
2725
+ const downRoute = opts.root ? `from ${oneLine(cotalRoot())}, run \`cotal down\`` : "`cotal down`";
2726
+ console.log(c.dim(`\nWatch: \`cotal watch --space ${m.space}\` (terminal) · Dashboard: configure the explicit web service preset separately · Tear down: ${downRoute}`));
1963
2727
  // A declared-user-auth manifest whose auth service never became ready, or a degraded control
1964
2728
  // plane: the mesh is up + recorded, but this launch did not deliver what it declared — exit
1965
2729
  // non-zero so CI/wrappers don't read success (the consequence line printed at the failure above).
1966
- if (!authService || !controlPlane)
2730
+ if (!authService || !controlPlane || !summaryRecorded)
1967
2731
  process.exitCode = 1;
1968
2732
  }
1969
2733
  /** Return a copy of the prepared manifest with CLI overrides applied to broker/space/runtime, so the
@@ -1984,7 +2748,6 @@ function applyUpOverrides(prepared, o) {
1984
2748
  manifest: {
1985
2749
  ...m,
1986
2750
  broker: Object.keys(broker).length ? broker : undefined,
1987
- space: o.space ?? m.space,
1988
2751
  runtime: o.runtime ?? m.runtime,
1989
2752
  },
1990
2753
  };
@@ -2120,7 +2883,7 @@ async function serveReadyListener(l) {
2120
2883
  // USER MODE: the auth service comes up FIRST among the daemons — until its callout answers,
2121
2884
  // every user-mode connect to this broker is denied, so `up` must not report a usable user mesh
2122
2885
  // (nor let agents race it) on a half-started auth plane.
2123
- const svc = await startUserAuthService(space, server, setup, l.publicExchange);
2886
+ const svc = await startUserAuthService(space, server, setup, l.publicExchange, l.quietBoot);
2124
2887
  // Record BEFORE the control plane comes up: the manager's fail-closed mode detection requires
2125
2888
  // an authoritative registry entry (marker-without-registry is a refused start, not a guess),
2126
2889
  // so the record must exist by the time it boots. A manager/delivery failure after this leaves
@@ -2148,11 +2911,11 @@ async function serveReadyListener(l) {
2148
2911
  ...(l.maxFileStore !== undefined ? { maxFileStore: l.maxFileStore } : {}),
2149
2912
  storeDir: l.storeDir,
2150
2913
  ts: new Date().toISOString(),
2151
- }, "started");
2914
+ }, "started", l.quietBoot);
2152
2915
  // Commit the policy only for a listener that is up and recorded (S5), and before the control
2153
2916
  // plane (S9). startDeliveryWithBroker is HANDED the transport decision, so it does not depend on
2154
2917
  // the file at all.
2155
- commitTransportPolicy(cotalRoot(), transport);
2918
+ commitTransportPolicy(cotalRoot(), transport, l.quietBoot);
2156
2919
  // The delivery daemon self-gates on `.cotal/auth`, so an open mesh has none. Class-2 credential
2157
2920
  // renewal is NOT wired here: the MANAGER is the renewal owner (it is resident in every mesh mode,
2158
2921
  // where a foreground `up` process is not).
@@ -2167,22 +2930,17 @@ async function serveReadyListener(l) {
2167
2930
  maxSessions,
2168
2931
  noManager: l.noManager,
2169
2932
  resumeAttempt: l.resumeAttempt,
2170
- resumeCommitToken: l.resumeCommitToken,
2933
+ resumeCommit: l.resumeCommit,
2171
2934
  wsPort: setup?.wsPort, // P2 item 6: the console session client's broker ws port
2172
2935
  });
2936
+ seedPersonaAfterUp(cotalRoot(), l.quietBoot);
2173
2937
  return { authService: svc.ok, controlPlane };
2174
2938
  }
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) {
2939
+ /** Prepare the existing broker's local trust, configuration and launch inputs without starting a
2940
+ * listener, auth service, delivery daemon or manager. This is an explicit mutating phase, not a
2941
+ * dry-run or service-adapter planning hook. Its returned setup includes private authority material
2942
+ * for the coordinating caller only; it must not be logged or serialized into a public receipt. */
2943
+ export async function prepareBrokerStart(opts) {
2186
2944
  const server = opts.server ?? DEFAULT_SERVER;
2187
2945
  const useAuth = !opts.open;
2188
2946
  // Belt on the one boot that both renders the broker config and can be reached by any caller: an
@@ -2190,31 +2948,70 @@ opts) {
2190
2948
  // rather than refused. Callers guard this too; this is the seam that cannot be bypassed.
2191
2949
  if (opts.rotateSys && !useAuth)
2192
2950
  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());
2951
+ const space = opts.space ?? folderSpace();
2194
2952
  ensureRootForSpace(space); // may pin the cwd as this space's root — before any cotalPath use
2195
2953
  refuseOpenOverUserState(Boolean(opts.open), space);
2954
+ const root = cotalRoot();
2196
2955
  const storeDir = opts.storeDir ? resolve(opts.storeDir) : cotalPath("nats");
2197
- mkdirSync(storeDir, { recursive: true });
2198
- await claimSpace(space, server, cotalRoot());
2956
+ if (opts.existingStore) {
2957
+ if (opts.existingStore.named !== storeDir)
2958
+ throw new Error("prepareBrokerStart: the pinned existing store is not the store being prepared");
2959
+ recheckExistingStore(opts.existingStore, { space, storeDir });
2960
+ }
2961
+ else
2962
+ mkdirSync(storeDir, { recursive: true, mode: 0o700 });
2963
+ await claimSpace(space, server, root);
2199
2964
  const seedFile = opts.seed ?? loadChannelsFile(opts.channels);
2200
2965
  const host = opts.host ?? "127.0.0.1";
2201
2966
  // The transport arrives decided. The dial-host SAN is re-checked here because THIS is where the
2202
2967
  // effective server is finally known — a manifest may name a different host than the flags did, and
2203
2968
  // a certificate that is valid for one is not thereby valid for the other.
2204
2969
  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;
2970
+ const setup = useAuth ? await authSetup(storeDir, server, space, host, opts.userAuth, transport, opts.rotateSys, opts.maxFileStore, opts.quietBoot) : undefined;
2206
2971
  const port = Number(new URL(server).port) || 4222;
2207
2972
  // Same rule as the foreground path: every route to a listener names its transport (see
2208
2973
  // `writeOpenBrokerConf`). Detach must not be the mode where the fence quietly does not apply.
2209
2974
  const confPath = setup ? setup.confPath : writeOpenBrokerConf(storeDir, { port, host, transport, maxFileStore: opts.maxFileStore });
2975
+ // Trust preparation awaits; the pinned store is checked again before its config is handed back.
2976
+ if (opts.existingStore)
2977
+ recheckExistingStore(opts.existingStore, { space, storeDir });
2210
2978
  const args = [
2211
2979
  "-c", confPath,
2212
2980
  ...(opts.boundListener ? ["--name", opts.boundListener.serverName] : []),
2213
2981
  ];
2214
2982
  const { bin, source } = await resolveNatsServer();
2983
+ return { root, server, space, useAuth, storeDir, seedFile, host, transport, setup, confPath, args, bin, source };
2984
+ }
2985
+ /**
2986
+ * Open the detached broker's log with {@link openPrivateAppend}: created `0600` whatever the umask,
2987
+ * never through a symlink, and an earlier log this user owns set to `0600`. A symlink, a log another
2988
+ * user owns or a name that is not a regular file is refused and left unchanged.
2989
+ */
2990
+ export function openBrokerLog(path) {
2991
+ try {
2992
+ return openPrivateAppend(path);
2993
+ }
2994
+ catch (error) {
2995
+ if (error.code !== "EPERM")
2996
+ throw error;
2997
+ 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` });
2998
+ }
2999
+ }
3000
+ /**
3001
+ * Start a background nats-server (JetStream), wait until it's reachable, pre-create the
3002
+ * space's streams, and leave it running detached (pid in `.cotal/nats.pid`). Used by
3003
+ * `up --detach`. When `onLine` is given, boot output is tailed from the
3004
+ * log file and forwarded — the child writes to the file (not a pipe), so it survives the
3005
+ * parent exiting.
3006
+ */
3007
+ export async function startMeshDetached(
3008
+ // The `= {}` default is gone with the optional transport: an options object that can be omitted
3009
+ // entirely cannot carry a mandatory decision.
3010
+ opts) {
3011
+ const { server, space, useAuth, storeDir, seedFile, transport, setup, args, bin, source } = await prepareBrokerStart(opts);
2215
3012
  const logPath = cotalPath("nats.log");
2216
- const startOffset = existsSync(logPath) ? statSync(logPath).size : 0;
2217
- const fd = openSync(logPath, "a");
3013
+ const fd = openBrokerLog(logPath);
3014
+ const startOffset = fstatSync(fd).size;
2218
3015
  const listenerStartedAt = new Date().toISOString();
2219
3016
  const child = spawn(bin, args, { detached: true, stdio: ["ignore", fd, fd] });
2220
3017
  closeSync(fd);
@@ -2236,10 +3033,11 @@ opts) {
2236
3033
  maxFileStore: opts.maxFileStore,
2237
3034
  publicExchange: opts.publicExchange,
2238
3035
  resumeAttempt: opts.resumeAttempt,
2239
- resumeCommitToken: opts.resumeCommitToken,
3036
+ resumeCommit: opts.resumeCommit,
2240
3037
  runtime: opts.runtime,
2241
3038
  launch: opts.launch,
2242
3039
  noManager: opts.noManager,
3040
+ quietBoot: opts.quietBoot,
2243
3041
  });
2244
3042
  return {
2245
3043
  server,
@@ -2247,6 +3045,7 @@ opts) {
2247
3045
  source,
2248
3046
  controlPlane: controlPlane !== undefined,
2249
3047
  authService,
3048
+ deliveryResponderBound: useAuth ? controlPlane?.responderBound === true : null,
2250
3049
  delivery: useAuth && deliveryUp(space),
2251
3050
  manager: managerUp(space),
2252
3051
  };
@@ -2284,6 +3083,14 @@ function refuseOpenOverUserState(open, space) {
2284
3083
  function ensureRootForSpace(space) {
2285
3084
  const root = cotalRoot();
2286
3085
  const cwd = process.cwd();
3086
+ // A prepared space starts only in the root `cotal space create` gave it. Checked before the mkdir
3087
+ // below, so a refused start leaves nothing behind.
3088
+ const prepared = findPreparedSpace(space);
3089
+ if (prepared && canonicalRoot(prepared.root) !== canonicalRoot(root))
3090
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `space "${space}" is prepared in ${prepared.root}`, {
3091
+ target: { space, root: prepared.root },
3092
+ remedy: `start it with \`cotal up\` there, or \`cotal space forget ${space}\` to start it here`,
3093
+ });
2287
3094
  // What spaces does this root already host? Prefer auth material; fall back to a live MeshEntry
2288
3095
  // whose root is this directory (open meshes have no auth dir).
2289
3096
  const hosted = listSpaceAccounts(authDir(root));
@@ -2291,16 +3098,43 @@ function ensureRootForSpace(space) {
2291
3098
  return;
2292
3099
  const existing = hosted.length
2293
3100
  ? hosted
2294
- : [loadMeshes().find((m) => m.root === root || realpathSafe(m.root) === realpathSafe(root))?.space].filter((s) => !!s);
3101
+ : [loadMeshes().find((m) => m.root === root || realpathSafe(m.root) === realpathSafe(root))?.space ?? preparedSpaceAt(root)?.space].filter((s) => !!s);
2295
3102
  if (existing.length === 0 || existing.includes(space))
2296
3103
  return;
2297
3104
  const names = existing.map((s) => `"${s}"`).join(", ");
2298
3105
  if (root !== cwd) {
2299
- mkdirSync(join(cwd, ".cotal"), { recursive: true });
3106
+ mkdirSync(join(cwd, ".cotal"), { recursive: true, mode: 0o700 });
2300
3107
  console.log(c.dim(`nearest mesh root ${root} hosts ${names} - making this folder its own root for "${space}"`));
2301
3108
  return;
2302
3109
  }
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)`);
3110
+ throw new CommandFailure("refused", "CONFLICT", `this folder is the root of ${names} (${root}/.cotal), so it can't also run "${space}"`, {
3111
+ target: { space, root, hosted: existing },
3112
+ 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)`,
3113
+ });
3114
+ }
3115
+ /** The space a `cotal up` that names none runs in this folder. The root's sole account names it
3116
+ * first, as {@link resolveSpace} does. An open mesh has no account, and its first start replaces
3117
+ * the prepared record with a registration, so the space this root's stack journal or its locally
3118
+ * started registration names comes next. Without it a second `up` in the same folder resolved the
3119
+ * default space and refused its own mesh. Several names there are refused, never picked. Then the
3120
+ * space prepared here, then the default.
3121
+ *
3122
+ * Only `up` asks this. `resolveSpace` also decides whether identity cleanup may attribute a root to
3123
+ * a space (`reset-space-plan.ts`) and, through `resolveRuntimeSpace`, which space a legacy `down`
3124
+ * removes credentials for; those keep their own answer. */
3125
+ function folderSpace() {
3126
+ const root = cotalRoot();
3127
+ if (soleSpaceOf(authDir(root)) === undefined) {
3128
+ const named = [...new Set([readStackJournal(root)?.journal.space, ...localMeshesForRoot(root).map((m) => m.space)])].filter((s) => s !== undefined);
3129
+ if (named.length > 1)
3130
+ 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`, {
3131
+ target: { root, spaces: named },
3132
+ remedy: "name the space to run with `--space`",
3133
+ });
3134
+ if (named.length === 1)
3135
+ return named[0];
3136
+ }
3137
+ return resolveSpace(process.cwd());
2304
3138
  }
2305
3139
  function realpathSafe(p) {
2306
3140
  try {
@@ -2406,9 +3240,9 @@ export const recordOurMeshForTest = (m, provenance) => recordOurMesh(m, provenan
2406
3240
  * — i.e. the first mesh, OR when `current` dangles at a space that's no longer in the registry (a
2407
3241
  * ghost pointer is not a default). Never silently redirect a `current` that still resolves to a live
2408
3242
  * mesh; just say another is the default and how to switch. */
2409
- function recordOurMesh(m, provenance) {
3243
+ function recordOurMesh(m, provenance, quietBoot = false) {
2410
3244
  const cur = getCurrent();
2411
- const usableCurrent = cur && findMesh(cur) ? cur : undefined; // compute before recording m
3245
+ const usableCurrent = cur && (findMesh(cur) || findPreparedSpace(cur)) ? cur : undefined; // compute before recording m
2412
3246
  const prior = findMesh(m.space);
2413
3247
  const origin = provenance === "refresh" && (prior?.origin === "manual" || prior?.origin === "catalog") ? prior.origin : "up";
2414
3248
  // A REFRESH starts nothing: it concluded the mesh is up from reachability alone, so `m` holds only
@@ -2420,13 +3254,28 @@ function recordOurMesh(m, provenance) {
2420
3254
  if (provenance === "refresh" && !prior)
2421
3255
  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
3256
  recordMesh(provenance === "refresh" ? { ...prior, ...m, origin } : { ...m, origin });
3257
+ removePreparedSpace(m.space); // started: the registration is its record now
2423
3258
  if (!usableCurrent) {
2424
3259
  setCurrent(m.space);
2425
3260
  return;
2426
3261
  }
2427
- if (usableCurrent !== m.space)
3262
+ if (usableCurrent !== m.space && !quietBoot)
2428
3263
  console.log(c.dim(`"${m.space}" up; current is still "${usableCurrent}" - \`cotal use ${m.space}\` to switch`));
2429
3264
  }
3265
+ /** Write the default persona into the root this `up` started or refreshed when it has none, and
3266
+ * say so. The mesh is already up, so a write that fails is reported and the start stands. */
3267
+ function seedPersonaAfterUp(root, quiet = false) {
3268
+ let written;
3269
+ try {
3270
+ written = seedDefaultPersona(root);
3271
+ }
3272
+ catch (e) {
3273
+ console.error(c.yellow(`! the default persona was not written in ${root}: ${e.message}`));
3274
+ return;
3275
+ }
3276
+ if (written && !quiet)
3277
+ console.log(c.dim(` wrote ${written.what}: ${written.path}`));
3278
+ }
2430
3279
  /** Poll a growing log file and forward newly-appended lines until `stopped()` is true. */
2431
3280
  function tailLines(path, from, onLine, stopped) {
2432
3281
  let offset = from;
@@ -2559,6 +3408,45 @@ function reconcileHostAndServer(host, explicitServer, source = "--host", urlSour
2559
3408
  }
2560
3409
  return explicitServer;
2561
3410
  }
3411
+ /** Bind the manifest's exact listener address before any team-boot write. Releasing this
3412
+ * socket is not a reservation: the real broker still owns the final bind verdict. */
3413
+ async function assertFreshTeamBindAvailable(server, host, space) {
3414
+ const url = new URL(server), port = Number(url.port || "4222");
3415
+ const displayServer = brokerAddressForDisplay(server) ?? "not displayable";
3416
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65535)
3417
+ throw new CommandFailure("refused", "USAGE_INVALID", "the fresh team broker needs a concrete TCP port before it can check its bind address", { target: { space } });
3418
+ await new Promise((resolve, reject) => {
3419
+ const socket = createServer(), controller = new AbortController();
3420
+ socket.unref();
3421
+ let settled = false;
3422
+ const finish = (error) => {
3423
+ if (settled)
3424
+ return;
3425
+ settled = true;
3426
+ clearTimeout(timer);
3427
+ if (error)
3428
+ reject(error);
3429
+ else
3430
+ resolve();
3431
+ };
3432
+ const timer = setTimeout(() => {
3433
+ controller.abort();
3434
+ 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 } }));
3435
+ }, 1500);
3436
+ 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" })));
3437
+ try {
3438
+ socket.listen({ port, host, signal: controller.signal }, () => {
3439
+ if (settled)
3440
+ return;
3441
+ 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));
3442
+ });
3443
+ }
3444
+ catch {
3445
+ controller.abort();
3446
+ finish(new CommandFailure("refused", "TARGET_UNAVAILABLE", "the selected broker bind address was rejected before startup; no other listener was chosen", { target: { space, server: displayServer } }));
3447
+ }
3448
+ });
3449
+ }
2562
3450
  async function serverWithFreePort(server, host) {
2563
3451
  const url = new URL(server);
2564
3452
  url.port = String(await freePort(host));
@@ -2695,12 +3583,13 @@ opts = {}) {
2695
3583
  writeBrokerPolicy(root, { version: 1, transport: validated });
2696
3584
  return validated;
2697
3585
  }
2698
- /** Persist + announce a transport that has been APPLIED (listener started and proved). */
2699
- function commitTransportPolicy(root, transport) {
3586
+ /** Persist a transport after its listener starts; a structured boot leaves stdout to its receipt. */
3587
+ function commitTransportPolicy(root, transport, quietBoot = false) {
2700
3588
  if (transport.kind !== "tls-required")
2701
3589
  return;
2702
3590
  writeBrokerPolicy(root, { version: 1, transport });
2703
- announceTransport(transport);
3591
+ if (!quietBoot)
3592
+ announceTransport(transport);
2704
3593
  }
2705
3594
  function announceTransport(transport) {
2706
3595
  if (transport.kind !== "tls-required")
@@ -2830,8 +3719,8 @@ function validateRecorded(transport, dialHost, opts = {}) {
2830
3719
  * does not state its transport.
2831
3720
  */
2832
3721
  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 }));
3722
+ const confPath = cotalPath("server-open.conf");
3723
+ writeSecretFile(confPath, openServerConfig({ port: opts.port, host: opts.host, storeDir, maxFileStore: opts.maxFileStore, transport: opts.transport }));
2835
3724
  return confPath;
2836
3725
  }
2837
3726
  /** Ensure the space's trust material exists, render a server config, and mint a privileged
@@ -2855,7 +3744,7 @@ async function authSetup(storeDir, server, space, host = "127.0.0.1", user,
2855
3744
  // operator's `--tls-cert` sat validated and unused. A default here cannot be right, because the
2856
3745
  // safe value and the common value are different values — every caller knows its transport, and
2857
3746
  // the one that does not is the one that must not compile.
2858
- transport, rotateSys = false, maxFileStore) {
3747
+ transport, rotateSys = false, maxFileStore, quietBoot = false) {
2859
3748
  const dir = authDir(cotalRoot()); // the broker config (server.conf) still lands under the FS auth dir
2860
3749
  const store = workspaceSecretStore(cotalRoot());
2861
3750
  let auth = await getSpaceAuth(store, space);
@@ -2898,7 +3787,7 @@ transport, rotateSys = false, maxFileStore) {
2898
3787
  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
3788
  }
2900
3789
  // The DATA half of the membership bundle, on EVERY path — see healMembershipDataCreds.
2901
- await healMembershipDataCreds(auth, cotalRoot(), space);
3790
+ await healMembershipDataCreds(auth, cotalRoot(), space, quietBoot);
2902
3791
  // The $SYS creds must be signed by the system account THIS boot is about to put in `server.conf`.
2903
3792
  // A rotation that committed the trust record and then died leaves them stale, unexpired, and
2904
3793
  // broker-dead and, crash-before-either-write, stale in a way that no comparison between the two
@@ -2964,7 +3853,9 @@ transport, rotateSys = false, maxFileStore) {
2964
3853
  : await resolveAuthProvider().preloadAccounts({ store, space: enabledSpace });
2965
3854
  extraAccounts.push(...accounts);
2966
3855
  }
2967
- writeFileSync(confPath, serverConfig(auth, spaces, { transport, port, storeDir, maxFileStore, host, wsPort, wsHost: host, extraAccounts }));
3856
+ // Owner-private regardless of umask, as `writeOpenBrokerConf` writes the open configuration: the
3857
+ // broker preset refuses a configuration that other local users can write.
3858
+ writeSecretFile(confPath, serverConfig(auth, spaces, { transport, port, storeDir, maxFileStore, host, wsPort, wsHost: host, extraAccounts }));
2968
3859
  // Ephemeral setup cred: used only to probe reachability, pre-create the space streams/buckets
2969
3860
  // (setupSpaceStreams) and seed the channel registry (seedChannelRegistry) — all within the
2970
3861
  // enumerated `provisioner` scope. No broad `manager` residual for the up path.
@@ -3046,7 +3937,7 @@ async function assertRootBrokerStopped(root) {
3046
3937
  * its own error text — advice that could not succeed. Healing here fixes both spellings at once:
3047
3938
  * the ordinary `up` repairs the data half with no rotation at all, and a rotation now repairs it
3048
3939
  * too, because this runs after both branches converge. */
3049
- async function healMembershipDataCreds(auth, root, space) {
3940
+ async function healMembershipDataCreds(auth, root, space, quietBoot = false) {
3050
3941
  try {
3051
3942
  const store = workspaceSecretStore(root);
3052
3943
  // THE RESOLVERS, not the bare kinds (P7 §2 rule 1). Both reads below are absent-means-MINT, which
@@ -3067,7 +3958,7 @@ async function healMembershipDataCreds(auth, root, space) {
3067
3958
  writeSecretFile(configPath, JSON.stringify({ accountId: auth.account.pub }));
3068
3959
  wrote.push(MEMBERSHIP_CONFIG_KIND);
3069
3960
  }
3070
- if (wrote.length)
3961
+ if (wrote.length && !quietBoot)
3071
3962
  console.log(c.dim(`• membership: provisioned ${wrote.join(" + ")} - the data-account half needs no system-account rotation`));
3072
3963
  }
3073
3964
  catch (e) {