@cotal-ai/cli 0.100.2 → 0.101.1

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 (626) hide show
  1. package/dist/chat/chat-view.d.ts.map +1 -1
  2. package/dist/chat/chat-view.js +5 -1
  3. package/dist/chat/chat-view.js.map +1 -1
  4. package/dist/chat/engine.d.ts +2 -1
  5. package/dist/chat/engine.d.ts.map +1 -1
  6. package/dist/chat/engine.js +2 -1
  7. package/dist/chat/engine.js.map +1 -1
  8. package/dist/chat/frontend.d.ts.map +1 -1
  9. package/dist/chat/frontend.js +13 -7
  10. package/dist/chat/frontend.js.map +1 -1
  11. package/dist/chat/native-session.d.ts +22 -3
  12. package/dist/chat/native-session.d.ts.map +1 -1
  13. package/dist/chat/native-session.js +91 -19
  14. package/dist/chat/native-session.js.map +1 -1
  15. package/dist/chat/open-session.d.ts +1 -0
  16. package/dist/chat/open-session.d.ts.map +1 -1
  17. package/dist/chat/open-session.js +1 -1
  18. package/dist/chat/open-session.js.map +1 -1
  19. package/dist/chat/picker.d.ts +5 -0
  20. package/dist/chat/picker.d.ts.map +1 -1
  21. package/dist/chat/picker.js +23 -10
  22. package/dist/chat/picker.js.map +1 -1
  23. package/dist/chat/plain.d.ts.map +1 -1
  24. package/dist/chat/plain.js +36 -10
  25. package/dist/chat/plain.js.map +1 -1
  26. package/dist/chat/session.d.ts +5 -0
  27. package/dist/chat/session.d.ts.map +1 -1
  28. package/dist/chat/static-session.d.ts +1 -0
  29. package/dist/chat/static-session.d.ts.map +1 -1
  30. package/dist/chat/static-session.js +24 -8
  31. package/dist/chat/static-session.js.map +1 -1
  32. package/dist/chat/stdio-io.d.ts +2 -0
  33. package/dist/chat/stdio-io.d.ts.map +1 -1
  34. package/dist/chat/stdio-io.js +6 -6
  35. package/dist/chat/stdio-io.js.map +1 -1
  36. package/dist/chat/stdio.d.ts +3 -2
  37. package/dist/chat/stdio.d.ts.map +1 -1
  38. package/dist/chat/stdio.js +26 -25
  39. package/dist/chat/stdio.js.map +1 -1
  40. package/dist/chat/user-session.d.ts +1 -0
  41. package/dist/chat/user-session.d.ts.map +1 -1
  42. package/dist/chat/user-session.js +1 -1
  43. package/dist/chat/user-session.js.map +1 -1
  44. package/dist/chat/view.d.ts +5 -4
  45. package/dist/chat/view.d.ts.map +1 -1
  46. package/dist/chat/view.js +10 -8
  47. package/dist/chat/view.js.map +1 -1
  48. package/dist/command.d.ts +5 -0
  49. package/dist/command.d.ts.map +1 -1
  50. package/dist/command.js +295 -82
  51. package/dist/command.js.map +1 -1
  52. package/dist/commands/agents.d.ts +29 -5
  53. package/dist/commands/agents.d.ts.map +1 -1
  54. package/dist/commands/agents.js +100 -35
  55. package/dist/commands/agents.js.map +1 -1
  56. package/dist/commands/backup-maintenance.d.ts.map +1 -1
  57. package/dist/commands/backup-maintenance.js +54 -21
  58. package/dist/commands/backup-maintenance.js.map +1 -1
  59. package/dist/commands/backup-read.d.ts.map +1 -1
  60. package/dist/commands/backup-read.js +12 -15
  61. package/dist/commands/backup-read.js.map +1 -1
  62. package/dist/commands/backup-restore.d.ts.map +1 -1
  63. package/dist/commands/backup-restore.js +20 -4
  64. package/dist/commands/backup-restore.js.map +1 -1
  65. package/dist/commands/backup.d.ts.map +1 -1
  66. package/dist/commands/backup.js +156 -28
  67. package/dist/commands/backup.js.map +1 -1
  68. package/dist/commands/channel-members.d.ts +1 -1
  69. package/dist/commands/channel-members.d.ts.map +1 -1
  70. package/dist/commands/channel-members.js +115 -29
  71. package/dist/commands/channel-members.js.map +1 -1
  72. package/dist/commands/channels.d.ts +11 -1
  73. package/dist/commands/channels.d.ts.map +1 -1
  74. package/dist/commands/channels.js +109 -20
  75. package/dist/commands/channels.js.map +1 -1
  76. package/dist/commands/chat.d.ts +11 -3
  77. package/dist/commands/chat.d.ts.map +1 -1
  78. package/dist/commands/chat.js +50 -22
  79. package/dist/commands/chat.js.map +1 -1
  80. package/dist/commands/clean.d.ts +10 -5
  81. package/dist/commands/clean.d.ts.map +1 -1
  82. package/dist/commands/clean.js +245 -42
  83. package/dist/commands/clean.js.map +1 -1
  84. package/dist/commands/completion.d.ts +15 -2
  85. package/dist/commands/completion.d.ts.map +1 -1
  86. package/dist/commands/completion.js +91 -26
  87. package/dist/commands/completion.js.map +1 -1
  88. package/dist/commands/config.d.ts +24 -1
  89. package/dist/commands/config.d.ts.map +1 -1
  90. package/dist/commands/config.js +65 -13
  91. package/dist/commands/config.js.map +1 -1
  92. package/dist/commands/console.d.ts.map +1 -1
  93. package/dist/commands/console.js +5 -4
  94. package/dist/commands/console.js.map +1 -1
  95. package/dist/commands/describe.d.ts +4 -2
  96. package/dist/commands/describe.d.ts.map +1 -1
  97. package/dist/commands/describe.js +4 -4
  98. package/dist/commands/describe.js.map +1 -1
  99. package/dist/commands/doctor.d.ts +1 -1
  100. package/dist/commands/doctor.d.ts.map +1 -1
  101. package/dist/commands/doctor.js +261 -34
  102. package/dist/commands/doctor.js.map +1 -1
  103. package/dist/commands/down-manifest.d.ts.map +1 -1
  104. package/dist/commands/down-manifest.js +9 -6
  105. package/dist/commands/down-manifest.js.map +1 -1
  106. package/dist/commands/down-services.d.ts +17 -16
  107. package/dist/commands/down-services.d.ts.map +1 -1
  108. package/dist/commands/down-services.js +29 -53
  109. package/dist/commands/down-services.js.map +1 -1
  110. package/dist/commands/down.d.ts +2 -2
  111. package/dist/commands/down.d.ts.map +1 -1
  112. package/dist/commands/down.js +96 -67
  113. package/dist/commands/down.js.map +1 -1
  114. package/dist/commands/endpoint-deregister.d.ts.map +1 -1
  115. package/dist/commands/endpoint-deregister.js +2 -2
  116. package/dist/commands/endpoint-deregister.js.map +1 -1
  117. package/dist/commands/endpoint.d.ts +2 -1
  118. package/dist/commands/endpoint.d.ts.map +1 -1
  119. package/dist/commands/endpoint.js +2 -2
  120. package/dist/commands/endpoint.js.map +1 -1
  121. package/dist/commands/endpoints.d.ts +1 -0
  122. package/dist/commands/endpoints.d.ts.map +1 -1
  123. package/dist/commands/endpoints.js +20 -5
  124. package/dist/commands/endpoints.js.map +1 -1
  125. package/dist/commands/feedback.d.ts.map +1 -1
  126. package/dist/commands/feedback.js +40 -2
  127. package/dist/commands/feedback.js.map +1 -1
  128. package/dist/commands/help.d.ts.map +1 -1
  129. package/dist/commands/help.js +2 -1
  130. package/dist/commands/help.js.map +1 -1
  131. package/dist/commands/history-clear.d.ts.map +1 -1
  132. package/dist/commands/history-clear.js +67 -51
  133. package/dist/commands/history-clear.js.map +1 -1
  134. package/dist/commands/history.d.ts +17 -2
  135. package/dist/commands/history.d.ts.map +1 -1
  136. package/dist/commands/history.js +221 -34
  137. package/dist/commands/history.js.map +1 -1
  138. package/dist/commands/join.d.ts +2 -0
  139. package/dist/commands/join.d.ts.map +1 -1
  140. package/dist/commands/join.js +132 -80
  141. package/dist/commands/join.js.map +1 -1
  142. package/dist/commands/meshes-add.d.ts +19 -4
  143. package/dist/commands/meshes-add.d.ts.map +1 -1
  144. package/dist/commands/meshes-add.js +114 -15
  145. package/dist/commands/meshes-add.js.map +1 -1
  146. package/dist/commands/meshes-wizard.d.ts +1 -0
  147. package/dist/commands/meshes-wizard.d.ts.map +1 -1
  148. package/dist/commands/meshes-wizard.js +45 -13
  149. package/dist/commands/meshes-wizard.js.map +1 -1
  150. package/dist/commands/meshes.d.ts +1 -1
  151. package/dist/commands/meshes.d.ts.map +1 -1
  152. package/dist/commands/meshes.js +76 -47
  153. package/dist/commands/meshes.js.map +1 -1
  154. package/dist/commands/mint.d.ts.map +1 -1
  155. package/dist/commands/mint.js +212 -19
  156. package/dist/commands/mint.js.map +1 -1
  157. package/dist/commands/models.d.ts +5 -1
  158. package/dist/commands/models.d.ts.map +1 -1
  159. package/dist/commands/models.js +21 -13
  160. package/dist/commands/models.js.map +1 -1
  161. package/dist/commands/persona-remote.d.ts.map +1 -1
  162. package/dist/commands/persona-remote.js +24 -13
  163. package/dist/commands/persona-remote.js.map +1 -1
  164. package/dist/commands/persona.d.ts +1 -1
  165. package/dist/commands/persona.d.ts.map +1 -1
  166. package/dist/commands/persona.js +92 -23
  167. package/dist/commands/persona.js.map +1 -1
  168. package/dist/commands/personas.d.ts.map +1 -1
  169. package/dist/commands/personas.js +59 -40
  170. package/dist/commands/personas.js.map +1 -1
  171. package/dist/commands/reset-space-apply.d.ts.map +1 -1
  172. package/dist/commands/reset-space-apply.js +69 -17
  173. package/dist/commands/reset-space-apply.js.map +1 -1
  174. package/dist/commands/reset-store-apply.d.ts +16 -0
  175. package/dist/commands/reset-store-apply.d.ts.map +1 -1
  176. package/dist/commands/reset-store-apply.js +122 -23
  177. package/dist/commands/reset-store-apply.js.map +1 -1
  178. package/dist/commands/reset.d.ts.map +1 -1
  179. package/dist/commands/reset.js +8 -7
  180. package/dist/commands/reset.js.map +1 -1
  181. package/dist/commands/revoke-credential.d.ts +5 -0
  182. package/dist/commands/revoke-credential.d.ts.map +1 -0
  183. package/dist/commands/revoke-credential.js +128 -0
  184. package/dist/commands/revoke-credential.js.map +1 -0
  185. package/dist/commands/send.d.ts +11 -3
  186. package/dist/commands/send.d.ts.map +1 -1
  187. package/dist/commands/send.js +284 -47
  188. package/dist/commands/send.js.map +1 -1
  189. package/dist/commands/service-actions.d.ts +2 -1
  190. package/dist/commands/service-actions.d.ts.map +1 -1
  191. package/dist/commands/service-actions.js +117 -21
  192. package/dist/commands/service-actions.js.map +1 -1
  193. package/dist/commands/service-log-follow.js +1 -1
  194. package/dist/commands/service-log-follow.js.map +1 -1
  195. package/dist/commands/service-registry.d.ts +1 -1
  196. package/dist/commands/service-registry.d.ts.map +1 -1
  197. package/dist/commands/service-registry.js +74 -30
  198. package/dist/commands/service-registry.js.map +1 -1
  199. package/dist/commands/service-set-stop.d.ts.map +1 -1
  200. package/dist/commands/service-set-stop.js +3 -2
  201. package/dist/commands/service-set-stop.js.map +1 -1
  202. package/dist/commands/setup-start.d.ts.map +1 -1
  203. package/dist/commands/setup-start.js +46 -5
  204. package/dist/commands/setup-start.js.map +1 -1
  205. package/dist/commands/setup.d.ts.map +1 -1
  206. package/dist/commands/setup.js +28 -13
  207. package/dist/commands/setup.js.map +1 -1
  208. package/dist/commands/space-delete.d.ts.map +1 -1
  209. package/dist/commands/space-delete.js +130 -41
  210. package/dist/commands/space-delete.js.map +1 -1
  211. package/dist/commands/space-registration.d.ts +13 -6
  212. package/dist/commands/space-registration.d.ts.map +1 -1
  213. package/dist/commands/space-registration.js +167 -46
  214. package/dist/commands/space-registration.js.map +1 -1
  215. package/dist/commands/space.d.ts +15 -1
  216. package/dist/commands/space.d.ts.map +1 -1
  217. package/dist/commands/space.js +66 -24
  218. package/dist/commands/space.js.map +1 -1
  219. package/dist/commands/spawn-preview.d.ts.map +1 -1
  220. package/dist/commands/spawn-preview.js +48 -10
  221. package/dist/commands/spawn-preview.js.map +1 -1
  222. package/dist/commands/spawn.d.ts +36 -13
  223. package/dist/commands/spawn.d.ts.map +1 -1
  224. package/dist/commands/spawn.js +306 -130
  225. package/dist/commands/spawn.js.map +1 -1
  226. package/dist/commands/stack-down.d.ts +9 -3
  227. package/dist/commands/stack-down.d.ts.map +1 -1
  228. package/dist/commands/stack-down.js +348 -64
  229. package/dist/commands/stack-down.js.map +1 -1
  230. package/dist/commands/stack-gone.d.ts +17 -0
  231. package/dist/commands/stack-gone.d.ts.map +1 -0
  232. package/dist/commands/stack-gone.js +218 -0
  233. package/dist/commands/stack-gone.js.map +1 -0
  234. package/dist/commands/stack-up.d.ts +64 -4
  235. package/dist/commands/stack-up.d.ts.map +1 -1
  236. package/dist/commands/stack-up.js +482 -55
  237. package/dist/commands/stack-up.js.map +1 -1
  238. package/dist/commands/status.d.ts +76 -2
  239. package/dist/commands/status.d.ts.map +1 -1
  240. package/dist/commands/status.js +550 -112
  241. package/dist/commands/status.js.map +1 -1
  242. package/dist/commands/team-agent-apply.d.ts.map +1 -1
  243. package/dist/commands/team-agent-apply.js +4 -3
  244. package/dist/commands/team-agent-apply.js.map +1 -1
  245. package/dist/commands/team-agent-remove.d.ts.map +1 -1
  246. package/dist/commands/team-agent-remove.js +4 -4
  247. package/dist/commands/team-agent-remove.js.map +1 -1
  248. package/dist/commands/team-boot-controller.d.ts.map +1 -1
  249. package/dist/commands/team-boot-controller.js +8 -2
  250. package/dist/commands/team-boot-controller.js.map +1 -1
  251. package/dist/commands/team-channel-remove.d.ts.map +1 -1
  252. package/dist/commands/team-channel-remove.js +26 -10
  253. package/dist/commands/team-channel-remove.js.map +1 -1
  254. package/dist/commands/team-deploy-apply.d.ts.map +1 -1
  255. package/dist/commands/team-deploy-apply.js +4 -3
  256. package/dist/commands/team-deploy-apply.js.map +1 -1
  257. package/dist/commands/team-mixed-remove.js +5 -5
  258. package/dist/commands/team-mixed-remove.js.map +1 -1
  259. package/dist/commands/team.d.ts.map +1 -1
  260. package/dist/commands/team.js +94 -32
  261. package/dist/commands/team.js.map +1 -1
  262. package/dist/commands/telemetry.d.ts.map +1 -1
  263. package/dist/commands/telemetry.js +3 -1
  264. package/dist/commands/telemetry.js.map +1 -1
  265. package/dist/commands/topology.d.ts.map +1 -1
  266. package/dist/commands/topology.js +11 -7
  267. package/dist/commands/topology.js.map +1 -1
  268. package/dist/commands/up.d.ts +6 -6
  269. package/dist/commands/up.d.ts.map +1 -1
  270. package/dist/commands/up.js +963 -240
  271. package/dist/commands/up.js.map +1 -1
  272. package/dist/commands/update.d.ts.map +1 -1
  273. package/dist/commands/update.js +9 -3
  274. package/dist/commands/update.js.map +1 -1
  275. package/dist/commands/use.d.ts +5 -1
  276. package/dist/commands/use.d.ts.map +1 -1
  277. package/dist/commands/use.js +55 -12
  278. package/dist/commands/use.js.map +1 -1
  279. package/dist/commands/watch.d.ts +4 -1
  280. package/dist/commands/watch.d.ts.map +1 -1
  281. package/dist/commands/watch.js +15 -3
  282. package/dist/commands/watch.js.map +1 -1
  283. package/dist/commands/who.d.ts +2 -0
  284. package/dist/commands/who.d.ts.map +1 -1
  285. package/dist/commands/who.js +18 -5
  286. package/dist/commands/who.js.map +1 -1
  287. package/dist/commands/whoami.d.ts +44 -5
  288. package/dist/commands/whoami.d.ts.map +1 -1
  289. package/dist/commands/whoami.js +168 -16
  290. package/dist/commands/whoami.js.map +1 -1
  291. package/dist/console/app.d.ts +1 -1
  292. package/dist/console/app.d.ts.map +1 -1
  293. package/dist/console/app.js +15 -9
  294. package/dist/console/app.js.map +1 -1
  295. package/dist/console/launch.d.ts +25 -0
  296. package/dist/console/launch.d.ts.map +1 -0
  297. package/dist/console/launch.js +56 -0
  298. package/dist/console/launch.js.map +1 -0
  299. package/dist/console/ui/CommandPalette.d.ts +5 -4
  300. package/dist/console/ui/CommandPalette.d.ts.map +1 -1
  301. package/dist/console/ui/CommandPalette.js +136 -45
  302. package/dist/console/ui/CommandPalette.js.map +1 -1
  303. package/dist/console/ui/Help.js +1 -1
  304. package/dist/console/ui/Help.js.map +1 -1
  305. package/dist/console/ui/Modal.d.ts +10 -0
  306. package/dist/console/ui/Modal.d.ts.map +1 -0
  307. package/dist/console/ui/Modal.js +8 -0
  308. package/dist/console/ui/Modal.js.map +1 -0
  309. package/dist/console/ui/NewAgent.d.ts +14 -0
  310. package/dist/console/ui/NewAgent.d.ts.map +1 -0
  311. package/dist/console/ui/NewAgent.js +114 -0
  312. package/dist/console/ui/NewAgent.js.map +1 -0
  313. package/dist/console/ui/StatusBar.d.ts +1 -2
  314. package/dist/console/ui/StatusBar.d.ts.map +1 -1
  315. package/dist/console/ui/StatusBar.js +6 -8
  316. package/dist/console/ui/StatusBar.js.map +1 -1
  317. package/dist/console/ui/topo/Map.d.ts.map +1 -1
  318. package/dist/console/ui/topo/Map.js +1 -2
  319. package/dist/console/ui/topo/Map.js.map +1 -1
  320. package/dist/console/ui/topo/Matrix.js +2 -2
  321. package/dist/console/ui/topo/Matrix.js.map +1 -1
  322. package/dist/console/ui/topo/Sequence.d.ts.map +1 -1
  323. package/dist/console/ui/topo/Sequence.js +5 -4
  324. package/dist/console/ui/topo/Sequence.js.map +1 -1
  325. package/dist/console/ui/topo/model.d.ts +2 -1
  326. package/dist/console/ui/topo/model.d.ts.map +1 -1
  327. package/dist/console/ui/topo/model.js +4 -3
  328. package/dist/console/ui/topo/model.js.map +1 -1
  329. package/dist/exec-endpoint/service-adapter.d.ts.map +1 -1
  330. package/dist/exec-endpoint/service-adapter.js +13 -3
  331. package/dist/exec-endpoint/service-adapter.js.map +1 -1
  332. package/dist/ext-loader.d.ts +4 -0
  333. package/dist/ext-loader.d.ts.map +1 -1
  334. package/dist/ext-loader.js +6 -0
  335. package/dist/ext-loader.js.map +1 -1
  336. package/dist/help.d.ts.map +1 -1
  337. package/dist/help.js +44 -23
  338. package/dist/help.js.map +1 -1
  339. package/dist/index.d.ts.map +1 -1
  340. package/dist/index.js +59 -54
  341. package/dist/index.js.map +1 -1
  342. package/dist/lib/agent-skills.d.ts.map +1 -1
  343. package/dist/lib/agent-skills.js +2 -1
  344. package/dist/lib/agent-skills.js.map +1 -1
  345. package/dist/lib/attach-client.js +2 -2
  346. package/dist/lib/attach-client.js.map +1 -1
  347. package/dist/lib/backup-artifact.d.ts +29 -8
  348. package/dist/lib/backup-artifact.d.ts.map +1 -1
  349. package/dist/lib/backup-artifact.js +147 -26
  350. package/dist/lib/backup-artifact.js.map +1 -1
  351. package/dist/lib/broker-service.d.ts +27 -3
  352. package/dist/lib/broker-service.d.ts.map +1 -1
  353. package/dist/lib/broker-service.js +142 -29
  354. package/dist/lib/broker-service.js.map +1 -1
  355. package/dist/lib/broker-store-health.d.ts +89 -0
  356. package/dist/lib/broker-store-health.d.ts.map +1 -0
  357. package/dist/lib/broker-store-health.js +171 -0
  358. package/dist/lib/broker-store-health.js.map +1 -0
  359. package/dist/lib/cancel.d.ts +4 -4
  360. package/dist/lib/cancel.d.ts.map +1 -1
  361. package/dist/lib/cancel.js +5 -5
  362. package/dist/lib/cancel.js.map +1 -1
  363. package/dist/lib/completion-install.d.ts +11 -2
  364. package/dist/lib/completion-install.d.ts.map +1 -1
  365. package/dist/lib/completion-install.js +79 -21
  366. package/dist/lib/completion-install.js.map +1 -1
  367. package/dist/lib/completion-scripts.d.ts.map +1 -1
  368. package/dist/lib/completion-scripts.js +2 -2
  369. package/dist/lib/completion-scripts.js.map +1 -1
  370. package/dist/lib/completion.d.ts +5 -1
  371. package/dist/lib/completion.d.ts.map +1 -1
  372. package/dist/lib/completion.js +10 -0
  373. package/dist/lib/completion.js.map +1 -1
  374. package/dist/lib/concrete-channel.d.ts +6 -0
  375. package/dist/lib/concrete-channel.d.ts.map +1 -0
  376. package/dist/lib/concrete-channel.js +17 -0
  377. package/dist/lib/concrete-channel.js.map +1 -0
  378. package/dist/lib/confirmation-required.d.ts +3 -12
  379. package/dist/lib/confirmation-required.d.ts.map +1 -1
  380. package/dist/lib/confirmation-required.js +9 -8
  381. package/dist/lib/confirmation-required.js.map +1 -1
  382. package/dist/lib/connect.d.ts +9 -0
  383. package/dist/lib/connect.d.ts.map +1 -1
  384. package/dist/lib/connect.js +27 -0
  385. package/dist/lib/connect.js.map +1 -1
  386. package/dist/lib/control.d.ts +42 -12
  387. package/dist/lib/control.d.ts.map +1 -1
  388. package/dist/lib/control.js +148 -34
  389. package/dist/lib/control.js.map +1 -1
  390. package/dist/lib/controller-restore.d.ts.map +1 -1
  391. package/dist/lib/controller-restore.js +12 -7
  392. package/dist/lib/controller-restore.js.map +1 -1
  393. package/dist/lib/credential-authority.d.ts.map +1 -1
  394. package/dist/lib/credential-authority.js +3 -0
  395. package/dist/lib/credential-authority.js.map +1 -1
  396. package/dist/lib/credential-exports.d.ts +17 -0
  397. package/dist/lib/credential-exports.d.ts.map +1 -0
  398. package/dist/lib/credential-exports.js +21 -0
  399. package/dist/lib/credential-exports.js.map +1 -0
  400. package/dist/lib/debug-flag.d.ts +4 -0
  401. package/dist/lib/debug-flag.d.ts.map +1 -0
  402. package/dist/lib/debug-flag.js +7 -0
  403. package/dist/lib/debug-flag.js.map +1 -0
  404. package/dist/lib/default-persona.d.ts +2 -0
  405. package/dist/lib/default-persona.d.ts.map +1 -1
  406. package/dist/lib/default-persona.js +2 -0
  407. package/dist/lib/default-persona.js.map +1 -1
  408. package/dist/lib/delivery-proc.d.ts +1 -1
  409. package/dist/lib/delivery-proc.d.ts.map +1 -1
  410. package/dist/lib/delivery-proc.js +5 -4
  411. package/dist/lib/delivery-proc.js.map +1 -1
  412. package/dist/lib/delivery-responder.d.ts +7 -3
  413. package/dist/lib/delivery-responder.d.ts.map +1 -1
  414. package/dist/lib/delivery-responder.js +8 -4
  415. package/dist/lib/delivery-responder.js.map +1 -1
  416. package/dist/lib/denied-write.d.ts +8 -0
  417. package/dist/lib/denied-write.d.ts.map +1 -0
  418. package/dist/lib/denied-write.js +24 -0
  419. package/dist/lib/denied-write.js.map +1 -0
  420. package/dist/lib/endpoint-capability-gates.js +2 -2
  421. package/dist/lib/endpoint-capability-gates.js.map +1 -1
  422. package/dist/lib/flag-value-refusal.d.ts +8 -0
  423. package/dist/lib/flag-value-refusal.d.ts.map +1 -0
  424. package/dist/lib/flag-value-refusal.js +10 -0
  425. package/dist/lib/flag-value-refusal.js.map +1 -0
  426. package/dist/lib/install-umask.d.ts +5 -0
  427. package/dist/lib/install-umask.d.ts.map +1 -1
  428. package/dist/lib/install-umask.js +25 -0
  429. package/dist/lib/install-umask.js.map +1 -1
  430. package/dist/lib/interrupt-notice.d.ts +23 -1
  431. package/dist/lib/interrupt-notice.d.ts.map +1 -1
  432. package/dist/lib/interrupt-notice.js +27 -6
  433. package/dist/lib/interrupt-notice.js.map +1 -1
  434. package/dist/lib/interrupt-report.d.ts +7 -0
  435. package/dist/lib/interrupt-report.d.ts.map +1 -0
  436. package/dist/lib/interrupt-report.js +24 -0
  437. package/dist/lib/interrupt-report.js.map +1 -0
  438. package/dist/lib/isolated-broker.d.ts +1 -1
  439. package/dist/lib/isolated-broker.d.ts.map +1 -1
  440. package/dist/lib/isolated-broker.js +17 -8
  441. package/dist/lib/isolated-broker.js.map +1 -1
  442. package/dist/lib/legacy-start.d.ts +8 -6
  443. package/dist/lib/legacy-start.d.ts.map +1 -1
  444. package/dist/lib/legacy-start.js +36 -36
  445. package/dist/lib/legacy-start.js.map +1 -1
  446. package/dist/lib/manager-choice.d.ts +92 -4
  447. package/dist/lib/manager-choice.d.ts.map +1 -1
  448. package/dist/lib/manager-choice.js +338 -23
  449. package/dist/lib/manager-choice.js.map +1 -1
  450. package/dist/lib/manager-proc.d.ts.map +1 -1
  451. package/dist/lib/manager-proc.js +7 -6
  452. package/dist/lib/manager-proc.js.map +1 -1
  453. package/dist/lib/manifest/index.d.ts +5 -1
  454. package/dist/lib/manifest/index.d.ts.map +1 -1
  455. package/dist/lib/manifest/index.js +50 -5
  456. package/dist/lib/manifest/index.js.map +1 -1
  457. package/dist/lib/manifest/preflight.d.ts +4 -0
  458. package/dist/lib/manifest/preflight.d.ts.map +1 -1
  459. package/dist/lib/manifest/preflight.js +18 -1
  460. package/dist/lib/manifest/preflight.js.map +1 -1
  461. package/dist/lib/manifest/resolve.d.ts +8 -0
  462. package/dist/lib/manifest/resolve.d.ts.map +1 -1
  463. package/dist/lib/manifest/resolve.js +104 -11
  464. package/dist/lib/manifest/resolve.js.map +1 -1
  465. package/dist/lib/missing-flags.js +1 -1
  466. package/dist/lib/missing-flags.js.map +1 -1
  467. package/dist/lib/nats-bin.d.ts +28 -5
  468. package/dist/lib/nats-bin.d.ts.map +1 -1
  469. package/dist/lib/nats-bin.js +85 -7
  470. package/dist/lib/nats-bin.js.map +1 -1
  471. package/dist/lib/nearest-word.d.ts +14 -0
  472. package/dist/lib/nearest-word.d.ts.map +1 -0
  473. package/dist/lib/nearest-word.js +76 -0
  474. package/dist/lib/nearest-word.js.map +1 -0
  475. package/dist/lib/no-expiry-record.d.ts +8 -0
  476. package/dist/lib/no-expiry-record.d.ts.map +1 -0
  477. package/dist/lib/no-expiry-record.js +27 -0
  478. package/dist/lib/no-expiry-record.js.map +1 -0
  479. package/dist/lib/paths.d.ts +31 -0
  480. package/dist/lib/paths.d.ts.map +1 -1
  481. package/dist/lib/paths.js +92 -2
  482. package/dist/lib/paths.js.map +1 -1
  483. package/dist/lib/persona-files.d.ts +29 -6
  484. package/dist/lib/persona-files.d.ts.map +1 -1
  485. package/dist/lib/persona-files.js +179 -36
  486. package/dist/lib/persona-files.js.map +1 -1
  487. package/dist/lib/personas.d.ts +18 -1
  488. package/dist/lib/personas.d.ts.map +1 -1
  489. package/dist/lib/personas.js +65 -6
  490. package/dist/lib/personas.js.map +1 -1
  491. package/dist/lib/prompts.d.ts +7 -1
  492. package/dist/lib/prompts.d.ts.map +1 -1
  493. package/dist/lib/prompts.js +43 -3
  494. package/dist/lib/prompts.js.map +1 -1
  495. package/dist/lib/registry-errors.d.ts +2 -1
  496. package/dist/lib/registry-errors.d.ts.map +1 -1
  497. package/dist/lib/registry-errors.js +6 -2
  498. package/dist/lib/registry-errors.js.map +1 -1
  499. package/dist/lib/reset-space-plan.d.ts +2 -0
  500. package/dist/lib/reset-space-plan.d.ts.map +1 -1
  501. package/dist/lib/reset-space-plan.js +1 -1
  502. package/dist/lib/reset-space-plan.js.map +1 -1
  503. package/dist/lib/restore.d.ts +45 -3
  504. package/dist/lib/restore.d.ts.map +1 -1
  505. package/dist/lib/restore.js +233 -39
  506. package/dist/lib/restore.js.map +1 -1
  507. package/dist/lib/rolled-back-runs.d.ts +36 -0
  508. package/dist/lib/rolled-back-runs.d.ts.map +1 -0
  509. package/dist/lib/rolled-back-runs.js +96 -0
  510. package/dist/lib/rolled-back-runs.js.map +1 -0
  511. package/dist/lib/service-custody-win32.d.ts +25 -0
  512. package/dist/lib/service-custody-win32.d.ts.map +1 -0
  513. package/dist/lib/service-custody-win32.js +67 -0
  514. package/dist/lib/service-custody-win32.js.map +1 -0
  515. package/dist/lib/service-definitions.d.ts +16 -3
  516. package/dist/lib/service-definitions.d.ts.map +1 -1
  517. package/dist/lib/service-definitions.js +99 -27
  518. package/dist/lib/service-definitions.js.map +1 -1
  519. package/dist/lib/service-instances.d.ts +46 -5
  520. package/dist/lib/service-instances.d.ts.map +1 -1
  521. package/dist/lib/service-instances.js +112 -18
  522. package/dist/lib/service-instances.js.map +1 -1
  523. package/dist/lib/service-journal.js +1 -1
  524. package/dist/lib/service-journal.js.map +1 -1
  525. package/dist/lib/service-presets.d.ts.map +1 -1
  526. package/dist/lib/service-presets.js +16 -0
  527. package/dist/lib/service-presets.js.map +1 -1
  528. package/dist/lib/service-process.d.ts +53 -15
  529. package/dist/lib/service-process.d.ts.map +1 -1
  530. package/dist/lib/service-process.js +533 -86
  531. package/dist/lib/service-process.js.map +1 -1
  532. package/dist/lib/service-systemd-install.js +1 -1
  533. package/dist/lib/service-systemd-install.js.map +1 -1
  534. package/dist/lib/space-streams.d.ts +18 -0
  535. package/dist/lib/space-streams.d.ts.map +1 -0
  536. package/dist/lib/space-streams.js +35 -0
  537. package/dist/lib/space-streams.js.map +1 -0
  538. package/dist/lib/spawn-defaults.d.ts +25 -1
  539. package/dist/lib/spawn-defaults.d.ts.map +1 -1
  540. package/dist/lib/spawn-defaults.js +37 -1
  541. package/dist/lib/spawn-defaults.js.map +1 -1
  542. package/dist/lib/stack-journal.d.ts +157 -14
  543. package/dist/lib/stack-journal.d.ts.map +1 -1
  544. package/dist/lib/stack-journal.js +406 -49
  545. package/dist/lib/stack-journal.js.map +1 -1
  546. package/dist/lib/stack-listeners.d.ts +17 -0
  547. package/dist/lib/stack-listeners.d.ts.map +1 -0
  548. package/dist/lib/stack-listeners.js +54 -0
  549. package/dist/lib/stack-listeners.js.map +1 -0
  550. package/dist/lib/stack-members.d.ts +13 -0
  551. package/dist/lib/stack-members.d.ts.map +1 -0
  552. package/dist/lib/stack-members.js +24 -0
  553. package/dist/lib/stack-members.js.map +1 -0
  554. package/dist/lib/stack-resume.d.ts.map +1 -1
  555. package/dist/lib/stack-resume.js +5 -2
  556. package/dist/lib/stack-resume.js.map +1 -1
  557. package/dist/lib/stack-runs.d.ts +34 -0
  558. package/dist/lib/stack-runs.d.ts.map +1 -0
  559. package/dist/lib/stack-runs.js +75 -0
  560. package/dist/lib/stack-runs.js.map +1 -0
  561. package/dist/lib/status.d.ts +11 -0
  562. package/dist/lib/status.d.ts.map +1 -1
  563. package/dist/lib/status.js +4 -5
  564. package/dist/lib/status.js.map +1 -1
  565. package/dist/lib/stdout-owner.d.ts +12 -3
  566. package/dist/lib/stdout-owner.d.ts.map +1 -1
  567. package/dist/lib/stdout-owner.js +33 -5
  568. package/dist/lib/stdout-owner.js.map +1 -1
  569. package/dist/lib/store-dir.d.ts +68 -4
  570. package/dist/lib/store-dir.d.ts.map +1 -1
  571. package/dist/lib/store-dir.js +253 -17
  572. package/dist/lib/store-dir.js.map +1 -1
  573. package/dist/lib/team-additive-attempt.d.ts +1 -1
  574. package/dist/lib/team-channel-removal.d.ts.map +1 -1
  575. package/dist/lib/team-channel-removal.js +4 -0
  576. package/dist/lib/team-channel-removal.js.map +1 -1
  577. package/dist/lib/team-deploy-inspection.d.ts +13 -0
  578. package/dist/lib/team-deploy-inspection.d.ts.map +1 -1
  579. package/dist/lib/team-deploy-inspection.js +12 -0
  580. package/dist/lib/team-deploy-inspection.js.map +1 -1
  581. package/dist/lib/team-text.d.ts +6 -0
  582. package/dist/lib/team-text.d.ts.map +1 -0
  583. package/dist/lib/team-text.js +36 -0
  584. package/dist/lib/team-text.js.map +1 -0
  585. package/dist/lib/transient.d.ts +14 -8
  586. package/dist/lib/transient.d.ts.map +1 -1
  587. package/dist/lib/transient.js +72 -11
  588. package/dist/lib/transient.js.map +1 -1
  589. package/dist/lib/unusable-file.d.ts +13 -0
  590. package/dist/lib/unusable-file.d.ts.map +1 -0
  591. package/dist/lib/unusable-file.js +12 -0
  592. package/dist/lib/unusable-file.js.map +1 -0
  593. package/dist/lib/up-report.d.ts +6 -0
  594. package/dist/lib/up-report.d.ts.map +1 -1
  595. package/dist/lib/up-report.js +13 -0
  596. package/dist/lib/up-report.js.map +1 -1
  597. package/dist/lib/verdict.d.ts +14 -0
  598. package/dist/lib/verdict.d.ts.map +1 -0
  599. package/dist/lib/verdict.js +15 -0
  600. package/dist/lib/verdict.js.map +1 -0
  601. package/dist/managed-handoff.d.ts +11 -6
  602. package/dist/managed-handoff.d.ts.map +1 -1
  603. package/dist/managed-handoff.js +27 -18
  604. package/dist/managed-handoff.js.map +1 -1
  605. package/dist/render.d.ts +5 -2
  606. package/dist/render.d.ts.map +1 -1
  607. package/dist/render.js +44 -10
  608. package/dist/render.js.map +1 -1
  609. package/dist/telemetry.d.ts +4 -3
  610. package/dist/telemetry.d.ts.map +1 -1
  611. package/dist/telemetry.js +14 -6
  612. package/dist/telemetry.js.map +1 -1
  613. package/dist/ui.d.ts +3 -2
  614. package/dist/ui.d.ts.map +1 -1
  615. package/dist/ui.js +6 -4
  616. package/dist/ui.js.map +1 -1
  617. package/dist/view/mesh-view.d.ts.map +1 -1
  618. package/dist/view/mesh-view.js +4 -1
  619. package/dist/view/mesh-view.js.map +1 -1
  620. package/dist/watch-data.d.ts +9 -1
  621. package/dist/watch-data.d.ts.map +1 -1
  622. package/dist/watch-data.js +17 -3
  623. package/dist/watch-data.js.map +1 -1
  624. package/dist/watch-json.js +4 -3
  625. package/dist/watch-json.js.map +1 -1
  626. package/package.json +5 -5
