bailinghub 0.9.4 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (334) hide show
  1. package/README.en.md +6 -6
  2. package/README.md +6 -6
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/docker-compose.images.yml +2 -2
  5. package/docs/AGENT_CLIENT_QUICKSTART.en.md +1 -3
  6. package/docs/AGENT_CLIENT_QUICKSTART.md +1 -1
  7. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +87 -2
  8. package/docs/AGENT_CLIENT_RUNTIME_API.md +36 -2
  9. package/docs/AGENT_KNOWLEDGE_API.en.md +77 -0
  10. package/docs/AGENT_KNOWLEDGE_API.md +86 -0
  11. package/docs/AGENT_TASK_CONTROL.md +4 -4
  12. package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +1 -1
  13. package/docs/ARCHITECTURE.md +4 -0
  14. package/docs/CHANGELOG.en.md +24 -1
  15. package/docs/CHANGELOG.md +24 -1
  16. package/docs/COMPATIBILITY.en.md +27 -1
  17. package/docs/CONTRACT.en.md +1 -1
  18. package/docs/CONTRACT.md +1 -1
  19. package/docs/IMPLEMENTATION_STATUS.en.md +28 -15
  20. package/docs/IMPLEMENTATION_STATUS.md +28 -15
  21. package/docs/INDEPENDENT_VALIDATION.en.md +6 -4
  22. package/docs/INDEPENDENT_VALIDATION.md +6 -4
  23. package/docs/INTEGRATION_WALKTHROUGH.md +65 -0
  24. package/docs/MODEL_BILLING.en.md +2 -0
  25. package/docs/MODEL_BILLING.md +6 -2
  26. package/docs/MODEL_CONTINUATION.en.md +54 -0
  27. package/docs/MODEL_CONTINUATION.md +54 -0
  28. package/docs/MODEL_OUTPUT_BUDGET.en.md +69 -0
  29. package/docs/MODEL_OUTPUT_BUDGET.md +69 -0
  30. package/docs/OPERATIONS.en.md +16 -4
  31. package/docs/OPERATIONS.md +16 -4
  32. package/docs/QUICKSTART.md +1 -1
  33. package/docs/README.en.md +7 -0
  34. package/docs/README.md +7 -0
  35. package/docs/RELEASE_NOTES_NEXT.en.md +3 -3
  36. package/docs/RELEASE_NOTES_NEXT.md +3 -3
  37. package/docs/RELEASE_NOTES_v0.10.0.en.md +58 -0
  38. package/docs/RELEASE_NOTES_v0.10.0.md +58 -0
  39. package/docs/RELEASE_NOTES_v0.10.1.en.md +41 -0
  40. package/docs/RELEASE_NOTES_v0.10.1.md +41 -0
  41. package/docs/UPGRADE_PLAN.en.md +118 -0
  42. package/docs/UPGRADE_PLAN.md +124 -0
  43. package/docs/UPGRADE_v0.10.0.en.md +47 -0
  44. package/docs/UPGRADE_v0.10.0.md +47 -0
  45. package/docs/UPGRADE_v0.10.1.en.md +66 -0
  46. package/docs/UPGRADE_v0.10.1.md +66 -0
  47. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +38 -22
  48. package/package.json +10 -5
  49. package/schemas/tool-definition.schema.json +13 -0
  50. package/scripts/check-doc-links.mjs +6 -0
  51. package/scripts/check-image-tags.sh +1 -1
  52. package/scripts/check-php-sdk-artifacts.mjs +152 -0
  53. package/scripts/check-php-sdk-artifacts.test.mjs +99 -0
  54. package/scripts/check-release-consistency.test.mjs +2 -2
  55. package/scripts/doctor-upgrade-plan.test.ts +205 -0
  56. package/scripts/doctor-upgrade-plan.ts +276 -0
  57. package/scripts/doctor.ts +4 -1
  58. package/scripts/e2e-console-approval-details.mjs +134 -0
  59. package/scripts/e2e-console-config-races.mjs +180 -0
  60. package/scripts/e2e-console-kb-audit.mjs +170 -0
  61. package/scripts/e2e-console-operations-audit.mjs +152 -0
  62. package/scripts/e2e-console-runtime-audit.mjs +179 -0
  63. package/scripts/e2e-console-settings-audit.mjs +125 -0
  64. package/scripts/e2e-console-troubleshooting-extra.mjs +267 -0
  65. package/scripts/e2e-console.mjs +476 -7
  66. package/scripts/install.sh +1 -1
  67. package/scripts/publish-images.sh +1 -1
  68. package/scripts/release-audit.mjs +9 -1
  69. package/scripts/sdk-declaration-contract-test.ts +34 -0
  70. package/scripts/sdk-p1-check.mjs +62 -26
  71. package/scripts/verify-github-repo.mjs +8 -0
  72. package/sdk/dotnet/Bailing.Connect/BailingConnect.cs +4 -4
  73. package/sdk/dotnet/README.md +8 -0
  74. package/sdk/dotnet/tests/Declaration/Declaration.csproj +11 -0
  75. package/sdk/dotnet/tests/Declaration/Program.cs +74 -0
  76. package/sdk/go/README.md +8 -0
  77. package/sdk/go/bailingconnect/connect.go +5 -5
  78. package/sdk/go/bailingconnect/declaration_test.go +107 -0
  79. package/sdk/java/README.md +13 -0
  80. package/sdk/java/src/main/java/com/bailing/connect/BailingConnect.java +4 -4
  81. package/sdk/java/tests/DeclarationTest.java +70 -0
  82. package/sdk/node/README.md +8 -0
  83. package/sdk/node/src/index.mjs +4 -4
  84. package/sdk/node/tests/declaration.test.mjs +41 -0
  85. package/sdk/php/README.md +16 -0
  86. package/sdk/php/src/Attributes/AiTool.php +4 -4
  87. package/sdk/php/src/SpecBuilder.php +8 -8
  88. package/sdk/php/tests/declaration-serialization.php +103 -0
  89. package/sdk/php7/README.md +14 -0
  90. package/sdk/php7/src/ToolDef.php +3 -3
  91. package/sdk/php7/src/ToolSpec.php +8 -13
  92. package/sdk/php7/tests/declaration-serialization.php +103 -0
  93. package/sdk/python/README.md +8 -0
  94. package/sdk/python/bailing_connect/__init__.py +6 -6
  95. package/sdk/python/tests/test_declaration.py +61 -0
  96. package/src/app/agent-client-runtime.test.ts +115 -2
  97. package/src/app/agent-client-runtime.ts +40 -11
  98. package/src/app/agent-knowledge.test.ts +171 -0
  99. package/src/app/agent-knowledge.ts +233 -0
  100. package/src/app/agent-tool-catalog-revision.test.ts +31 -0
  101. package/src/app/agent-tool-invocations.test.ts +7 -2
  102. package/src/app/agent-tool-invocations.ts +67 -7
  103. package/src/app/approval-continuations.test.ts +49 -1
  104. package/src/app/http.test.ts +16 -1
  105. package/src/app/http.ts +3 -3
  106. package/src/app/kernel-boot-recovery.mysql.test.ts +132 -0
  107. package/src/app/kernel-boot-recovery.test.ts +157 -0
  108. package/src/app/kernel.ts +12 -8
  109. package/src/app/readiness.mysql.test.ts +120 -0
  110. package/src/app/readiness.test.ts +111 -26
  111. package/src/app/readiness.ts +26 -22
  112. package/src/app/runtime-lifecycle.ts +34 -3
  113. package/src/app/tool-approvals.test.ts +83 -0
  114. package/src/app/tool-approvals.ts +25 -7
  115. package/src/app/tool-proxy-payload.test.ts +81 -0
  116. package/src/app/tool-proxy.ts +24 -2
  117. package/src/core/config/console-diagnostic-location.test.ts +36 -0
  118. package/src/core/config/console-form-guard.test.ts +69 -0
  119. package/src/core/config/console-task-location.test.ts +64 -0
  120. package/src/core/contracts/explicit-capability-values.test.ts +62 -0
  121. package/src/core/contracts/openapi-tools.ts +18 -7
  122. package/src/core/contracts/schema-readiness.ts +11 -0
  123. package/src/core/contracts/tool-annotations.ts +4 -4
  124. package/src/core/contracts/tool-definition.ts +26 -0
  125. package/src/core/contracts/tool-guidance.test.ts +77 -0
  126. package/src/core/contracts/tool-guidance.ts +31 -0
  127. package/src/core/contracts/tool-input-limits.ts +15 -0
  128. package/src/core/contracts/tools-idempotency.test.ts +90 -0
  129. package/src/core/contracts/tools.ts +52 -9
  130. package/src/core/runtime/agent-execution-memory.test.ts +64 -0
  131. package/src/core/runtime/agent-execution-memory.ts +63 -0
  132. package/src/core/state/state-contracts.ts +3 -0
  133. package/src/infrastructure/config/config-observability-ledger.ts +2 -0
  134. package/src/infrastructure/schema/schema-readiness.ts +29 -0
  135. package/src/infrastructure/state/state-mysql.ts +3 -0
  136. package/src/modules/usage/contracts.ts +7 -0
  137. package/src/modules/usage/http.ts +2 -0
  138. package/src/modules/usage/model-continuation.test.ts +109 -0
  139. package/src/modules/usage/model-gateway.ts +5 -1
  140. package/src/modules/usage/output-budget.mysql.test.ts +84 -0
  141. package/src/modules/usage/output-budget.test.ts +167 -0
  142. package/src/modules/usage/output-budget.ts +73 -0
  143. package/src/modules/usage/provider-stream.test.ts +22 -0
  144. package/src/modules/usage/provider.ts +2 -3
  145. package/src/modules/usage/repository.ts +6 -0
  146. package/src/modules/usage/test-harness.ts +4 -2
  147. package/src/routes/admin-approval-view.test.ts +109 -0
  148. package/src/routes/admin-approval-view.ts +36 -0
  149. package/src/routes/admin-readiness.test.ts +52 -0
  150. package/src/routes/admin-runtime-ux.test.ts +51 -0
  151. package/src/routes/admin-runtime-ux.ts +25 -0
  152. package/src/routes/admin-runtime.ts +36 -8
  153. package/src/routes/admin.ts +9 -0
  154. package/src/routes/agent-api.test.ts +80 -1
  155. package/src/routes/agent-api.ts +63 -4
  156. package/src/routes/agent-tool-detail.test.ts +140 -0
  157. package/src/routes/public-default.ts +1 -1
  158. package/src/services/kb-agent.test.ts +84 -0
  159. package/src/services/kb.ts +73 -0
  160. package/web/connect/bailing-connect-php.tgz +0 -0
  161. package/web/connect/bailing-connect-php7.tgz +0 -0
  162. package/web/console/assets/Accounts-CjIBO3sU.css +1 -0
  163. package/web/console/assets/Accounts-Dhyw-7wF.js +3 -0
  164. package/web/console/assets/AgentClients-BA0M26-I.css +1 -0
  165. package/web/console/assets/AgentClients-DWxb8-ko.js +1 -0
  166. package/web/console/assets/AgentTasks-DOyxANnx.css +1 -0
  167. package/web/console/assets/AgentTasks-DUHD4dzr.js +2 -0
  168. package/web/console/assets/Approvals-Brl-2uJq.css +1 -0
  169. package/web/console/assets/Approvals-CQx1YWxW.js +1 -0
  170. package/web/console/assets/Audit--QcdVlMh.js +1 -0
  171. package/web/console/assets/Audit-DAdmOnIs.css +1 -0
  172. package/web/console/assets/{BrandLockup-CffORQse.js → BrandLockup-DQcaW4Nt.js} +1 -1
  173. package/web/console/assets/Channels-DJJU3ksE.css +1 -0
  174. package/web/console/assets/Channels-cGS5WfQ-.js +105 -0
  175. package/web/console/assets/ChatEntries-BYpji27B.css +1 -0
  176. package/web/console/assets/ChatEntries-nh23Iz5O.js +7 -0
  177. package/web/console/assets/Clients-CX5EeYio.js +3 -0
  178. package/web/console/assets/Clients-CbZAou8E.css +1 -0
  179. package/web/console/assets/Cost-C6oQvz9P.css +1 -0
  180. package/web/console/assets/Cost-DOZfdNS9.js +1 -0
  181. package/web/console/assets/Credentials--aHs57yV.css +1 -0
  182. package/web/console/assets/Credentials-sy6W9Sac.js +1 -0
  183. package/web/console/assets/Diagnostics-CKs27Dnv.css +1 -0
  184. package/web/console/assets/Diagnostics-CyoM1XrZ.js +1 -0
  185. package/web/console/assets/Executors-2Upi6bOS.css +1 -0
  186. package/web/console/assets/Executors-BQqqiFwt.js +1 -0
  187. package/web/console/assets/HelpTip-DLlhaGQp.js +1 -0
  188. package/web/console/assets/HelpTip-bbDEyuqV.css +1 -0
  189. package/web/console/assets/Kb-5R3ce4UU.js +5 -0
  190. package/web/console/assets/Kb-BM_PYi11.css +1 -0
  191. package/web/console/assets/{Login-CGgLGTE1.js → Login-YKeUwdgo.js} +1 -1
  192. package/web/console/assets/Projects-DHwHrPT9.css +1 -0
  193. package/web/console/assets/Projects-Grgb6fOv.js +1 -0
  194. package/web/console/assets/Routes-DR_Yf02e.css +1 -0
  195. package/web/console/assets/Routes-DYgrXlRJ.js +138 -0
  196. package/web/console/assets/Runs-CwTddJJj.js +3 -0
  197. package/web/console/assets/Runs-D4FOvNfu.css +1 -0
  198. package/web/console/assets/Setup-Ca0b1d1-.css +1 -0
  199. package/web/console/assets/Setup-D_xUPNDq.js +1 -0
  200. package/web/console/assets/Shell-BTg8Vw_L.css +1 -0
  201. package/web/console/assets/Shell-Dfam2Uoj.js +1 -0
  202. package/web/console/assets/StorageBuckets-7QLBpV4a.css +1 -0
  203. package/web/console/assets/StorageBuckets-CP6e50wI.js +1 -0
  204. package/web/console/assets/SystemSettings-BRYKyJNa.js +1 -0
  205. package/web/console/assets/SystemSettings-HsXGx0aH.css +1 -0
  206. package/web/console/assets/SystemStatus-B-VfRsQd.css +1 -0
  207. package/web/console/assets/SystemStatus-CbPsDsGt.js +1 -0
  208. package/web/console/assets/Targets-1j4-g6rC.css +1 -0
  209. package/web/console/assets/Targets-C2LkR2AF.js +1 -0
  210. package/web/console/assets/Tools-C9HPJqJb.css +1 -0
  211. package/web/console/assets/Tools-C9JNJUS0.js +2 -0
  212. package/web/console/assets/Usage-D1Mv6vGY.js +1 -0
  213. package/web/console/assets/Usage-DMOzUsqh.css +1 -0
  214. package/web/console/assets/UsageAccess-77LmGCm6.js +1 -0
  215. package/web/console/assets/UsageAccess-C6ZGxEgJ.css +1 -0
  216. package/web/console/assets/{UsageHelp-CzS2gI40.js → UsageHelp-BmuiE1Ew.js} +1 -1
  217. package/web/console/assets/client-route-draft-DxZRxKPT.js +1 -0
  218. package/web/console/assets/console-location-Csv-xsnl.js +1 -0
  219. package/web/console/assets/form-guard-8GrFpry0.js +1 -0
  220. package/web/console/assets/{index-65JiiUr4.js → index-B_5UfiTw.js} +1 -1
  221. package/web/console/assets/index-MjZJEFIN.js +2 -0
  222. package/web/console/assets/{request-DKycpD7z.js → request-rqm6MT0s.js} +1 -1
  223. package/web/console/assets/runtime-feedback-gPfZVNvY.js +1 -0
  224. package/web/console/assets/{schema-SCiNxBlR.js → schema-o3mK4mid.js} +1 -1
  225. package/web/console/assets/task-page-location-DWiGtAln.js +1 -0
  226. package/web/console/assets/use-list-location-FvLFt0Tq.css +1 -0
  227. package/web/console/assets/use-list-location-cIPy2cKM.js +1 -0
  228. package/web/console/assets/use-unsaved-form-DScKD0h9.js +1 -0
  229. package/web/console/assets/{util-DZYfJ5Zo.js → util-B40VqOwl.js} +1 -1
  230. package/web/console/assets/{vendor-element-8cVcdt5T.js → vendor-element-BT8tHCFk.js} +1 -1
  231. package/web/console/assets/{vendor-mammoth-CnDA23N0.js → vendor-mammoth-CVIXVxTN.js} +1 -1
  232. package/web/console/assets/{vendor-vue-Co7x2FW6.js → vendor-vue-DhbG0vd4.js} +7 -7
  233. package/web/console/index.html +3 -3
  234. package/web-admin/package-lock.json +4 -4
  235. package/web-admin/package.json +1 -1
  236. package/web-admin/src/client-route-draft.ts +25 -0
  237. package/web-admin/src/components/AgentSetupPanel.vue +54 -41
  238. package/web-admin/src/components/HelpTip.vue +4 -1
  239. package/web-admin/src/components/ListLocationBar.vue +22 -0
  240. package/web-admin/src/components/NotificationOutboxPanel.vue +35 -7
  241. package/web-admin/src/console-entry.test.ts +26 -0
  242. package/web-admin/src/console-entry.ts +20 -0
  243. package/web-admin/src/console-location.ts +35 -0
  244. package/web-admin/src/form-guard.ts +35 -0
  245. package/web-admin/src/layout/Shell.vue +18 -65
  246. package/web-admin/src/onboarding-state.test.ts +174 -0
  247. package/web-admin/src/onboarding-state.ts +122 -0
  248. package/web-admin/src/pages/Accounts.vue +44 -24
  249. package/web-admin/src/pages/AgentClients.vue +47 -29
  250. package/web-admin/src/pages/AgentTasks.vue +57 -12
  251. package/web-admin/src/pages/Approvals.vue +105 -25
  252. package/web-admin/src/pages/Audit.vue +15 -6
  253. package/web-admin/src/pages/Channels.vue +136 -43
  254. package/web-admin/src/pages/ChatEntries.vue +96 -41
  255. package/web-admin/src/pages/Clients.vue +87 -26
  256. package/web-admin/src/pages/Cost.vue +15 -4
  257. package/web-admin/src/pages/Credentials.vue +63 -32
  258. package/web-admin/src/pages/Diagnostics.vue +103 -54
  259. package/web-admin/src/pages/Executors.vue +103 -40
  260. package/web-admin/src/pages/Kb.vue +278 -128
  261. package/web-admin/src/pages/Projects.vue +44 -16
  262. package/web-admin/src/pages/Routes.vue +168 -247
  263. package/web-admin/src/pages/Runs.vue +163 -91
  264. package/web-admin/src/pages/Setup.vue +182 -291
  265. package/web-admin/src/pages/StorageBuckets.vue +61 -25
  266. package/web-admin/src/pages/SystemSettings.vue +76 -51
  267. package/web-admin/src/pages/SystemStatus.vue +54 -30
  268. package/web-admin/src/pages/Targets.vue +45 -17
  269. package/web-admin/src/pages/Tools.vue +133 -68
  270. package/web-admin/src/pages/Usage.vue +64 -25
  271. package/web-admin/src/pages/UsageAccess.vue +11 -8
  272. package/web-admin/src/route-call-snippets.test.ts +82 -0
  273. package/web-admin/src/route-call-snippets.ts +178 -0
  274. package/web-admin/src/router.ts +11 -29
  275. package/web-admin/src/runtime-feedback.ts +43 -0
  276. package/web-admin/src/task-page-location.ts +66 -0
  277. package/web-admin/src/usage-output-budget.test.ts +26 -0
  278. package/web-admin/src/usage-output-budget.ts +46 -0
  279. package/web-admin/src/use-list-location.ts +24 -0
  280. package/web-admin/src/use-unsaved-form.ts +38 -0
  281. package/web-admin/tests/model-output-budget.browser.mjs +69 -0
  282. package/web/console/assets/Accounts-Bervi5JU.css +0 -1
  283. package/web/console/assets/Accounts-Dhj6PjXP.js +0 -3
  284. package/web/console/assets/AgentClients-CMy8StAH.js +0 -1
  285. package/web/console/assets/AgentClients-i52AI6YV.css +0 -1
  286. package/web/console/assets/AgentTasks-BsG850Il.css +0 -1
  287. package/web/console/assets/AgentTasks-DA1xZdmP.js +0 -2
  288. package/web/console/assets/Approvals-DIsd7R8N.js +0 -1
  289. package/web/console/assets/Approvals-DlTSHl_7.css +0 -1
  290. package/web/console/assets/Audit-AUDABLTX.js +0 -1
  291. package/web/console/assets/Audit-CSu6_3oD.css +0 -1
  292. package/web/console/assets/Channels-B8rjsM0S.js +0 -105
  293. package/web/console/assets/Channels-CCn0L1jg.css +0 -1
  294. package/web/console/assets/ChatEntries-DsYtcXN6.css +0 -1
  295. package/web/console/assets/ChatEntries-iZjJMEUZ.js +0 -7
  296. package/web/console/assets/Clients-CSHIsaWU.css +0 -1
  297. package/web/console/assets/Clients-CwgpGCSD.js +0 -3
  298. package/web/console/assets/Cost-B2tNxu71.js +0 -1
  299. package/web/console/assets/Cost-CjT39DSZ.css +0 -1
  300. package/web/console/assets/Credentials-BuwFB-fV.js +0 -1
  301. package/web/console/assets/Credentials-ioLP0qYN.css +0 -1
  302. package/web/console/assets/Diagnostics-Ya05PTDp.css +0 -1
  303. package/web/console/assets/Diagnostics-z5glms11.js +0 -1
  304. package/web/console/assets/Executors-Bc4SvjeH.js +0 -1
  305. package/web/console/assets/Executors-CjhEM54c.css +0 -1
  306. package/web/console/assets/HelpTip-CA6Bm7Nx.css +0 -1
  307. package/web/console/assets/HelpTip-Dtdt2tKR.js +0 -1
  308. package/web/console/assets/Kb-BRbRHxLy.js +0 -5
  309. package/web/console/assets/Kb-CzIzd9xr.css +0 -1
  310. package/web/console/assets/Projects-Bm8AjsNx.css +0 -1
  311. package/web/console/assets/Projects-CPWw3con.js +0 -1
  312. package/web/console/assets/Routes-CMIaE0Bx.js +0 -124
  313. package/web/console/assets/Routes-CyXV4Pba.css +0 -1
  314. package/web/console/assets/Runs-B8HuE700.js +0 -3
  315. package/web/console/assets/Runs-Bv6CV_Hk.css +0 -1
  316. package/web/console/assets/Setup-D7nxgn-9.css +0 -1
  317. package/web/console/assets/Setup-G8RKzliR.js +0 -1
  318. package/web/console/assets/Shell-DimHgraJ.js +0 -1
  319. package/web/console/assets/Shell-ykb-tUfo.css +0 -1
  320. package/web/console/assets/StorageBuckets-CVgpZRWY.css +0 -1
  321. package/web/console/assets/StorageBuckets-CiVYXIE2.js +0 -1
  322. package/web/console/assets/SystemSettings-BjiHyrXO.css +0 -1
  323. package/web/console/assets/SystemSettings-DF8sZNen.js +0 -1
  324. package/web/console/assets/SystemStatus-BlHywK13.js +0 -1
  325. package/web/console/assets/SystemStatus-I11I67rw.css +0 -1
  326. package/web/console/assets/Targets-BXaoPoAJ.js +0 -1
  327. package/web/console/assets/Targets-DTb5tn6z.css +0 -1
  328. package/web/console/assets/Tools-B22lNHXq.js +0 -2
  329. package/web/console/assets/Tools-DU8ei6sd.css +0 -1
  330. package/web/console/assets/Usage-C02EzoI2.js +0 -1
  331. package/web/console/assets/Usage-CAeDGjrb.css +0 -1
  332. package/web/console/assets/UsageAccess-CGGaWTuj.css +0 -1
  333. package/web/console/assets/UsageAccess-DOb-cyPE.js +0 -1
  334. package/web/console/assets/index-CK0ZCTZv.js +0 -2
