@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,1005 @@
1
+ #!/usr/bin/env node
2
+ import { chmod, open, readFile, rename, stat } from 'node:fs/promises';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, isAbsolute, join } from 'node:path';
7
+ import { isDeepStrictEqual } from 'node:util';
8
+ import { isMap, isSeq, parseDocument } from 'yaml';
9
+ import { installDshResidentService, residentServiceKind } from './resident.js';
10
+ import { isMainEntry, withDshHomeLifecycleLock } from './setup.js';
11
+ import { assertEffectiveSupervisedGrowthConfig, configureSupervisedGrowthProfilePatch, supervisedGrowthDatabasePaths, supervisedGrowthBindingQuery, supervisedGrowthAnalystRuntimeConfig, supervisedGrowthRecoveryRuntimeConfig, } from './supervised-growth-profile.js';
12
+ const keyPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
13
+ function argumentValue(argv, index, option) {
14
+ const value = argv[index + 1];
15
+ if (value === undefined || value.startsWith('--'))
16
+ throw new Error(`supervised-growth setup: ${option} requires a value`);
17
+ return value;
18
+ }
19
+ export function parseSupervisedGrowthSetupArgs(argv) {
20
+ const result = {
21
+ profile: 'web', timeoutMs: 300_000, ackExistingAutomations: false, help: false,
22
+ };
23
+ for (let index = 0; index < argv.length; index += 1) {
24
+ const option = argv[index];
25
+ if (option === '--help' || option === '-h')
26
+ result.help = true;
27
+ else if (option === '--profile')
28
+ result.profile = argumentValue(argv, index++, option);
29
+ else if (option === '--timeout-ms')
30
+ result.timeoutMs = Number(argumentValue(argv, index++, option));
31
+ else if (option === '--ack-existing-automations')
32
+ result.ackExistingAutomations = true;
33
+ else
34
+ throw new Error(`supervised-growth setup: unknown option: ${option}`);
35
+ }
36
+ if (!keyPattern.test(result.profile))
37
+ throw new Error('supervised-growth setup: invalid profile');
38
+ if (!Number.isSafeInteger(result.timeoutMs) || result.timeoutMs < 30_000 || result.timeoutMs > 900_000) {
39
+ throw new Error('supervised-growth setup: timeout-ms must be an integer from 30000 to 900000');
40
+ }
41
+ return result;
42
+ }
43
+ export function assertSupervisedGrowthAutomationGuard(records, acknowledged) {
44
+ // Enabling the scheduler would start every durable active row. A legacy
45
+ // heartbeat is not intrinsically safe: it may carry broad tools or a
46
+ // different route. Keep the guard stricter than necessary until an exact
47
+ // managed-definition hash can prove a pre-existing row is this overlay.
48
+ // The exact legacy managed job is migrated with scheduler=false, its execute
49
+ // grant removed, and its Heartbeat profile reconciled to paused before the
50
+ // active scheduler is restored. Other durable active rows remain an explicit
51
+ // operator decision.
52
+ const existing = records.filter(record => record.status === 'active'
53
+ && !(record.id === 'heartbeat:supervised-growth' && record.owner === 'assistant-heartbeat')
54
+ && !(record.id === 'heartbeat:supervised-growth-analyst' && record.owner === 'assistant-heartbeat')
55
+ && !(record.id === 'recovery:supervised-growth'
56
+ && record.owner === 'dsh-ray-assistant-recovery'));
57
+ if (existing.length > 0 && !acknowledged) {
58
+ throw new Error('supervised-growth setup: active automations already exist; rerun with --ack-existing-automations to leave them untouched');
59
+ }
60
+ }
61
+ export function selectUniqueOwnerBinding(bindings) {
62
+ if (bindings.length === 0) {
63
+ throw new Error('supervised-growth setup: no matching owner DM binding; send the bot a new direct message, then retry');
64
+ }
65
+ if (bindings.length > 1) {
66
+ throw new Error('supervised-growth setup: multiple matching owner DM bindings found; revoke stale bindings before enabling growth');
67
+ }
68
+ return bindings[0];
69
+ }
70
+ /** Compare the complete durable route snapshot, including its optimistic version. */
71
+ export function sameSupervisedGrowthBinding(left, right) {
72
+ return left.id === right.id
73
+ && left.conversation.channel === right.conversation.channel
74
+ && left.conversation.account === right.conversation.account
75
+ && left.conversation.tenant === right.conversation.tenant
76
+ && left.conversation.kind === right.conversation.kind
77
+ && left.conversation.chat === right.conversation.chat
78
+ && left.conversation.thread === right.conversation.thread
79
+ && left.principal.channel === right.principal.channel
80
+ && left.principal.account === right.principal.account
81
+ && left.principal.tenant === right.principal.tenant
82
+ && left.principal.user === right.principal.user
83
+ && left.workspace === right.workspace
84
+ && left.agentPreset === right.agentPreset
85
+ && left.sessionId === right.sessionId
86
+ && left.generation === right.generation
87
+ && left.policyRef === right.policyRef
88
+ && left.status === right.status
89
+ && left.createdAt === right.createdAt
90
+ && left.updatedAt === right.updatedAt
91
+ && left.version === right.version;
92
+ }
93
+ function help() {
94
+ return [
95
+ 'Usage: dsh-supervised-growth-setup [options]',
96
+ '',
97
+ 'Activates the bounded supervised-growth overlay only after one exact owner Lark DM binding is present.',
98
+ ' --profile <name> DSH profile (default: web)',
99
+ ' --timeout-ms <30000..900000> bounded wait for the owner DM (default: 300000)',
100
+ ' --ack-existing-automations acknowledge active jobs may run when the scheduler is enabled',
101
+ ].join('\n');
102
+ }
103
+ async function atomicWrite(path, value) {
104
+ const temporary = join(dirname(path), `.cordis.patch.yml.supervised-growth-${process.pid}`);
105
+ const file = await open(temporary, 'w', 0o600);
106
+ try {
107
+ await file.writeFile(value, 'utf8');
108
+ await file.sync();
109
+ }
110
+ finally {
111
+ await file.close();
112
+ }
113
+ await rename(temporary, path);
114
+ await chmod(path, 0o600);
115
+ }
116
+ function dumpProfile(profile) {
117
+ const result = spawnSync('dsh', ['--profile', profile, '--dump-config'], {
118
+ encoding: 'utf8', maxBuffer: 4 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'],
119
+ });
120
+ if (result.status !== 0) {
121
+ const detail = typeof result.stderr === 'string' ? result.stderr.trim().slice(0, 2_000) : '';
122
+ throw new Error(`supervised-growth setup: DSH rejected the updated profile${detail === '' ? '' : `: ${detail}`}`);
123
+ }
124
+ return typeof result.stdout === 'string' ? result.stdout : String(result.stdout ?? '');
125
+ }
126
+ export async function commitSupervisedGrowthPatch(input) {
127
+ await atomicWrite(input.patchPath, input.updatedPatch);
128
+ try {
129
+ return input.validate();
130
+ }
131
+ catch (error) {
132
+ await atomicWrite(input.patchPath, input.originalPatch);
133
+ throw error;
134
+ }
135
+ }
136
+ /**
137
+ * Keep the post-write activation sequence transactional from the operator's
138
+ * point of view: a failed readiness, binding re-read, restart, or health check
139
+ * rewrites the original profile and asks the host to restore its old resident
140
+ * service before reporting failure.
141
+ */
142
+ export async function activateSupervisedGrowthPatch(input) {
143
+ const effectiveConfig = await commitSupervisedGrowthPatch(input);
144
+ try {
145
+ await input.afterCommit(effectiveConfig);
146
+ return effectiveConfig;
147
+ }
148
+ catch (error) {
149
+ await atomicWrite(input.patchPath, input.originalPatch);
150
+ try {
151
+ await input.restore();
152
+ }
153
+ catch (rollbackError) {
154
+ throw new Error(`supervised-growth setup: activation failed and rollback service restore also failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, { cause: error });
155
+ }
156
+ throw error;
157
+ }
158
+ }
159
+ /**
160
+ * Transactional two-restart activation. Preview and production deliberately
161
+ * share one nonce and catalog digest, but production is not even written until
162
+ * the caller has attested the restarted preview bootstrap. Any failure restores
163
+ * the exact original patch bytes and restarts that original profile.
164
+ */
165
+ export async function activateSupervisedGrowthRecoveryStages(input) {
166
+ try {
167
+ await atomicWrite(input.patchPath, input.previewPatch);
168
+ const previewEffective = input.validate('preview');
169
+ await input.afterStage('preview', previewEffective);
170
+ const activePatch = input.buildActivePatch(previewEffective);
171
+ await atomicWrite(input.patchPath, activePatch);
172
+ const activeEffective = input.validate('active');
173
+ await input.afterStage('active', activeEffective);
174
+ return activeEffective;
175
+ }
176
+ catch (error) {
177
+ await atomicWrite(input.patchPath, input.originalPatch);
178
+ try {
179
+ await input.restore();
180
+ }
181
+ catch (rollbackError) {
182
+ throw new Error(`supervised-growth setup: activation failed and rollback service restore also failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`, { cause: error });
183
+ }
184
+ throw error;
185
+ }
186
+ }
187
+ function delay(milliseconds) {
188
+ return new Promise(resolve => setTimeout(resolve, milliseconds));
189
+ }
190
+ function residentHealthCommand(command, args) {
191
+ const result = spawnSync(command, args, {
192
+ encoding: 'utf8', maxBuffer: 128 * 1024, stdio: ['ignore', 'pipe', 'pipe'],
193
+ });
194
+ return {
195
+ status: result.status,
196
+ stdout: typeof result.stdout === 'string' ? result.stdout : String(result.stdout ?? ''),
197
+ stderr: typeof result.stderr === 'string' ? result.stderr : String(result.stderr ?? ''),
198
+ };
199
+ }
200
+ function residentHealthy(service, run) {
201
+ if (service.kind === 'systemd') {
202
+ return run('/usr/bin/systemctl', ['--user', 'is-active', '--quiet', service.target]).status === 0;
203
+ }
204
+ if (service.kind === 'launchd') {
205
+ const result = run('/bin/launchctl', ['print', service.target]);
206
+ return result.status === 0 && /(?:^|\n)\s*state = running\s*(?:\n|$)/u.test(result.stdout);
207
+ }
208
+ // schtasks' status text is localized and its successful Query does not prove
209
+ // the task process is alive. Do not report an unverifiable Windows task as
210
+ // a healthy unattended supervisor.
211
+ throw new Error('supervised-growth setup: Windows does not provide a verifiable resident health gate for this activation');
212
+ }
213
+ /** Bounded post-restart health check; registration alone is not sufficient. */
214
+ export async function verifySupervisedGrowthResidentService(service, dependencies = {}) {
215
+ const run = dependencies.run ?? residentHealthCommand;
216
+ const wait = dependencies.wait ?? delay;
217
+ const attempts = dependencies.attempts ?? 3;
218
+ const retryDelayMs = dependencies.retryDelayMs ?? 250;
219
+ if (!Number.isSafeInteger(attempts) || attempts < 1 || attempts > 5
220
+ || !Number.isSafeInteger(retryDelayMs) || retryDelayMs < 0 || retryDelayMs > 5_000) {
221
+ throw new Error('supervised-growth setup: invalid resident health check bounds');
222
+ }
223
+ let lastFailure;
224
+ for (let index = 0; index < attempts; index += 1) {
225
+ try {
226
+ if (residentHealthy(service, run))
227
+ return;
228
+ lastFailure = new Error('resident service did not report a running state');
229
+ }
230
+ catch (error) {
231
+ lastFailure = error;
232
+ }
233
+ if (index + 1 < attempts)
234
+ await wait(retryDelayMs);
235
+ }
236
+ throw new Error(`supervised-growth setup: resident service is not healthy after restart${lastFailure instanceof Error ? `: ${lastFailure.message}` : ''}`);
237
+ }
238
+ export async function restartAndVerifySupervisedGrowthResident(input) {
239
+ const service = await (input.install ?? installDshResidentService)({ dshHome: input.dshHome, profile: input.profile });
240
+ await (input.verify ?? verifySupervisedGrowthResidentService)(service);
241
+ return service;
242
+ }
243
+ export const SUPERVISED_GROWTH_LIFECYCLE_ATTESTATION_PROTOCOL = 'dsh-ray/supervised-growth-lifecycle-attestation/v1';
244
+ export const SUPERVISED_GROWTH_MANAGED_AUTOMATION_PROJECTION_PROTOCOL = 'dsh-ray/supervised-growth-managed-automations/v1';
245
+ function canonicalJson(value) {
246
+ if (value === null || typeof value !== 'object')
247
+ return JSON.stringify(value) ?? 'null';
248
+ if (Array.isArray(value))
249
+ return `[${value.map(canonicalJson).join(',')}]`;
250
+ const record = value;
251
+ return `{${Object.keys(record).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(',')}}`;
252
+ }
253
+ function digestJson(value) {
254
+ return createHash('sha256').update(canonicalJson(value)).digest('hex');
255
+ }
256
+ function deepFreeze(value) {
257
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
258
+ for (const child of Object.values(value))
259
+ deepFreeze(child);
260
+ Object.freeze(value);
261
+ }
262
+ return value;
263
+ }
264
+ function sortedAutomationRecords(records) {
265
+ return Object.freeze([...records].sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0));
266
+ }
267
+ function effectivePluginConfig(effectiveConfig, id) {
268
+ const document = parseDocument(effectiveConfig, { uniqueKeys: true });
269
+ if (document.errors.length > 0 || !isSeq(document.contents)) {
270
+ throw new Error('supervised-growth lifecycle: effective profile is invalid');
271
+ }
272
+ const rows = document.contents.items.filter(item => isMap(item)
273
+ && item.get('id') === id);
274
+ if (rows.length !== 1 || rows[0].get('disabled') === true) {
275
+ throw new Error(`supervised-growth lifecycle: ${id} must be uniquely enabled`);
276
+ }
277
+ const config = rows[0].get('config', true);
278
+ if (!isMap(config))
279
+ throw new Error(`supervised-growth lifecycle: ${id} config is invalid`);
280
+ return config;
281
+ }
282
+ function assertLifecycleProviderContract(input) {
283
+ const expected = input.stage === 'preview' ? ['larkChannel'] : [];
284
+ if (!Array.isArray(input.externalProviderExemptions)
285
+ || !isDeepStrictEqual(input.externalProviderExemptions, expected)) {
286
+ throw new Error(`supervised-growth lifecycle: ${input.stage} external provider exemptions are invalid`);
287
+ }
288
+ const lark = effectivePluginConfig(input.effectiveConfig, 'dsh-ray-lark-channel');
289
+ const health = effectivePluginConfig(input.effectiveConfig, 'dsh-ray-assistant-health');
290
+ const providers = health.get('requiredProviders', true);
291
+ const requiredProviders = isSeq(providers) ? providers.toJSON() : undefined;
292
+ if (input.stage === 'preview') {
293
+ if (lark.get('enabled') !== false) {
294
+ throw new Error('supervised-growth lifecycle: preview Lark channel must be disabled');
295
+ }
296
+ if (requiredProviders === undefined || requiredProviders.includes('larkChannel')) {
297
+ throw new Error('supervised-growth lifecycle: preview Health must exempt larkChannel');
298
+ }
299
+ }
300
+ else {
301
+ if (lark.get('enabled') !== true) {
302
+ throw new Error('supervised-growth lifecycle: active Lark channel must be enabled');
303
+ }
304
+ if (requiredProviders === undefined || !requiredProviders.includes('larkChannel')) {
305
+ throw new Error('supervised-growth lifecycle: active Health must require larkChannel');
306
+ }
307
+ }
308
+ return Object.freeze([...expected]);
309
+ }
310
+ function sameRecoveryObservation(left, right) {
311
+ return left.snapshotDigest === right.snapshotDigest
312
+ && left.database.device === right.database.device
313
+ && left.database.inode === right.database.inode
314
+ && left.database.digest === right.database.digest;
315
+ }
316
+ function sameAutomationObservation(left, right) {
317
+ return left.inventoryDigest === right.inventoryDigest
318
+ && left.database.device === right.database.device
319
+ && left.database.inode === right.database.inode
320
+ && left.database.digest === right.database.digest
321
+ && isDeepStrictEqual(left.sidecars, right.sidecars)
322
+ && left.inFlightCount === right.inFlightCount
323
+ && isDeepStrictEqual(left.records, right.records);
324
+ }
325
+ function recoveryJobIdentity(effectiveConfig) {
326
+ const config = supervisedGrowthRecoveryRuntimeConfig(effectiveConfig);
327
+ const jobs = config['jobs'];
328
+ if (!Array.isArray(jobs))
329
+ throw new Error('supervised-growth lifecycle: Recovery jobs are invalid');
330
+ const matches = jobs.filter((job) => typeof job === 'object'
331
+ && job !== null && !Array.isArray(job) && job['id'] === 'supervised-growth');
332
+ if (matches.length !== 1) {
333
+ throw new Error('supervised-growth lifecycle: exact Recovery job is missing or duplicated');
334
+ }
335
+ const job = matches[0];
336
+ if ((job['activationState'] !== 'preview' && job['activationState'] !== 'active')
337
+ || typeof job['activationNonce'] !== 'string' || job['activationNonce'].trim() === ''
338
+ || !/^[a-f\d]{64}$/u.test(String(job['catalogDigest']))) {
339
+ throw new Error('supervised-growth lifecycle: Recovery activation identity is invalid');
340
+ }
341
+ return {
342
+ activationState: job['activationState'],
343
+ activationNonce: job['activationNonce'],
344
+ catalogDigest: String(job['catalogDigest']),
345
+ };
346
+ }
347
+ function configuredRecoveryIdentities(effectiveConfig) {
348
+ const jobs = supervisedGrowthRecoveryRuntimeConfig(effectiveConfig)['jobs'];
349
+ if (!Array.isArray(jobs) || jobs.length > 100) {
350
+ throw new Error('supervised-growth lifecycle: Recovery jobs are invalid');
351
+ }
352
+ const result = new Map();
353
+ for (const [index, raw] of jobs.entries()) {
354
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
355
+ throw new Error(`supervised-growth lifecycle: Recovery job ${index} is invalid`);
356
+ }
357
+ const job = raw;
358
+ const id = job['id'];
359
+ const activationState = job['activationState'] ?? 'paused';
360
+ const activationNonce = job['activationNonce'];
361
+ if (typeof id !== 'string' || id.trim() === ''
362
+ || (activationState !== 'active' && activationState !== 'paused' && activationState !== 'preview')
363
+ || typeof activationNonce !== 'string' || activationNonce.trim() === '') {
364
+ throw new Error(`supervised-growth lifecycle: Recovery job ${index} identity is invalid`);
365
+ }
366
+ const automationId = `recovery:${id.normalize('NFC').trim()}`;
367
+ if (result.has(automationId)) {
368
+ throw new Error('supervised-growth lifecycle: Recovery automation ids are duplicated');
369
+ }
370
+ result.set(automationId, Object.freeze({
371
+ activationState, activationNonce: activationNonce.normalize('NFC').trim(),
372
+ }));
373
+ }
374
+ return result;
375
+ }
376
+ async function lifecycleDependencies(dependencies) {
377
+ const [automations, recovery] = await Promise.all([
378
+ import('@dsh-ray/assistant-automations'),
379
+ import('@dsh-ray/assistant-recovery'),
380
+ ]);
381
+ return {
382
+ inspectRecovery: dependencies.inspectRecovery ?? recovery.inspectRecoveryOperatorSnapshot,
383
+ inspectAutomations: dependencies.inspectAutomations ?? automations.inspectAutomationsOperatorSnapshot,
384
+ expectedBootstrap: dependencies.expectedBootstrap ?? expectedSupervisedGrowthRecoveryBootstrap,
385
+ expectedAnalystDefinition: dependencies.expectedAnalystDefinition
386
+ ?? expectedSupervisedGrowthAnalystDefinition,
387
+ definitionDigest: dependencies.definitionDigest ?? automations.automationDefinitionDigest,
388
+ };
389
+ }
390
+ async function expectedManagedAutomationRecords(input, dependencies) {
391
+ const recovery = await import('@dsh-ray/assistant-recovery');
392
+ const normalized = recovery.normalizeRecoveryConfig({
393
+ ...supervisedGrowthRecoveryRuntimeConfig(input.effectiveConfig),
394
+ databasePath: input.recoveryDatabasePath,
395
+ });
396
+ const supervisedJob = normalized.jobs.find(candidate => candidate.id === 'supervised-growth');
397
+ if (supervisedJob === undefined || supervisedJob.activationState !== input.stage) {
398
+ throw new Error('supervised-growth lifecycle: effective Recovery stage does not match the requested target');
399
+ }
400
+ const analystDefinition = await dependencies.expectedAnalystDefinition(input.effectiveConfig);
401
+ const records = normalized.jobs.map(job => [`recovery:${job.id}`, Object.freeze({
402
+ owner: 'dsh-ray-assistant-recovery',
403
+ status: job.activationState === 'active' ? 'active' : 'paused',
404
+ definitionHash: dependencies.definitionDigest(recovery.recoveryAutomationDefinition(job, normalized.maxStepDurationMs, job.activationState === 'preview' ? 'preview' : 'production')),
405
+ })]);
406
+ records.push(['heartbeat:supervised-growth-analyst', Object.freeze({
407
+ owner: 'assistant-heartbeat',
408
+ status: input.stage === 'active' ? 'active' : 'paused',
409
+ definitionHash: dependencies.definitionDigest(analystDefinition),
410
+ })]);
411
+ return new Map(records);
412
+ }
413
+ /** Build the exact content-free managed projection before a Host is started. */
414
+ export async function expectedSupervisedGrowthManagedAutomationDigest(input, supplied = {}) {
415
+ const dependencies = await lifecycleDependencies(supplied);
416
+ const expected = await expectedManagedAutomationRecords(input, dependencies);
417
+ const records = Object.freeze([...expected.entries()].map(([id, record]) => Object.freeze({
418
+ id, owner: record.owner, status: record.status, definitionHash: record.definitionHash,
419
+ })).sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0));
420
+ const unsigned = Object.freeze({
421
+ protocol: SUPERVISED_GROWTH_MANAGED_AUTOMATION_PROJECTION_PROTOCOL,
422
+ records,
423
+ });
424
+ return deepFreeze({ ...unsigned, digest: digestJson(unsigned) });
425
+ }
426
+ function assertManagedAutomationInventory(input) {
427
+ if (input.snapshot.inFlightCount !== 0
428
+ || input.snapshot.records.some(record => record.runningTaskCount !== 0)) {
429
+ throw new Error('supervised-growth lifecycle: Automations has in-flight work');
430
+ }
431
+ const records = new Map(input.snapshot.records.map(record => [record.id, record]));
432
+ for (const [id, expected] of input.expected) {
433
+ const actual = records.get(id);
434
+ if (actual === undefined || actual.owner !== expected.owner || actual.status !== expected.status
435
+ || actual.definitionHash !== expected.definitionHash) {
436
+ throw new Error(`supervised-growth lifecycle: managed automation ${id} does not match the exact ${input.stage} definition`);
437
+ }
438
+ }
439
+ const legacy = records.get('heartbeat:supervised-growth');
440
+ if (legacy?.status === 'active') {
441
+ throw new Error('supervised-growth lifecycle: legacy supervised-growth automation is active');
442
+ }
443
+ for (const record of input.snapshot.records) {
444
+ if (record.status !== 'active' || record.owner !== 'dsh-ray-assistant-recovery')
445
+ continue;
446
+ if (!input.expected.has(record.id)) {
447
+ throw new Error(`supervised-growth lifecycle: unexpected active managed automation ${record.id}`);
448
+ }
449
+ }
450
+ }
451
+ function assertRecoverySnapshot(input) {
452
+ const bootstrap = input.snapshot.bootstrap;
453
+ if (input.previousGeneration !== undefined
454
+ && bootstrap.generation <= input.previousGeneration) {
455
+ throw new Error('supervised-growth lifecycle: Recovery bootstrap generation did not strictly advance');
456
+ }
457
+ if (bootstrap.status !== 'succeeded' || !bootstrap.attestationValid
458
+ || bootstrap.attestationSetDigest !== input.expected.attestationSetDigest
459
+ || !isDeepStrictEqual(bootstrap.attestations, input.expected.attestations)) {
460
+ throw new Error(`supervised-growth lifecycle: Recovery ${input.stage} proof does not match the exact effective plan`);
461
+ }
462
+ const configured = configuredRecoveryIdentities(input.effectiveConfig);
463
+ if (bootstrap.attestations.length !== configured.size) {
464
+ throw new Error('supervised-growth lifecycle: Recovery attestation set is incomplete');
465
+ }
466
+ for (const attestation of bootstrap.attestations) {
467
+ const job = configured.get(attestation.automationId);
468
+ if (job === undefined || job.activationState !== attestation.activationState
469
+ || job.activationNonce !== attestation.activationNonce) {
470
+ throw new Error('supervised-growth lifecycle: Recovery attestation identity does not match effective config');
471
+ }
472
+ }
473
+ }
474
+ async function observeLifecycle(input, dependencies) {
475
+ const expectedBootstrap = await dependencies.expectedBootstrap(input.effectiveConfig, input.recoveryDatabasePath);
476
+ const expectedManaged = await expectedManagedAutomationRecords(input, dependencies);
477
+ const [recovery, automations] = await Promise.all([
478
+ dependencies.inspectRecovery(input.recoveryDatabasePath),
479
+ dependencies.inspectAutomations(input.automationsDatabasePath),
480
+ ]);
481
+ return { recovery, automations, expectedBootstrap, expectedManaged };
482
+ }
483
+ function createLifecycleAttestation(input, observed) {
484
+ const identity = recoveryJobIdentity(input.effectiveConfig);
485
+ const externalProviderExemptions = assertLifecycleProviderContract(input);
486
+ const recoveryAttestation = observed.expectedBootstrap.attestations.find(value => value.automationId === 'recovery:supervised-growth');
487
+ if (recoveryAttestation === undefined || recoveryAttestation.activationState !== input.stage) {
488
+ throw new Error('supervised-growth lifecycle: supervised Recovery attestation is missing');
489
+ }
490
+ const recoveryDefinition = observed.expectedManaged.get('recovery:supervised-growth');
491
+ if (recoveryDefinition === undefined)
492
+ throw new Error('supervised-growth lifecycle: Recovery definition is missing');
493
+ // The content-free contract carries the runbook identity through the
494
+ // definition digest, while explicit catalog/nonce digests make upgrade
495
+ // policy checks possible without persisting either secret-free raw value.
496
+ const unsigned = deepFreeze({
497
+ protocol: SUPERVISED_GROWTH_LIFECYCLE_ATTESTATION_PROTOCOL,
498
+ schemaVersion: 1,
499
+ profile: input.profile.normalize('NFC').trim(),
500
+ stage: input.stage,
501
+ externalProviderExemptions,
502
+ effectiveConfigDigest: createHash('sha256').update(input.effectiveConfig).digest('hex'),
503
+ recovery: deepFreeze({
504
+ schemaVersion: observed.recovery.schemaVersion,
505
+ database: observed.recovery.database,
506
+ snapshotDigest: observed.recovery.snapshotDigest,
507
+ bootstrapGeneration: observed.recovery.bootstrap.generation,
508
+ bootstrapAttestationSetDigest: observed.recovery.bootstrap.attestationSetDigest,
509
+ bootstrapAttestations: observed.recovery.bootstrap.attestations,
510
+ activationNonceDigest: createHash('sha256').update(identity.activationNonce).digest('hex'),
511
+ catalogDigest: identity.catalogDigest,
512
+ }),
513
+ automations: deepFreeze({
514
+ schemaVersion: observed.automations.schemaVersion,
515
+ database: observed.automations.database,
516
+ sidecars: observed.automations.sidecars,
517
+ inventoryDigest: observed.automations.inventoryDigest,
518
+ snapshotDigest: digestJson(observed.automations),
519
+ inFlightCount: 0,
520
+ records: sortedAutomationRecords(observed.automations.records),
521
+ }),
522
+ });
523
+ return deepFreeze({ ...unsigned, attestationDigest: digestJson(unsigned) });
524
+ }
525
+ export function supervisedGrowthLifecycleAttestationDigest(value) {
526
+ return digestJson(value);
527
+ }
528
+ /**
529
+ * Capture one stable, content-free supervised lifecycle baseline. This function
530
+ * does not lock, stop, restart, patch, migrate, or otherwise mutate a service.
531
+ */
532
+ export async function captureSupervisedGrowthLifecycleAttestation(input, supplied = {}) {
533
+ if (!keyPattern.test(input.profile))
534
+ throw new Error('supervised-growth lifecycle: invalid profile');
535
+ assertLifecycleProviderContract(input);
536
+ const dependencies = await lifecycleDependencies(supplied);
537
+ const first = await observeLifecycle(input, dependencies);
538
+ assertRecoverySnapshot({
539
+ stage: input.stage, effectiveConfig: input.effectiveConfig,
540
+ snapshot: first.recovery, expected: first.expectedBootstrap,
541
+ });
542
+ assertManagedAutomationInventory({ stage: input.stage, snapshot: first.automations, expected: first.expectedManaged });
543
+ const second = await observeLifecycle(input, dependencies);
544
+ if (!sameRecoveryObservation(first.recovery, second.recovery)
545
+ || !sameAutomationObservation(first.automations, second.automations)
546
+ || !isDeepStrictEqual(first.expectedBootstrap, second.expectedBootstrap)
547
+ || !isDeepStrictEqual([...first.expectedManaged], [...second.expectedManaged])) {
548
+ throw new Error('supervised-growth lifecycle: operator state changed while capturing the baseline');
549
+ }
550
+ assertRecoverySnapshot({
551
+ stage: input.stage, effectiveConfig: input.effectiveConfig,
552
+ snapshot: second.recovery, expected: second.expectedBootstrap,
553
+ });
554
+ assertManagedAutomationInventory({ stage: input.stage, snapshot: second.automations, expected: second.expectedManaged });
555
+ return createLifecycleAttestation(input, second);
556
+ }
557
+ /**
558
+ * Verify a stable successor against a prior accepted lifecycle proof. The new
559
+ * Recovery generation must be strictly newer; a changed runbook/catalog must
560
+ * also carry a fresh activation nonce so old preview authority cannot be reused.
561
+ */
562
+ export async function verifySupervisedGrowthLifecycleSuccessor(input, supplied = {}) {
563
+ const { attestationDigest, ...unsignedBaseline } = input.baseline;
564
+ if (input.baseline.protocol !== SUPERVISED_GROWTH_LIFECYCLE_ATTESTATION_PROTOCOL
565
+ || input.baseline.schemaVersion !== 1
566
+ || attestationDigest !== supervisedGrowthLifecycleAttestationDigest(unsignedBaseline)
567
+ || input.target.profile !== input.baseline.profile) {
568
+ throw new Error('supervised-growth lifecycle: baseline contract is invalid');
569
+ }
570
+ const successor = await captureSupervisedGrowthLifecycleAttestation(input.target, supplied);
571
+ if (successor.recovery.bootstrapGeneration <= input.baseline.recovery.bootstrapGeneration) {
572
+ throw new Error('supervised-growth lifecycle: Recovery successor generation did not strictly advance');
573
+ }
574
+ // Preview and active intentionally share one nonce even though their exact
575
+ // Automation definitions differ (preview is paused and uses a one-shot
576
+ // schedule; active is scheduled). The catalog digest is the stable identity
577
+ // of the compiled Recovery runbook, so only a catalog change requires a new
578
+ // nonce across lifecycle generations.
579
+ const runbookChanged = successor.recovery.catalogDigest !== input.baseline.recovery.catalogDigest;
580
+ if (runbookChanged
581
+ && successor.recovery.activationNonceDigest === input.baseline.recovery.activationNonceDigest) {
582
+ throw new Error('supervised-growth lifecycle: changed Recovery runbook reused the old activation nonce');
583
+ }
584
+ return successor;
585
+ }
586
+ async function inspectRecoveryBootstrap(databasePath) {
587
+ const { RecoveryStore } = await import('@dsh-ray/assistant-recovery');
588
+ const store = new RecoveryStore({ path: databasePath });
589
+ try {
590
+ return store.health();
591
+ }
592
+ finally {
593
+ store.close();
594
+ }
595
+ }
596
+ async function recoveryBootstrapGenerationBeforeRestart(databasePath) {
597
+ try {
598
+ await stat(databasePath);
599
+ }
600
+ catch (error) {
601
+ if (typeof error === 'object' && error !== null && 'code' in error
602
+ && error.code === 'ENOENT')
603
+ return 0;
604
+ throw error;
605
+ }
606
+ const generation = (await inspectRecoveryBootstrap(databasePath)).bootstrapGeneration;
607
+ if (!Number.isSafeInteger(generation) || generation < 0) {
608
+ throw new Error('supervised-growth setup: persisted Recovery bootstrap generation is invalid before restart');
609
+ }
610
+ return generation;
611
+ }
612
+ async function automationSnapshots(databasePath) {
613
+ const { listAutomationsLocally } = await import('@dsh-ray/assistant-automations');
614
+ return listAutomationsLocally(databasePath);
615
+ }
616
+ function effectiveOwnerRoutes(effectiveConfig) {
617
+ const document = parseDocument(effectiveConfig, { uniqueKeys: true });
618
+ if (document.errors.length > 0) {
619
+ throw new Error(`supervised-growth setup: invalid effective profile YAML: ${document.errors[0].message}`);
620
+ }
621
+ if (!isSeq(document.contents)) {
622
+ throw new Error('supervised-growth setup: effective profile must be a YAML sequence');
623
+ }
624
+ const rows = document.contents.items.filter(item => isMap(item)
625
+ && item.get('id') === 'dsh-ray-assistant-delivery');
626
+ if (rows.length !== 1 || rows[0].get('disabled') === true) {
627
+ throw new Error('supervised-growth setup: effective assistant-delivery row must be uniquely enabled');
628
+ }
629
+ const configNode = rows[0].get('config', true);
630
+ if (!isMap(configNode)) {
631
+ throw new Error('supervised-growth setup: effective assistant-delivery config must be a YAML mapping');
632
+ }
633
+ const routesNode = configNode.get('ownerRoutes', true);
634
+ if (routesNode === undefined)
635
+ return Object.freeze([]);
636
+ if (!isSeq(routesNode)) {
637
+ throw new Error('supervised-growth setup: effective assistant-delivery.ownerRoutes must be a YAML sequence');
638
+ }
639
+ return Object.freeze(routesNode.items.map((item, index) => {
640
+ if (!isMap(item)) {
641
+ throw new Error(`supervised-growth setup: effective ownerRoutes[${index}] must be a YAML mapping`);
642
+ }
643
+ const value = item.toJSON();
644
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
645
+ throw new Error(`supervised-growth setup: effective ownerRoutes[${index}] must be a YAML mapping`);
646
+ }
647
+ return value;
648
+ }));
649
+ }
650
+ /**
651
+ * Rebuild Recovery's complete content-free bootstrap proof from the final DSH
652
+ * config. The same Delivery authority hash and Recovery activation-plan digest
653
+ * algorithms used by the live service are deliberately reused here.
654
+ */
655
+ export async function expectedSupervisedGrowthRecoveryBootstrap(effectiveConfig, recoveryDatabasePath) {
656
+ const [delivery, recovery] = await Promise.all([
657
+ import('@dsh-ray/assistant-delivery'),
658
+ import('@dsh-ray/assistant-recovery'),
659
+ ]);
660
+ const normalized = recovery.normalizeRecoveryConfig({
661
+ ...supervisedGrowthRecoveryRuntimeConfig(effectiveConfig),
662
+ databasePath: recoveryDatabasePath,
663
+ });
664
+ const authorityHash = delivery.ownerRouteAuthorityHash;
665
+ const authorities = new Map();
666
+ for (const raw of effectiveOwnerRoutes(effectiveConfig)) {
667
+ const rawId = raw.id;
668
+ if (typeof rawId !== 'string') {
669
+ throw new Error('supervised-growth setup: effective owner route id is invalid');
670
+ }
671
+ const id = rawId.normalize('NFC').trim();
672
+ const authority = raw;
673
+ const digest = authorityHash(authority);
674
+ if (authorities.has(id)) {
675
+ throw new Error(`supervised-growth setup: effective owner route ${id} is duplicated`);
676
+ }
677
+ authorities.set(id, digest);
678
+ }
679
+ const attestations = recovery.canonicalRecoveryBootstrapAttestationSet(normalized.jobs.map(job => {
680
+ const route = authorities.get(job.ownerRouteId);
681
+ if (route === undefined) {
682
+ throw new Error(`supervised-growth setup: Recovery job ${job.id} has no effective owner route`);
683
+ }
684
+ return Object.freeze({
685
+ automationId: recovery.recoveryAutomationId(job.id),
686
+ activationState: job.activationState,
687
+ activationNonce: job.activationNonce,
688
+ activationPlanDigest: recovery.recoveryActivationPlanDigest(job, normalized.maxStepDurationMs, route),
689
+ });
690
+ }));
691
+ return Object.freeze({
692
+ attestations,
693
+ attestationSetDigest: recovery.recoveryBootstrapAttestationSetDigest(attestations),
694
+ });
695
+ }
696
+ async function expectedRecoveryProductionDefinition(effectiveConfig, recoveryDatabasePath) {
697
+ const recovery = await import('@dsh-ray/assistant-recovery');
698
+ const runtimeConfig = supervisedGrowthRecoveryRuntimeConfig(effectiveConfig);
699
+ const normalized = recovery.normalizeRecoveryConfig({ ...runtimeConfig, databasePath: recoveryDatabasePath });
700
+ const job = normalized.jobs.find(candidate => candidate.id === 'supervised-growth');
701
+ if (job === undefined) {
702
+ throw new Error('supervised-growth setup: effective Recovery job is missing during runtime attestation');
703
+ }
704
+ return recovery.recoveryAutomationDefinition(job, normalized.maxStepDurationMs, 'production');
705
+ }
706
+ /**
707
+ * Rebuild the exact analyst definition from final config and its private,
708
+ * managed scratch. Drifted scratch bytes fail activation instead of silently
709
+ * changing what the unattended analyst will do.
710
+ */
711
+ async function expectedSupervisedGrowthAnalystDefinition(effectiveConfig) {
712
+ const heartbeatRuntime = supervisedGrowthAnalystRuntimeConfig(effectiveConfig);
713
+ const heartbeat = await import('@dsh-ray/assistant-heartbeat');
714
+ const normalized = heartbeat.normalizeHeartbeatConfig({
715
+ heartbeats: [heartbeatRuntime.heartbeat],
716
+ maxScratchBytes: heartbeatRuntime.maxScratchBytes,
717
+ });
718
+ const profile = normalized.heartbeats[0];
719
+ if (profile === undefined || profile.id !== 'supervised-growth-analyst') {
720
+ throw new Error('supervised-growth setup: normalized analyst heartbeat is missing');
721
+ }
722
+ const raw = await readFile(profile.scratchPath, 'utf8');
723
+ const content = raw.normalize('NFC').replace(/\r\n?/gu, '\n').trim();
724
+ if (content !== profile.initialScratch.normalize('NFC').replace(/\r\n?/gu, '\n').trim()) {
725
+ throw new Error('supervised-growth setup: managed analyst scratch drifted from the attested contract');
726
+ }
727
+ if (Buffer.byteLength(content, 'utf8') > heartbeatRuntime.maxScratchBytes) {
728
+ throw new Error('supervised-growth setup: managed analyst scratch exceeds its configured bound');
729
+ }
730
+ const revision = createHash('sha256').update(content, 'utf8').digest('hex');
731
+ return heartbeat.heartbeatDefinition(profile, content, revision);
732
+ }
733
+ /**
734
+ * Persisted plugin bootstrap, not merely OS process state, is the stage gate.
735
+ * Preview additionally proves both model-free jobs are paused; active proves the
736
+ * exact compiled production definition is the sole active managed replacement.
737
+ */
738
+ export async function verifySupervisedGrowthRecoveryStage(input, dependencies = {}) {
739
+ const inspect = dependencies.inspectRecovery ?? inspectRecoveryBootstrap;
740
+ const listAll = dependencies.listAutomations
741
+ ?? dependencies.listActiveAutomations
742
+ ?? automationSnapshots;
743
+ const expectedBootstrap = await (dependencies.expectedBootstrap
744
+ ?? expectedSupervisedGrowthRecoveryBootstrap)(input.effectiveConfig, input.recoveryDatabasePath);
745
+ const expectedDefinition = input.stage === 'active'
746
+ ? await (dependencies.expectedProductionDefinition ?? expectedRecoveryProductionDefinition)(input.effectiveConfig, input.recoveryDatabasePath)
747
+ : undefined;
748
+ const expectedAnalystDefinition = await (dependencies.expectedAnalystDefinition ?? expectedSupervisedGrowthAnalystDefinition)(input.effectiveConfig);
749
+ const wait = dependencies.wait ?? delay;
750
+ const retryDelayMs = dependencies.retryDelayMs ?? 250;
751
+ if (!Number.isSafeInteger(input.previousBootstrapGeneration) || input.previousBootstrapGeneration < 0
752
+ || !Number.isSafeInteger(input.timeoutMs) || input.timeoutMs < 1 || input.timeoutMs > 900_000
753
+ || !Number.isSafeInteger(retryDelayMs) || retryDelayMs < 1 || retryDelayMs > 5_000) {
754
+ throw new Error('supervised-growth setup: invalid Recovery bootstrap verification bounds');
755
+ }
756
+ let remaining = input.timeoutMs;
757
+ let highestObservedGeneration = input.previousBootstrapGeneration;
758
+ let lastFailure;
759
+ for (;;) {
760
+ try {
761
+ const health = await inspect(input.recoveryDatabasePath);
762
+ const generation = health.bootstrapGeneration;
763
+ if (!Number.isSafeInteger(generation) || generation < 0) {
764
+ throw new Error('supervised-growth setup: Recovery bootstrap generation is invalid');
765
+ }
766
+ if (generation < highestObservedGeneration) {
767
+ throw new Error(`supervised-growth setup: Recovery bootstrap generation regressed from ${highestObservedGeneration} to ${generation}`);
768
+ }
769
+ highestObservedGeneration = generation;
770
+ if (generation > input.previousBootstrapGeneration) {
771
+ if (health.bootstrapStatus === 'failed') {
772
+ throw new Error(`supervised-growth setup: Recovery ${input.stage} bootstrap failed${health.bootstrapFailureCode === undefined ? '' : `: ${health.bootstrapFailureCode}`}`);
773
+ }
774
+ if (health.bootstrapStatus === 'succeeded') {
775
+ if (!health.bootstrapAttestationValid) {
776
+ throw new Error(`supervised-growth setup: Recovery ${input.stage} bootstrap attestation is invalid`);
777
+ }
778
+ if (!isDeepStrictEqual(health.bootstrapAttestations, expectedBootstrap.attestations)) {
779
+ throw new Error(`supervised-growth setup: Recovery ${input.stage} exact bootstrap attestation set does not match the effective plan`);
780
+ }
781
+ if (health.bootstrapAttestationSetDigest !== expectedBootstrap.attestationSetDigest) {
782
+ throw new Error(`supervised-growth setup: Recovery ${input.stage} bootstrap attestation set digest does not match the effective plan`);
783
+ }
784
+ const automations = await listAll(input.automationsDatabasePath);
785
+ const stableHealth = await inspect(input.recoveryDatabasePath);
786
+ const stableGeneration = stableHealth.bootstrapGeneration;
787
+ if (!Number.isSafeInteger(stableGeneration) || stableGeneration < 0) {
788
+ throw new Error('supervised-growth setup: Recovery bootstrap generation is invalid');
789
+ }
790
+ if (stableGeneration < highestObservedGeneration) {
791
+ throw new Error(`supervised-growth setup: Recovery bootstrap generation regressed from ${highestObservedGeneration} to ${stableGeneration}`);
792
+ }
793
+ highestObservedGeneration = stableGeneration;
794
+ if (stableGeneration !== generation) {
795
+ lastFailure = new Error('Recovery bootstrap generation changed while attesting Automations');
796
+ }
797
+ else {
798
+ if (stableHealth.bootstrapStatus !== 'succeeded'
799
+ || !stableHealth.bootstrapAttestationValid
800
+ || stableHealth.bootstrapAttestationSetDigest !== expectedBootstrap.attestationSetDigest
801
+ || !isDeepStrictEqual(stableHealth.bootstrapAttestations, expectedBootstrap.attestations)) {
802
+ throw new Error(`supervised-growth setup: Recovery ${input.stage} bootstrap attestation changed while attesting Automations`);
803
+ }
804
+ const legacyActive = automations.find(record => record.id === 'heartbeat:supervised-growth'
805
+ && record.status === 'active');
806
+ const recoveries = automations.filter(record => record.id === 'recovery:supervised-growth'
807
+ && record.status === 'active');
808
+ const analysts = automations.filter(record => record.id === 'heartbeat:supervised-growth-analyst');
809
+ const analyst = analysts.length === 1 ? analysts[0] : undefined;
810
+ const expectedAnalystStatus = input.stage === 'active' ? 'active' : 'paused';
811
+ const analystExact = analyst !== undefined
812
+ && analyst.owner === 'assistant-heartbeat'
813
+ && analyst.status === expectedAnalystStatus
814
+ && isDeepStrictEqual(analyst.definition, expectedAnalystDefinition);
815
+ if (!analystExact) {
816
+ throw new Error(`supervised-growth setup: ${input.stage} analyst automation does not match its exact attested definition`);
817
+ }
818
+ if (legacyActive === undefined && input.stage === 'preview' && recoveries.length === 0) {
819
+ return generation;
820
+ }
821
+ if (legacyActive === undefined && input.stage === 'active' && recoveries.length === 1) {
822
+ const record = recoveries[0];
823
+ if (record.owner === 'dsh-ray-assistant-recovery'
824
+ && isDeepStrictEqual(record.definition, expectedDefinition))
825
+ return generation;
826
+ throw new Error('supervised-growth setup: active Recovery automation definition does not match the compiled plan');
827
+ }
828
+ lastFailure = new Error(input.stage === 'preview'
829
+ ? 'legacy/recovery/analyst preview automations have not reached their attested paused state'
830
+ : 'exact Recovery and analyst production automations are not active');
831
+ }
832
+ }
833
+ }
834
+ else if (health.bootstrapStatus === 'succeeded'
835
+ && health.bootstrapAttestationValid
836
+ && health.bootstrapAttestationSetDigest === expectedBootstrap.attestationSetDigest
837
+ && isDeepStrictEqual(health.bootstrapAttestations, expectedBootstrap.attestations)) {
838
+ throw new Error(`supervised-growth setup: Recovery ${input.stage} bootstrap reused generation ${generation}`);
839
+ }
840
+ else {
841
+ lastFailure = new Error(`waiting for a Recovery bootstrap generation newer than ${input.previousBootstrapGeneration}`);
842
+ }
843
+ }
844
+ catch (error) {
845
+ // A current-generation explicit bootstrap failure or definition mismatch
846
+ // is terminal. Missing/busy DB state and not-yet-reconciled paused rows are
847
+ // retried within the same bounded gate.
848
+ if (error instanceof Error
849
+ && (/Recovery (?:preview|active) bootstrap failed/u.test(error.message)
850
+ || /bootstrap (?:attestation|generation)/u.test(error.message)
851
+ || /bootstrap reused generation/u.test(error.message)
852
+ || /analyst automation/u.test(error.message)
853
+ || /definition does not match/u.test(error.message)))
854
+ throw error;
855
+ lastFailure = error;
856
+ }
857
+ if (remaining <= 0) {
858
+ throw new Error(`supervised-growth setup: Recovery ${input.stage} bootstrap did not become ready${lastFailure instanceof Error ? `: ${lastFailure.message}` : ''}`);
859
+ }
860
+ const waitFor = Math.min(retryDelayMs, remaining);
861
+ await wait(waitFor);
862
+ remaining -= waitFor;
863
+ }
864
+ }
865
+ async function awaitOwnerBinding(input) {
866
+ const { findActiveOwnerDmBindingsLocally } = await import('@dsh-ray/assistant-delivery');
867
+ const deadline = Date.now() + input.timeoutMs;
868
+ let prompted = false;
869
+ for (;;) {
870
+ const bindings = findActiveOwnerDmBindingsLocally({ databasePath: input.databasePath, ...input.query });
871
+ if (bindings.length > 1)
872
+ return selectUniqueOwnerBinding(bindings);
873
+ if (bindings.length === 1)
874
+ return selectUniqueOwnerBinding(bindings);
875
+ if (!prompted) {
876
+ prompted = true;
877
+ process.stdout.write('未找到与当前 profile 精确匹配的 owner 私聊绑定。请 owner 再给机器人发送一条普通私聊;等待期间不会修改配置。\n');
878
+ }
879
+ if (Date.now() >= deadline) {
880
+ throw new Error('supervised-growth setup: timed out waiting for an exact owner DM binding; profile was not changed');
881
+ }
882
+ await delay(Math.min(1_000, Math.max(1, deadline - Date.now())));
883
+ }
884
+ }
885
+ async function assertSelectedOwnerBindingCurrent(input) {
886
+ const { findActiveOwnerDmBindingsLocally } = await import('@dsh-ray/assistant-delivery');
887
+ const current = selectUniqueOwnerBinding(findActiveOwnerDmBindingsLocally({
888
+ databasePath: input.databasePath,
889
+ ...input.query,
890
+ }));
891
+ if (!sameSupervisedGrowthBinding(current, input.selected)) {
892
+ throw new Error('supervised-growth setup: selected owner binding changed before activation; profile was not changed');
893
+ }
894
+ }
895
+ export async function runSupervisedGrowthSetup(argv = process.argv.slice(2)) {
896
+ const args = parseSupervisedGrowthSetupArgs(argv);
897
+ if (args.help) {
898
+ process.stdout.write(`${help()}\n`);
899
+ return;
900
+ }
901
+ if (residentServiceKind(process.platform) === 'windows-task-best-effort') {
902
+ throw new Error('supervised-growth setup: Windows has no verifiable resident health gate; profile was not changed');
903
+ }
904
+ const dshHome = process.env.DSH_HOME?.trim() || join(homedir(), '.dsh');
905
+ if (!isAbsolute(dshHome))
906
+ throw new Error('supervised-growth setup: DSH_HOME must be absolute');
907
+ return withDshHomeLifecycleLock(dshHome, async () => {
908
+ const patchPath = join(dshHome, 'profiles', args.profile, 'cordis.patch.yml');
909
+ const originalPatch = await readFile(patchPath, 'utf8');
910
+ const effectiveBefore = dumpProfile(args.profile);
911
+ const query = supervisedGrowthBindingQuery(effectiveBefore, dshHome);
912
+ const databases = supervisedGrowthDatabasePaths(effectiveBefore, dshHome);
913
+ const binding = await awaitOwnerBinding({
914
+ databasePath: databases.deliveryDatabasePath, query, timeoutMs: args.timeoutMs,
915
+ });
916
+ const { listActiveAutomationsLocally } = await import('@dsh-ray/assistant-automations');
917
+ assertSupervisedGrowthAutomationGuard(listActiveAutomationsLocally(databases.automationsDatabasePath), args.ackExistingAutomations);
918
+ const { RECOVERY_CATALOG_DIGEST } = await import('@dsh-ray/assistant-recovery');
919
+ const activationNonce = randomUUID();
920
+ const previewPatch = configureSupervisedGrowthProfilePatch({
921
+ profilePatch: originalPatch,
922
+ effectiveConfig: effectiveBefore,
923
+ dshHome,
924
+ binding,
925
+ activationState: 'preview',
926
+ activationNonce,
927
+ recoveryCatalogDigest: RECOVERY_CATALOG_DIGEST,
928
+ });
929
+ await assertSelectedOwnerBindingCurrent({
930
+ databasePath: databases.deliveryDatabasePath,
931
+ query,
932
+ selected: binding,
933
+ });
934
+ let service;
935
+ let acceptedBootstrapGeneration;
936
+ await activateSupervisedGrowthRecoveryStages({
937
+ patchPath,
938
+ originalPatch,
939
+ previewPatch,
940
+ validate: stage => {
941
+ const effectiveConfig = dumpProfile(args.profile);
942
+ assertEffectiveSupervisedGrowthConfig({
943
+ effectiveConfig,
944
+ dshHome,
945
+ binding,
946
+ activationState: stage,
947
+ activationNonce,
948
+ recoveryCatalogDigest: RECOVERY_CATALOG_DIGEST,
949
+ });
950
+ return effectiveConfig;
951
+ },
952
+ buildActivePatch: previewEffective => configureSupervisedGrowthProfilePatch({
953
+ profilePatch: previewPatch,
954
+ effectiveConfig: previewEffective,
955
+ dshHome,
956
+ binding,
957
+ activationState: 'active',
958
+ activationNonce,
959
+ recoveryCatalogDigest: RECOVERY_CATALOG_DIGEST,
960
+ }),
961
+ afterStage: async (stage, effectiveConfig) => {
962
+ const effectiveDatabases = supervisedGrowthDatabasePaths(effectiveConfig, dshHome);
963
+ if (effectiveDatabases.deliveryDatabasePath !== databases.deliveryDatabasePath
964
+ || effectiveDatabases.automationsDatabasePath !== databases.automationsDatabasePath
965
+ || effectiveDatabases.recoveryDatabasePath !== databases.recoveryDatabasePath) {
966
+ throw new Error('supervised-growth setup: a higher-priority profile layer changed a guarded local database path');
967
+ }
968
+ // The binding is re-read after the atomic write and again immediately
969
+ // before restart. A rotation/revocation/version change must never become
970
+ // a background delivery grant merely because its old snapshot was valid.
971
+ await assertSelectedOwnerBindingCurrent({
972
+ databasePath: databases.deliveryDatabasePath,
973
+ query,
974
+ selected: binding,
975
+ });
976
+ const previousBootstrapGeneration = acceptedBootstrapGeneration
977
+ ?? await recoveryBootstrapGenerationBeforeRestart(databases.recoveryDatabasePath);
978
+ service = await restartAndVerifySupervisedGrowthResident({ dshHome, profile: args.profile });
979
+ acceptedBootstrapGeneration = await verifySupervisedGrowthRecoveryStage({
980
+ stage,
981
+ effectiveConfig,
982
+ recoveryDatabasePath: databases.recoveryDatabasePath,
983
+ automationsDatabasePath: databases.automationsDatabasePath,
984
+ previousBootstrapGeneration,
985
+ timeoutMs: args.timeoutMs,
986
+ });
987
+ },
988
+ restore: async () => {
989
+ dumpProfile(args.profile);
990
+ await restartAndVerifySupervisedGrowthResident({ dshHome, profile: args.profile });
991
+ },
992
+ });
993
+ if (service === undefined)
994
+ throw new Error('supervised-growth setup: resident restart did not return a service');
995
+ process.stdout.write(`supervised-growth/v2 Recovery 已启用:owner binding ${binding.id},Recovery 每日上限 7;独立 adoption analyst 每日上限 1。\n`
996
+ + `DSH Host 已由 ${service.kind} 重启并通过健康检查。状态:${service.statusCommand}\n日志:${service.logCommand}\n`);
997
+ });
998
+ }
999
+ if (process.argv[1] !== undefined && isMainEntry(import.meta.url, process.argv[1])) {
1000
+ void runSupervisedGrowthSetup().catch(error => {
1001
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
1002
+ process.exitCode = 1;
1003
+ });
1004
+ }
1005
+ //# sourceMappingURL=supervised-growth-setup.js.map