@@ -1,8 +1,8 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
- import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
4
- import { isAbsolute, join, resolve } from "node:path";
5
- import { CommandFailure, assertRecordIdentity, canonicalRoot, commandIsCotalSupervisor, isCommandFailure, maintenanceAdmitsStackWork, readMaintenanceJournal, readProcessCommand, readServiceStopRequest, resolveNativeServiceTarget, resolveOnPath, serviceAdapterReadiness, serviceMetadataDigest, spaceKey, serviceAdapterKernelStopPlan, serviceAdapterKernelStopResult, serviceAdapterStopPlan, serviceAdapterStopAbandonment, serviceAdapterStopRefusal, serviceAdapterStopResult, isWorkspaceTargetError, targetErrorCode, workspaceErrorParts } from "@cotal-ai/workspace";
3
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, renameSync, unlinkSync } from "node:fs";
4
+ import { basename, isAbsolute, join, resolve } from "node:path";
5
+ import { CommandFailure, assertRecordIdentity, shellPath, boundedValue, canonicalRoot, commandIsCotalSupervisor, isCommandFailure, maintenanceAdmitsStackWork, readMaintenanceJournal, readProcessCommand, readServiceStopRequest, resolveNativeServiceTarget, loopbackListeners, processGroupMembers, processGroupOf, serviceAdapterReadiness, serviceMetadataDigest, spaceKey, serviceAdapterKernelStopPlan, serviceAdapterKernelStopResult, serviceAdapterStopPlan, serviceAdapterStopAbandonment, serviceAdapterStopRefusal, serviceAdapterStopResult, isWorkspaceTargetError, oneLine, targetErrorCode, workspaceErrorParts, localRecordAccess } from "@cotal-ai/workspace";
6
6
  import { refuseRecordedSupervisor } from "./service-supervision.js";
