@dsh-ray/lark-channel 0.0.1-seed.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (344) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +206 -1
  3. package/bin/dsh-lark-setup.js +37 -0
  4. package/bin/dsh-ray-setup.js +34 -0
  5. package/bin/dsh-supervised-growth-setup.js +34 -0
  6. package/cordis.patch.yml +23 -0
  7. package/docs/operations.md +133 -0
  8. package/docs/progress-security.md +125 -0
  9. package/docs/rsi-setup.md +216 -0
  10. package/docs/setup.md +358 -0
  11. package/docs/supervised-growth.md +95 -0
  12. package/lib/adapter.d.ts +185 -0
  13. package/lib/adapter.d.ts.map +1 -0
  14. package/lib/adapter.js +2072 -0
  15. package/lib/adapter.js.map +1 -0
  16. package/lib/answer-card.d.ts +40 -0
  17. package/lib/answer-card.d.ts.map +1 -0
  18. package/lib/answer-card.js +262 -0
  19. package/lib/answer-card.js.map +1 -0
  20. package/lib/approval.d.ts +26 -0
  21. package/lib/approval.d.ts.map +1 -0
  22. package/lib/approval.js +104 -0
  23. package/lib/approval.js.map +1 -0
  24. package/lib/business-cli-install.d.ts +9 -0
  25. package/lib/business-cli-install.d.ts.map +1 -0
  26. package/lib/business-cli-install.js +367 -0
  27. package/lib/business-cli-install.js.map +1 -0
  28. package/lib/business-environment.d.ts +2 -0
  29. package/lib/business-environment.d.ts.map +1 -0
  30. package/lib/business-environment.js +16 -0
  31. package/lib/business-environment.js.map +1 -0
  32. package/lib/business-skill.d.ts +32 -0
  33. package/lib/business-skill.d.ts.map +1 -0
  34. package/lib/business-skill.js +202 -0
  35. package/lib/business-skill.js.map +1 -0
  36. package/lib/command-card.d.ts +3 -0
  37. package/lib/command-card.d.ts.map +1 -0
  38. package/lib/command-card.js +480 -0
  39. package/lib/command-card.js.map +1 -0
  40. package/lib/config.d.ts +32 -0
  41. package/lib/config.d.ts.map +1 -0
  42. package/lib/config.js +115 -0
  43. package/lib/config.js.map +1 -0
  44. package/lib/group-thread.d.ts +20 -0
  45. package/lib/group-thread.d.ts.map +1 -0
  46. package/lib/group-thread.js +36 -0
  47. package/lib/group-thread.js.map +1 -0
  48. package/lib/index.d.ts +34 -0
  49. package/lib/index.d.ts.map +1 -0
  50. package/lib/index.js +53 -0
  51. package/lib/index.js.map +1 -0
  52. package/lib/launchd-control.d.ts +24 -0
  53. package/lib/launchd-control.d.ts.map +1 -0
  54. package/lib/launchd-control.js +68 -0
  55. package/lib/launchd-control.js.map +1 -0
  56. package/lib/launchd-identity.d.ts +34 -0
  57. package/lib/launchd-identity.d.ts.map +1 -0
  58. package/lib/launchd-identity.js +184 -0
  59. package/lib/launchd-identity.js.map +1 -0
  60. package/lib/launchd-target-lock.d.ts +6 -0
  61. package/lib/launchd-target-lock.d.ts.map +1 -0
  62. package/lib/launchd-target-lock.js +48 -0
  63. package/lib/launchd-target-lock.js.map +1 -0
  64. package/lib/launchd.d.ts +62 -0
  65. package/lib/launchd.d.ts.map +1 -0
  66. package/lib/launchd.js +370 -0
  67. package/lib/launchd.js.map +1 -0
  68. package/lib/model-picker.d.ts +24 -0
  69. package/lib/model-picker.d.ts.map +1 -0
  70. package/lib/model-picker.js +95 -0
  71. package/lib/model-picker.js.map +1 -0
  72. package/lib/normalize.d.ts +12 -0
  73. package/lib/normalize.d.ts.map +1 -0
  74. package/lib/normalize.js +85 -0
  75. package/lib/normalize.js.map +1 -0
  76. package/lib/permission-picker.d.ts +29 -0
  77. package/lib/permission-picker.d.ts.map +1 -0
  78. package/lib/permission-picker.js +145 -0
  79. package/lib/permission-picker.js.map +1 -0
  80. package/lib/progress.d.ts +34 -0
  81. package/lib/progress.d.ts.map +1 -0
  82. package/lib/progress.js +354 -0
  83. package/lib/progress.js.map +1 -0
  84. package/lib/resident.d.ts +13 -0
  85. package/lib/resident.d.ts.map +1 -0
  86. package/lib/resident.js +41 -0
  87. package/lib/resident.js.map +1 -0
  88. package/lib/rsi-authority-config.d.ts +29 -0
  89. package/lib/rsi-authority-config.d.ts.map +1 -0
  90. package/lib/rsi-authority-config.js +233 -0
  91. package/lib/rsi-authority-config.js.map +1 -0
  92. package/lib/rsi-authority-resources.d.ts +36 -0
  93. package/lib/rsi-authority-resources.d.ts.map +1 -0
  94. package/lib/rsi-authority-resources.js +139 -0
  95. package/lib/rsi-authority-resources.js.map +1 -0
  96. package/lib/rsi-authority-runtime.d.ts +51 -0
  97. package/lib/rsi-authority-runtime.d.ts.map +1 -0
  98. package/lib/rsi-authority-runtime.js +496 -0
  99. package/lib/rsi-authority-runtime.js.map +1 -0
  100. package/lib/rsi-bootstrap-manifest.d.ts +53 -0
  101. package/lib/rsi-bootstrap-manifest.d.ts.map +1 -0
  102. package/lib/rsi-bootstrap-manifest.js +507 -0
  103. package/lib/rsi-bootstrap-manifest.js.map +1 -0
  104. package/lib/rsi-bootstrap.d.ts +61 -0
  105. package/lib/rsi-bootstrap.d.ts.map +1 -0
  106. package/lib/rsi-bootstrap.js +597 -0
  107. package/lib/rsi-bootstrap.js.map +1 -0
  108. package/lib/rsi-build.d.ts +76 -0
  109. package/lib/rsi-build.d.ts.map +1 -0
  110. package/lib/rsi-build.js +210 -0
  111. package/lib/rsi-build.js.map +1 -0
  112. package/lib/rsi-host-authorities.d.ts +18 -0
  113. package/lib/rsi-host-authorities.d.ts.map +1 -0
  114. package/lib/rsi-host-authorities.js +129 -0
  115. package/lib/rsi-host-authorities.js.map +1 -0
  116. package/lib/rsi-host-update.d.ts +179 -0
  117. package/lib/rsi-host-update.d.ts.map +1 -0
  118. package/lib/rsi-host-update.js +568 -0
  119. package/lib/rsi-host-update.js.map +1 -0
  120. package/lib/rsi-install-inputs.d.ts +45 -0
  121. package/lib/rsi-install-inputs.d.ts.map +1 -0
  122. package/lib/rsi-install-inputs.js +345 -0
  123. package/lib/rsi-install-inputs.js.map +1 -0
  124. package/lib/rsi-install.d.ts +117 -0
  125. package/lib/rsi-install.d.ts.map +1 -0
  126. package/lib/rsi-install.js +791 -0
  127. package/lib/rsi-install.js.map +1 -0
  128. package/lib/rsi-linux-cgroup-roots.d.ts +3 -0
  129. package/lib/rsi-linux-cgroup-roots.d.ts.map +1 -0
  130. package/lib/rsi-linux-cgroup-roots.js +3 -0
  131. package/lib/rsi-linux-cgroup-roots.js.map +1 -0
  132. package/lib/rsi-linux-creation-build.d.ts +36 -0
  133. package/lib/rsi-linux-creation-build.d.ts.map +1 -0
  134. package/lib/rsi-linux-creation-build.js +213 -0
  135. package/lib/rsi-linux-creation-build.js.map +1 -0
  136. package/lib/rsi-linux-native-materialize.d.ts +31 -0
  137. package/lib/rsi-linux-native-materialize.d.ts.map +1 -0
  138. package/lib/rsi-linux-native-materialize.js +162 -0
  139. package/lib/rsi-linux-native-materialize.js.map +1 -0
  140. package/lib/rsi-linux-native-relocation.d.ts +124 -0
  141. package/lib/rsi-linux-native-relocation.d.ts.map +1 -0
  142. package/lib/rsi-linux-native-relocation.js +1571 -0
  143. package/lib/rsi-linux-native-relocation.js.map +1 -0
  144. package/lib/rsi-linux-native-resources.d.ts +97 -0
  145. package/lib/rsi-linux-native-resources.d.ts.map +1 -0
  146. package/lib/rsi-linux-native-resources.js +521 -0
  147. package/lib/rsi-linux-native-resources.js.map +1 -0
  148. package/lib/rsi-linux-repository-bootstrap.d.ts +17 -0
  149. package/lib/rsi-linux-repository-bootstrap.d.ts.map +1 -0
  150. package/lib/rsi-linux-repository-bootstrap.js +317 -0
  151. package/lib/rsi-linux-repository-bootstrap.js.map +1 -0
  152. package/lib/rsi-linux-runner-states.d.ts +20 -0
  153. package/lib/rsi-linux-runner-states.d.ts.map +1 -0
  154. package/lib/rsi-linux-runner-states.js +70 -0
  155. package/lib/rsi-linux-runner-states.js.map +1 -0
  156. package/lib/rsi-linux-runtime-bootstrap.d.ts +10 -0
  157. package/lib/rsi-linux-runtime-bootstrap.d.ts.map +1 -0
  158. package/lib/rsi-linux-runtime-bootstrap.js +38 -0
  159. package/lib/rsi-linux-runtime-bootstrap.js.map +1 -0
  160. package/lib/rsi-linux-source-build.d.ts +28 -0
  161. package/lib/rsi-linux-source-build.d.ts.map +1 -0
  162. package/lib/rsi-linux-source-build.js +43 -0
  163. package/lib/rsi-linux-source-build.js.map +1 -0
  164. package/lib/rsi-local-activation.d.ts +78 -0
  165. package/lib/rsi-local-activation.d.ts.map +1 -0
  166. package/lib/rsi-local-activation.js +486 -0
  167. package/lib/rsi-local-activation.js.map +1 -0
  168. package/lib/rsi-local-cohort.d.ts +70 -0
  169. package/lib/rsi-local-cohort.d.ts.map +1 -0
  170. package/lib/rsi-local-cohort.js +810 -0
  171. package/lib/rsi-local-cohort.js.map +1 -0
  172. package/lib/rsi-local-install.d.ts +70 -0
  173. package/lib/rsi-local-install.d.ts.map +1 -0
  174. package/lib/rsi-local-install.js +363 -0
  175. package/lib/rsi-local-install.js.map +1 -0
  176. package/lib/rsi-local-pair-install.d.ts +53 -0
  177. package/lib/rsi-local-pair-install.d.ts.map +1 -0
  178. package/lib/rsi-local-pair-install.js +215 -0
  179. package/lib/rsi-local-pair-install.js.map +1 -0
  180. package/lib/rsi-local-profile-update.d.ts +25 -0
  181. package/lib/rsi-local-profile-update.d.ts.map +1 -0
  182. package/lib/rsi-local-profile-update.js +226 -0
  183. package/lib/rsi-local-profile-update.js.map +1 -0
  184. package/lib/rsi-local-roots-extension.d.ts +11 -0
  185. package/lib/rsi-local-roots-extension.d.ts.map +1 -0
  186. package/lib/rsi-local-roots-extension.js +31 -0
  187. package/lib/rsi-local-roots-extension.js.map +1 -0
  188. package/lib/rsi-local-update-build.d.ts +37 -0
  189. package/lib/rsi-local-update-build.d.ts.map +1 -0
  190. package/lib/rsi-local-update-build.js +75 -0
  191. package/lib/rsi-local-update-build.js.map +1 -0
  192. package/lib/rsi-local-update.d.ts +39 -0
  193. package/lib/rsi-local-update.d.ts.map +1 -0
  194. package/lib/rsi-local-update.js +205 -0
  195. package/lib/rsi-local-update.js.map +1 -0
  196. package/lib/rsi-memory-learning.d.ts +36 -0
  197. package/lib/rsi-memory-learning.d.ts.map +1 -0
  198. package/lib/rsi-memory-learning.js +111 -0
  199. package/lib/rsi-memory-learning.js.map +1 -0
  200. package/lib/rsi-native-install.d.ts +38 -0
  201. package/lib/rsi-native-install.d.ts.map +1 -0
  202. package/lib/rsi-native-install.js +312 -0
  203. package/lib/rsi-native-install.js.map +1 -0
  204. package/lib/rsi-native-launchd.d.ts +7 -0
  205. package/lib/rsi-native-launchd.d.ts.map +1 -0
  206. package/lib/rsi-native-launchd.js +49 -0
  207. package/lib/rsi-native-launchd.js.map +1 -0
  208. package/lib/rsi-native-profile.d.ts +76 -0
  209. package/lib/rsi-native-profile.d.ts.map +1 -0
  210. package/lib/rsi-native-profile.js +530 -0
  211. package/lib/rsi-native-profile.js.map +1 -0
  212. package/lib/rsi-native-runtime-bootstrap.d.ts +44 -0
  213. package/lib/rsi-native-runtime-bootstrap.d.ts.map +1 -0
  214. package/lib/rsi-native-runtime-bootstrap.js +619 -0
  215. package/lib/rsi-native-runtime-bootstrap.js.map +1 -0
  216. package/lib/rsi-ordinary-use-learning.d.ts +60 -0
  217. package/lib/rsi-ordinary-use-learning.d.ts.map +1 -0
  218. package/lib/rsi-ordinary-use-learning.js +103 -0
  219. package/lib/rsi-ordinary-use-learning.js.map +1 -0
  220. package/lib/rsi-owner-profile.d.ts +37 -0
  221. package/lib/rsi-owner-profile.d.ts.map +1 -0
  222. package/lib/rsi-owner-profile.js +178 -0
  223. package/lib/rsi-owner-profile.js.map +1 -0
  224. package/lib/rsi-plugin-creation.d.ts +46 -0
  225. package/lib/rsi-plugin-creation.d.ts.map +1 -0
  226. package/lib/rsi-plugin-creation.js +227 -0
  227. package/lib/rsi-plugin-creation.js.map +1 -0
  228. package/lib/rsi-plugin-revision.d.ts +38 -0
  229. package/lib/rsi-plugin-revision.d.ts.map +1 -0
  230. package/lib/rsi-plugin-revision.js +221 -0
  231. package/lib/rsi-plugin-revision.js.map +1 -0
  232. package/lib/rsi-profile.d.ts +81 -0
  233. package/lib/rsi-profile.d.ts.map +1 -0
  234. package/lib/rsi-profile.js +551 -0
  235. package/lib/rsi-profile.js.map +1 -0
  236. package/lib/rsi-release-build.d.ts +59 -0
  237. package/lib/rsi-release-build.d.ts.map +1 -0
  238. package/lib/rsi-release-build.js +219 -0
  239. package/lib/rsi-release-build.js.map +1 -0
  240. package/lib/rsi-scanner-retirement-config.d.ts +34 -0
  241. package/lib/rsi-scanner-retirement-config.d.ts.map +1 -0
  242. package/lib/rsi-scanner-retirement-config.js +272 -0
  243. package/lib/rsi-scanner-retirement-config.js.map +1 -0
  244. package/lib/rsi-scanner-retirement-runtime.d.ts +23 -0
  245. package/lib/rsi-scanner-retirement-runtime.d.ts.map +1 -0
  246. package/lib/rsi-scanner-retirement-runtime.js +98 -0
  247. package/lib/rsi-scanner-retirement-runtime.js.map +1 -0
  248. package/lib/rsi-scanner-retirement-stage.d.ts +55 -0
  249. package/lib/rsi-scanner-retirement-stage.d.ts.map +1 -0
  250. package/lib/rsi-scanner-retirement-stage.js +181 -0
  251. package/lib/rsi-scanner-retirement-stage.js.map +1 -0
  252. package/lib/rsi-scanner-retirement-transition.d.ts +57 -0
  253. package/lib/rsi-scanner-retirement-transition.d.ts.map +1 -0
  254. package/lib/rsi-scanner-retirement-transition.js +330 -0
  255. package/lib/rsi-scanner-retirement-transition.js.map +1 -0
  256. package/lib/rsi-service-environment.d.ts +6 -0
  257. package/lib/rsi-service-environment.d.ts.map +1 -0
  258. package/lib/rsi-service-environment.js +113 -0
  259. package/lib/rsi-service-environment.js.map +1 -0
  260. package/lib/rsi-service-setup.d.ts +10 -0
  261. package/lib/rsi-service-setup.d.ts.map +1 -0
  262. package/lib/rsi-service-setup.js +34 -0
  263. package/lib/rsi-service-setup.js.map +1 -0
  264. package/lib/rsi-setup.d.ts +92 -0
  265. package/lib/rsi-setup.d.ts.map +1 -0
  266. package/lib/rsi-setup.js +908 -0
  267. package/lib/rsi-setup.js.map +1 -0
  268. package/lib/rsi-source-maintenance.d.ts +33 -0
  269. package/lib/rsi-source-maintenance.d.ts.map +1 -0
  270. package/lib/rsi-source-maintenance.js +407 -0
  271. package/lib/rsi-source-maintenance.js.map +1 -0
  272. package/lib/rsi-source-update.d.ts +26 -0
  273. package/lib/rsi-source-update.d.ts.map +1 -0
  274. package/lib/rsi-source-update.js +276 -0
  275. package/lib/rsi-source-update.js.map +1 -0
  276. package/lib/rsi-source.d.ts +34 -0
  277. package/lib/rsi-source.d.ts.map +1 -0
  278. package/lib/rsi-source.js +487 -0
  279. package/lib/rsi-source.js.map +1 -0
  280. package/lib/rsi-systemd-bootstrap.d.ts +46 -0
  281. package/lib/rsi-systemd-bootstrap.d.ts.map +1 -0
  282. package/lib/rsi-systemd-bootstrap.js +271 -0
  283. package/lib/rsi-systemd-bootstrap.js.map +1 -0
  284. package/lib/sdk.d.ts +216 -0
  285. package/lib/sdk.d.ts.map +1 -0
  286. package/lib/sdk.js +1990 -0
  287. package/lib/sdk.js.map +1 -0
  288. package/lib/service.d.ts +63 -0
  289. package/lib/service.d.ts.map +1 -0
  290. package/lib/service.js +599 -0
  291. package/lib/service.js.map +1 -0
  292. package/lib/setup-business.d.ts +49 -0
  293. package/lib/setup-business.d.ts.map +1 -0
  294. package/lib/setup-business.js +335 -0
  295. package/lib/setup-business.js.map +1 -0
  296. package/lib/setup-materialization.d.ts +15 -0
  297. package/lib/setup-materialization.d.ts.map +1 -0
  298. package/lib/setup-materialization.js +221 -0
  299. package/lib/setup-materialization.js.map +1 -0
  300. package/lib/setup-profile.d.ts +23 -0
  301. package/lib/setup-profile.d.ts.map +1 -0
  302. package/lib/setup-profile.js +1248 -0
  303. package/lib/setup-profile.js.map +1 -0
  304. package/lib/setup.d.ts +298 -0
  305. package/lib/setup.d.ts.map +1 -0
  306. package/lib/setup.js +3310 -0
  307. package/lib/setup.js.map +1 -0
  308. package/lib/supervised-growth-profile.d.ts +111 -0
  309. package/lib/supervised-growth-profile.d.ts.map +1 -0
  310. package/lib/supervised-growth-profile.js +903 -0
  311. package/lib/supervised-growth-profile.js.map +1 -0
  312. package/lib/supervised-growth-setup.d.ts +201 -0
  313. package/lib/supervised-growth-setup.d.ts.map +1 -0
  314. package/lib/supervised-growth-setup.js +1005 -0
  315. package/lib/supervised-growth-setup.js.map +1 -0
  316. package/lib/systemd.d.ts +70 -0
  317. package/lib/systemd.d.ts.map +1 -0
  318. package/lib/systemd.js +308 -0
  319. package/lib/systemd.js.map +1 -0
  320. package/lib/tool-approval.d.ts +22 -0
  321. package/lib/tool-approval.d.ts.map +1 -0
  322. package/lib/tool-approval.js +107 -0
  323. package/lib/tool-approval.js.map +1 -0
  324. package/lib/types.d.ts +351 -0
  325. package/lib/types.d.ts.map +1 -0
  326. package/lib/types.js +11 -0
  327. package/lib/types.js.map +1 -0
  328. package/lib/user-question.d.ts +31 -0
  329. package/lib/user-question.d.ts.map +1 -0
  330. package/lib/user-question.js +161 -0
  331. package/lib/user-question.js.map +1 -0
  332. package/lib/version.d.ts +2 -0
  333. package/lib/version.d.ts.map +1 -0
  334. package/lib/version.js +2 -0
  335. package/lib/version.js.map +1 -0
  336. package/lib/windows-task.d.ts +42 -0
  337. package/lib/windows-task.d.ts.map +1 -0
  338. package/lib/windows-task.js +143 -0
  339. package/lib/windows-task.js.map +1 -0
  340. package/lib/ws-card-callback.d.ts +7 -0
  341. package/lib/ws-card-callback.d.ts.map +1 -0
  342. package/lib/ws-card-callback.js +51 -0
  343. package/lib/ws-card-callback.js.map +1 -0
  344. package/package.json +162 -4