@@ -0,0 +1,205 @@
1
+ import test, { type TestContext } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createHash } from 'node:crypto';
4
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, symlinkSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { spawnSync } from 'node:child_process';
9
+ import { BAILINGHUB_CORE_ARTIFACT_V1, type BailingHubCoreArtifactManifestV1 as Manifest } from '../src/kernel-api/v1/artifact';
10
+ import { runUpgradePlan, compareVersions, type UpgradeSnapshot, type UpgradePlanOptions } from './doctor-upgrade-plan';
11
+ const ID = '1'.repeat(64); const OTHER = '2'.repeat(64); const SECRET = 'private-credential-never-print';
12
+ const sha = (value: string) => createHash('sha256').update(value).digest('hex');
13
+ function manifest(version: string, files: string[], retired = false): Manifest {
14
+ const migrations = files.map((filename) => ({ filename, checksumSha256: sha(`-- ${filename}\n`) }));
15
+ const retiredMigrations = retired ? [{ filename: '020_retired.sql', checksumSha256: sha('old bytes'), byteLength: 9, replay: 'never' as const }] : [];
16
+ const manifestSha256 = createHash('sha256').update('bailinghub-core-artifact-v1').update('\0').update(version).update('\0active\0')
17
+ .update(migrations.map((m) => `${m.filename}\0${m.checksumSha256}`).join('\n')).update('\0retired\0')
18
+ .update(retiredMigrations.map((m) => `${m.filename}\0${m.checksumSha256}\0${m.byteLength}\0${m.replay}`).join('\n')).digest('hex');
19
+ return { packageName: 'bailinghub', version, migrations, retiredMigrations, latestMigration: files.at(-1)!, manifestSha256 };
20
+ }
21
+ function fixture(t: TestContext, version = '0.9.4', retired = false) {
22
+ const root = mkdtempSync(join(tmpdir(), 'upgrade-plan-')); t.after(() => rmSync(root, { recursive: true, force: true }));
23
+ function artifact(name: string, m: Manifest) {
24
+ const dir = join(root, name); mkdirSync(join(dir, 'sql'), { recursive: true });
25
+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'bailinghub', version: m.version, scripts: { prestart: `echo ${SECRET}` } }));
26
+ writeFileSync(join(dir, 'config.json'), SECRET); writeFileSync(join(dir, '.env'), SECRET);
27
+ for (const file of m.migrations) writeFileSync(join(dir, 'sql', file.filename), `-- ${file.filename}\n`);
28
+ const path = join(root, `${name}.json`); writeFileSync(path, JSON.stringify(m));
29
+ return { dir, path };
30
+ }
31
+ const from = manifest('0.9.3', ['001_initial.sql', '067_delivery.sql'], retired);
32
+ const to = manifest(version, ['001_initial.sql', '067_delivery.sql', '068_notifications.sql'], retired);
33
+ const a = artifact('from', from); const b = artifact('to', to);
34
+ const snapshot: UpgradeSnapshot = { schema: 'bailing.upgrade-snapshot.v1', captured_at: '2026-01-01T00:00:00Z', source_manifest_sha256: from.manifestSha256,
35
+ state: { backend: 'mysql', database_id: ID }, configuration: { backend: 'mysql', database_id: ID },
36
+ databases: [{ id: ID, ledger_complete: true, checksum_column: 'present', rows: from.migrations.map((m) => ({ filename: m.filename, checksum_sha256: m.checksumSha256 })) }] };
37
+ const snapshotPath = join(root, 'snapshot.json');
38
+ const options: UpgradePlanOptions = { fromArtifact: a.dir, fromManifest: a.path, toArtifact: b.dir, toManifest: b.path, snapshot: snapshotPath };
39
+ function run() { writeFileSync(snapshotPath, JSON.stringify(snapshot)); return runUpgradePlan(options); }
40
+ return { root, from, to, snapshot, options, run };
41
+ }
42
+ test('official exported manifest digest and SQL inventory are compatible with the planner', (t) => {
43
+ const root = mkdtempSync(join(tmpdir(), 'upgrade-official-')); t.after(() => rmSync(root, { recursive: true, force: true }));
44
+ const path = join(root, 'official.json'); writeFileSync(path, JSON.stringify(BAILINGHUB_CORE_ARTIFACT_V1));
45
+ const artifact = fileURLToPath(new URL('../', import.meta.url));
46
+ const report = runUpgradePlan({ fromArtifact: artifact, fromManifest: path, toArtifact: artifact, toManifest: path });
47
+ assert.equal(report.from?.manifestSha256, BAILINGHUB_CORE_ARTIFACT_V1.manifestSha256);
48
+ assert.equal(report.to?.manifestSha256, BAILINGHUB_CORE_ARTIFACT_V1.manifestSha256);
49
+ assert.equal(report.result, 'incomplete'); assert.equal(report.exit_code, 2);
50
+ });
51
+ test('shared MySQL generates one pending plan and honest rollback/scope without reading config', (t) => {
52
+ const f = fixture(t); const report = f.run();
53
+ assert.equal(report.result, 'reviewable'); assert.equal(report.direction, 'upgrade');
54
+ assert.equal(report.databases.length, 1); assert.deepEqual(report.databases[0]?.roles, ['state', 'configuration']);
55
+ assert.deepEqual(report.databases[0]?.pending, ['068_notifications.sql']);
56
+ assert.equal(report.databases[0]?.rollback_after_migration, 'blocked_by_old_manifest');
57
+ assert.equal(report.scope.actual_runtime, 'not_verified'); assert.equal(report.scope.database_connections, false);
58
+ assert.ok(!JSON.stringify(report).includes(SECRET));
59
+ });
60
+ test('separate configuration database is checked independently and can block the plan', (t) => {
61
+ const f = fixture(t); f.snapshot.configuration.database_id = OTHER;
62
+ f.snapshot.databases.push({ ...f.snapshot.databases[0]!, id: OTHER, rows: [{ filename: '001_initial.sql', checksum_sha256: '0'.repeat(64) }] });
63
+ const report = f.run(); assert.equal(report.snapshot?.topology, 'separate_mysql'); assert.equal(report.databases.length, 2);
64
+ assert.equal(report.result, 'blocked'); assert.deepEqual(report.databases[1]?.hash_conflicts, ['001_initial.sql']);
65
+ });
66
+ test('missing configuration snapshot is incomplete, never silently treated as shared', (t) => {
67
+ const f = fixture(t); f.snapshot.configuration.database_id = OTHER;
68
+ assert.equal(f.run().result, 'incomplete');
69
+ });
70
+ test('JSONL state still plans configuration MySQL; files-only explicitly has no SQL', (t) => {
71
+ const f = fixture(t); f.snapshot.state = { backend: 'jsonl', database_id: null };
72
+ let report = f.run(); assert.equal(report.result, 'reviewable'); assert.deepEqual(report.databases[0]?.roles, ['configuration']);
73
+ f.snapshot.configuration = { backend: 'file', database_id: null }; f.snapshot.databases = [];
74
+ report = f.run(); assert.equal(report.snapshot?.topology, 'files_only'); assert.deepEqual(report.databases, []);
75
+ });
76
+ test('unknown and newer ledger records block rather than being removed or ignored', (t) => {
77
+ const f = fixture(t); f.snapshot.databases[0]!.rows.push({ filename: '999_future.sql', checksum_sha256: null });
78
+ const report = f.run(); assert.equal(report.result, 'blocked'); assert.deepEqual(report.databases[0]?.unknown_migrations, ['999_future.sql']);
79
+ });
80
+ test('legacy null checksums are incomplete and never backfilled', (t) => {
81
+ const f = fixture(t); f.snapshot.databases[0]!.rows[0]!.checksum_sha256 = null;
82
+ assert.equal(f.run().result, 'incomplete');
83
+ assert.equal(JSON.parse(readFileSync(f.options.snapshot!, 'utf8')).databases[0].rows[0].checksum_sha256, null);
84
+ });
85
+ test('missing checksum column and partial ledgers are incomplete and cannot produce definitive pending lists', (t) => {
86
+ const f = fixture(t); f.snapshot.databases[0]!.checksum_column = 'absent'; f.snapshot.databases[0]!.rows = [];
87
+ f.snapshot.databases[0]!.ledger_complete = false;
88
+ const report = f.run(); assert.equal(report.result, 'incomplete'); assert.equal(report.databases[0]?.pending, null);
89
+ });
90
+ test('known retired evidence is accepted but never scheduled for replay', (t) => {
91
+ const f = fixture(t, '0.9.4', true); const retired = f.from.retiredMigrations[0]!;
92
+ f.snapshot.databases[0]!.rows.push({ filename: retired.filename, checksum_sha256: retired.checksumSha256 });
93
+ const report = f.run(); assert.equal(report.result, 'reviewable'); assert.ok(!report.databases[0]?.pending?.includes(retired.filename));
94
+ });
95
+ function rewriteManifest(path: string, value: Manifest): void {
96
+ const manifestSha256 = createHash('sha256').update('bailinghub-core-artifact-v1').update('\0').update(value.version)
97
+ .update('\0active\0').update(value.migrations.map((m) => `${m.filename}\0${m.checksumSha256}`).join('\n'))
98
+ .update('\0retired\0').update(value.retiredMigrations.map((m) => `${m.filename}\0${m.checksumSha256}\0${m.byteLength}\0${m.replay}`).join('\n')).digest('hex');
99
+ writeFileSync(path, JSON.stringify({ ...value, manifestSha256 }));
100
+ }
101
+ test('reactivated retired migration is blocked even with matching bytes and recomputed manifest', (t) => {
102
+ const f = fixture(t, '0.9.4', true); const retired = f.from.retiredMigrations[0]!;
103
+ const migrations = [...f.to.migrations, { filename: retired.filename, checksumSha256: retired.checksumSha256 }].sort((a, b) => a.filename.localeCompare(b.filename));
104
+ rewriteManifest(f.options.toManifest!, { ...f.to, migrations, retiredMigrations: [] });
105
+ writeFileSync(join(f.options.toArtifact!, 'sql', retired.filename), 'old bytes');
106
+ const report = f.run(); assert.ok(report.to, 'target is internally self-consistent');
107
+ assert.equal(report.result, 'blocked'); assert.equal(report.exit_code, 1);
108
+ assert.ok(report.checks.some((c) => c.reason === 'target_reactivates_retired_migration'));
109
+ assert.ok(!report.databases[0]?.pending?.includes(retired.filename), 'never recommend replaying retired evidence, even in a blocked report');
110
+ });
111
+ test('published active migration cannot be silently reclassified as retired', (t) => {
112
+ const f = fixture(t); const active = f.to.migrations.find((m) => m.filename === '067_delivery.sql')!;
113
+ const migrations = f.to.migrations.filter((m) => m.filename !== active.filename);
114
+ rewriteManifest(f.options.toManifest!, { ...f.to, migrations, retiredMigrations: [{ ...active, byteLength: Buffer.byteLength(`-- ${active.filename}\n`), replay: 'never' }] });
115
+ rmSync(join(f.options.toArtifact!, 'sql', active.filename));
116
+ const report = f.run(); assert.ok(report.to, 'target is internally self-consistent'); assert.equal(report.result, 'blocked');
117
+ assert.ok(report.checks.some((c) => c.reason === 'target_reclassifies_published_active_migration'));
118
+ });
119
+ test('retired byte length changes cannot hide behind unchanged SQL checksum', (t) => {
120
+ const f = fixture(t, '0.9.4', true);
121
+ rewriteManifest(f.options.toManifest!, { ...f.to, retiredMigrations: f.to.retiredMigrations.map((m) => ({ ...m, byteLength: m.byteLength + 1 })) });
122
+ const report = f.run(); assert.ok(report.to, 'target is internally self-consistent'); assert.equal(report.result, 'blocked');
123
+ assert.ok(report.checks.some((c) => c.reason === 'target_changes_retired_migration_evidence'));
124
+ });
125
+ test('retired evidence must retain replay never', (t) => {
126
+ const f = fixture(t, '0.9.4', true);
127
+ const malformed = { ...f.to, retiredMigrations: f.to.retiredMigrations.map((m) => ({ ...m, replay: 'allowed' })) } as unknown as Manifest;
128
+ rewriteManifest(f.options.toManifest!, malformed);
129
+ const report = f.run(); assert.equal(report.result, 'blocked'); assert.equal(report.to, null);
130
+ });
131
+ test('source version snapshot mismatch is blocked', (t) => {
132
+ const f = fixture(t); f.snapshot.source_manifest_sha256 = f.to.manifestSha256;
133
+ assert.equal(f.run().result, 'blocked');
134
+ });
135
+ test('same version different manifest and downgrade are blocked', (t) => {
136
+ for (const version of ['0.9.3', '0.9.2', '0.9.3-rc.1']) { const f = fixture(t, version); assert.equal(f.run().result, 'blocked'); }
137
+ });
138
+ test('SemVer comparison uses numeric components and prereleases, never prefix matches', () => {
139
+ assert.equal(compareVersions('0.9.10', '0.9.4'), 1); assert.equal(compareVersions('1.0.0-rc.10', '1.0.0-rc.2'), 1);
140
+ assert.equal(compareVersions('1.0.0-rc.1', '1.0.0'), -1); assert.equal(compareVersions('1.0.0+one', '1.0.0+two'), 0);
141
+ });
142
+ test('SQL tampering, forged digest, missing inventory, malformed version and duplicate numbers are rejected', (t) => {
143
+ for (const mutate of [
144
+ (f: ReturnType<typeof fixture>) => writeFileSync(join(f.options.toArtifact!, 'sql/068_notifications.sql'), 'tampered'),
145
+ (f: ReturnType<typeof fixture>) => writeFileSync(f.options.toManifest!, JSON.stringify({ ...f.to, manifestSha256: '0'.repeat(64) })),
146
+ (f: ReturnType<typeof fixture>) => writeFileSync(join(f.options.toArtifact!, 'sql/069_omitted.sql'), '-- unseen'),
147
+ (f: ReturnType<typeof fixture>) => writeFileSync(join(f.options.toArtifact!, 'sql/068_duplicate.sql'), '-- duplicate'),
148
+ (f: ReturnType<typeof fixture>) => writeFileSync(f.options.toManifest!, JSON.stringify({ ...f.to, version: 'v0.9.4' })),
149
+ (f: ReturnType<typeof fixture>) => writeFileSync(f.options.toManifest!, JSON.stringify({ ...f.to, version: '0.9.4-01' })),
150
+ ]) { const f = fixture(t); mutate(f); assert.equal(f.run().result, 'blocked'); }
151
+ });
152
+ test('manifest traversal paths and symlink SQL files/directories are rejected without exposing content', (t) => {
153
+ for (const kind of ['traversal', 'file', 'directory']) {
154
+ const f = fixture(t);
155
+ if (kind === 'traversal') writeFileSync(f.options.toManifest!, JSON.stringify({ ...f.to, migrations: [{ filename: '../config.json', checksumSha256: sha(SECRET) }] }));
156
+ else if (kind === 'file') { const path = join(f.options.toArtifact!, 'sql/068_notifications.sql'); rmSync(path); symlinkSync(join(f.options.toArtifact!, 'config.json'), path); }
157
+ else { rmSync(join(f.options.toArtifact!, 'sql'), { recursive: true }); symlinkSync(join(f.options.fromArtifact!, 'sql'), join(f.options.toArtifact!, 'sql')); }
158
+ const report = f.run(); assert.equal(report.result, 'blocked'); assert.ok(!JSON.stringify(report).includes(SECRET));
159
+ }
160
+ });
161
+ test('invalid snapshot fields, duplicate identities and future snapshot are rejected', (t) => {
162
+ for (const mutate of [
163
+ (f: ReturnType<typeof fixture>) => { f.snapshot.state.database_id = SECRET; },
164
+ (f: ReturnType<typeof fixture>) => { f.snapshot.databases.push(f.snapshot.databases[0]!); },
165
+ (f: ReturnType<typeof fixture>) => { f.snapshot.databases[0]!.rows.push(f.snapshot.databases[0]!.rows[0]!); },
166
+ (f: ReturnType<typeof fixture>) => { f.snapshot.captured_at = '2999-01-01T00:00:00Z'; },
167
+ ]) { const f = fixture(t); mutate(f); const report = f.run(); assert.equal(report.result, 'blocked'); assert.ok(!JSON.stringify(report).includes(SECRET)); }
168
+ });
169
+ test('recomputed manifest cannot conceal changed published SQL history', (t) => {
170
+ const f = fixture(t);
171
+ const changed = JSON.parse(JSON.stringify(f.to)) as Manifest;
172
+ const migrations = changed.migrations.map((m) => m.filename === '001_initial.sql' ? { ...m, checksumSha256: sha('changed history') } : m);
173
+ const manifestSha256 = createHash('sha256').update('bailinghub-core-artifact-v1').update('\0').update(changed.version)
174
+ .update('\0active\0').update(migrations.map((m) => `${m.filename}\0${m.checksumSha256}`).join('\n')).update('\0retired\0').digest('hex');
175
+ writeFileSync(f.options.toManifest!, JSON.stringify({ ...changed, migrations, manifestSha256 }));
176
+ writeFileSync(join(f.options.toArtifact!, 'sql/001_initial.sql'), 'changed history');
177
+ const report = f.run(); assert.ok(report.to, 'altered target is internally self-consistent');
178
+ assert.equal(report.result, 'blocked');
179
+ assert.ok(report.checks.some((c) => c.reason === 'target_changes_published_migration_checksum'));
180
+ });
181
+ test('missing source ledger entries are incomplete even when pending SQL is identifiable', (t) => {
182
+ const f = fixture(t); f.snapshot.databases[0]!.rows.pop();
183
+ const report = f.run(); assert.equal(report.result, 'incomplete');
184
+ assert.deepEqual(report.databases[0]?.source_missing, ['067_delivery.sql']);
185
+ assert.deepEqual(report.databases[0]?.pending, ['067_delivery.sql', '068_notifications.sql']);
186
+ });
187
+ test('a self-consistent synthetic artifact never becomes trusted release or deployment evidence', (t) => {
188
+ const f = fixture(t); const report = f.run(); assert.equal(report.result, 'reviewable');
189
+ assert.equal(report.scope.release_authenticity, 'not_verified');
190
+ assert.equal(report.scope.database_identity, 'snapshot_claim_only');
191
+ assert.equal(report.scope.schema_objects, 'not_checked');
192
+ assert.equal(report.scope.backup_restore, 'not_tested'); assert.equal(report.scope.execution_authorized, false);
193
+ });
194
+ test('CLI dispatch is read-only, emits clean JSON, and unsupported flags are redacted', (t) => {
195
+ const f = fixture(t); f.run();
196
+ const cli = fileURLToPath(new URL('./doctor.ts', import.meta.url));
197
+ const loader = fileURLToPath(new URL('../node_modules/tsx/dist/loader.mjs', import.meta.url));
198
+ const args = ['--import', loader, cli, '--upgrade-plan', '--json'];
199
+ const output = spawnSync(process.execPath, [...args, '--from-artifact', f.options.fromArtifact!, '--from-manifest', f.options.fromManifest!, '--to-artifact', f.options.toArtifact!, '--to-manifest', f.options.toManifest!, '--snapshot', f.options.snapshot!], { cwd: f.root, encoding: 'utf8' });
200
+ assert.equal(output.status, 0, output.stderr); assert.equal(JSON.parse(output.stdout).result, 'reviewable'); assert.equal(output.stderr, '');
201
+ const bad = spawnSync(process.execPath, [...args, '--deployment', '--password', SECRET], { cwd: f.root, encoding: 'utf8' });
202
+ assert.equal(bad.status, 64); assert.ok(!`${bad.stdout}${bad.stderr}`.includes(SECRET));
203
+ const missing = spawnSync(process.execPath, args, { cwd: f.root, encoding: 'utf8' }); assert.equal(missing.status, 2);
204
+ assert.equal(JSON.parse(missing.stdout).result, 'incomplete');
205
+ });
@@ -0,0 +1,276 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs';
3
+ import { isAbsolute, join, relative, resolve } from 'node:path';
4
+ import { assertOfficialMigrationFilenames } from '../src/infrastructure/schema/migration-files';
5
+ import type { BailingHubCoreArtifactManifestV1 } from '../src/kernel-api/v1/artifact';
6
+
7
+ type Manifest = BailingHubCoreArtifactManifestV1;
8
+ type Check = { id: string; state: 'pass' | 'fail' | 'unknown'; reason: string };
9
+ type Row = { filename: string; checksum_sha256: string | null };
10
+ type Database = { id: string; ledger_complete: boolean; checksum_column: 'present' | 'absent'; rows: Row[] };
11
+ export interface UpgradeSnapshot {
12
+ schema: 'bailing.upgrade-snapshot.v1';
13
+ captured_at: string;
14
+ source_manifest_sha256: string;
15
+ state: { backend: 'mysql' | 'jsonl'; database_id: string | null };
16
+ configuration: { backend: 'mysql' | 'file'; database_id: string | null };
17
+ databases: Database[];
18
+ }
19
+ export interface UpgradePlanOptions {
20
+ fromArtifact?: string;
21
+ fromManifest?: string;
22
+ toArtifact?: string;
23
+ toManifest?: string;
24
+ snapshot?: string;
25
+ }
26
+ export interface UpgradePlanReport {
27
+ schema: 'bailing.upgrade-plan.v1';
28
+ mode: 'offline';
29
+ result: 'reviewable' | 'blocked' | 'incomplete';
30
+ exit_code: 0 | 1 | 2;
31
+ basis: 'supplied_local_artifacts_and_snapshot';
32
+ from: Manifest | null;
33
+ to: Manifest | null;
34
+ direction: 'upgrade' | 'same_version' | 'downgrade' | 'unknown';
35
+ snapshot: { captured_at: string; sha256: string; topology: 'shared_mysql' | 'separate_mysql' | 'mixed' | 'files_only' } | null;
36
+ databases: { id: string; roles: string[]; pending: string[] | null; missing_checksums: string[]; hash_conflicts: string[]; unknown_migrations: string[]; source_missing: string[] | null; rollback_after_migration: 'blocked_by_old_manifest' | 'requires_validation' | 'unknown' }[];
37
+ checks: Check[];
38
+ actions: { id: string; detail: string }[];
39
+ scope: { network: false; subprocesses: false; config_credentials_read: false; database_connections: false; mutations: false; release_authenticity: 'not_verified'; actual_runtime: 'not_verified'; database_identity: 'snapshot_claim_only'; schema_objects: 'not_checked'; backup_restore: 'not_tested'; execution_authorized: false };
40
+ }
41
+ const HEX = /^[a-f0-9]{64}$/;
42
+ const FILENAME = /^\d{3}_[a-z0-9][a-z0-9_-]*\.sql$/;
43
+ const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
44
+ const MAX_JSON = 4 * 1024 * 1024;
45
+ function object(value: unknown): Record<string, unknown> {
46
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('invalid_object');
47
+ return value as Record<string, unknown>;
48
+ }
49
+ function digest(bytes: string | Buffer): string { return createHash('sha256').update(bytes).digest('hex'); }
50
+ function read(file: string, maximum = MAX_JSON): Buffer {
51
+ const stat = lstatSync(file);
52
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > maximum) throw new Error('invalid_input_file');
53
+ return readFileSync(file);
54
+ }
55
+ // Paths inside an artifact are fixed, and symlinked files/directories are rejected.
56
+ // Never import or execute code from an operator-supplied artifact.
57
+ function artifactFile(root: string, file: string, maximum = MAX_JSON): Buffer {
58
+ const canonical = realpathSync(root);
59
+ let current = canonical;
60
+ for (const part of file.split('/')) {
61
+ current = join(current, part);
62
+ if (lstatSync(current).isSymbolicLink()) throw new Error('artifact_symlink');
63
+ }
64
+ const delta = relative(canonical, realpathSync(current));
65
+ if (delta.startsWith('..') || isAbsolute(delta)) throw new Error('artifact_path_escape');
66
+ return read(current, maximum);
67
+ }
68
+ function validVersion(value: unknown): value is string {
69
+ if (typeof value !== 'string' || value.length > 80) return false;
70
+ const match = SEMVER.exec(value);
71
+ return !!match && !(match[4]?.split('.').some((part) => /^\d+$/.test(part) && part.length > 1 && part[0] === '0'));
72
+ }
73
+ export function compareVersions(left: string, right: string): number {
74
+ const a = SEMVER.exec(left)!;
75
+ const b = SEMVER.exec(right)!;
76
+ for (let i = 1; i <= 3; i++) {
77
+ if (BigInt(a[i]!) !== BigInt(b[i]!)) return BigInt(a[i]!) > BigInt(b[i]!) ? 1 : -1;
78
+ }
79
+ if (!a[4] || !b[4]) return a[4] === b[4] ? 0 : a[4] ? -1 : 1;
80
+ const ap = a[4].split('.'); const bp = b[4].split('.');
81
+ for (let i = 0; i < Math.max(ap.length, bp.length); i++) {
82
+ const x = ap[i]; const y = bp[i];
83
+ if (x === y) continue;
84
+ if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
85
+ const xn = /^\d+$/.test(x); const yn = /^\d+$/.test(y);
86
+ if (xn && yn) return BigInt(x) > BigInt(y) ? 1 : -1;
87
+ if (xn !== yn) return xn ? -1 : 1;
88
+ return x > y ? 1 : -1;
89
+ }
90
+ return 0;
91
+ }
92
+ // This is the v1 manifest digest format from kernel-api/v1/artifact.ts. The
93
+ // official exported manifest is the input; no locally assumed retired list.
94
+ function manifestDigest(manifest: Manifest): string {
95
+ return createHash('sha256').update('bailinghub-core-artifact-v1').update('\0').update(manifest.version)
96
+ .update('\0active\0').update(manifest.migrations.map((m) => `${m.filename}\0${m.checksumSha256}`).join('\n'))
97
+ .update('\0retired\0').update(manifest.retiredMigrations.map((m) => `${m.filename}\0${m.checksumSha256}\0${m.byteLength}\0${m.replay}`).join('\n')).digest('hex');
98
+ }
99
+ function readManifest(root: string, manifestPath: string): Manifest {
100
+ const input = object(JSON.parse(read(manifestPath).toString('utf8')));
101
+ if (input.packageName !== 'bailinghub' || !validVersion(input.version) || typeof input.manifestSha256 !== 'string' || !HEX.test(input.manifestSha256)) throw new Error('invalid_manifest');
102
+ if (!Array.isArray(input.migrations) || !input.migrations.length || input.migrations.length > 1000 || !Array.isArray(input.retiredMigrations) || input.retiredMigrations.length > 1000) throw new Error('invalid_manifest');
103
+ const migrations = input.migrations.map((value) => {
104
+ const m = object(value);
105
+ if (typeof m.filename !== 'string' || !FILENAME.test(m.filename) || typeof m.checksumSha256 !== 'string' || !HEX.test(m.checksumSha256)) throw new Error('invalid_migration');
106
+ return { filename: m.filename, checksumSha256: m.checksumSha256 };
107
+ });
108
+ assertOfficialMigrationFilenames(migrations.map((m) => m.filename));
109
+ const retiredMigrations = input.retiredMigrations.map((value) => {
110
+ const m = object(value);
111
+ if (typeof m.filename !== 'string' || !FILENAME.test(m.filename) || typeof m.checksumSha256 !== 'string' || !HEX.test(m.checksumSha256) || typeof m.byteLength !== 'number' || !Number.isSafeInteger(m.byteLength) || m.byteLength < 0 || m.replay !== 'never') throw new Error('invalid_retired_migration');
112
+ return { filename: m.filename, checksumSha256: m.checksumSha256, byteLength: m.byteLength, replay: 'never' as const };
113
+ });
114
+ const names = migrations.map((m) => m.filename);
115
+ if (names.join('\n') !== [...names].sort().join('\n') || new Set([...names, ...retiredMigrations.map((m) => m.filename)]).size !== migrations.length + retiredMigrations.length || input.latestMigration !== names.at(-1)) throw new Error('invalid_manifest_order');
116
+ const manifest: Manifest = { packageName: 'bailinghub', version: input.version, migrations, retiredMigrations, latestMigration: names.at(-1)!, manifestSha256: input.manifestSha256 };
117
+ if (manifestDigest(manifest) !== manifest.manifestSha256) throw new Error('manifest_digest_mismatch');
118
+ const pkg = object(JSON.parse(artifactFile(root, 'package.json').toString('utf8')));
119
+ if (pkg.name !== manifest.packageName || pkg.version !== manifest.version) throw new Error('artifact_package_mismatch');
120
+ // Validate all SQL filenames, including files omitted from the supplied manifest.
121
+ artifactFile(root, `sql/${names[0]}`, 16 * 1024 * 1024);
122
+ const sqlNames = readdirSync(join(realpathSync(root), 'sql')).filter((file) => file.endsWith('.sql')).sort();
123
+ assertOfficialMigrationFilenames(sqlNames);
124
+ if (sqlNames.join('\n') !== names.join('\n')) throw new Error('artifact_sql_inventory_mismatch');
125
+ for (const m of migrations) if (digest(artifactFile(root, `sql/${m.filename}`, 16 * 1024 * 1024)) !== m.checksumSha256) throw new Error('artifact_sql_digest_mismatch');
126
+ return manifest;
127
+ }
128
+ function readSnapshot(path: string): { snapshot: UpgradeSnapshot; sha256: string } {
129
+ const bytes = read(path); const value = object(JSON.parse(bytes.toString('utf8')));
130
+ if (value.schema !== 'bailing.upgrade-snapshot.v1' || typeof value.captured_at !== 'string' || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{3})?Z$/.test(value.captured_at) || !Number.isFinite(Date.parse(value.captured_at)) || typeof value.source_manifest_sha256 !== 'string' || !HEX.test(value.source_manifest_sha256)) throw new Error('invalid_snapshot');
131
+ const state = object(value.state); const configuration = object(value.configuration);
132
+ if (!['mysql', 'jsonl'].includes(String(state.backend)) || !['mysql', 'file'].includes(String(configuration.backend))) throw new Error('unsupported_backend');
133
+ for (const role of [state, configuration]) {
134
+ if (role.backend === 'mysql' ? typeof role.database_id !== 'string' || !HEX.test(role.database_id) : role.database_id !== null) throw new Error('invalid_database_identity');
135
+ }
136
+ if (!Array.isArray(value.databases) || value.databases.length > 2) throw new Error('invalid_databases');
137
+ const databases = value.databases.map((entry): Database => {
138
+ const db = object(entry);
139
+ if (typeof db.id !== 'string' || !HEX.test(db.id) || typeof db.ledger_complete !== 'boolean' || !['present', 'absent'].includes(String(db.checksum_column)) || !Array.isArray(db.rows) || db.rows.length > 2000) throw new Error('invalid_database');
140
+ const rows = db.rows.map((entry): Row => {
141
+ const row = object(entry);
142
+ if (typeof row.filename !== 'string' || !FILENAME.test(row.filename) || (row.checksum_sha256 !== null && (typeof row.checksum_sha256 !== 'string' || !HEX.test(row.checksum_sha256)))) throw new Error('invalid_ledger_row');
143
+ return { filename: row.filename, checksum_sha256: row.checksum_sha256 as string | null };
144
+ });
145
+ if (new Set(rows.map((r) => r.filename)).size !== rows.length || (db.checksum_column === 'absent' && rows.some((r) => r.checksum_sha256 !== null))) throw new Error('contradictory_ledger');
146
+ return { id: db.id, ledger_complete: db.ledger_complete, checksum_column: db.checksum_column as Database['checksum_column'], rows };
147
+ });
148
+ if (new Set(databases.map((d) => d.id)).size !== databases.length) throw new Error('duplicate_database');
149
+ // Never retain unknown fields (which may contain accidental credentials).
150
+ return { sha256: digest(bytes), snapshot: { schema: 'bailing.upgrade-snapshot.v1', captured_at: value.captured_at, source_manifest_sha256: value.source_manifest_sha256,
151
+ state: { backend: state.backend as 'mysql' | 'jsonl', database_id: state.database_id as string | null },
152
+ configuration: { backend: configuration.backend as 'mysql' | 'file', database_id: configuration.database_id as string | null }, databases } };
153
+ }
154
+ function known(manifest: Manifest): Map<string, string> { return new Map([...manifest.migrations, ...manifest.retiredMigrations].map((m) => [m.filename, m.checksumSha256])); }
155
+ export function runUpgradePlan(options: UpgradePlanOptions): UpgradePlanReport {
156
+ const report: UpgradePlanReport = {
157
+ schema: 'bailing.upgrade-plan.v1', mode: 'offline', result: 'incomplete', exit_code: 2, basis: 'supplied_local_artifacts_and_snapshot', from: null, to: null, direction: 'unknown', snapshot: null, databases: [], checks: [],
158
+ scope: { network: false, subprocesses: false, config_credentials_read: false, database_connections: false, mutations: false, release_authenticity: 'not_verified', actual_runtime: 'not_verified', database_identity: 'snapshot_claim_only', schema_objects: 'not_checked', backup_restore: 'not_tested', execution_authorized: false },
159
+ actions: [
160
+ { id: 'identity', detail: 'Confirm official tag/commit/package or image digest and that the source artifact and effective state/configuration stores match the running deployment. An offline manifest covers version and SQL, not whole-artifact authenticity.' },
161
+ { id: 'backup', detail: 'Retain the source artifact and a consistent restore set: state/configuration databases, migration ledgers, config/secrets, JSONL, attachments and other runtime data. Test restore in isolation; do not include credentials or business payloads in this report.' },
162
+ { id: 'drain', detail: 'Stop new intake and all writers sharing these stores; drain every replica and accepted background work. Reconcile approvals, pending/unknown business effects, notification outbox and DLQ receipts; keep original IDs.' },
163
+ { id: 'migrate', detail: 'After reviewing the version-specific upgrade guide, use only the target official migrator, once per distinct MySQL database, never concurrently. npm run db:init covers state.mysql only; a separate configuration MySQL needs migrateBailingHubCoreSchema({mysql: configurationDatabase}). JSONL/file stores have no SQL migration.' },
164
+ { id: 'acceptance', detail: 'After manual migration, collect fresh ledgers; verify actual tables/indexes, readiness and isolated permission/approval/recovery/notification flows before reopening traffic. This plan runs none of these checks.' },
165
+ { id: 'rollback', detail: 'Do not delete ledger rows, replay retired migrations or assume switching the old tag is safe. New records may be rejected by the old manifest or ignored by old workers. Restore a tested consistent set and reconcile later external refunds/messages; DB restore cannot undo external effects.' },
166
+ ],
167
+ };
168
+ const add = (id: string, state: Check['state'], reason: string) => report.checks.push({ id, state, reason });
169
+ for (const side of ['from', 'to'] as const) {
170
+ const root = side === 'from' ? options.fromArtifact : options.toArtifact;
171
+ const path = side === 'from' ? options.fromManifest : options.toManifest;
172
+ if (!root || !path) { add(`${side}.artifact`, 'unknown', 'explicit_artifact_directory_and_manifest_required'); continue; }
173
+ try { report[side] = readManifest(root, path); add(`${side}.artifact`, 'pass', 'local_package_sql_and_manifest_match'); }
174
+ catch { add(`${side}.artifact`, 'fail', 'artifact_or_manifest_unreadable_invalid_or_mismatched'); }
175
+ }
176
+ const from = report.from; const to = report.to;
177
+ if (from && to) {
178
+ const cmp = compareVersions(to.version, from.version);
179
+ report.direction = cmp < 0 ? 'downgrade' : cmp > 0 ? 'upgrade' : 'same_version';
180
+ add('version.direction', cmp < 0 ? 'fail' : 'pass', cmp < 0 ? 'downgrade_requires_separate_restore_procedure' : report.direction);
181
+ if (!cmp && from.manifestSha256 !== to.manifestSha256) add('version.identity', 'fail', 'same_version_has_different_manifest');
182
+ const targetKnown = known(to);
183
+ const targetActive = new Set(to.migrations.map((m) => m.filename));
184
+ const targetRetired = new Map(to.retiredMigrations.map((m) => [m.filename, m]));
185
+ // Retirement is not a reversible classification. Never put evidence-only
186
+ // SQL back in the replayable sequence, even when its bytes still match.
187
+ for (const m of from.retiredMigrations) {
188
+ if (targetActive.has(m.filename)) add('migration.history', 'fail', 'target_reactivates_retired_migration');
189
+ const retired = targetRetired.get(m.filename);
190
+ if (retired && (retired.byteLength !== m.byteLength || retired.replay !== m.replay)) {
191
+ add('migration.history', 'fail', 'target_changes_retired_migration_evidence');
192
+ }
193
+ }
194
+ for (const m of from.migrations) {
195
+ if (targetRetired.has(m.filename)) add('migration.history', 'fail', 'target_reclassifies_published_active_migration');
196
+ }
197
+ for (const m of [...from.migrations, ...from.retiredMigrations]) {
198
+ if (!targetKnown.has(m.filename)) add('migration.history', 'fail', 'target_drops_known_migration_evidence');
199
+ else if (targetKnown.get(m.filename) !== m.checksumSha256) add('migration.history', 'fail', 'target_changes_published_migration_checksum');
200
+ }
201
+ }
202
+ if (!options.snapshot) add('snapshot', 'unknown', 'explicit_sanitized_snapshot_required');
203
+ else {
204
+ try {
205
+ const { snapshot, sha256 } = readSnapshot(options.snapshot);
206
+ const roles = [snapshot.state, snapshot.configuration];
207
+ const required = [...new Set(roles.flatMap((r) => r.database_id ? [r.database_id] : []))];
208
+ const topology = required.length === 2 ? 'separate_mysql' : required.length === 0 ? 'files_only' : roles.every((r) => r.backend === 'mysql') ? 'shared_mysql' : 'mixed';
209
+ report.snapshot = { captured_at: snapshot.captured_at, sha256, topology };
210
+ add('snapshot.binding', !from ? 'unknown' : from.manifestSha256 === snapshot.source_manifest_sha256 ? 'pass' : 'fail', !from ? 'source_manifest_unavailable' : from.manifestSha256 === snapshot.source_manifest_sha256 ? 'supplied_snapshot_claim_matches_source_manifest' : 'snapshot_source_manifest_mismatch');
211
+ add('snapshot.topology', required.every((id) => snapshot.databases.some((d) => d.id === id)) && snapshot.databases.every((d) => required.includes(d.id)) ? 'pass' : 'unknown', 'database_roles_require_exact_snapshot_coverage');
212
+ if (Date.parse(snapshot.captured_at) > Date.now() + 300_000) add('snapshot.time', 'fail', 'snapshot_timestamp_is_in_the_future');
213
+ // Age cannot establish freshness: the operator must recollect after any change.
214
+ for (const db of snapshot.databases.filter((d) => required.includes(d.id))) {
215
+ const dbRoles = [snapshot.state.database_id === db.id ? 'state' : '', snapshot.configuration.database_id === db.id ? 'configuration' : ''].filter(Boolean);
216
+ add(`database.${dbRoles.join('+')}.completeness`, db.ledger_complete ? 'pass' : 'unknown', db.ledger_complete ? 'operator_asserted_complete_ledger_snapshot' : 'partial_ledger_cannot_determine_pending');
217
+ if (!to || !from) continue;
218
+ const rows = new Map(db.rows.map((r) => [r.filename, r.checksum_sha256])); const targetKnown = known(to); const sourceKnown = known(from);
219
+ const pending = to.migrations.filter((m) => !rows.has(m.filename) && !from.retiredMigrations.some((retired) => retired.filename === m.filename)).map((m) => m.filename);
220
+ const missing = db.rows.filter((r) => r.checksum_sha256 === null).map((r) => r.filename);
221
+ const conflicts = db.rows.filter((r) => r.checksum_sha256 !== null && targetKnown.has(r.filename) && targetKnown.get(r.filename) !== r.checksum_sha256).map((r) => r.filename);
222
+ const unknown = db.rows.filter((r) => !targetKnown.has(r.filename) || !sourceKnown.has(r.filename)).map((r) => r.filename);
223
+ const sourceMissing = from.migrations.filter((m) => !rows.has(m.filename)).map((m) => m.filename);
224
+ report.databases.push({ id: db.id, roles: dbRoles, pending: db.ledger_complete ? pending : null, missing_checksums: missing, hash_conflicts: conflicts, unknown_migrations: unknown, source_missing: db.ledger_complete ? sourceMissing : null, rollback_after_migration: !db.ledger_complete ? 'unknown' : pending.some((name) => !sourceKnown.has(name)) ? 'blocked_by_old_manifest' : 'requires_validation' });
225
+ if (unknown.length) add(`database.${dbRoles.join('+')}.ledger.known`, 'fail', 'ledger_contains_migration_unknown_to_source_or_target');
226
+ if (conflicts.length) add(`database.${dbRoles.join('+')}.ledger.checksums`, 'fail', 'ledger_checksum_conflict');
227
+ if (missing.length || db.checksum_column === 'absent') add(`database.${dbRoles.join('+')}.ledger.checksums`, 'unknown', 'legacy_checksums_missing_no_backfill_performed');
228
+ if (db.ledger_complete && sourceMissing.length) add(`database.${dbRoles.join('+')}.ledger.source`, 'unknown', 'source_migrations_missing_in_claimed_current_database');
229
+ }
230
+ } catch { add('snapshot', 'fail', 'snapshot_unreadable_invalid_or_contradictory'); }
231
+ }
232
+ if (report.checks.some((c) => c.state === 'fail')) { report.result = 'blocked'; report.exit_code = 1; }
233
+ else if (report.checks.some((c) => c.state === 'unknown')) { report.result = 'incomplete'; report.exit_code = 2; }
234
+ else { report.result = 'reviewable'; report.exit_code = 0; }
235
+ return report;
236
+ }
237
+ export const UPGRADE_PLAN_USAGE = `BailingHub offline, read-only upgrade plan
238
+ Usage: npm run --silent doctor -- --upgrade-plan --from-artifact <dir> --from-manifest <json> --to-artifact <dir> --to-manifest <json> --snapshot <json> --json
239
+ Options: --from-artifact, --from-manifest, --to-artifact, --to-manifest, --snapshot,
240
+ --json, --help. Paths are explicit; no defaults or environment discovery.
241
+ Manifests: export BAILINGHUB_CORE_ARTIFACT_V1 from each trusted artifact (see docs/UPGRADE_PLAN.md).
242
+ Exit: 0 reviewable offline comparison, NOT deployment readiness; 1 blocked/mismatched;
243
+ 2 incomplete/missing evidence; 64 invalid arguments.
244
+ No network, subprocesses, config/credential loading, DB connection, migration, write,
245
+ backup, restore, automatic upgrade or execution approval. Snapshot facts are supplied,
246
+ not live verified. Review version-specific guides and recollect after changes.
247
+ `;
248
+ export function runUpgradePlanCli(args: string[], cwd: string): number {
249
+ let json = false; let invalid = false;
250
+ const options: UpgradePlanOptions = {};
251
+ const flags: Record<string, keyof UpgradePlanOptions> = { '--from-artifact': 'fromArtifact', '--from-manifest': 'fromManifest', '--to-artifact': 'toArtifact', '--to-manifest': 'toManifest', '--snapshot': 'snapshot' };
252
+ const seen = new Set<string>();
253
+ for (let i = 0; i < args.length; i++) {
254
+ const arg = args[i]!;
255
+ if (arg === '--upgrade-plan') continue;
256
+ if (arg === '--help') { console.log(UPGRADE_PLAN_USAGE); return 0; }
257
+ if (arg === '--json') { json = true; continue; }
258
+ const key = flags[arg]; const value = args[i + 1];
259
+ if (!key || !value || value.startsWith('--') || seen.has(arg)) { invalid = true; continue; }
260
+ options[key] = resolve(cwd, value); seen.add(arg); i++;
261
+ }
262
+ if (invalid) {
263
+ console.log(json ? JSON.stringify({ schema: 'bailing.upgrade-plan.v1', result: 'invalid_arguments', exit_code: 64, reason: 'invalid_or_unsupported_argument' }) : 'Invalid upgrade plan arguments. Use --upgrade-plan --help.');
264
+ return 64;
265
+ }
266
+ const report = runUpgradePlan(options);
267
+ if (json) console.log(JSON.stringify(report, null, 2));
268
+ else {
269
+ console.log(`BailingHub offline upgrade plan: ${report.result} (${report.from?.version ?? '?'} -> ${report.to?.version ?? '?'})`);
270
+ for (const check of report.checks) console.log(`${check.state} ${check.id}: ${check.reason}`);
271
+ for (const db of report.databases) console.log(`${db.roles.join('+')}: pending=${db.pending?.length ?? 'unknown'}, missing_checksums=${db.missing_checksums.length}, conflicts=${db.hash_conflicts.length}, unknown=${db.unknown_migrations.length}`);
272
+ for (const action of report.actions) console.log(`${action.id}: ${action.detail}`);
273
+ console.log('Offline evidence only; runtime, database identity, schema objects, authenticity and restoration are not verified. Use --json for full inventory.');
274
+ }
275
+ return report.exit_code;
276
+ }
package/scripts/doctor.ts CHANGED
@@ -2,8 +2,11 @@ import { execFileSync } from 'node:child_process';
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { runDeploymentDoctorCli } from './doctor-deployment';
5
+ import { runUpgradePlanCli } from './doctor-upgrade-plan';
5
6
 
6
- if (process.argv.includes('--deployment')) {
7
+ if (process.argv.includes('--upgrade-plan')) {
8
+ process.exitCode = runUpgradePlanCli(process.argv.slice(2), process.cwd());
9
+ } else if (process.argv.includes('--deployment')) {
7
10
  process.exitCode = await runDeploymentDoctorCli(process.argv.slice(2), process.cwd());
8
11
  } else {
9
12