7
7
  import { serviceInstallIntents } from "./service-install-intent.js";
8
8
  import { serviceUninstallIntents } from "./service-uninstall-intent.js";
@@ -11,10 +11,16 @@ import { selfArgv } from "./self-exec.js";
11
11
  import { loadServiceAdapter, resolveServiceAdapter, sameServiceAdapterPin } from "./service-adapters.js";
12
12
  import { serviceDefinitionStore, validateServiceDefinition } from "./service-definitions.js";
13
13
  import { instanceProjection, observeServiceProcess, processServiceHost, requireProcessIdentity, serviceInstances, serviceInstanceStore } from "./service-instances.js";
14
- import { maintenanceStackView } from "./stack-journal.js";
14
+ import { maintenanceStackView, STACK_DEFINITION, stackMemberRecord } from "./stack-journal.js";
15
+ import { askCustodian, custodiedPlatform, custodyLog, removeCustodyCapability, startCustodiedService } from "./service-custody-win32.js";
15
16
  export const PROCESS_SERVICE_CAPABILITIES = Object.freeze({ multiInstance: true, foreground: true, logs: true, install: false });
16
17
  const delay = (ms) => new Promise((done) => setTimeout(done, ms));
18
+ /** How long a launch with process readiness waits for an immediate exit before it reports the process running. */
19
+ const PROCESS_SETTLE_MS = 1000;
17
20
  const gone = (state) => state === "gone" || state === "previous-boot" || state === "foreign-pid";