@@ -0,0 +1,791 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { access, lstat, mkdir, open, readdir, readFile, realpath, rename, unlink } from 'node:fs/promises';
3
+ import { constants } from 'node:fs';
4
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
5
+ import { setTimeout as delay } from 'node:timers/promises';
6
+ import { listActiveAutomationsForReadiness } from '@dsh-ray/assistant-automations';
7
+ import { growthObjectDigest } from '@dsh-ray/assistant-growth-contract';
8
+ import { isDeepStrictEqual } from 'node:util';
9
+ import { controlPlaneDigest, queryRuntimeObserver, runtimeConfigDigest } from '@dsh-ray/plugin-control-plane';
10
+ import { withDshHomeLifecycleLock } from './setup.js';
11
+ import { prepareRsiSourceWorkspace } from './rsi-source.js';
12
+ import { rsiBuildResources as io } from './rsi-build.js';
13
+ import { prepareRsiReleaseBuildEnvironment, readRsiReleaseBuildEnvironment, RsiReleaseBuildUnavailableError } from './rsi-release-build.js';
14
+ import { prepareRsiAuthorityRuntime } from './rsi-authority-runtime.js';
15
+ import { prepareRsiAuthorityResources } from './rsi-authority-resources.js';
16
+ import { createRsiBootstrapManifest } from './rsi-bootstrap-manifest.js';
17
+ import { validateRsiPluginCreationSetup } from './rsi-plugin-creation.js';
18
+ import { validateRsiPluginRevisionSetup } from './rsi-plugin-revision.js';
19
+ import { prepareLinuxRsiRuntime, readLinuxRsiRuntime, LinuxRsiRuntimeUnavailableError } from './rsi-linux-runtime-bootstrap.js';
20
+ import { prepareLinuxRsiRepositoryRuntime, readLinuxRsiRepositoryRuntime } from './rsi-linux-repository-bootstrap.js';
21
+ import { prepareLinuxRsiCreationBuildEnvironment, readLinuxRsiCreationBuildEnvironment, RsiLinuxCreationBuildUnavailableError } from './rsi-linux-creation-build.js';
22
+ import { discoverLinuxCgroupRoots, RsiLinuxCgroupUnavailableError } from './rsi-linux-cgroup-roots.js';
23
+ import { prepareRsiLinuxRunnerStates } from './rsi-linux-runner-states.js';
24
+ import { inspectRsiOwnerConfiguration, prepareRsiOwnerConfiguration, verifyExistingRsiOwnerConfiguration } from './rsi-bootstrap.js';
25
+ import { collectRsiInstalledInputs, RsiInstalledInputsUnavailableError } from './rsi-install-inputs.js';
26
+ import { captureRsiSystemdUnitProperties, readRsiSystemdUnitProperties } from './rsi-systemd-bootstrap.js';
27
+ import { configureRsiSetupLocked, rsiSetupPorts } from './rsi-setup.js';
28
+ import { systemdServicePaths } from './systemd.js';
29
+ import { readRsiServiceEnvironment } from './rsi-service-environment.js';
30
+ import { version } from './version.js';
31
+ import { readRsiLocalCohort, verifyRsiLocalInstalledPackages } from './rsi-local-cohort.js';
32
+ import { installRsiLocalProfile, isRsiLocalPackageRepairable } from './rsi-local-install.js';
33
+ import { assertRsiSchedulerActivation, captureRsiAutomationInventories, rsiDatabasePaths } from './rsi-owner-profile.js';
34
+ const profilePattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
35
+ const coordinatorBundles = ['assistant-policy', 'assistant-automations', 'plugin-control-plane'];
36
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
37
+ function fail(message) { throw new Error(`rsi install: ${message}`); }
38
+ async function exists(path) {
39
+ try {
40
+ await lstat(path);
41
+ return true;
42
+ }
43
+ catch (error) {
44
+ if (error.code !== 'ENOENT')
45
+ throw error;
46
+ return false;
47
+ }
48
+ }
49
+ async function snapshotPrivateConfigTree(root) {
50
+ const entries = new Map();
51
+ const walk = async (directory) => {
52
+ for (const item of await readdir(directory, { withFileTypes: true })) {
53
+ const path = join(directory, item.name);
54
+ const stat = await lstat(path);
55
+ if (stat.isDirectory()) {
56
+ await io.directory(path);
57
+ await walk(path);
58
+ }
59
+ else if (stat.isFile()) {
60
+ if (stat.nlink !== 1 || await realpath(path) !== path)
61
+ fail(`unsafe config file: ${path}`);
62
+ entries.set(path, await io.readStable(path, 2_097_152, true));
63
+ }
64
+ else {
65
+ fail(`unsafe config entry: ${path}`);
66
+ }
67
+ }
68
+ };
69
+ await io.directory(root);
70
+ await walk(root);
71
+ return entries;
72
+ }
73
+ async function atomicWritePrivateConfigFile(path, bytes) {
74
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
75
+ const temporary = `${path}.${randomUUID()}.tmp`;
76
+ const descriptor = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
77
+ try {
78
+ await descriptor.writeFile(bytes);
79
+ await descriptor.sync();
80
+ }
81
+ finally {
82
+ await descriptor.close();
83
+ }
84
+ try {
85
+ await rename(temporary, path);
86
+ await io.syncDirectory(dirname(path));
87
+ }
88
+ catch (error) {
89
+ await unlink(temporary).catch(() => { });
90
+ throw error;
91
+ }
92
+ }
93
+ async function restorePrivateConfigTree(root, snapshot) {
94
+ const dirs = new Set([root]);
95
+ const walk = async (directory) => {
96
+ for (const item of await readdir(directory, { withFileTypes: true })) {
97
+ const path = join(directory, item.name);
98
+ const stat = await lstat(path);
99
+ if (stat.isDirectory()) {
100
+ dirs.add(path);
101
+ await walk(path);
102
+ }
103
+ else if (stat.isFile() && !snapshot.has(path)) {
104
+ await unlink(path).catch(error => { if (error.code !== 'ENOENT')
105
+ throw error; });
106
+ }
107
+ }
108
+ };
109
+ await walk(root);
110
+ for (const [path, bytes] of snapshot) {
111
+ const current = await exists(path) ? await io.readStable(path, 2_097_152, true).catch(() => null) : null;
112
+ if (current === null || !current.equals(bytes)) {
113
+ await atomicWritePrivateConfigFile(path, bytes);
114
+ }
115
+ }
116
+ for (const directory of [...dirs].sort((left, right) => right.length - left.length)) {
117
+ await io.syncDirectory(directory);
118
+ }
119
+ }
120
+ /** Stable per-target name, including for a maximum-length target profile. */
121
+ export function rsiCoordinatorProfile(profile) {
122
+ if (!profilePattern.test(profile))
123
+ fail('invalid target profile');
124
+ return `rsi-${profile.slice(0, 43)}-${hash(profile).slice(0, 12)}`;
125
+ }
126
+ async function prepareResources(input, signal) {
127
+ const source = await prepareRsiSourceWorkspace({ ...input, version, signal });
128
+ const runtime = await prepareRsiAuthorityRuntime({ ...input, signal });
129
+ const resources = await prepareRsiAuthorityResources({ ...input, signal });
130
+ const storedManifest = join(resources.configRoot, 'manifest.json');
131
+ const previous = await exists(storedManifest)
132
+ ? JSON.parse((await io.readStable(storedManifest, 2_097_152, true)).toString('utf8'))
133
+ : undefined;
134
+ if (previous?.pluginCreation !== undefined)
135
+ validateRsiPluginCreationSetup(previous.pluginCreation, previous.sourceReviews.owner);
136
+ if (previous?.pluginRevision !== undefined)
137
+ validateRsiPluginRevisionSetup(previous.pluginRevision, previous.sourceReviews.owner);
138
+ const priorBuild = previous?.controlPlane.sourceBuild;
139
+ // Historical Docker-era manifests are readable but can never be continued by
140
+ // the linux-native installer. Migration requires its own signed handoff.
141
+ if (previous && (!priorBuild || 'backend' in priorBuild && priorBuild.backend !== 'linux-native')) {
142
+ fail('existing Linux installation has an unsupported build backend');
143
+ }
144
+ const enableCreation = !previous || previous.pluginCreation !== undefined;
145
+ let build;
146
+ let release;
147
+ let creationBuild;
148
+ let runnerStates;
149
+ const directories = [];
150
+ const resourceInput = { ...input, source, signal };
151
+ const base = await (previous ? readLinuxRsiRuntime : prepareLinuxRsiRuntime)(resourceInput);
152
+ release = await (previous ? readRsiReleaseBuildEnvironment : prepareRsiReleaseBuildEnvironment)({ ...resourceInput, build: base });
153
+ const repository = await (previous ? readLinuxRsiRepositoryRuntime : prepareLinuxRsiRepositoryRuntime)(resourceInput);
154
+ const cgroupRoots = await discoverLinuxCgroupRoots({ signal });
155
+ build = { sourceBuild: { backend: 'linux-native', repository, cgroupRoots } };
156
+ directories.push('linux-source-build-runner');
157
+ if (enableCreation) {
158
+ creationBuild = await (previous ? readLinuxRsiCreationBuildEnvironment : prepareLinuxRsiCreationBuildEnvironment)({
159
+ ...resourceInput, stateRoot: resources.stateRoot,
160
+ });
161
+ if (!isDeepStrictEqual(creationBuild.cgroupRoots, cgroupRoots))
162
+ fail('creation cgroup roots changed during preparation');
163
+ if (!previous || previous.pluginRevision)
164
+ directories.push('revision-review-runner', 'revision-regression-runner');
165
+ }
166
+ runnerStates = await prepareRsiLinuxRunnerStates(resources, {
167
+ creation: enableCreation, revision: enableCreation && (!previous || previous.pluginRevision !== undefined),
168
+ }, previous);
169
+ if (creationBuild)
170
+ directories.push('creation-review-runner', 'creation-adoption-runner');
171
+ for (const name of directories) {
172
+ const path = join(resources.stateRoot, name);
173
+ if (!previous && !await exists(path))
174
+ await mkdir(path, { mode: 0o700 });
175
+ await io.directory(path);
176
+ }
177
+ return { source, runtime, resources, build, release, ...(creationBuild ? { creationBuild } : {}),
178
+ ...(runnerStates ? { runnerStates } : {}) };
179
+ }
180
+ async function ensureCoordinator(input, coordinator, executor, signal, systemctlPin) {
181
+ const root = join(input.dshHome, 'profiles', coordinator);
182
+ const receiptPath = join(input.dshHome, `.rsi-coordinator-${hash(input.profile).slice(0, 16)}.json`);
183
+ const receipt = JSON.stringify({ schemaVersion: 1, targetProfile: input.profile, coordinatorProfile: coordinator,
184
+ version, sourceRepository: input.sourceRepository ?? null });
185
+ let owned = await exists(receiptPath);
186
+ if (owned && (await io.readStable(receiptPath, 65_536, true)).toString('utf8') !== receipt)
187
+ fail('coordinator preparation belongs to another installation');
188
+ if (await exists(root) && !owned)
189
+ fail('unregistered coordinator profile cannot be overwritten');
190
+ if (!await exists(root) && !owned) {
191
+ await io.writeExclusive(receiptPath, receipt);
192
+ await io.syncDirectory(input.dshHome);
193
+ owned = true;
194
+ }
195
+ const matches = async (name) => {
196
+ const path = join(root, 'node_modules', '@dsh-ray', name, 'package.json');
197
+ if (!await exists(path))
198
+ return false;
199
+ const manifest = JSON.parse((await io.readStable(await realpath(path), 65_536)).toString('utf8'));
200
+ if (manifest.name !== `@dsh-ray/${name}` || manifest.version !== version)
201
+ fail('coordinator must use the same installed plugin release');
202
+ return true;
203
+ };
204
+ let complete = (await Promise.all(coordinatorBundles.map(matches))).every(Boolean);
205
+ const local = input.sourceRepository ? await readRsiLocalCohort({ dshHome: input.dshHome, profile: input.profile }) : undefined;
206
+ if (local && (local.sourceRepository !== input.sourceRepository || local.version !== version))
207
+ fail('local coordinator cohort differs from the source installation');
208
+ if (local && complete) {
209
+ try {
210
+ await verifyRsiLocalInstalledPackages({ cohort: local, profilePath: root, bundles: [...coordinatorBundles] });
211
+ }
212
+ catch (error) {
213
+ if (!isRsiLocalPackageRepairable(error))
214
+ throw error;
215
+ complete = false;
216
+ }
217
+ }
218
+ if (!complete) {
219
+ if (!owned)
220
+ fail('unregistered coordinator profile cannot be overwritten');
221
+ const state = await status(systemctlPin, coordinator, signal);
222
+ if (!['inactive', 'failed'].includes(state.ActiveState) || state.MainPID !== '0')
223
+ fail('partial coordinator must be stopped before package repair');
224
+ if (local)
225
+ await installRsiLocalProfile({ dshHome: input.dshHome, profile: coordinator, cohort: local,
226
+ bundles: coordinatorBundles, dsh: { path: executor.path, pin: { path: executor.path, sha256: executor.sha256 } }, signal });
227
+ else
228
+ await io.command(executor.path, ['plugin', '--profile', coordinator, 'add', ...coordinatorBundles.map(name => `@dsh-ray/${name}@${version}`)], { ...process.env, DSH_HOME: input.dshHome, npm_config_loglevel: 'error' }, signal, 300_000, 2_097_152);
229
+ if (!(await Promise.all(coordinatorBundles.map(matches))).every(Boolean))
230
+ fail('coordinator package installation is incomplete');
231
+ }
232
+ if (local)
233
+ await verifyRsiLocalInstalledPackages({ cohort: local, profilePath: root, bundles: [...coordinatorBundles] });
234
+ await io.directory(root, false);
235
+ }
236
+ async function systemctl(pin, args, signal) {
237
+ if (pin.interpreter !== null)
238
+ fail('automatic installation requires native systemctl');
239
+ if (createHash('sha256').update(await io.readStable(pin.path, 268_435_456, false, true)).digest('hex') !== pin.sha256)
240
+ fail('systemctl changed');
241
+ return io.command(pin.path, ['--user', ...args], process.env, signal, 40_000, 262_144);
242
+ }
243
+ async function status(pin, profile, signal) {
244
+ const text = await systemctl(pin, ['show', `dsh-profile-${profile}.service`,
245
+ '--property=LoadState,ActiveState,MainPID,InvocationID,NRestarts,FragmentPath,DropInPaths,WorkingDirectory'], signal);
246
+ return Object.fromEntries(text.split('\n').filter(Boolean).map(line => {
247
+ const index = line.indexOf('=');
248
+ if (index < 1)
249
+ fail('invalid systemctl status');
250
+ return [line.slice(0, index), line.slice(index + 1)];
251
+ }));
252
+ }
253
+ async function stopManaged(input, profile, pin, signal) {
254
+ const state = await status(pin, profile, signal);
255
+ if (state.LoadState === 'not-found' && state.MainPID === '0' && state.ActiveState === 'inactive')
256
+ return false;
257
+ const paths = systemdServicePaths({ dshHome: input.dshHome, profile });
258
+ if (state.LoadState !== 'loaded' || state.FragmentPath !== paths.unitPath || state.DropInPaths !== ''
259
+ || state.WorkingDirectory !== join(input.dshHome, 'profiles', profile))
260
+ fail(`service ${profile} is not the target installation's managed unit`);
261
+ const active = state.ActiveState === 'active';
262
+ await systemctl(pin, ['stop', paths.unitName], signal);
263
+ const stopped = await status(pin, profile, signal);
264
+ if (!['inactive', 'failed'].includes(stopped.ActiveState) || stopped.MainPID !== '0')
265
+ fail(`service ${profile} did not stop`);
266
+ if (stopped.ActiveState === 'failed')
267
+ await systemctl(pin, ['reset-failed', paths.unitName], signal);
268
+ return active;
269
+ }
270
+ async function observerReady(observer, state, signal) {
271
+ const value = await queryRuntimeObserver({ ...observer, signal });
272
+ if (value.processId !== Number(state.MainPID) || value.invocationId !== state.InvocationID
273
+ || value.profilePath !== observer.profilePath || value.observerConfigDigest !== runtimeConfigDigest(observer)
274
+ || Math.abs(Date.now() - value.observedAt) > 5_000 || value.entries.length !== observer.targets.length)
275
+ fail('runtime observation differs from installed Host');
276
+ for (const target of observer.targets) {
277
+ const entry = value.entries.find(item => item.entryId === target.entryId);
278
+ if (!entry?.active || entry.module !== target.module || entry.configDigest !== target.configDigest
279
+ || target.services.some(name => !entry.services.some(service => service.name === name && service.instance !== null)))
280
+ fail('installed Loader entries are not ready');
281
+ }
282
+ }
283
+ export function assertRsiMemoryScanActivation(manifest, records) {
284
+ const learning = manifest.memoryLearning?.learning;
285
+ if (!learning)
286
+ return;
287
+ const owner = learning.owner, digest = growthObjectDigest(learning);
288
+ const id = `memory-scan-${growthObjectDigest([learning.authorityId, owner])}`;
289
+ const registration = records.find(item => item.id === id);
290
+ const definition = registration?.definition, execution = definition?.execution;
291
+ if (!registration || registration.owner !== 'assistant-memory-learning'
292
+ || definition?.principal !== owner.principalId || definition.workspace !== owner.workspace
293
+ || definition.agentPreset !== owner.agentPreset || definition.budgetId !== learning.scanBudgetId
294
+ || definition.budgetAmount !== learning.scanBudgetAmount || definition.retrySafety !== 'never'
295
+ || definition.maxRetries !== 0 || execution?.kind !== 'host'
296
+ || execution.executorId !== 'assistant-memory-learning-v1' || execution.executorContractVersion !== 1
297
+ || execution.runbookId !== 'scan' || execution.runbookVersion !== 1
298
+ || execution.catalogDigest !== growthObjectDigest({ executor: 'assistant-memory-learning-v1', contract: 1 })
299
+ || execution.ownerRouteId !== owner.authorityId || execution.activationNonce !== digest
300
+ || !isDeepStrictEqual(execution.targetScope, { workspace: owner.workspace, preset: owner.agentPreset })
301
+ || execution.scopeDigest !== growthObjectDigest([owner.workspace, owner.agentPreset])) {
302
+ fail('target has no matching owner-bound native memory scan activation');
303
+ }
304
+ }
305
+ async function ready(manifest, pin, signal, startedAt) {
306
+ const home = manifest.controlPlane.runtimeObserver.profilePath.split('/profiles/').slice(0, -1).join('/profiles/');
307
+ const memoryDatabasePath = manifest.memoryLearning === undefined ? undefined
308
+ : rsiDatabasePaths(rsiSetupPorts.dump(manifest.targetProfile, home), home).automationsDatabasePath;
309
+ if (manifest.memoryLearning) {
310
+ for (const [id, service] of [['dsh-ray-personal-assistant', 'personalMemory'],
311
+ ['dsh-ray-assistant-verifier', 'assistantVerifier'],
312
+ ['dsh-ray-assistant-memory-learning', 'assistantMemoryLearning']]) {
313
+ if (!manifest.controlPlane.runtimeObserver?.targets.some(target => target.entryId === id
314
+ && target.services.includes(service)))
315
+ fail(`target memory observer is missing ${id}`);
316
+ }
317
+ }
318
+ const deadline = Date.now() + 60_000;
319
+ let stableSince = 0, last = '', failure;
320
+ while (Date.now() < deadline) {
321
+ signal.throwIfAborted();
322
+ try {
323
+ const states = await Promise.all([manifest.targetProfile, manifest.coordinatorProfile].map(profile => status(pin, profile, signal)));
324
+ if (states.some(state => state.ActiveState !== 'active' || !/^\d+$/u.test(state.MainPID ?? '') || Number(state.MainPID) < 1
325
+ || !/^[a-f0-9]{32}$/u.test(state.InvocationID ?? '')))
326
+ fail('Host services are not running');
327
+ await observerReady(manifest.controlPlane.runtimeObserver, states[0], signal);
328
+ if (memoryDatabasePath)
329
+ assertRsiMemoryScanActivation(manifest, listActiveAutomationsForReadiness(memoryDatabasePath));
330
+ const scope = manifest.controlPlane.taskObservations.scope;
331
+ const coordinatorId = manifest.controlPlane.sourceAdoptions.handoff.coordinatorId;
332
+ const id = `adoption-coordinator-${controlPlaneDigest({ coordinatorId, scope }).slice(0, 40)}`;
333
+ const registration = listActiveAutomationsForReadiness(join(home, 'rsi-coordinators', manifest.coordinatorProfile, 'automations.sqlite')).find(item => item.id === id);
334
+ if (!registration || registration.owner !== 'plugin-control-plane-adoption-coordinator'
335
+ || registration.updatedAt < startedAt || registration.definition.execution?.kind !== 'host'
336
+ || registration.definition.execution.executorId !== 'plugin-control-plane-adoption-coordinator-v1'
337
+ || registration.definition.execution.ownerRouteId !== scope.ownerRouteId
338
+ || registration.definition.principal !== scope.principalId || registration.definition.workspace !== scope.workspace
339
+ || registration.definition.agentPreset !== scope.preset)
340
+ fail('coordinator has no fresh owner-bound native activation');
341
+ const current = JSON.stringify(states.map(state => [state.MainPID, state.InvocationID, state.NRestarts]));
342
+ if (last !== current) {
343
+ stableSince = Date.now();
344
+ last = current;
345
+ }
346
+ if (Date.now() - stableSince >= 12_000)
347
+ return;
348
+ }
349
+ catch (error) {
350
+ failure = error;
351
+ stableSince = 0;
352
+ last = '';
353
+ }
354
+ await delay(250, undefined, { signal });
355
+ }
356
+ throw new Error('rsi install: dual Host readiness failed; applied configuration retained for retry', { cause: failure });
357
+ }
358
+ export class RsiOwnerPreflightUnavailableError extends Error {
359
+ stage;
360
+ constructor(stage, message) {
361
+ super(`rsi owner preflight unavailable (${stage}): ${message}`);
362
+ this.name = 'RsiOwnerPreflightUnavailableError';
363
+ this.stage = stage;
364
+ }
365
+ }
366
+ async function preflightStage(stage, action) {
367
+ try {
368
+ return await action();
369
+ }
370
+ catch (error) {
371
+ if (error instanceof RsiOwnerPreflightUnavailableError)
372
+ throw error;
373
+ throw new RsiOwnerPreflightUnavailableError(stage, error instanceof Error ? error.message : String(error));
374
+ }
375
+ }
376
+ /**
377
+ * Pure shape/consistency check for the owner manifest that is about to be
378
+ * written. It never reads the file system: the full compile still runs at the
379
+ * configure step after the profile directory and authority state exist. A fresh
380
+ * install therefore passes without any installed policies or lstat of paths it
381
+ * is about to create; a retry additionally proves the installed release policy
382
+ * set is still readable.
383
+ */
384
+ export function validateRsiOwnerPreflightShape(value) {
385
+ const object = (value, label) => {
386
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
387
+ throw new Error(label + ' is missing');
388
+ return value;
389
+ };
390
+ const text = (value, label) => {
391
+ if (typeof value !== 'string' || value.length === 0 || value.length > 4096)
392
+ throw new Error(label + ' is invalid');
393
+ return value;
394
+ };
395
+ const manifest = object(value.manifest, 'manifest');
396
+ if (manifest.schemaVersion !== 1)
397
+ throw new Error('manifest schema is unsupported');
398
+ const target = text(manifest.targetProfile, 'targetProfile');
399
+ const coordinator = text(manifest.coordinatorProfile, 'coordinatorProfile');
400
+ if (target === coordinator)
401
+ throw new Error('target and coordinator profiles must differ');
402
+ const reviews = object(manifest.sourceReviews, 'sourceReviews');
403
+ const decisionRoot = text(reviews.decisionRoot, 'sourceReviews decisionRoot');
404
+ const controlPlane = object(manifest.controlPlane, 'controlPlane');
405
+ const releaseExecution = object(controlPlane.sourceReleaseExecution, 'sourceReleaseExecution');
406
+ const reviewDecisionRoot = text(releaseExecution.reviewDecisionRoot, 'sourceReleaseExecution reviewDecisionRoot');
407
+ if (decisionRoot !== reviewDecisionRoot)
408
+ throw new Error('source review decision roots differ');
409
+ const stateRoot = join(value.home, 'rsi-authorities', target, 'state');
410
+ for (const [label, path] of [['sourceReviews decisionRoot', decisionRoot],
411
+ ['sourceReleaseExecution reviewDecisionRoot', reviewDecisionRoot]]) {
412
+ if (!isAbsolute(path) || resolve(path) !== path || !path.startsWith(stateRoot + '/')) {
413
+ throw new Error(label + ' is outside the installation state root');
414
+ }
415
+ }
416
+ for (const [label, group] of [['sourceJobs', controlPlane.sourceJobs], ['sourceBuild', controlPlane.sourceBuild],
417
+ ['sourceAdoptions', controlPlane.sourceAdoptions], ['taskObservations', controlPlane.taskObservations]]) {
418
+ object(group, label);
419
+ }
420
+ const jobs = object(controlPlane.sourceJobs, 'sourceJobs');
421
+ if (typeof jobs.budgetId !== 'string' || typeof jobs.ownerRouteId !== 'string')
422
+ throw new Error('sourceJobs is incomplete');
423
+ const growth = object(manifest.growthDriver, 'growthDriver');
424
+ if (growth.enabled !== true || typeof growth.budgetId !== 'string' || typeof growth.usageLearning !== 'object') {
425
+ throw new Error('growthDriver is incomplete');
426
+ }
427
+ object(manifest.limits, 'limits');
428
+ const memory = manifest.memoryLearning;
429
+ if (memory !== undefined) {
430
+ const group = object(memory, 'memoryLearning');
431
+ for (const key of ['learning', 'reviews', 'adoption'])
432
+ object(group[key], 'memoryLearning ' + key);
433
+ }
434
+ const ordinary = manifest.ordinaryUseLearning;
435
+ if (ordinary !== undefined)
436
+ object(object(ordinary, 'ordinaryUseLearning').intakeEvaluation, 'ordinaryUseLearning intakeEvaluation');
437
+ const creation = manifest.pluginCreation;
438
+ if (creation !== undefined) {
439
+ const group = object(creation, 'pluginCreation');
440
+ for (const key of ['creation', 'reviews'])
441
+ object(group[key], 'pluginCreation ' + key);
442
+ }
443
+ const revision = manifest.pluginRevision;
444
+ if (revision !== undefined) {
445
+ const group = object(revision, 'pluginRevision');
446
+ for (const key of ['revision', 'reviews'])
447
+ object(group[key], 'pluginRevision ' + key);
448
+ }
449
+ for (const [label, profile] of [['targetPatch', value.profiles.targetPatch],
450
+ ['targetEffective', value.profiles.targetEffective], ['coordinatorPatch', value.profiles.coordinatorPatch],
451
+ ['coordinatorEffective', value.profiles.coordinatorEffective], ['coordinatorBase', value.profiles.coordinatorBase]]) {
452
+ // Compiled profile patches are full YAML documents; only the raw manifest
453
+ // fields above are small bounded strings.
454
+ if (typeof profile !== 'string' || profile.length === 0 || profile.length > 2_097_152) {
455
+ throw new Error(label + ' is invalid');
456
+ }
457
+ }
458
+ if (value.previousManifest !== undefined && (!value.installedPolicies || value.installedPolicies.length < 1)) {
459
+ throw new Error('installed release policies are unavailable');
460
+ }
461
+ }
462
+ /**
463
+ * Read-only readiness gate. It runs before any Host is stopped and before any
464
+ * owner grant, authority configuration or manifest is written; failures map to a
465
+ * not-ready result so a retry can run after fixing the Host without reconciling
466
+ * a partially issued authorization. Environment checks are limited to state the
467
+ * installer itself prepared (pinned user manager, delegated cgroup descriptor,
468
+ * private profiles/observer paths) plus the sandbox tool the runner needs.
469
+ */
470
+ export async function preflightRsiOwnerReadiness(value) {
471
+ const { input, prepared, manifest, profiles, signal } = value;
472
+ const home = input.dshHome, pair = [manifest.targetProfile, manifest.coordinatorProfile];
473
+ signal.throwIfAborted();
474
+ // Service manager: the pinned user manager must answer a read-only query.
475
+ await preflightStage('service-manager', () => systemctl(value.installed.systemctl, ['show-environment'], signal));
476
+ // release-pinned tools: re-read the exact bwrap and tar pins recorded by the
477
+ // release build environment. Existence, executable mode and content digest
478
+ // must still match; a PATH lookup or a foreign binary is not accepted.
479
+ await preflightStage('tool-pin', async () => {
480
+ const pins = prepared.release.releaseBuild;
481
+ for (const [label, pin] of [['bwrap', pins.sandboxExecutable], ['tar', pins.tarExecutable]]) {
482
+ if (!isAbsolute(pin.path) || resolve(pin.path) !== pin.path || !/^[a-f0-9]{64}$/u.test(pin.sha256)) {
483
+ throw new Error(label + ' release pin is invalid');
484
+ }
485
+ const entry = await lstat(pin.path);
486
+ if (!entry.isFile() || (entry.mode & 0o111) === 0)
487
+ throw new Error(label + ' release pin is not an executable file: ' + pin.path);
488
+ if (hash(await readFile(pin.path)) !== pin.sha256)
489
+ throw new Error(label + ' release pin content changed: ' + pin.path);
490
+ }
491
+ });
492
+ // cgroup: the delegated v1 descriptor frozen during preparation must still be
493
+ // complete, and each root must be a readable/searchable directory on the host.
494
+ await preflightStage('cgroup', async () => {
495
+ const roots = prepared.build.sourceBuild.cgroupRoots;
496
+ const raw = roots;
497
+ const keys = raw && typeof raw === 'object' ? Object.keys(raw).sort().join(',') : '';
498
+ let control;
499
+ if (roots?.mode === 'v1' && keys === 'cpu,freezer,memory,mode,pids') {
500
+ control = [roots.cpu, roots.memory, roots.pids, roots.freezer];
501
+ if (control.some(path => typeof path !== 'string' || !isAbsolute(path) || resolve(path) !== path)
502
+ || new Set(control).size !== 4) {
503
+ throw new Error('delegated cgroup v1 roots are incomplete');
504
+ }
505
+ }
506
+ else if (roots?.mode === 'v2' && keys === 'mode,unified') {
507
+ if (typeof roots.unified !== 'string' || !isAbsolute(roots.unified) || resolve(roots.unified) !== roots.unified) {
508
+ throw new Error('delegated cgroup v2 root is invalid');
509
+ }
510
+ control = [roots.unified];
511
+ }
512
+ else {
513
+ throw new Error('delegated cgroup roots are incomplete');
514
+ }
515
+ const probe = value.cgroupRootsProbe ?? (async (path, probeSignal) => {
516
+ probeSignal.throwIfAborted();
517
+ const entry = await lstat(path);
518
+ if (!entry.isDirectory())
519
+ throw new Error('delegated cgroup root is not a directory: ' + path);
520
+ await access(path, constants.R_OK | constants.X_OK);
521
+ });
522
+ for (const path of control)
523
+ await probe(path, signal);
524
+ });
525
+ // observer: the native socket path must fit sun_path, stay inside the private
526
+ // installation roots and name both profiles. A fresh install validates the
527
+ // shape of paths it is about to create; a retry also re-reads the existing
528
+ // private profile directories and observer socket parent.
529
+ await preflightStage('observer', async () => {
530
+ const observer = manifest.controlPlane.runtimeObserver;
531
+ if (!observer)
532
+ throw new Error('runtime observer is missing');
533
+ if (!isAbsolute(observer.socketPath) || resolve(observer.socketPath) !== observer.socketPath
534
+ || Buffer.byteLength(observer.socketPath) > 100)
535
+ throw new Error('runtime observer socket path is invalid');
536
+ const authorityRoot = join(home, 'rsi-authorities', pair[0]);
537
+ if (!isAbsolute(observer.keyPath) || resolve(observer.keyPath) !== observer.keyPath
538
+ || observer.keyPath !== join(authorityRoot, 'config', 'observer.key'))
539
+ throw new Error('runtime observer key path is invalid');
540
+ if (observer.profilePath !== join(home, 'profiles', pair[0]))
541
+ throw new Error('runtime observer profile differs from the target installation');
542
+ const socketParent = dirname(observer.socketPath);
543
+ if (socketParent !== join(authorityRoot, 'state'))
544
+ throw new Error('runtime observer socket is outside the installation state root');
545
+ const profilesRoot = join(home, 'profiles');
546
+ for (const profile of pair) {
547
+ const path = join(profilesRoot, profile);
548
+ if (!isAbsolute(path) || resolve(path) !== path || !path.startsWith(profilesRoot + '/'))
549
+ throw new Error('owner profile path is invalid');
550
+ }
551
+ if (value.previousManifest !== undefined) {
552
+ for (const profile of pair)
553
+ await io.directory(join(profilesRoot, profile), false);
554
+ await io.directory(socketParent);
555
+ }
556
+ });
557
+ // authority: shape and consistency only. The full compile remains at the
558
+ // configure step, where the profile directory and authority state exist; a
559
+ // fresh install must not require installed policies or lstat paths that are
560
+ // about to be created, while a retry still proves those policies are readable.
561
+ await preflightStage('authority', async () => {
562
+ validateRsiOwnerPreflightShape({ home, manifest, profiles,
563
+ ...(value.previousManifest === undefined ? {} : { previousManifest: value.previousManifest,
564
+ installedPolicies: value.installed.policies }) });
565
+ });
566
+ }
567
+ export const rsiInstallPorts = {
568
+ prepare: prepareResources, collect: collectRsiInstalledInputs, coordinator: ensureCoordinator, setup: rsiSetupPorts,
569
+ capture: captureRsiSystemdUnitProperties, readUnit: readRsiSystemdUnitProperties, stop: stopManaged, ready, configure: configureRsiSetupLocked, prepareOwner: prepareRsiOwnerConfiguration, preflight: preflightRsiOwnerReadiness,
570
+ };
571
+ /** Installer-owned process, never invoked from the Host being restarted. */
572
+ export async function installRsiOwnerDeployment(input, ports = rsiInstallPorts) {
573
+ if (!profilePattern.test(input.profile) || await realpath(input.dshHome) !== input.dshHome)
574
+ fail('invalid installation identity');
575
+ const signal = AbortSignal.any([input.signal ?? new AbortController().signal, AbortSignal.timeout(2_400_000)]);
576
+ signal.throwIfAborted();
577
+ return withDshHomeLifecycleLock(input.dshHome, async () => {
578
+ let prepared;
579
+ try {
580
+ prepared = await ports.prepare(input, signal);
581
+ }
582
+ catch (error) {
583
+ signal.throwIfAborted();
584
+ if (error instanceof RsiReleaseBuildUnavailableError
585
+ || error instanceof LinuxRsiRuntimeUnavailableError || error instanceof RsiLinuxCgroupUnavailableError
586
+ || error instanceof RsiLinuxCreationBuildUnavailableError)
587
+ return { mode: 'not-ready', reason: error.message };
588
+ throw error;
589
+ }
590
+ const { resources, runtime, source, build, release } = prepared;
591
+ const upgrading = input.upgradeExistingOwner === true;
592
+ let targetEffective = ports.setup.dump(input.profile, input.dshHome);
593
+ let installed;
594
+ try {
595
+ installed = await ports.collect({
596
+ dshHome: input.dshHome, targetProfile: input.profile, targetEffective, resources, source,
597
+ ...(upgrading ? { includeDisabledManagedRows: true } : {}),
598
+ });
599
+ }
600
+ catch (error) {
601
+ signal.throwIfAborted();
602
+ if (error instanceof RsiInstalledInputsUnavailableError)
603
+ return { mode: 'not-ready', reason: error.message };
604
+ throw error;
605
+ }
606
+ const coordinatorProfile = rsiCoordinatorProfile(input.profile);
607
+ await ports.coordinator(input, coordinatorProfile, installed.executor, signal, installed.systemctl);
608
+ const pair = [input.profile, coordinatorProfile];
609
+ const setupJournal = join(input.dshHome, '.rsi-setup-journal.json');
610
+ if (await exists(setupJournal)) {
611
+ const interrupted = JSON.parse((await io.readStable(setupJournal, 2_097_152, true)).toString('utf8'));
612
+ if (interrupted.stage === 'prepared') {
613
+ if (!Array.isArray(interrupted.entries) || interrupted.entries.length !== 2
614
+ || interrupted.entries.some((entry, index) => entry.profile !== pair[index]))
615
+ fail('interrupted setup belongs to another profile pair');
616
+ const recoveryRunning = [];
617
+ for (const profile of [...pair].reverse())
618
+ if (await ports.stop(input, profile, installed.systemctl, signal))
619
+ recoveryRunning.push(profile);
620
+ await ports.configure({ dshHome: input.dshHome, manifestPath: join(resources.configRoot, 'manifest.json'),
621
+ apply: false, rollback: true, start: false, confirmStopped: true, help: false }, ports.setup);
622
+ // A successful rollback restores a known deployment. Restore prior
623
+ // availability before any new owner or source preflight can fail.
624
+ for (const profile of recoveryRunning)
625
+ await ports.setup.start(profile, input.dshHome);
626
+ targetEffective = ports.setup.dump(input.profile, input.dshHome);
627
+ installed = await ports.collect({
628
+ dshHome: input.dshHome, targetProfile: input.profile, targetEffective, resources, source,
629
+ ...(upgrading ? { includeDisabledManagedRows: true } : {}),
630
+ });
631
+ }
632
+ }
633
+ const profiles = { targetPatch: (await io.readStable(join(input.dshHome, 'profiles', pair[0], 'cordis.patch.yml'), 2_097_152)).toString('utf8'),
634
+ targetEffective, coordinatorPatch: (await io.readStable(join(input.dshHome, 'profiles', pair[1], 'cordis.patch.yml'), 2_097_152)).toString('utf8'),
635
+ coordinatorEffective: ports.setup.dump(pair[1], input.dshHome), coordinatorBase: await ports.setup.base(pair[1], input.dshHome) };
636
+ const snapshot = await ports.setup.snapshot(targetEffective, input.dshHome);
637
+ if (snapshot.bindings.length !== 1)
638
+ fail('exactly one active owner DM is required');
639
+ const binding = snapshot.bindings[0];
640
+ const storedManifest = join(resources.configRoot, 'manifest.json');
641
+ let now = Date.now(), expiresAt = now + 365 * 86_400_000;
642
+ let enableCreation = true;
643
+ let enableOrdinaryUseLearning = input.enableOrdinaryUseLearning === true;
644
+ let skipMemoryLearning = input.skipMemoryLearning === true;
645
+ let intakeProvider = input.intakeProvider, intakeModel = input.intakeModel;
646
+ let previousManifest;
647
+ if (await exists(storedManifest)) {
648
+ // A retry or upgrade reuses the original installation's finite terms, never renews them.
649
+ const previous = JSON.parse((await io.readStable(storedManifest, 2_097_152, true)).toString('utf8'));
650
+ previousManifest = previous;
651
+ const host = JSON.parse((await io.readStable(join(resources.configRoot, 'host-authority.json'), 2_097_152, true)).toString('utf8'));
652
+ now = host.grant.notBefore;
653
+ expiresAt = previous.sourceReviews.expiresAt;
654
+ // Replaying or upgrading a legacy installation must not silently add a new creation authority.
655
+ enableCreation = previous.pluginCreation !== undefined;
656
+ const storedOrdinary = previous.ordinaryUseLearning?.intakeEvaluation;
657
+ if (!upgrading && input.enableOrdinaryUseLearning === true && storedOrdinary === undefined) {
658
+ fail('existing installation cannot be expanded with ordinary-use learning; install a fresh profile instead');
659
+ }
660
+ enableOrdinaryUseLearning = upgrading
661
+ ? (input.enableOrdinaryUseLearning === true || storedOrdinary !== undefined)
662
+ : storedOrdinary !== undefined;
663
+ if (upgrading) {
664
+ intakeProvider = input.intakeProvider ?? storedOrdinary?.provider;
665
+ intakeModel = input.intakeModel ?? storedOrdinary?.model;
666
+ }
667
+ else if (storedOrdinary !== undefined) {
668
+ intakeProvider = storedOrdinary.provider;
669
+ intakeModel = storedOrdinary.model;
670
+ }
671
+ // A skip decision is likewise frozen: an existing installation that already
672
+ // issued memory-learning grants must not drop or renew them, while an
673
+ // interrupted skip retry keeps the memory-learning chain absent.
674
+ if (input.skipMemoryLearning === true && previous.memoryLearning !== undefined) {
675
+ fail('existing installation cannot drop memory learning; reinstall a fresh profile to change the decision');
676
+ }
677
+ skipMemoryLearning = upgrading
678
+ ? (input.skipMemoryLearning === true || (previous.memoryLearning === undefined && !enableOrdinaryUseLearning))
679
+ : previous.memoryLearning === undefined;
680
+ }
681
+ const manifest = createRsiBootstrapManifest({ dshHome: input.dshHome, targetProfile: pair[0], coordinatorProfile: pair[1],
682
+ targetEffective, owner: binding, resources, runtime, source, sourceBuild: build.sourceBuild,
683
+ ...(enableCreation && prepared.creationBuild ? { creationBuild: prepared.creationBuild } : {}),
684
+ ...(prepared.runnerStates ? { runnerStates: prepared.runnerStates } : {}),
685
+ ...(previousManifest ? { enableRevision: previousManifest.pluginRevision !== undefined } : {}),
686
+ enableOrdinaryUseLearning,
687
+ skipMemoryLearning,
688
+ ...(upgrading ? { upgradeExistingOwner: true } : {}),
689
+ ...(intakeProvider !== undefined ? { intakeProvider } : {}),
690
+ ...(intakeModel !== undefined ? { intakeModel } : {}),
691
+ git: installed.git, now, expiresAt, plugins: installed.plugins,
692
+ observerTargets: installed.observerTargets, hostDeploymentInputs: installed.hostDeploymentInputs });
693
+ if (previousManifest && !upgrading && !isDeepStrictEqual(previousManifest, manifest))
694
+ fail('existing manifest differs before stopping Hosts');
695
+ if (previousManifest) {
696
+ if (upgrading) {
697
+ await verifyExistingRsiOwnerConfiguration({
698
+ resources, dshHome: input.dshHome, targetProfile: pair[0],
699
+ observerKeyPath: previousManifest.controlPlane.runtimeObserver.keyPath, signal,
700
+ });
701
+ }
702
+ else {
703
+ const compiledPatches = await ports.setup.compile({ manifest, dshHome: input.dshHome,
704
+ ...profiles, owner: binding });
705
+ await inspectRsiOwnerConfiguration({ manifest, resources, patches: compiledPatches, signal });
706
+ }
707
+ }
708
+ const inventories = await captureRsiAutomationInventories(ports.setup.automationInventory, targetEffective, profiles.coordinatorEffective, input.dshHome, coordinatorProfile);
709
+ assertRsiSchedulerActivation(inventories, input.ackExistingAutomations === true);
710
+ const previousJournal = await exists(setupJournal) ? (await io.readStable(setupJournal, 2_097_152, true)).toString('utf8') : null;
711
+ // Readiness preflight before stopping Hosts or issuing grants: the owner
712
+ // configuration (authorities, manifest and memory-learning grants) is only
713
+ // written after the pinned user manager, sandbox, delegated cgroup roots,
714
+ // observer placement and compiled owner profile are all readable.
715
+ try {
716
+ await ports.preflight({ input, prepared, installed, manifest, binding, profiles, signal,
717
+ ...(previousManifest === undefined ? {} : { previousManifest }) });
718
+ }
719
+ catch (error) {
720
+ signal.throwIfAborted();
721
+ if (error instanceof RsiOwnerPreflightUnavailableError)
722
+ return { mode: 'not-ready', reason: error.message };
723
+ throw error;
724
+ }
725
+ const running = new Set();
726
+ let applied = false;
727
+ let configSnapshot;
728
+ try {
729
+ for (const profile of [...pair].reverse())
730
+ if (await ports.stop(input, profile, installed.systemctl, signal))
731
+ running.add(profile);
732
+ signal.throwIfAborted();
733
+ if (!isDeepStrictEqual(snapshot.bindings, (await ports.setup.snapshot(targetEffective, input.dshHome)).bindings)
734
+ || ports.setup.dump(pair[0], input.dshHome) !== targetEffective
735
+ || ports.setup.dump(pair[1], input.dshHome) !== profiles.coordinatorEffective)
736
+ fail('owner or profile changed while stopping Hosts');
737
+ if (!isDeepStrictEqual(inventories, await captureRsiAutomationInventories(ports.setup.automationInventory, targetEffective, profiles.coordinatorEffective, input.dshHome, coordinatorProfile)))
738
+ fail('Automation inventory changed while stopping Hosts');
739
+ const unitProperties = await ports.capture({ dshHome: input.dshHome, profile: pair[0] }, { systemctl: { ...installed.systemctl, interpreter: null }, environment: manifest.serviceEnvironment.target, signal });
740
+ if (upgrading)
741
+ configSnapshot = await snapshotPrivateConfigTree(resources.configRoot);
742
+ const configuration = await ports.prepareOwner({ manifest, resources, runtime, source, releaseBuild: release.releaseBuild,
743
+ executor: installed.executor, systemctl: installed.systemctl, unitProperties, policies: installed.policies, now }, { binding, profiles, signal, upgradeExistingOwner: upgrading });
744
+ const args = { dshHome: input.dshHome, manifestPath: configuration.manifestPath, apply: true, rollback: false,
745
+ start: false, confirmStopped: true, help: false, ackExistingAutomations: input.ackExistingAutomations === true,
746
+ expectedAutomationInventories: inventories, upgradeExistingOwner: upgrading };
747
+ const deploymentPorts = { ...ports.setup, async validateServiceUnits(value, environment) {
748
+ await ports.setup.validateServiceUnits(value, environment);
749
+ const current = await ports.readUnit({ dshHome: input.dshHome, profile: pair[0] }, { systemctl: { ...installed.systemctl, interpreter: null }, signal });
750
+ if (!isDeepStrictEqual(current, unitProperties))
751
+ fail('final loaded systemd unit differs from the installation grant');
752
+ } };
753
+ await ports.configure(args, deploymentPorts);
754
+ applied = true;
755
+ signal.throwIfAborted();
756
+ // The setup journal remains the source of recovery truth after application.
757
+ const startedAt = Date.now();
758
+ await ports.setup.start(pair[1], input.dshHome);
759
+ await ports.setup.start(pair[0], input.dshHome);
760
+ await ports.ready(manifest, installed.systemctl, signal, startedAt);
761
+ await deploymentPorts.validateServiceUnits(manifest, manifest.serviceEnvironment.target);
762
+ return { mode: 'ready', profiles: pair, manifestPath: configuration.manifestPath };
763
+ }
764
+ catch (error) {
765
+ if (!applied) {
766
+ if (configSnapshot !== undefined) {
767
+ await restorePrivateConfigTree(resources.configRoot, configSnapshot);
768
+ }
769
+ // Restore availability only when all profile bytes and the unit are still
770
+ // the original deployment. Unknown outcomes retain stopped services.
771
+ const unchanged = await Promise.all(pair.map(async (profile, index) => {
772
+ const bytes = (await io.readStable(join(input.dshHome, 'profiles', profile, 'cordis.patch.yml'), 2_097_152)).toString('utf8');
773
+ return bytes === (index === 0 ? profiles.targetPatch : profiles.coordinatorPatch);
774
+ })).catch(() => [false]);
775
+ const recoveredJournal = await exists(setupJournal) ? (await io.readStable(setupJournal, 2_097_152, true)).toString('utf8') : null;
776
+ if (unchanged.every(Boolean) && recoveredJournal === previousJournal) {
777
+ for (const profile of [...pair].reverse())
778
+ if (running.has(profile)) {
779
+ const environment = await readRsiServiceEnvironment(input.dshHome, profile);
780
+ const rendered = await ports.setup.renderServiceUnit(profile, input.dshHome, environment ?? {});
781
+ const actual = await readFile(ports.setup.serviceUnitPath(profile, input.dshHome), 'utf8').catch(() => '');
782
+ if (actual === rendered)
783
+ await ports.setup.start(profile, input.dshHome);
784
+ }
785
+ }
786
+ }
787
+ throw error;
788
+ }
789
+ });
790
+ }
791
+ //# sourceMappingURL=rsi-install.js.map