21
+ /** A log this account may read and append to. Windows protects it with the access list Cotal sets
22
+ * when it creates the file and has no POSIX owner or mode to check, as for every local record. */
23
+ const privateLog = (info) => info.isFile() && (localRecordAccess() === "windows-acl" || info.uid === process.getuid() && (info.mode & 0o077) === 0);
18
24
  /** A record with no creation pin whose own state says no child exists: its launch failed before
19
25
  * a process did. There is nothing to stop. */
20
26
  const neverLaunched = (value) => !value.process && gone(observeServiceProcess(value));
@@ -80,14 +86,17 @@ export function retainedStopRequest(value) {
80
86
  * it has removed the request and released the reservation, and the record returns to what its
81
87
  * process shows, as after a refusal within the call. A record left `stopping` by a stopper that
82
88
  * exited before it published a request handed the child nothing, so it also returns to what its
83
- * process shows, as a stop that published nothing does within its call. Any other record, including
84
- * one whose adapter confirms less, is returned unchanged. */
89
+ * process shows, as a stop that published nothing does within its call. A signal stop whose
90
+ * exact process still runs (see {@link resumableSignalStop}) returns to `running`. Any other record,
91
+ * including one whose adapter confirms less, is returned unchanged. */
85
92
  export async function settleRetainedNativeStop(definition, row) {
86
93
  const value = row.record.value, launch = definition.record.value.launch, retained = retainedStopRequest(value);
87
94
  if (value.nativeStopRequired && value.process && value.state === "stopping" && !retained) {
88
95
  const observed = observeServiceProcess(value);
89
96
  return transition(row, { state: observed === "running" ? "running" : gone(observed) ? "failed" : "unknown", readiness: "not-checked" });
90
97
  }
98
+ if (resumableSignalStop(value))
99
+ return transition(row, { state: "running", readiness: "not-checked" });
91
100
  if (!retained || retained.publication !== "published" || launch.type !== "adapter" || !value.process)
92
101
  return row;
93
102
  const declared = resolveServiceAdapter(launch.adapter, launch.options);
@@ -108,6 +117,13 @@ export async function settleRetainedNativeStop(definition, row) {
108
117
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the adapter's settlement did not answer the retained request and its exact process exit; the record was kept", { target: instanceProjection(row) });
109
118
  return transition(row, { state: "stopped", requestId: retained.requestId, readiness: "not-checked", nativeStop: result });
110
119
  }
120
+ /** Whether {@link settleRetainedNativeStop} may change this record before a classification reads it:
121
+ * a native `stopping` record that published no request, a signal stop whose process still runs, or a
122
+ * published native stop, which only its adapter's receipts decide. */
123
+ export function retainedStopMaySettle(value) {
124
+ const retained = retainedStopRequest(value);
125
+ return value.nativeStopRequired && value.process !== undefined && value.state === "stopping" && !retained || resumableSignalStop(value) || retained?.publication === "published";
126
+ }
111
127
  /** Abandon the native stop `requestId` this record retains, on an operator's explicit request. The
112
128
  * caller holds the definition's writer lock. The adapter refuses unless no receipt settles the
113
129
  * request and its exact process and the stopper that published it have both exited; it then removes
@@ -133,6 +149,14 @@ export async function abandonRetainedNativeStop(definition, row, requestId) {
133
149
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the adapter's abandonment did not retire the request of an exited process; the record was kept", { target });
134
150
  return { row: transition(row, { state: "failed", readiness: "not-checked" }), abandonment };
135
151
  }
152
+ /** A broker's kernel-exit stop or a generic process stop that its stopper left `stopping` while that
153
+ * exact process still runs. Such a stop records `stopping` before it signals, so a stopper cut off
154
+ * in between signalled nothing, and no exit was observed as its own either way. Under the
155
+ * definition's writer lock its stopper has exited, so the record returns to `running` and the next
156
+ * stop signals the process again. */
157
+ export function resumableSignalStop(value) {
158
+ return !value.nativeStopRequired && value.state === "stopping" && value.process !== undefined && observeServiceProcess(value) === "running";
159
+ }
136
160
  /** A broker's kernel-exit stop or a generic process stop that its stopper left `stopping` when it
137
161
  * exited before it observed the exit, once that exact process is gone. Only an operator abandons it. */
138
162
  export function abandonableSignalStop(value) {
@@ -150,6 +174,26 @@ export function abandonRetainedSignalStop(row, requestId) {
150
174
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "the process this stop request names still runs; nothing was abandoned", { target });
151
175
  return transition(row, { state: "failed", readiness: "not-checked" });
152
176
  }
177
+ /** Record `failed`, on an operator's explicit request, a launch whose record names no process: its
178
+ * launcher ended after it recorded the launch and before it recorded the child. The caller holds the
179
+ * definition's writer lock, which that launcher held, so it has exited. A child it spawned without
180
+ * recording is not excluded, and nothing here looks for one. */
181
+ export function abandonUnresolvedLaunch(row) {
182
+ if (observeServiceProcess(row.record.value) !== "unresolved-launch")
183
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "this instance's launch is not unresolved: its record names a process or a settled state; nothing was abandoned", { target: instanceProjection(row) });
184
+ return transition(row, { state: "failed", readiness: "not-checked" });
185
+ }
186
+ /** What an interrupt records for each launch this process recorded and has not yet pinned to its child. */
187
+ const unpinnedLaunches = new Set();
188
+ /** For a command that ends itself on an interrupt: record each launch it has not yet pinned to its
189
+ * child. One with no spawned child is recorded `failed`. One whose child was spawned is recorded with
190
+ * that child's identity; when that cannot be read, it is recorded `failed` with the exit once the
191
+ * child has exited and `unknown` before, as a failed pin is. Without this, the record names no
192
+ * process, and only `down --abandon-launch` resolves it. */
193
+ export function settleInterruptedLaunches() {
194
+ for (const settle of unpinnedLaunches)
195
+ settle();
196
+ }
153
197
  /** The refusal for a retained native stop, made before any readiness probe, stop request or record
154
198
  * write. This command has no effect, so it is refused; only the earlier stop's outcome is unknown. A
155
199
  * request file that does not read as this launch's own is named an unknown publication. */
@@ -182,8 +226,18 @@ export function selectServiceInstance(rows, id, allowMissing = false) {
182
226
  return undefined;
183
227
  throw new CommandFailure("refused", "TARGET_NOT_FOUND", "no instance is recorded for this service definition");
184
228
  }
185
- if (rows.length !== 1)
186
- throw new CommandFailure("refused", "TARGET_AMBIGUOUS", `this definition has several instance records; choose --instance with one full ID: ${rows.map((row) => row.name).join(", ")}`, { target: { candidates: rows.map((row) => row.name) } });
229
+ if (rows.length !== 1) {
230
+ // Each record is named with its state, and one whose process is gone with the command that
231
+ // clears it. A record still marked running after its process exited reads as exited.
232
+ const { definition, space } = rows[0].record.value;
233
+ const ended = (row) => gone(observeServiceProcess(row.record.value));
234
+ const state = (row) => ended(row) && UNSETTLED_RUN.includes(row.record.value.state) ? "exited" : row.record.value.state;
235
+ const clear = rows.filter(ended).map((row) => `cotal service remove ${definition} --instance ${row.name} --space ${space} --yes`);
236
+ throw new CommandFailure("refused", "TARGET_AMBIGUOUS", `this definition has several instance records; choose --instance with one full ID: ${rows.map((row) => row.name).join(", ")}`, {
237
+ target: { candidates: rows.map((row) => row.name) },
238
+ remedy: `pass --instance with one of ${rows.map((row) => `${row.name} (${state(row)})`).join(", ")}${clear.length ? `; clear a stopped record you no longer need with ${clear.join("; ")}` : ""}`,
239
+ });
240
+ }
187
241
  return rows[0];
188
242
  }
189
243
  function sameIncarnation(before, after) {
@@ -201,21 +255,25 @@ function executable(definition) {
201
255
  if (definition.launch.type !== "process")
202
256
  throw new CommandFailure("refused", "UNSUPPORTED", "this driver accepts process definitions, not adapter options");
203
257
  const source = definition.launch.executable;
204
- const found = isAbsolute(source) ? source : /[\\/]/.test(source) ? resolve(definition.launch.cwd, source) : resolveOnPath(source);
205
- if (!found)
206
- throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "the declared executable is unavailable; no instance was allocated");
207
- return found;
258
+ return isAbsolute(source) ? source : resolve(definition.launch.cwd, source);
208
259
  }
209
260
  function environment(definition) {
210
261
  const env = {};
211
- for (const key of ["PATH", "HOME", "USER", "LOGNAME", "TMPDIR", "LANG", "LC_ALL", "TERM", "COLORTERM", "NO_COLOR", "FORCE_COLOR", "COTAL_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME", "XDG_RUNTIME_DIR"])
262
+ // LOCALAPPDATA locates Cotal's own folder on Windows when COTAL_HOME is unset, as HOME does elsewhere.
263
+ for (const key of ["PATH", "HOME", "USER", "LOGNAME", "TMPDIR", "LANG", "LC_ALL", "TERM", "COLORTERM", "NO_COLOR", "FORCE_COLOR", "COTAL_HOME", "LOCALAPPDATA", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME", "XDG_RUNTIME_DIR"])
212
264
  if (process.env[key] !== undefined)
213
265
  env[key] = process.env[key];
214
- for (const [destination, source] of Object.entries(definition.envRefs ?? {})) {
215
- if (process.env[source] === undefined)
216
- throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "a selected host environment reference is unavailable; no environment value was printed and no process was launched");
217
- env[destination] = process.env[source];
266
+ // Variable names are not secrets, so a missing one is named with the child variable it feeds.
267
+ const missing = Object.entries(definition.envRefs ?? {}).filter(([, source]) => process.env[source] === undefined);
268
+ if (missing.length) {
269
+ const sources = missing.map(([, source]) => source);
270
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `the environment this command runs in does not set ${missing.map(([destination, source]) => `${source} (passed to the service as ${destination})`).join(", ")}; no environment value was printed and no process was launched`, {
271
+ target: { missing: missing.map(([destination, source]) => ({ variable: source, as: destination })) },
272
+ remedy: `set ${sources.join(" and ")} in the shell that runs cotal, then run the command again`,
273
+ });
218
274
  }
275
+ for (const [destination, source] of Object.entries(definition.envRefs ?? {}))
276
+ env[destination] = process.env[source];
219
277
  if (definition.credentialRef)
220
278
  env.COTAL_CREDS = definition.credentialRef.path;
221
279
  return env;
@@ -224,6 +282,47 @@ export function serviceLogPath(space, id, create = false) {
224
282
  const dir = serviceInstanceStore(space).directory(create);
225
283
  return dir ? join(dir, `${spaceKey(id)}.log`) : undefined;
226
284
  }
285
+ /** The size at which a background launch moves the instance's log aside before it starts. */
286
+ const LOG_ROTATE_BYTES = 16 * 1024 * 1024;
287
+ /** Move a log that reached {@link LOG_ROTATE_BYTES} to `<log>.1`, replacing an earlier one, so the
288
+ * launch starts a fresh file. Only a start or restart rotates, so a running service's log grows
289
+ * until its next start. */
290
+ function rotateServiceLog(path) {
291
+ let info;
292
+ try {
293
+ info = lstatSync(path);
294
+ }
295
+ catch (error) {
296
+ if (error.code === "ENOENT")
297
+ return;
298
+ throw error;
299
+ }
300
+ if (!privateLog(info))
301
+ throw new Error("unprotected log target");
302
+ if (info.size >= LOG_ROTATE_BYTES)
303
+ renameSync(path, `${path}.1`);
304
+ }
305
+ /** Delete the instances' logs, `<log>` and the rotated `<log>.1`, and return the paths deleted. */
306
+ export function removeServiceLogs(space, ids) {
307
+ const removed = [];
308
+ for (const id of ids) {
309
+ const path = serviceLogPath(space, id);
310
+ if (!path)
311
+ continue;
312
+ for (const file of [path, `${path}.1`]) {
313
+ try {
314
+ unlinkSync(file);
315
+ removed.push(file);
316
+ }
317
+ catch (error) {
318
+ if (error.code === "ENOENT")
319
+ continue;
320
+ throw new CommandFailure("partial", "OPERATION_PARTIAL", `the definition and its stopped instance records were removed, but the log ${file} was not deleted: ${error.message}`, { target: { space, instanceId: id }, changed: removed.map((log) => ({ kind: "service-log", path: log })), remedy: `delete ${file} yourself` });
321
+ }
322
+ }
323
+ }
324
+ return removed;
325
+ }
227
326
  /** Both absent, or the same attempt and inventory digest. */
228
327
  function samePreserved(a, b) {
229
328
  return a === undefined ? b === undefined : b !== undefined && a.attemptId === b.attemptId && a.inventorySha256 === b.inventorySha256;
@@ -266,8 +365,71 @@ async function adapterCall(call, timeoutMs) {
266
365
  controller.abort();
267
366
  }
268
367
  }
368
+ /** What a failed bounded readiness request saw, in words. No response body or header is kept. */
369
+ function httpReadinessFailure(error) {
370
+ const code = error?.cause?.code;
371
+ if (code === "ECONNREFUSED")
372
+ return "connection refused, so nothing listened there";
373
+ if (error?.name === "TimeoutError")
374
+ return "no answer before the request timed out";
375
+ return typeof code === "string" ? `the request failed with ${code}` : "the request failed";
376
+ }
377
+ /** Whether something already answers `url` before a child is launched: any HTTP answer there would
378
+ * then not be the new process's. A refused, failed or unanswered request is not an answer. */
379
+ async function readinessAddressAnswers(url) {
380
+ try {
381
+ const response = await fetch(url, { redirect: "manual", credentials: "omit", signal: AbortSignal.timeout(1000) });
382
+ await response.body?.cancel();
383
+ return true;
384
+ }
385
+ catch {
386
+ return false;
387
+ }
388
+ }
389
+ /** The processes of this account that listen on `url`'s loopback address, each as its PID and
390
+ * program name. */
391
+ function addressHolders(url) {
392
+ return loopbackListeners(url).map((pid) => {
393
+ const command = readProcessCommand(pid);
394
+ return command.kind === "command" ? `${pid} (${basename(command.command.split(" ")[0])})` : String(pid);
395
+ });
396
+ }
397
+ /** A warning for each saved service of `space`, or of those of `names`, whose HTTP readiness address
398
+ * still answers while none of its instances runs, as a descendant that outlived a stop, or left the
399
+ * service's process group, can. It names the address and the processes of this account that listen
400
+ * there. Saved services that cannot be read give one warning saying no address was checked. */
401
+ export async function readinessAddressSurvivors(space, names) {
402
+ const idle = [];
403
+ try {
404
+ for (const row of serviceDefinitionStore(space).list()) {
405
+ const { readiness } = row.record.value;
406
+ if (readiness.type !== "http" || (names && !names.includes(row.name)))
407
+ continue;
408
+ if (!serviceInstances(space, row.name).some((instance) => observeServiceProcess(instance.record.value) === "running"))
409
+ idle.push({ name: row.name, url: readiness.url });
410
+ }
411
+ }
412
+ catch (error) {
413
+ // The command this reports for has already done its work, so an unreadable record is named here.
414
+ if (!(error instanceof CommandFailure))
415
+ throw error;
416
+ return [{ code: "SERVICE_ADDRESS_NOT_CHECKED", target: { space }, message: `the saved services could not be read (${error.message}), so no address a stopped one may still hold was checked` }];
417
+ }
418
+ const warnings = [];
419
+ for (const { name, url } of idle) {
420
+ if (!await readinessAddressAnswers(url))
421
+ continue;
422
+ const address = new URL(url).host;
423
+ const holders = addressHolders(url);
424
+ warnings.push({ code: "SERVICE_ADDRESS_HELD", target: { space, definition: name, address }, message: `something still answers ${address}, where ${name}'s HTTP readiness is checked, and no instance of ${name} runs${holders.length ? `; process ${holders.join(", ")} of this account listens there` : ""}` });
425
+ }
426
+ return warnings;
427
+ }
269
428
  export async function serviceReadiness(row, definition, adapter) {
270
429
  const deadline = Date.now() + definition.readiness.timeoutMs;
430
+ // The last HTTP readiness observation, named when the deadline passes first: the status the
431
+ // service answered with, or what a failed request saw.
432
+ let seen;
271
433
  do {
272
434
  const state = observeServiceProcess(row.record.value);
273
435
  if (gone(state))
@@ -304,11 +466,27 @@ export async function serviceReadiness(row, definition, adapter) {
304
466
  await response.body?.cancel();
305
467
  if (response.status === definition.readiness.expectedStatus && observeServiceProcess(row.record.value) === "running")
306
468
  return transition(row, { state: "running", readiness: "http-reachable" });
469
+ seen = { status: response.status };
470
+ }
471
+ catch (error) {
472
+ // A failed bounded HTTP read is not proof of process death or listener ownership.
473
+ seen = { failure: httpReadinessFailure(error) };
307
474
  }
308
- catch { /* A failed bounded HTTP read is not proof of process death or listener ownership. */ }
309
475
  await delay(Math.min(100, Math.max(0, deadline - Date.now())));
310
476
  } while (Date.now() < deadline);
311
477
  const uncertain = transition(row, { state: "unknown", readiness: "not-checked" });
478
+ if (definition.readiness.type === "http") {
479
+ // The address alone is named: a definition's URL is kept out of reports, and its path may carry a token.
480
+ const { definition: name, instanceId, space } = uncertain.record.value, host = new URL(definition.readiness.url).host;
481
+ const inspect = `read its output with cotal service logs ${name} --instance ${instanceId} --space ${space}, and stop it with cotal service stop ${name} --instance ${instanceId} --space ${space} --yes before another start`;
482
+ // A service that answered with another status said it is not ready, so the start failed.
483
+ if (seen && "status" in seen)
484
+ throw new CommandFailure("failed", "OPERATION_FAILED", `the owned process answered its HTTP readiness check on ${host} with status ${seen.status}, not ${definition.readiness.expectedStatus}, until its ${definition.readiness.timeoutMs} ms deadline passed. The process was left running, not relaunched or killed`, { target: instanceProjection(uncertain), remedy: inspect });
485
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", `the owned process did not answer its HTTP readiness check on ${host} with status ${definition.readiness.expectedStatus} within ${definition.readiness.timeoutMs} ms; the last check saw ${seen?.failure ?? "no completed request"}. The process was left running, not relaunched or killed`, {
486
+ target: instanceProjection(uncertain),
487
+ remedy: `${inspect}; cotal service show ${name} --space ${space} shows the readiness deadline it missed`,
488
+ });
489
+ }
312
490
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the owned process did not establish its declared readiness before the deadline; it was not relaunched or automatically killed", { target: instanceProjection(uncertain), remedy: "inspect service status/logs with the original full instance ID before another start" });
313
491
  }
314
492
  /** A target the adapter could not resolve, as the refusal its code and remedy name. */
@@ -318,7 +496,7 @@ function targetRefusal(error) {
318
496
  }
319
497
  export function prepareProcessService(definition) {
320
498
  processServiceHost();
321
- validateServiceDefinition(definition.record.value, definition.record.value.space);
499
+ validateServiceDefinition(definition.record.value, definition.record.value.space, true, false, definition.name);
322
500
  const launch = definition.record.value.launch;
323
501
  const program = launch.type === "process" ? executable(definition.record.value) : undefined;
324
502
  if (launch.type === "process" && commandIsCotalSupervisor([program, ...launch.args].join(" ")))
@@ -350,6 +528,17 @@ export function assertRestartAdmitted(definition) {
350
528
  if (!maintenanceAdmitsStackWork(root, value.space, server, maintenanceStackView(root, value.space)))
351
529
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "this root retains a maintenance or recovery attempt, under which the replacement start would be refused; nothing was stopped", { target: { space: value.space, definition: definition.name } });
352
530
  }
531
+ /** The refusal for a start that selects an instance of an earlier revision, as one a definition moved
532
+ * aside and added again leaves. Nothing adopts or removes it: an added service's Next stops it if it
533
+ * still runs, then forgets its record, so the next start launches the current revision. A stack
534
+ * member's records stay with its stack, so its refusal names no command. */
535
+ function staleRevisionInstance(definition, selected) {
536
+ const { name } = definition, { space } = definition.record.value, id = selected.name;
537
+ const forget = `forget its record with cotal service remove ${name} --instance ${id} --space ${space} --yes, then run cotal service start ${name} --space ${space} again`;
538
+ const remedy = Object.values(STACK_DEFINITION).includes(name) ? undefined
539
+ : gone(observeServiceProcess(selected.record.value)) ? forget : `stop it with cotal service stop ${name} --instance ${id} --space ${space} --yes, ${forget}`;
540
+ return new CommandFailure("refused", "CONFLICT", "this instance belongs to another definition revision; it was not adopted", { target: instanceProjection(selected), remedy });
541
+ }
353
542
  export async function startProcessService(definition, options, held) {
354
543
  const value = definition.record.value;
355
544
  if (options.attempt && (value.launch.type !== "adapter" || options.foreground))
@@ -367,10 +556,12 @@ export async function startProcessService(definition, options, held) {
367
556
  if (options.replacement && (options.brokerInstance || options.newInstance || options.instance !== undefined))
368
557
  throw new CommandFailure("refused", "UNSUPPORTED", "a journaled stack replacement is started only under its own IDs; no launch was allocated");
369
558
  const { program, adapter: declaredAdapter, cliInvocation, env, launcher } = prepareProcessService(definition);
559
+ if (options.foreground && custodiedPlatform())
560
+ throw new CommandFailure("refused", "UNSUPPORTED", "on Windows a service runs in the background under the custodian that holds its job; a terminal-attached foreground child was not substituted", { remedy: `start it in the background with cotal service start ${definition.name} --space ${value.space}` });
370
561
  if (declaredAdapter && (options.newInstance && !declaredAdapter.declaration.capabilities.multiInstance || options.foreground && !declaredAdapter.declaration.capabilities.foreground))
371
562
  throw new CommandFailure("refused", "UNSUPPORTED", "the selected adapter does not declare this multi-instance or foreground capability; no launch was allocated");
372
563
  const hold = held ?? serviceDefinitionStore(value.space).pin(definition);
373
- let child;
564
+ let child, unpinned, spawnedCustody;
374
565
  try {
375
566
  assertNoServiceUnitAttempts(value.space, definition.name);
376
567
  const rows = serviceInstances(value.space, definition.name);
@@ -391,7 +582,7 @@ export async function startProcessService(definition, options, held) {
391
582
  // A crash or failed start is settled from its own evidence before the relaunch checks below.
392
583
  const selected = chosen && settleExitedInstance(chosen);
393
584
  if (selected && selected.record.value.definitionRevision !== definition.record.revision)
394
- throw new CommandFailure("refused", "CONFLICT", "this instance belongs to another definition revision; it was not adopted");
585
+ throw staleRevisionInstance(definition, selected);
395
586
  if (selected && !sameServiceAdapterPin(selected.record.value.adapter, declaredAdapter?.pin))
396
587
  throw new CommandFailure("refused", "CONFLICT", "the recorded instance pins a different adapter declaration or package version; stop and explicitly remove its retained records before choosing a different provider", { target: instanceProjection(selected) });
397
588
  if (selected) {
@@ -413,12 +604,51 @@ export async function startProcessService(definition, options, held) {
413
604
  if (declaredAdapter?.declaration.stop === "kernel-exit" && selected.record.value.process && !settledExit && !(selected.record.value.state === "stopped" && selected.record.value.kernelStop))
414
605
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the original broker process disappeared during its retained stop request, without this controller's recorded exact-exit stop; no replacement listener was launched over its store", { target: instanceProjection(selected), remedy: `inspect the original request with cotal service status ${definition.name} --instance ${selected.name} --space ${value.space}` });
415
606
  }
607
+ // HTTP readiness proves only that something answers, so an address that answers before the
608
+ // launch could pass a child that never listened, such as a second instance on the first one's port.
609
+ if (value.readiness.type === "http" && await readinessAddressAnswers(value.readiness.url)) {
610
+ const host = new URL(value.readiness.url).host, live = rows.find((row) => observeServiceProcess(row.record.value) === "running");
611
+ // Another listener, such as a server that left a stopped instance's process group, is named as
612
+ // SERVICE_ADDRESS_HELD names it. It is not signalled: no instance of this service owns it.
613
+ const holders = live ? [] : addressHolders(value.readiness.url);
614
+ throw new CommandFailure("refused", "CONFLICT", `something already answers ${host}, where ${definition.name}'s HTTP readiness is checked, so a new process's readiness could not be told from it${holders.length ? `; process ${holders.join(", ")} of this account listens there` : ""}; nothing was launched`, {
615
+ target: { space: value.space, definition: definition.name, address: host, ...(live ? { instanceId: live.name } : {}) },
616
+ remedy: live ? `instance ${live.name} of ${definition.name} answers there; give another instance its own port, or stop that one with cotal service stop ${definition.name} --instance ${live.name} --space ${value.space} --yes first`
617
+ : holders.length ? `stop process ${holders.join(", ")}, which is not an instance of ${definition.name}, then run the command again` : `stop what listens on ${host}, then run the command again`,
618
+ });
619
+ }
416
620
  hold.check();
417
621
  const now = new Date().toISOString(), id = options.brokerInstance?.instanceId ?? options.replacement?.instanceId ?? selected?.name ?? randomUUID(), launchRequestId = options.brokerInstance?.launchRequestId ?? options.replacement?.launchRequestId ?? randomUUID();
418
622
  const instance = { schemaVersion: 1, instanceId: id, definition: definition.name, definitionRevision: definition.record.revision, space: value.space, host: processServiceHost(), requestId: launchRequestId, launchRequestId, state: "starting", launcher, readiness: "not-checked", supervisor: "none", ...(options.attempt ? { attempt: { attemptId: options.attempt.attemptId } } : {}), ...(declaredAdapter ? { adapter: declaredAdapter.pin, ...(declaredAdapter.declaration.stop === "native" ? { nativeStopRequired: true } : declaredAdapter.declaration.stop === "kernel-exit" ? { kernelStopRequired: true } : {}) } : {}), foreground: options.foreground === true, createdAt: selected?.record.value.createdAt ?? now, updatedAt: now };
419
623
  const store = serviceInstanceStore(value.space);
420
624
  store.commit(id, selected, instance);
625
+ // The replaced incarnation's custodian is gone, so its capability opens nothing.
626
+ removeCustodyCapability(value.space, selected?.record.value.custody);
421
627
  let row = store.read(id);
628
+ // Until the child's identity is recorded, an interrupt records this launch on its way out. On
629
+ // Windows that is its custodian, which can still be asked for the job once it is recorded.
630
+ unpinned = () => {
631
+ if (spawnedCustody) {
632
+ row = transition(row, { custody: spawnedCustody, state: "unknown", readiness: "not-checked" });
633
+ return;
634
+ }
635
+ if (child?.pid === undefined) {
636
+ row = transition(row, { state: "failed", readiness: "not-checked" });
637
+ return;
638
+ }
639
+ let identity;
640
+ try {
641
+ identity = requireProcessIdentity(child.pid);
642
+ }
643
+ catch {
644
+ identity = undefined;
645
+ }
646
+ row = transition(row, identity ? { process: identity } : { state: exited ? "failed" : "unknown", ...(exited ? { exit: { code: exitCode, signal: exitSignal } } : {}) });
647
+ };
648
+ unpinnedLaunches.add(unpinned);
649
+ // Smoke only: hold a recorded launch before its child exists, so a signal can land in that window.
650
+ if (process.env.COTAL_SMOKE_HOLD_AFTER_LAUNCH_RECORD === "1")
651
+ await delay(60_000);
422
652
  let adapter;
423
653
  let launch;
424
654
  try {
@@ -431,7 +661,7 @@ export async function startProcessService(definition, options, held) {
431
661
  const provider = await loadServiceAdapter(declaredAdapter, value.launch.options);
432
662
  hold.check();
433
663
  const plan = await adapterCall(() => provider.build(context), Math.min(10000, value.readiness.timeoutMs));
434
- const validated = validateServiceDefinition({ ...value, launch: { type: "process", ...plan }, readiness: { type: "process", timeoutMs: value.readiness.timeoutMs } }, value.space);
664
+ const validated = validateServiceDefinition({ ...value, launch: { type: "process", ...plan }, readiness: { type: "process", timeoutMs: value.readiness.timeoutMs } }, value.space, true, true);
435
665
  if (validated.launch.type !== "process")
436
666
  throw new Error("invalid adapter launch plan");
437
667
  const executablePath = executable(validated);
@@ -447,66 +677,120 @@ export async function startProcessService(definition, options, held) {
447
677
  // No child is spawned above this point, so this incarnation has no process: the record is
448
678
  // failed either way. Only the provider's own work stays unattributed on an unknown error.
449
679
  row = transition(row, { state: "failed", readiness: "not-checked" });
450
- if (failure?.outcome === "refused")
451
- throw new CommandFailure("refused", failure.code, `service preparation was refused before a child launch: ${failure.message}`, { target: instanceProjection(row), native: { code: failure.code, outcome: failure.outcome, detail: failure.message }, remedy: failure.remedy });
680
+ if (failure?.outcome === "refused") {
681
+ // A record the adapter refused on, whose process a member of this space's stack runs, is
682
+ // named with that member, as `up` names a service it does not replace.
683
+ const path = failure.target?.path;
684
+ const member = typeof path === "string" ? stackMemberRecord(value.space, path) : undefined;
685
+ throw new CommandFailure("refused", failure.code, member
686
+ ? `service preparation was refused before a child launch: the ${member.definition} member of this space's controller stack runs the process recorded at ${path} (pid ${member.pid}, instance ${member.instanceId}), so ${definition.name} does not start beside it`
687
+ : `service preparation was refused before a child launch: ${failure.message}`, { target: instanceProjection(row), native: { code: failure.code, outcome: failure.outcome, detail: failure.message },
688
+ remedy: member ? `stop it with \`cotal down ${member.definition} --instance ${member.instanceId} --space ${value.space} --yes\`, then run \`cotal service start ${definition.name} --space ${value.space}\` again` : failure.remedy });
689
+ }
452
690
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "service preparation did not establish an accepted direct-child launch plan; no child was launched, and no provider or launch was retried", { target: instanceProjection(row) });
453
691
  }
454
692
  const path = serviceLogPath(value.space, id, true);
455
693
  let log;
694
+ // Where this launch's own log lines start, so a failure quotes this launch and not an earlier one.
695
+ let logFrom;
456
696
  let exitCode = null, exitSignal = null;
457
697
  let exited = false;
458
698
  let done;
459
699
  const exit = new Promise((resolve) => { done = resolve; });
460
- try {
461
- if (!options.foreground) {
462
- log = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
463
- const info = fstatSync(log);
464
- if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o077) !== 0)
465
- throw new Error("unprotected log target");
466
- }
467
- child = spawn(launch.program, [...launch.args], { cwd: launch.cwd, env, shell: false, detached: !options.foreground, stdio: options.foreground ? "inherit" : ["ignore", log, log] });
468
- if (!options.foreground)
469
- child.unref();
470
- child.once("exit", (code, signal) => { exited = true; exitCode = code; exitSignal = signal; done(); });
471
- await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
472
- }
473
- catch {
474
- row = transition(row, { state: "failed", readiness: "not-checked" });
475
- throw new CommandFailure("failed", "OPERATION_FAILED", "the native process launch failed before a service child was established; its instance receipt was retained", { target: instanceProjection(row) });
476
- }
477
- finally {
478
- if (log !== undefined)
479
- closeSync(log);
480
- }
481
- if (!child.pid)
482
- throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the launch has no confirmed process ID; its instance intent was retained and no retry was made", { target: instanceProjection(row) });
483
700
  let identity;
484
- try {
485
- identity = requireProcessIdentity(child.pid);
701
+ if (custodiedPlatform()) {
702
+ // Windows: a custodian creates the program inside a kill-on-close job and reports its pin.
703
+ let started;
704
+ try {
705
+ rotateServiceLog(path);
706
+ logFrom = custodyLog(path);
707
+ started = await startCustodiedService(row.record.value, { ...launch, env }, path, (custody) => { spawnedCustody = custody; });
708
+ }
709
+ catch (error) {
710
+ row = transition(row, spawnedCustody ? { custody: spawnedCustody, state: "unknown", readiness: "not-checked" } : { state: "failed", readiness: "not-checked" });
711
+ throw new CommandFailure(spawnedCustody ? "unknown" : "failed", spawnedCustody ? "OPERATION_UNKNOWN" : "OPERATION_FAILED", `the custodied process launch did not report a running service child (${error.message}); its instance receipt was retained`, { target: instanceProjection(row) });
712
+ }
713
+ identity = started.process;
714
+ row = transition(row, { process: identity, custody: started.custody });
715
+ unpinnedLaunches.delete(unpinned);
716
+ // The custodian holds the program; this launch watches its pin to notice an early exit.
717
+ const pinned = identity;
718
+ const watch = setInterval(() => {
719
+ if (assertRecordIdentity(pinned).kind === "match")
720
+ return;
721
+ clearInterval(watch);
722
+ exited = true;
723
+ done();
724
+ }, 100);
725
+ watch.unref();
726
+ exit.then(async () => {
727
+ try {
728
+ exitCode = (await askCustodian(row, { op: "status" })).root.exit;
729
+ }
730
+ catch { /* The custodian already left with its job; the log keeps the cause. */ }
731
+ });
486
732
  }
487
- catch {
488
- if (!exited)
489
- child.kill("SIGTERM");
490
- await Promise.race([exit, delay(3000)]);
491
- row = transition(row, { state: exited ? "failed" : "unknown", ...(exited ? { exit: { code: exitCode, signal: exitSignal } } : {}) });
492
- throw new CommandFailure(exited ? "failed" : "unknown", exited ? "OPERATION_FAILED" : "OPERATION_UNKNOWN", "the child could not be creation-pinned; its native child handle was asked to exit, and no replacement was launched", { target: instanceProjection(row) });
733
+ else {
734
+ try {
735
+ if (!options.foreground) {
736
+ rotateServiceLog(path);
737
+ log = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
738
+ const info = fstatSync(log);
739
+ if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o077) !== 0)
740
+ throw new Error("unprotected log target");
741
+ logFrom = info.size;
742
+ }
743
+ child = spawn(launch.program, [...launch.args], { cwd: launch.cwd, env, shell: false, detached: !options.foreground, stdio: options.foreground ? "inherit" : ["ignore", log, log] });
744
+ if (!options.foreground)
745
+ child.unref();
746
+ child.once("exit", (code, signal) => { exited = true; exitCode = code; exitSignal = signal; done(); });
747
+ await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
748
+ }
749
+ catch {
750
+ row = transition(row, { state: "failed", readiness: "not-checked" });
751
+ throw new CommandFailure("failed", "OPERATION_FAILED", "the native process launch failed before a service child was established; its instance receipt was retained", { target: instanceProjection(row) });
752
+ }
753
+ finally {
754
+ if (log !== undefined)
755
+ closeSync(log);
756
+ }
757
+ if (!child.pid)
758
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the launch has no confirmed process ID; its instance intent was retained and no retry was made", { target: instanceProjection(row) });
759
+ try {
760
+ identity = requireProcessIdentity(child.pid);
761
+ }
762
+ catch {
763
+ if (!exited)
764
+ child.kill("SIGTERM");
765
+ await Promise.race([exit, delay(3000)]);
766
+ row = transition(row, { state: exited ? "failed" : "unknown", ...(exited ? { exit: { code: exitCode, signal: exitSignal } } : {}) });
767
+ throw new CommandFailure(exited ? "failed" : "unknown", exited ? "OPERATION_FAILED" : "OPERATION_UNKNOWN", "the child could not be creation-pinned; its native child handle was asked to exit, and no replacement was launched", { target: instanceProjection(row) });
768
+ }
769
+ row = transition(row, { process: identity });
770
+ unpinnedLaunches.delete(unpinned);
493
771
  }
494
- row = transition(row, { process: identity });
772
+ // A process that exits at once never ran: process readiness first gives it a moment to do so,
773
+ // and that exit is then settled below with the code this parent observed.
774
+ if (value.readiness.type === "process")
775
+ await Promise.race([exit, delay(Math.min(PROCESS_SETTLE_MS, value.readiness.timeoutMs))]);
495
776
  let running;
496
777
  try {
497
778
  running = await serviceReadiness(row, value, adapter);
498
779
  }
499
780
  catch (error) {
500
781
  // Only an exit of the pinned child itself is settled here, with the exit this parent observed.
501
- if (!isCommandFailure(error) || error.code !== "OPERATION_FAILED")
782
+ if (!isCommandFailure(error) || error.code !== "OPERATION_FAILED" || observeServiceProcess(row.record.value) === "running")
502
783
  throw error;
503
784
  await Promise.race([exit, delay(1000)]);
504
785
  const failed = transition(row, { state: "failed", readiness: "not-checked", ...(exited ? { exit: { code: exitCode, signal: exitSignal } } : {}) });
505
- throw new CommandFailure("failed", "OPERATION_FAILED", `the owned service process exited before readiness was established${exited ? ` (exit code ${exitCode ?? "none"}, signal ${exitSignal ?? "none"})` : ""}; its log records the cause`, { target: instanceProjection(failed), remedy: `read its log with cotal service logs ${definition.name} --instance ${id} --space ${value.space}` });
786
+ const last = logFrom === undefined ? undefined : lastLoggedLine(path, logFrom);
787
+ throw new CommandFailure("failed", "OPERATION_FAILED", `the owned service process exited before readiness was established${exited ? ` (exit code ${exitCode ?? "none"}, signal ${exitSignal ?? "none"})` : ""}; ${last ? `the last line it logged is: ${last}` : "its log records the cause"}`, { target: instanceProjection(failed), remedy: `read its log with cotal service logs ${definition.name} --instance ${id} --space ${value.space}` });
506
788
  }
507
789
  return { instance: running, noOp: false, child, exit: { done: exit, observed: () => exited, result: () => ({ code: exitCode, signal: exitSignal }) } };
508
790
  }
509
791
  finally {
792
+ if (unpinned)
793
+ unpinnedLaunches.delete(unpinned);
510
794
  if (!held)
511
795
  hold.release();
512
796
  }
@@ -601,6 +885,46 @@ export function preflightProcessServiceStop(definition, selected) {
601
885
  if (command.kind !== "command" || commandIsCotalSupervisor(command.command))
602
886
  throw new CommandFailure("refused", "UNSUPPORTED", "a selected process has an unreadable or manager-supervisor role; no generic set stop bypassed its native impact policy");
603
887
  }
888
+ /** How long a process stop waits after SIGTERM before it sends SIGKILL. */
889
+ export const PROCESS_STOP_GRACE_MS = 15_000;
890
+ /** Windows generic stop: the custodian terminates the instance's whole job, so a program that already
891
+ * exited is stopped with the members it left. The receipt names the program only when it was still
892
+ * running; the stop completes once the custodian, which holds the job, has exited. */
893
+ async function stopCustodiedProcess(current, initial) {
894
+ let row = current;
895
+ if ((initial !== "running" && initial !== "members-running") || !row.record.value.process)
896
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "the selected process is foreign, unreadable or unresolved; it was not signalled", { target: instanceProjection(row) });
897
+ const held = await askCustodian(row, { op: "status" });
898
+ if (commandIsCotalSupervisor([held.program, ...held.args].join(" ")))
899
+ throw new CommandFailure("refused", "UNSUPPORTED", "generic process stop cannot bypass manager agent-impact guards; use its supported service adapter. No job was terminated", { target: instanceProjection(row) });
900
+ const program = { ...row.record.value.process }, custodian = row.record.value.custody.custodian;
901
+ row = transition(row, { state: "stopping", requestId: randomUUID() });
902
+ const ended = await askCustodian(row, { op: "terminate", code: 1 });
903
+ for (const deadline = Date.now() + 5000; assertRecordIdentity(custodian).kind === "match" && Date.now() < deadline;)
904
+ await delay(100);
905
+ if (ended.members.length || ended.root.exit === null || assertRecordIdentity(custodian).kind === "match")
906
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", `the service's job did not confirm it emptied${ended.members.length ? `; process ${ended.members.join(", ")} still ran in it` : ""}; its record was retained and no restart was attempted`, { target: instanceProjection(row) });
907
+ removeCustodyCapability(row.record.value.space, row.record.value.custody);
908
+ const processStop = initial === "running" ? { processStop: { kind: "process-exit", requestId: row.record.value.requestId, process: program, signal: "job-terminate", observedAt: new Date().toISOString() } } : {};
909
+ return { instance: transition(row, { state: "stopped", readiness: "not-checked", ...processStop }), noOp: false };
910
+ }
911
+ /** Windows: a program with a native or kernel-exit stop policy exited on its own, and its job still
912
+ * holds processes. Those end with the job, so a manager's agents end only on `--with-agents`. The
913
+ * custodian terminates the job to empty, and the record settles as an exit no stop explains. */
914
+ async function endLeftoverJob(current, membersMayEnd) {
915
+ const row = current;
916
+ const held = await askCustodian(row, { op: "status" });
917
+ if (!membersMayEnd && held.members.length)
918
+ throw new CommandFailure("refused", "UNSUPPORTED", `the service's program exited while its job still holds process ${held.members.join(", ")}, which would end with it; nothing was stopped`, { target: instanceProjection(row), remedy: `end them with cotal service stop ${row.record.value.definition} --instance ${row.name} --space ${row.record.value.space} --with-agents --yes` });
919
+ const custodian = row.record.value.custody.custodian;
920
+ const ended = await askCustodian(row, { op: "terminate", code: 1 });
921
+ for (const deadline = Date.now() + 5000; assertRecordIdentity(custodian).kind === "match" && Date.now() < deadline;)
922
+ await delay(100);
923
+ if (ended.members.length || assertRecordIdentity(custodian).kind === "match")
924
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", `the service's job did not confirm it emptied${ended.members.length ? `; process ${ended.members.join(", ")} still ran in it` : ""}; its record was retained`, { target: instanceProjection(row) });
925
+ removeCustodyCapability(row.record.value.space, row.record.value.custody);
926
+ return { instance: settleExitedInstance(row), noOp: false };
927
+ }
604
928
  /** Only the stored creation-pinned process is signalled. Every escalation rechecks its identity. */
605
929
  export async function stopProcessService(definition, selected, held, native, kernel) {
606
930
  const hold = held ?? serviceDefinitionStore(definition.record.value.space).pin(definition);
@@ -625,6 +949,8 @@ export async function stopProcessService(definition, selected, held, native, ker
625
949
  // Already gone without a stop of ours: record that exit under this lock; nothing is signalled.
626
950
  if (goneWithoutStop(row.record.value))
627
951
  return { instance: settleExitedInstance(row), noOp: true };
952
+ if (initial === "members-running")
953
+ return await endLeftoverJob(row, native?.withAgents === true);
628
954
  if (initial !== "running" || !row.record.value.process)
629
955
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "native stop has no current attributable process or retained returned receipt; disappearance was not treated as completion", { target: instanceProjection(row) });
630
956
  if (!native?.plan)
@@ -638,16 +964,26 @@ export async function stopProcessService(definition, selected, held, native, ker
638
964
  if (native.preserved && !native.requestId)
639
965
  throw new CommandFailure("refused", "USAGE_INVALID", "a preserved-exit stop needs its journaled attempt's request ID; no request was published");
640
966
  const requestId = native.requestId ?? randomUUID(), target = { ...row.record.value.process }, began = Date.now();
967
+ if (custodiedPlatform() && !native.withAgents) {
968
+ // A Windows manager's agents run in its job and end with it, so a stop that keeps them refuses.
969
+ const others = (await askCustodian(row, { op: "status" })).members.filter((pid) => pid !== target.pid);
970
+ if (others.length)
971
+ throw new CommandFailure("refused", "UNSUPPORTED", `on Windows the manager's job also holds process ${others.join(", ")}, which would end with it; nothing was stopped`, { target: instanceProjection(row), remedy: `stop it with its agents, cotal service stop ${definition.name} --instance ${row.name} --space ${row.record.value.space} --with-agents --yes` });
972
+ }
641
973
  row = transition(row, { state: "stopping", requestId });
642
974
  let returned = false;
643
975
  try {
644
976
  const raw = await adapterCall((signal) => provider.stop({ ...adapterContext(definition, row.record.value), process: target, withAgents: native.withAgents, ...(native.preserved ? { preserved: { ...native.preserved } } : {}), requestId, plan, signal }), 45000);
645
977
  returned = true;
646
978
  const result = serviceAdapterStopResult(raw);
979
+ // A Windows custodian exits a moment after the job it held empties.
980
+ for (const deadline = Date.now() + 5000; custodiedPlatform() && observeServiceProcess(row.record.value) === "members-running" && Date.now() < deadline;)
981
+ await delay(100);
647
982
  // The terminal kind must answer the submitted request: a preserved stop returns only
648
983
  // `preserved-exit-returned`, an ordinary stop only `returned`.
649
984
  if (result.nativeStop !== (native.preserved ? "preserved-exit-returned" : "returned") || result.requestId !== requestId || result.scopeSha256 !== plan.scopeSha256 || result.process.pid !== target.pid || result.process.token !== target.token || Date.parse(result.observedAt) < began - 1000 || Date.parse(result.observedAt) > Date.now() + 1000 || !gone(observeServiceProcess(row.record.value)))
650
985
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the native service did not confirm both its original returned stop and the exact process exit");
986
+ removeCustodyCapability(row.record.value.space, row.record.value.custody);
651
987
  return { instance: transition(row, { state: "stopped", readiness: "not-checked", nativeStop: result }), noOp: false, nativeStop: result };
652
988
  }
653
989
  catch (error) {
@@ -672,6 +1008,8 @@ export async function stopProcessService(definition, selected, held, native, ker
672
1008
  throw new CommandFailure("refused", "UNSUPPORTED", "generic process stop does not accept an agent-reap policy");
673
1009
  if (gone(initial))
674
1010
  return { instance: transition(row, { state: "stopped", readiness: "not-checked" }), noOp: true };
1011
+ if (custodiedPlatform())
1012
+ return await stopCustodiedProcess(row, initial);
675
1013
  if (initial !== "running" || !row.record.value.process)
676
1014
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "the selected process is foreign, unreadable or unresolved; it was not signalled", { target: instanceProjection(row) });
677
1015
  const command = readProcessCommand(row.record.value.process.pid);
@@ -681,10 +1019,28 @@ export async function stopProcessService(definition, selected, held, native, ker
681
1019
  // The receipt names the last signal this call itself delivered to the pinned process. A process
682
1020
  // that was already gone before any delivery gets no receipt: absence is not a stop.
683
1021
  let delivered;
1022
+ // A background start leads its own process group, so the stop signals that group and waits for
1023
+ // it to empty: a descendant such as a backgrounded server goes with the process. A foreground
1024
+ // start shares the command's group and is signalled alone. A group ID is not reused while a
1025
+ // member lives, so after its leader exits the group is signalled only while members remain.
1026
+ const pid = row.record.value.process.pid;
1027
+ let group = false;
1028
+ const members = () => (group ? processGroupMembers(pid) : []);
684
1029
  const signal = (name) => {
685
1030
  const state = observeServiceProcess(row.record.value);
686
- if (gone(state))
1031
+ if (gone(state)) {
1032
+ if (!members().length)
1033
+ return;
1034
+ try {
1035
+ process.kill(-pid, name);
1036
+ delivered = name;
1037
+ }
1038
+ catch (error) {
1039
+ if (error.code !== "ESRCH")
1040
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the signal to the service's remaining process group was not confirmed; its record was retained", { target: instanceProjection(row) });
1041
+ }
687
1042
  return;
1043
+ }
688
1044
  if (state !== "running")
689
1045
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "service ownership became uncertain before signalling; its record was retained", { target: instanceProjection(row) });
690
1046
  const role = readProcessCommand(row.record.value.process.pid);
@@ -693,8 +1049,9 @@ export async function stopProcessService(definition, selected, held, native, ker
693
1049
  const identity = assertRecordIdentity(row.record.value.process);
694
1050
  if (identity.kind !== "match")
695
1051
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the exact process incarnation changed before a signal; no successor was signalled", { target: instanceProjection(row) });
1052
+ group ||= processGroupOf(pid) === pid;
696
1053
  try {
697
- process.kill(row.record.value.process.pid, name);
1054
+ process.kill(group ? -pid : pid, name);
698
1055
  delivered = name;
699
1056
  }
700
1057
  catch (error) {
@@ -703,20 +1060,20 @@ export async function stopProcessService(definition, selected, held, native, ker
703
1060
  }
704
1061
  };
705
1062
  signal("SIGTERM");
706
- for (const [timeout, escalation] of [[15000, "SIGKILL"], [3000, undefined]]) {
1063
+ for (const [timeout, escalation] of [[PROCESS_STOP_GRACE_MS, "SIGKILL"], [3000, undefined]]) {
707
1064
  const deadline = Date.now() + timeout;
708
1065
  while (Date.now() < deadline) {
709
1066
  const state = observeServiceProcess(row.record.value);
710
- if (gone(state))
1067
+ if (gone(state) && !members().length)
711
1068
  return { instance: transition(row, { state: "stopped", readiness: "not-checked", ...(delivered ? { processStop: { kind: "process-exit", requestId: row.record.value.requestId, process: { ...row.record.value.process }, signal: delivered, observedAt: new Date().toISOString() } } : {}) }), noOp: false };
712
- if (state !== "running")
1069
+ if (!gone(state) && state !== "running")
713
1070
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the service exit could not be established; its identity and stop receipt were retained", { target: instanceProjection(row) });
714
1071
  await delay(100);
715
1072
  }
716
1073
  if (escalation)
717
1074
  signal(escalation);
718
1075
  }
719
- throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the selected service process did not confirm exit; its record was retained and no restart was attempted", { target: instanceProjection(row) });
1076
+ throw new CommandFailure("unknown", "OPERATION_UNKNOWN", `the selected service process${members().length ? ` group, with process ${members().join(", ")},` : ""} did not confirm exit; its record was retained and no restart was attempted`, { target: instanceProjection(row) });
720
1077
  }
721
1078
  finally {
722
1079
  if (!held)
@@ -742,6 +1099,8 @@ async function stopKernelService(definition, current, hold, declared, initial, n
742
1099
  return { instance: settleExitedInstance(row), noOp: true };
743
1100
  if (value.state === "stopping")
744
1101
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "an earlier broker stop request is retained without its exact-exit receipt; it was not resubmitted", { target: instanceProjection(row) });
1102
+ if (initial === "members-running")
1103
+ return await endLeftoverJob(row, true);
745
1104
  if (initial !== "running" || !value.process)
746
1105
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the broker has no current attributable process or retained exact-exit receipt; disappearance was not treated as a completed stop", { target: instanceProjection(row) });
747
1106
  if (!kernel?.plan)
@@ -754,7 +1113,8 @@ async function stopKernelService(definition, current, hold, declared, initial, n
754
1113
  if (fresh.scopeSha256 !== confirmed.scopeSha256 || serviceMetadataDigest(fresh.binding) !== serviceMetadataDigest(confirmed.binding))
755
1114
  throw new CommandFailure("refused", "CONFLICT", "the broker binding or dependant scope changed after confirmation; no signal was sent", { target: instanceProjection(row) });
756
1115
  hold.check();
757
- const role = readProcessCommand(target.pid);
1116
+ // On Windows the custodian reports the exact program it launched, which is the broker's role.
1117
+ const role = custodiedPlatform() ? await askCustodian(row, { op: "status" }).then((held) => ({ kind: "command", command: [held.program, ...held.args].join(" ") }), () => ({ kind: "unreadable" })) : readProcessCommand(target.pid);
758
1118
  if (role.kind !== "command" || commandIsCotalSupervisor(role.command) || assertRecordIdentity(target).kind !== "match")
759
1119
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "the broker process identity or role could not be re-established immediately before the signal; no signal was sent", { target: instanceProjection(row) });
760
1120
  const requestId = randomUUID();
@@ -762,7 +1122,11 @@ async function stopKernelService(definition, current, hold, declared, initial, n
762
1122
  try {
763
1123
  if (assertRecordIdentity(target).kind !== "match")
764
1124
  throw new Error("identity changed");
765
- process.kill(target.pid, "SIGTERM");
1125
+ // Windows has no SIGTERM to deliver: the custodian terminates the broker's job.
1126
+ if (custodiedPlatform())
1127
+ await askCustodian(row, { op: "terminate", code: 1 });
1128
+ else
1129
+ process.kill(target.pid, "SIGTERM");
766
1130
  }
767
1131
  catch {
768
1132
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the exact broker signal was not confirmed delivered to the pinned process; its stop request was retained and no exit was attributed to it", { target: instanceProjection(row) });
@@ -777,9 +1141,11 @@ async function stopKernelService(definition, current, hold, declared, initial, n
777
1141
  }
778
1142
  catch { /* The observed exit stands; an unreadable trace is reported as retained, never removed. */ }
779
1143
  const kernelStop = serviceAdapterKernelStopResult({ kind: "kernel-exit", requestId, scopeSha256: confirmed.scopeSha256, process: target, observation: "exact-process-exit", brokerShutdownTrace: trace, cleanup: "not-checked", observedAt: new Date().toISOString() });
1144
+ removeCustodyCapability(row.record.value.space, row.record.value.custody);
780
1145
  return { instance: transition(row, { state: "stopped", readiness: "not-checked", kernelStop }), noOp: false, kernelStop };
781
1146
  }
782
- if (state !== "running")
1147
+ // A Windows custodian outlives its emptied job by a moment before it exits.
1148
+ if (state !== "running" && state !== "members-running")
783
1149
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the broker exit could not be attributed; its stop request was retained", { target: instanceProjection(row) });
784
1150
  await delay(100);
785
1151
  }
@@ -794,22 +1160,25 @@ export function assertNoServiceUnitAttempts(space, name) {
794
1160
  if (pending.length || actions.length)
795
1161
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "a retained native installation, removal or unit action names this definition; no direct process effect was substituted", { target: { space, name, attempts: [...pending, ...actions].map((row) => ({ instanceId: row.name, attemptId: row.record.value.attemptId })) } });
796
1162
  }
797
- export function removableServiceInstances(space, name) {
798
- const pending = [...serviceInstallIntents(space), ...serviceUninstallIntents(space)].filter((row) => row.record.value.definition === name);
1163
+ export function removableServiceInstances(space, name, instanceId) {
1164
+ const named = (row) => instanceId === undefined || row.name === instanceId;
1165
+ const pending = [...serviceInstallIntents(space), ...serviceUninstallIntents(space)].filter((row) => row.record.value.definition === name && named(row));
799
1166
  if (pending.length)
800
1167
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "service remove cannot discard a definition while an installation or removal attempt may still own a unit, private store or enable link", { target: { space, name, attempts: pending.map((row) => ({ instanceId: row.name, attemptId: row.record.value.attemptId, step: row.record.value.step, position: row.record.value.position })) }, remedy: "inspect and reconcile every retained native unit attempt before removing this definition" });
801
1168
  const nativeActions = serviceUnitActionStore(space).list();
802
1169
  if (nativeActions.some((row) => row.name !== row.record.value.instanceId))
803
1170
  throw new CommandFailure("refused", "SCHEMA_INVALID", "a native action filename differs from its full instance ID; no definition was removed");
804
- const actions = nativeActions.filter((row) => row.record.value.definition === name);
1171
+ const actions = nativeActions.filter((row) => row.record.value.definition === name && named(row));
805
1172
  if (actions.length)
806
1173
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "service remove cannot discard a definition while an exact native action is retained", { target: { space, name, attempts: actions.map((row) => ({ instanceId: row.name, attemptId: row.record.value.attemptId, operation: row.record.value.operation, position: row.record.value.position })) } });
807
- const rows = serviceInstances(space, name);
1174
+ const rows = serviceInstances(space, name).filter(named);
1175
+ if (instanceId !== undefined && !rows.length)
1176
+ throw new CommandFailure("refused", "TARGET_NOT_FOUND", "the full instance ID does not belong to this selected definition and space", { target: { space, name, instanceId } });
808
1177
  for (const row of rows)
809
1178
  refuseRecordedSupervisor(row.record.value, "remove");
810
1179
  for (const row of rows)
811
1180
  if (!gone(observeServiceProcess(row.record.value)))
812
- throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "service remove requires every recorded owned instance stopped and its supervisor uninstalled", { target: instanceProjection(row), remedy: `use cotal service stop ${name} --instance ${row.name} before removing its definition` });
1181
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "service remove requires every recorded owned instance stopped and its supervisor uninstalled", { target: instanceProjection(row), remedy: `use cotal service stop ${name} --instance ${row.name} before removing ${instanceId === undefined ? "its definition" : "its record"}` });
813
1182
  // A settled exit is a record of evidence, not an unknown request. An unsettled one is settled by
814
1183
  // the named stop, which signals nothing when the process is already gone.
815
1184
  const settle = (row) => row.record.value.state === "stopping" || retainedStopRequest(row.record.value) ? { remedy: `inspect the original request with cotal service status ${name} --instance ${row.name} --space ${space}` }
@@ -822,12 +1191,27 @@ export function removableServiceInstances(space, name) {
822
1191
  throw new CommandFailure("unknown", "OPERATION_UNKNOWN", "the broker has no recorded exact-exit stop from this controller; its launch cannot be forgotten merely because the process disappeared", { target: instanceProjection(row), ...settle(row) });
823
1192
  return rows;
824
1193
  }
825
- /** Called under the definition writer lock, after stopped/host/supervisor checks for every row. */
1194
+ /** Forget one stopped instance record of a kept definition, under the definition writer lock and
1195
+ * after the checks `service remove` makes for each record. Its logs stay. */
1196
+ export function removeStoppedInstanceRecord(definition, instanceId) {
1197
+ const space = definition.record.value.space;
1198
+ const hold = serviceDefinitionStore(space).pin(definition);
1199
+ try {
1200
+ const [row] = removableServiceInstances(space, definition.name, instanceId);
1201
+ serviceInstanceStore(space).commit(row.name, row, undefined);
1202
+ }
1203
+ finally {
1204
+ hold.release();
1205
+ }
1206
+ }
1207
+ /** Called under the definition writer lock, after stopped/host/supervisor checks for every row.
1208
+ * Returns the full IDs whose records it removed. */
826
1209
  export function removeStoppedInstanceRecords(space, name) {
827
1210
  const rows = removableServiceInstances(space, name), removed = [];
828
1211
  try {
829
1212
  for (const row of rows) {
830
1213
  serviceInstanceStore(space).commit(row.name, row, undefined);
1214
+ removeCustodyCapability(space, row.record.value.custody);
831
1215
  removed.push(row.name);
832
1216
  }
833
1217
  }
@@ -836,37 +1220,64 @@ export function removeStoppedInstanceRecords(space, name) {
836
1220
  throw error;
837
1221
  throw new CommandFailure("partial", "OPERATION_PARTIAL", "some stopped instance records were removed, but the definition was kept after another record changed", { target: { space, name }, changed: removed.map((instanceId) => ({ kind: "stopped-instance-record", instanceId })), remedy: "inspect the remaining records before another removal; no process was signalled and logs were retained" });
838
1222
  }
1223
+ return removed;
839
1224
  }
1225
+ /** The most a finite tail reads back from the end of a log, the size at which a start rotates it. */
1226
+ const LOG_TAIL_BYTES = LOG_ROTATE_BYTES;
840
1227
  /** Read only bounded regular-file bytes; log data is not promised to be secret-redacted. */
841
1228
  export function readServiceLog(space, id, tail) {
842
1229
  const path = serviceLogPath(space, id);
843
1230
  if (!path)
844
1231
  return { lines: [], omittedBytes: 0, path: null };
1232
+ return readOwnedLogTail(path, tail);
1233
+ }
1234
+ /** The refusal for a log this account cannot open, with the step that gives its owner read and write back. */
1235
+ function unreadableLog(path, code) {
1236
+ return new CommandFailure("refused", "PERMISSION_DENIED", `the log ${path} cannot be read by this account (${code}); nothing was read or changed`, { target: { path }, remedy: `make it readable by you, for example with chmod u+rw ${shellPath(path)}` });
1237
+ }
1238
+ /** The last `tail` lines of an owned private log file, from at most its last 1 MiB. A log this
1239
+ * account cannot read is refused with the step that gives its owner read and write back. */
1240
+ export function readOwnedLogTail(path, tail) {
845
1241
  let fd;
846
1242
  try {
847
1243
  fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
848
1244
  }
849
1245
  catch (error) {
850
- if (error.code === "ENOENT")
1246
+ const code = error.code;
1247
+ if (code === "ENOENT")
851
1248
  return { lines: [], omittedBytes: 0, path };
1249
+ if (code === "EACCES" || code === "EPERM")
1250
+ throw unreadableLog(path, code);
852
1251
  throw error;
853
1252
  }
854
1253
  try {
855
1254
  const info = fstatSync(fd);
856
1255
  if (![info.size, info.dev, info.ino].every((number) => Number.isSafeInteger(number) && number >= 0))
857
1256
  throw new CommandFailure("refused", "UNSUPPORTED", "this log's native file coordinates cannot be represented safely; no approximate byte offsets were reported");
858
- if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o077) !== 0)
1257
+ if (!privateLog(info))
859
1258
  throw new CommandFailure("refused", "PERMISSION_DENIED", "the service log is not an owned private regular file");
860
- const length = Math.min(info.size, 1024 * 1024), start = info.size - length;
861
- const buffer = Buffer.alloc(length);
862
- let offset = 0;
863
- while (offset < length) {
864
- const count = readSync(fd, buffer, offset, length - offset, start + offset);
865
- if (!count)
1259
+ // Read back 1 MiB at a time until the bytes hold `tail` whole lines, the file's start or the bound.
1260
+ const limit = Math.min(info.size, LOG_TAIL_BYTES), chunks = [];
1261
+ let start = info.size, newlines = 0;
1262
+ while (info.size - start < limit && (start === info.size || newlines < tail)) {
1263
+ const length = Math.min(1024 * 1024, limit - (info.size - start)), chunk = Buffer.alloc(length);
1264
+ let offset = 0;
1265
+ while (offset < length) {
1266
+ const count = readSync(fd, chunk, offset, length - offset, start - length + offset);
1267
+ if (!count)
1268
+ break;
1269
+ offset += count;
1270
+ }
1271
+ if (offset < length)
866
1272
  break;
867
- offset += count;
1273
+ chunks.unshift(chunk);
1274
+ start -= length;
1275
+ for (let at = chunk.indexOf(10); at !== -1; at = chunk.indexOf(10, at + 1))
1276
+ newlines++;
1277
+ if (start + length === info.size && chunk[length - 1] === 10)
1278
+ newlines--;
868
1279
  }
869
- let text = buffer.subarray(0, offset).toString("utf8");
1280
+ let text = Buffer.concat(chunks).toString("utf8");
870
1281
  if (start)
871
1282
  text = text.includes("\n") ? text.slice(text.indexOf("\n") + 1) : "";
872
1283
  const all = text.replace(/\n$/, "").split("\n");
@@ -876,7 +1287,40 @@ export function readServiceLog(space, id, tail) {
876
1287
  closeSync(fd);
877
1288
  }
878
1289
  }
879
- /** One bounded raw log slice. File identity and byte offsets are local file facts, not global sequences. */
1290
+ /** The last line an owned private log holds past byte `from`, as one bounded line of operator output,
1291
+ * or undefined when nothing was logged there or the log cannot be read as an owned file. */
1292
+ function lastLoggedLine(path, from) {
1293
+ let fd;
1294
+ try {
1295
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1296
+ }
1297
+ catch {
1298
+ return undefined;
1299
+ }
1300
+ try {
1301
+ const info = fstatSync(fd);
1302
+ if (!privateLog(info) || info.size <= from)
1303
+ return undefined;
1304
+ const length = Math.min(info.size - from, 8192), bytes = Buffer.alloc(length);
1305
+ let read = 0;
1306
+ while (read < length) {
1307
+ const count = readSync(fd, bytes, read, length - read, info.size - length + read);
1308
+ if (!count)
1309
+ break;
1310
+ read += count;
1311
+ }
1312
+ const line = bytes.subarray(0, read).toString("utf8").split("\n").map((text) => text.trim()).filter(Boolean).pop();
1313
+ return line ? oneLine(boundedValue(line, 400)) : undefined;
1314
+ }
1315
+ catch {
1316
+ return undefined;
1317
+ }
1318
+ finally {
1319
+ closeSync(fd);
1320
+ }
1321
+ }
1322
+ /** One bounded raw log slice. File identity and byte offsets are local file facts, not global sequences.
1323
+ * A log this account cannot read is refused as `readOwnedLogTail` refuses it. */
880
1324
  export function serviceLogSlice(space, id, position, tail) {
881
1325
  const path = serviceLogPath(space, id);
882
1326
  if (!path)
@@ -886,15 +1330,18 @@ export function serviceLogSlice(space, id, position, tail) {
886
1330
  fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
887
1331
  }
888
1332
  catch (error) {
889
- if (error.code === "ENOENT")
1333
+ const code = error.code;
1334
+ if (code === "ENOENT")
890
1335
  return undefined;
1336
+ if (code === "EACCES" || code === "EPERM")
1337
+ throw unreadableLog(path, code);
891
1338
  throw error;
892
1339
  }
893
1340
  try {
894
1341
  const info = fstatSync(fd);
895
1342
  if (![info.size, info.dev, info.ino].every((number) => Number.isSafeInteger(number) && number >= 0))
896
1343
  throw new CommandFailure("refused", "UNSUPPORTED", "this log's native file coordinates cannot be represented safely; no approximate byte offsets were reported");
897
- if (!info.isFile() || info.uid !== process.getuid() || (info.mode & 0o077) !== 0)
1344
+ if (!privateLog(info))
898
1345
  throw new CommandFailure("refused", "PERMISSION_DENIED", "the selected service log is not an owned private regular file");
899
1346
  const replaced = position !== undefined && (position.dev !== info.dev || position.ino !== info.ino);
900
1347
  const truncated = position !== undefined && !replaced && info.size < position.offset;