bailinghub 0.9.4 → 0.10.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 (298) hide show
  1. package/README.en.md +6 -6
  2. package/README.md +6 -6
  3. package/THIRD_PARTY_NOTICES.md +1 -1
  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 +12 -0
  15. package/docs/CHANGELOG.md +12 -0
  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 +19 -15
  20. package/docs/IMPLEMENTATION_STATUS.md +19 -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 +5 -0
  34. package/docs/README.md +5 -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/UPGRADE_PLAN.en.md +118 -0
  40. package/docs/UPGRADE_PLAN.md +124 -0
  41. package/docs/UPGRADE_v0.10.0.en.md +47 -0
  42. package/docs/UPGRADE_v0.10.0.md +47 -0
  43. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +38 -22
  44. package/package.json +8 -5
  45. package/schemas/tool-definition.schema.json +13 -0
  46. package/scripts/check-doc-links.mjs +4 -0
  47. package/scripts/check-image-tags.sh +1 -1
  48. package/scripts/check-release-consistency.test.mjs +2 -2
  49. package/scripts/doctor-upgrade-plan.test.ts +205 -0
  50. package/scripts/doctor-upgrade-plan.ts +276 -0
  51. package/scripts/doctor.ts +4 -1
  52. package/scripts/e2e-console-approval-details.mjs +134 -0
  53. package/scripts/e2e-console-config-races.mjs +180 -0
  54. package/scripts/e2e-console-kb-audit.mjs +170 -0
  55. package/scripts/e2e-console-operations-audit.mjs +152 -0
  56. package/scripts/e2e-console-runtime-audit.mjs +179 -0
  57. package/scripts/e2e-console-settings-audit.mjs +125 -0
  58. package/scripts/e2e-console-troubleshooting-extra.mjs +267 -0
  59. package/scripts/e2e-console.mjs +476 -7
  60. package/scripts/install.sh +1 -1
  61. package/scripts/publish-images.sh +1 -1
  62. package/scripts/release-audit.mjs +4 -0
  63. package/scripts/verify-github-repo.mjs +4 -0
  64. package/src/app/agent-client-runtime.test.ts +115 -2
  65. package/src/app/agent-client-runtime.ts +40 -11
  66. package/src/app/agent-knowledge.test.ts +171 -0
  67. package/src/app/agent-knowledge.ts +233 -0
  68. package/src/app/agent-tool-catalog-revision.test.ts +31 -0
  69. package/src/app/agent-tool-invocations.test.ts +7 -2
  70. package/src/app/agent-tool-invocations.ts +67 -7
  71. package/src/app/approval-continuations.test.ts +49 -1
  72. package/src/app/http.test.ts +16 -1
  73. package/src/app/http.ts +3 -3
  74. package/src/app/kernel-boot-recovery.mysql.test.ts +132 -0
  75. package/src/app/kernel-boot-recovery.test.ts +157 -0
  76. package/src/app/kernel.ts +12 -8
  77. package/src/app/readiness.mysql.test.ts +120 -0
  78. package/src/app/readiness.test.ts +111 -26
  79. package/src/app/readiness.ts +26 -22
  80. package/src/app/runtime-lifecycle.ts +34 -3
  81. package/src/app/tool-approvals.test.ts +83 -0
  82. package/src/app/tool-approvals.ts +25 -7
  83. package/src/app/tool-proxy-payload.test.ts +81 -0
  84. package/src/app/tool-proxy.ts +24 -2
  85. package/src/core/config/console-diagnostic-location.test.ts +36 -0
  86. package/src/core/config/console-form-guard.test.ts +69 -0
  87. package/src/core/config/console-task-location.test.ts +64 -0
  88. package/src/core/contracts/openapi-tools.ts +16 -5
  89. package/src/core/contracts/schema-readiness.ts +11 -0
  90. package/src/core/contracts/tool-definition.ts +26 -0
  91. package/src/core/contracts/tool-guidance.test.ts +77 -0
  92. package/src/core/contracts/tool-guidance.ts +31 -0
  93. package/src/core/contracts/tool-input-limits.ts +15 -0
  94. package/src/core/contracts/tools-idempotency.test.ts +90 -0
  95. package/src/core/contracts/tools.ts +52 -9
  96. package/src/core/runtime/agent-execution-memory.test.ts +64 -0
  97. package/src/core/runtime/agent-execution-memory.ts +63 -0
  98. package/src/core/state/state-contracts.ts +3 -0
  99. package/src/infrastructure/config/config-observability-ledger.ts +2 -0
  100. package/src/infrastructure/schema/schema-readiness.ts +29 -0
  101. package/src/infrastructure/state/state-mysql.ts +3 -0
  102. package/src/modules/usage/contracts.ts +7 -0
  103. package/src/modules/usage/http.ts +2 -0
  104. package/src/modules/usage/model-continuation.test.ts +109 -0
  105. package/src/modules/usage/model-gateway.ts +5 -1
  106. package/src/modules/usage/output-budget.mysql.test.ts +84 -0
  107. package/src/modules/usage/output-budget.test.ts +167 -0
  108. package/src/modules/usage/output-budget.ts +73 -0
  109. package/src/modules/usage/provider-stream.test.ts +22 -0
  110. package/src/modules/usage/provider.ts +2 -3
  111. package/src/modules/usage/repository.ts +6 -0
  112. package/src/modules/usage/test-harness.ts +4 -2
  113. package/src/routes/admin-approval-view.test.ts +109 -0
  114. package/src/routes/admin-approval-view.ts +36 -0
  115. package/src/routes/admin-readiness.test.ts +52 -0
  116. package/src/routes/admin-runtime-ux.test.ts +51 -0
  117. package/src/routes/admin-runtime-ux.ts +25 -0
  118. package/src/routes/admin-runtime.ts +36 -8
  119. package/src/routes/admin.ts +9 -0
  120. package/src/routes/agent-api.test.ts +80 -1
  121. package/src/routes/agent-api.ts +63 -4
  122. package/src/routes/agent-tool-detail.test.ts +140 -0
  123. package/src/routes/public-default.ts +1 -1
  124. package/src/services/kb-agent.test.ts +84 -0
  125. package/src/services/kb.ts +73 -0
  126. package/web/console/assets/Accounts-CjIBO3sU.css +1 -0
  127. package/web/console/assets/Accounts-Dhyw-7wF.js +3 -0
  128. package/web/console/assets/AgentClients-BA0M26-I.css +1 -0
  129. package/web/console/assets/AgentClients-DWxb8-ko.js +1 -0
  130. package/web/console/assets/AgentTasks-DOyxANnx.css +1 -0
  131. package/web/console/assets/AgentTasks-DUHD4dzr.js +2 -0
  132. package/web/console/assets/Approvals-Brl-2uJq.css +1 -0
  133. package/web/console/assets/Approvals-CQx1YWxW.js +1 -0
  134. package/web/console/assets/Audit--QcdVlMh.js +1 -0
  135. package/web/console/assets/Audit-DAdmOnIs.css +1 -0
  136. package/web/console/assets/{BrandLockup-CffORQse.js → BrandLockup-DQcaW4Nt.js} +1 -1
  137. package/web/console/assets/Channels-DJJU3ksE.css +1 -0
  138. package/web/console/assets/Channels-cGS5WfQ-.js +105 -0
  139. package/web/console/assets/ChatEntries-BYpji27B.css +1 -0
  140. package/web/console/assets/ChatEntries-nh23Iz5O.js +7 -0
  141. package/web/console/assets/Clients-CX5EeYio.js +3 -0
  142. package/web/console/assets/Clients-CbZAou8E.css +1 -0
  143. package/web/console/assets/Cost-C6oQvz9P.css +1 -0
  144. package/web/console/assets/Cost-DOZfdNS9.js +1 -0
  145. package/web/console/assets/Credentials--aHs57yV.css +1 -0
  146. package/web/console/assets/Credentials-sy6W9Sac.js +1 -0
  147. package/web/console/assets/Diagnostics-CKs27Dnv.css +1 -0
  148. package/web/console/assets/Diagnostics-CyoM1XrZ.js +1 -0
  149. package/web/console/assets/Executors-2Upi6bOS.css +1 -0
  150. package/web/console/assets/Executors-BQqqiFwt.js +1 -0
  151. package/web/console/assets/HelpTip-DLlhaGQp.js +1 -0
  152. package/web/console/assets/HelpTip-bbDEyuqV.css +1 -0
  153. package/web/console/assets/Kb-5R3ce4UU.js +5 -0
  154. package/web/console/assets/Kb-BM_PYi11.css +1 -0
  155. package/web/console/assets/{Login-CGgLGTE1.js → Login-YKeUwdgo.js} +1 -1
  156. package/web/console/assets/Projects-DHwHrPT9.css +1 -0
  157. package/web/console/assets/Projects-Grgb6fOv.js +1 -0
  158. package/web/console/assets/Routes-DR_Yf02e.css +1 -0
  159. package/web/console/assets/Routes-DYgrXlRJ.js +138 -0
  160. package/web/console/assets/Runs-CwTddJJj.js +3 -0
  161. package/web/console/assets/Runs-D4FOvNfu.css +1 -0
  162. package/web/console/assets/Setup-Ca0b1d1-.css +1 -0
  163. package/web/console/assets/Setup-D_xUPNDq.js +1 -0
  164. package/web/console/assets/Shell-BTg8Vw_L.css +1 -0
  165. package/web/console/assets/Shell-Dfam2Uoj.js +1 -0
  166. package/web/console/assets/StorageBuckets-7QLBpV4a.css +1 -0
  167. package/web/console/assets/StorageBuckets-CP6e50wI.js +1 -0
  168. package/web/console/assets/SystemSettings-BRYKyJNa.js +1 -0
  169. package/web/console/assets/SystemSettings-HsXGx0aH.css +1 -0
  170. package/web/console/assets/SystemStatus-B-VfRsQd.css +1 -0
  171. package/web/console/assets/SystemStatus-CbPsDsGt.js +1 -0
  172. package/web/console/assets/Targets-1j4-g6rC.css +1 -0
  173. package/web/console/assets/Targets-C2LkR2AF.js +1 -0
  174. package/web/console/assets/Tools-C9HPJqJb.css +1 -0
  175. package/web/console/assets/Tools-C9JNJUS0.js +2 -0
  176. package/web/console/assets/Usage-D1Mv6vGY.js +1 -0
  177. package/web/console/assets/Usage-DMOzUsqh.css +1 -0
  178. package/web/console/assets/UsageAccess-77LmGCm6.js +1 -0
  179. package/web/console/assets/UsageAccess-C6ZGxEgJ.css +1 -0
  180. package/web/console/assets/{UsageHelp-CzS2gI40.js → UsageHelp-BmuiE1Ew.js} +1 -1
  181. package/web/console/assets/client-route-draft-DxZRxKPT.js +1 -0
  182. package/web/console/assets/console-location-Csv-xsnl.js +1 -0
  183. package/web/console/assets/form-guard-8GrFpry0.js +1 -0
  184. package/web/console/assets/{index-65JiiUr4.js → index-B_5UfiTw.js} +1 -1
  185. package/web/console/assets/index-MjZJEFIN.js +2 -0
  186. package/web/console/assets/{request-DKycpD7z.js → request-rqm6MT0s.js} +1 -1
  187. package/web/console/assets/runtime-feedback-gPfZVNvY.js +1 -0
  188. package/web/console/assets/{schema-SCiNxBlR.js → schema-o3mK4mid.js} +1 -1
  189. package/web/console/assets/task-page-location-DWiGtAln.js +1 -0
  190. package/web/console/assets/use-list-location-FvLFt0Tq.css +1 -0
  191. package/web/console/assets/use-list-location-cIPy2cKM.js +1 -0
  192. package/web/console/assets/use-unsaved-form-DScKD0h9.js +1 -0
  193. package/web/console/assets/{util-DZYfJ5Zo.js → util-B40VqOwl.js} +1 -1
  194. package/web/console/assets/{vendor-element-8cVcdt5T.js → vendor-element-BT8tHCFk.js} +1 -1
  195. package/web/console/assets/{vendor-mammoth-CnDA23N0.js → vendor-mammoth-CVIXVxTN.js} +1 -1
  196. package/web/console/assets/{vendor-vue-Co7x2FW6.js → vendor-vue-DhbG0vd4.js} +7 -7
  197. package/web/console/index.html +3 -3
  198. package/web-admin/package-lock.json +4 -4
  199. package/web-admin/package.json +1 -1
  200. package/web-admin/src/client-route-draft.ts +25 -0
  201. package/web-admin/src/components/AgentSetupPanel.vue +54 -41
  202. package/web-admin/src/components/HelpTip.vue +4 -1
  203. package/web-admin/src/components/ListLocationBar.vue +22 -0
  204. package/web-admin/src/components/NotificationOutboxPanel.vue +35 -7
  205. package/web-admin/src/console-entry.test.ts +26 -0
  206. package/web-admin/src/console-entry.ts +20 -0
  207. package/web-admin/src/console-location.ts +35 -0
  208. package/web-admin/src/form-guard.ts +35 -0
  209. package/web-admin/src/layout/Shell.vue +18 -65
  210. package/web-admin/src/onboarding-state.test.ts +174 -0
  211. package/web-admin/src/onboarding-state.ts +122 -0
  212. package/web-admin/src/pages/Accounts.vue +44 -24
  213. package/web-admin/src/pages/AgentClients.vue +47 -29
  214. package/web-admin/src/pages/AgentTasks.vue +57 -12
  215. package/web-admin/src/pages/Approvals.vue +105 -25
  216. package/web-admin/src/pages/Audit.vue +15 -6
  217. package/web-admin/src/pages/Channels.vue +136 -43
  218. package/web-admin/src/pages/ChatEntries.vue +96 -41
  219. package/web-admin/src/pages/Clients.vue +87 -26
  220. package/web-admin/src/pages/Cost.vue +15 -4
  221. package/web-admin/src/pages/Credentials.vue +63 -32
  222. package/web-admin/src/pages/Diagnostics.vue +103 -54
  223. package/web-admin/src/pages/Executors.vue +103 -40
  224. package/web-admin/src/pages/Kb.vue +278 -128
  225. package/web-admin/src/pages/Projects.vue +44 -16
  226. package/web-admin/src/pages/Routes.vue +168 -247
  227. package/web-admin/src/pages/Runs.vue +163 -91
  228. package/web-admin/src/pages/Setup.vue +182 -291
  229. package/web-admin/src/pages/StorageBuckets.vue +61 -25
  230. package/web-admin/src/pages/SystemSettings.vue +76 -51
  231. package/web-admin/src/pages/SystemStatus.vue +54 -30
  232. package/web-admin/src/pages/Targets.vue +45 -17
  233. package/web-admin/src/pages/Tools.vue +133 -68
  234. package/web-admin/src/pages/Usage.vue +64 -25
  235. package/web-admin/src/pages/UsageAccess.vue +11 -8
  236. package/web-admin/src/route-call-snippets.test.ts +82 -0
  237. package/web-admin/src/route-call-snippets.ts +178 -0
  238. package/web-admin/src/router.ts +11 -29
  239. package/web-admin/src/runtime-feedback.ts +43 -0
  240. package/web-admin/src/task-page-location.ts +66 -0
  241. package/web-admin/src/usage-output-budget.test.ts +26 -0
  242. package/web-admin/src/usage-output-budget.ts +46 -0
  243. package/web-admin/src/use-list-location.ts +24 -0
  244. package/web-admin/src/use-unsaved-form.ts +38 -0
  245. package/web-admin/tests/model-output-budget.browser.mjs +69 -0
  246. package/web/console/assets/Accounts-Bervi5JU.css +0 -1
  247. package/web/console/assets/Accounts-Dhj6PjXP.js +0 -3
  248. package/web/console/assets/AgentClients-CMy8StAH.js +0 -1
  249. package/web/console/assets/AgentClients-i52AI6YV.css +0 -1
  250. package/web/console/assets/AgentTasks-BsG850Il.css +0 -1
  251. package/web/console/assets/AgentTasks-DA1xZdmP.js +0 -2
  252. package/web/console/assets/Approvals-DIsd7R8N.js +0 -1
  253. package/web/console/assets/Approvals-DlTSHl_7.css +0 -1
  254. package/web/console/assets/Audit-AUDABLTX.js +0 -1
  255. package/web/console/assets/Audit-CSu6_3oD.css +0 -1
  256. package/web/console/assets/Channels-B8rjsM0S.js +0 -105
  257. package/web/console/assets/Channels-CCn0L1jg.css +0 -1
  258. package/web/console/assets/ChatEntries-DsYtcXN6.css +0 -1
  259. package/web/console/assets/ChatEntries-iZjJMEUZ.js +0 -7
  260. package/web/console/assets/Clients-CSHIsaWU.css +0 -1
  261. package/web/console/assets/Clients-CwgpGCSD.js +0 -3
  262. package/web/console/assets/Cost-B2tNxu71.js +0 -1
  263. package/web/console/assets/Cost-CjT39DSZ.css +0 -1
  264. package/web/console/assets/Credentials-BuwFB-fV.js +0 -1
  265. package/web/console/assets/Credentials-ioLP0qYN.css +0 -1
  266. package/web/console/assets/Diagnostics-Ya05PTDp.css +0 -1
  267. package/web/console/assets/Diagnostics-z5glms11.js +0 -1
  268. package/web/console/assets/Executors-Bc4SvjeH.js +0 -1
  269. package/web/console/assets/Executors-CjhEM54c.css +0 -1
  270. package/web/console/assets/HelpTip-CA6Bm7Nx.css +0 -1
  271. package/web/console/assets/HelpTip-Dtdt2tKR.js +0 -1
  272. package/web/console/assets/Kb-BRbRHxLy.js +0 -5
  273. package/web/console/assets/Kb-CzIzd9xr.css +0 -1
  274. package/web/console/assets/Projects-Bm8AjsNx.css +0 -1
  275. package/web/console/assets/Projects-CPWw3con.js +0 -1
  276. package/web/console/assets/Routes-CMIaE0Bx.js +0 -124
  277. package/web/console/assets/Routes-CyXV4Pba.css +0 -1
  278. package/web/console/assets/Runs-B8HuE700.js +0 -3
  279. package/web/console/assets/Runs-Bv6CV_Hk.css +0 -1
  280. package/web/console/assets/Setup-D7nxgn-9.css +0 -1
  281. package/web/console/assets/Setup-G8RKzliR.js +0 -1
  282. package/web/console/assets/Shell-DimHgraJ.js +0 -1
  283. package/web/console/assets/Shell-ykb-tUfo.css +0 -1
  284. package/web/console/assets/StorageBuckets-CVgpZRWY.css +0 -1
  285. package/web/console/assets/StorageBuckets-CiVYXIE2.js +0 -1
  286. package/web/console/assets/SystemSettings-BjiHyrXO.css +0 -1
  287. package/web/console/assets/SystemSettings-DF8sZNen.js +0 -1
  288. package/web/console/assets/SystemStatus-BlHywK13.js +0 -1
  289. package/web/console/assets/SystemStatus-I11I67rw.css +0 -1
  290. package/web/console/assets/Targets-BXaoPoAJ.js +0 -1
  291. package/web/console/assets/Targets-DTb5tn6z.css +0 -1
  292. package/web/console/assets/Tools-B22lNHXq.js +0 -2
  293. package/web/console/assets/Tools-DU8ei6sd.css +0 -1
  294. package/web/console/assets/Usage-C02EzoI2.js +0 -1
  295. package/web/console/assets/Usage-CAeDGjrb.css +0 -1
  296. package/web/console/assets/UsageAccess-CGGaWTuj.css +0 -1
  297. package/web/console/assets/UsageAccess-DOb-cyPE.js +0 -1
  298. package/web/console/assets/index-CK0ZCTZv.js +0 -2
@@ -0,0 +1,132 @@
1
+ import assert from 'node:assert/strict';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { mkdtemp, rm } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import test from 'node:test';
8
+ import { createPool, type Pool } from 'mysql2/promise';
9
+ import type { AppConfig } from '../core/config/config';
10
+ import { MysqlPoolOwner } from '../infrastructure/mysql/pool-owner';
11
+ import { migrateBailingHubCoreSchema } from '../infrastructure/schema/core-schema-migrator';
12
+ import { MysqlStore } from '../infrastructure/state/state-mysql';
13
+ import { createBailingHubKernel } from './kernel';
14
+
15
+ const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
16
+
17
+ // A fresh schema runs the complete migration history before the 2s boot timer.
18
+ // Leave setup headroom on shared CI hosts; the actual lock observation below
19
+ // still has its own short deadline, so a recovery regression cannot hide here.
20
+ test('standalone boot recovery retains its MySQL pool while an actual requeue UPDATE waits on a row lock', { skip: !enabled, timeout: 120_000 }, async t => {
21
+ const startedAt = performance.now();
22
+ const database = `boot_recovery_${randomUUID().replaceAll('-', '')}`;
23
+ const dir = await mkdtemp(join(tmpdir(), 'kernel-boot-mysql-'));
24
+ const mysql = { host: '127.0.0.1', port: Number(process.env.BAILING_USAGE_TEST_MYSQL_PORT ?? 16307),
25
+ user: 'root', password: '', database, connectionLimit: 4 };
26
+ // Explicitly loopback-only, random disposable schema; no deployment config.
27
+ const admin = createPool({ ...mysql, database: undefined });
28
+ let kernel: ReturnType<typeof createBailingHubKernel> | undefined;
29
+ let server: ReturnType<ReturnType<typeof createBailingHubKernel>['createStandaloneServer']> | undefined;
30
+ let lockConnection: Awaited<ReturnType<typeof admin.getConnection>> | undefined;
31
+ let created = false;
32
+ let failure: unknown;
33
+ const releaseTestLockOnAbort = () => {
34
+ // This is the fixture's external blocker, never the runtime's SQL pool.
35
+ // Destroying this connection rolls back its transaction even after timeout.
36
+ lockConnection?.destroy();
37
+ lockConnection = undefined;
38
+ };
39
+ t.signal.addEventListener('abort', releaseTestLockOnAbort, { once: true });
40
+ try {
41
+ await admin.query(`CREATE DATABASE \`${database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
42
+ created = true;
43
+ await migrateBailingHubCoreSchema({ mysql, logger: { log() {}, warn() {} } });
44
+ t.signal.throwIfAborted();
45
+ t.diagnostic(`isolated schema migration completed in ${Math.round(performance.now() - startedAt)}ms`);
46
+ const seed = new MysqlStore(mysql);
47
+ await seed.init();
48
+ try {
49
+ await seed.createJob({ job_id: 'synthetic-orphan', request_id: 'synthetic-recovery', status: 'running',
50
+ target: 'synthetic-uninstalled', source: 'test', profile: 'readonly', project: '', input_preview: '', metadata: {},
51
+ created_at: new Date().toISOString(), updated_at: new Date().toISOString() });
52
+ } finally { await seed.close(); }
53
+ t.signal.throwIfAborted();
54
+ lockConnection = await admin.getConnection();
55
+ await lockConnection.beginTransaction();
56
+ await lockConnection.query(`SELECT job_id FROM \`${database}\`.bz_jobs WHERE job_id=? FOR UPDATE`, ['synthetic-orphan']);
57
+
58
+ const config: AppConfig = { root: process.cwd(), runtimeRoot: dir, env: 'development',
59
+ server: { host: '127.0.0.1', port: 0, token: '' }, brand: { name: 'Synthetic SQL recovery test' },
60
+ displayTz: 'Asia/Shanghai', displayTzLabel: '北京时间', auditRetentionDays: 0, alerts: null,
61
+ metrics: { enabled: false, token: '', scrapeTimeoutMs: 1000 }, bootstrapAdmin: null,
62
+ concurrency: 1, killSwitchFile: join(dir, '.paused'), claudeBin: 'synthetic-unused', defaultProfile: 'readonly', brainDir: join(dir, 'brain'),
63
+ state: { backend: 'mysql', jsonlPath: join(dir, 'jobs.jsonl'), mysql }, projects: {}, llmCredentials: {},
64
+ executor: { hubUrl: '', token: '', executorId: 'synthetic', targets: [], waitMs: 100, concurrency: 1, labels: [] } };
65
+ let closes = 0, recoveryPool: Pool | undefined;
66
+ const originalClose = MysqlPoolOwner.prototype.close, originalUpdate = MysqlStore.prototype.updateJobIfStatus;
67
+ t.mock.method(MysqlPoolOwner.prototype, 'close', async function (this: MysqlPoolOwner) { closes++; await originalClose.call(this); });
68
+ t.mock.method(MysqlStore.prototype, 'updateJobIfStatus', async function (this: MysqlStore, ...args: Parameters<typeof originalUpdate>) {
69
+ if (args[0] === 'synthetic-orphan' && args[2].status === 'queued') recoveryPool = (this as unknown as { pool: Pool }).pool;
70
+ return await originalUpdate.apply(this, args);
71
+ });
72
+ kernel = createBailingHubKernel({ instanceKey: database, config, schedulerMode: 'standalone', bootstrapLocalAdmin: false,
73
+ logger: { log() {}, warn() {}, error() {} } });
74
+ server = kernel.createStandaloneServer({ exit() {} });
75
+ await server.start();
76
+ t.signal.throwIfAborted();
77
+
78
+ let waitingOnSql = false;
79
+ const lockDeadline = performance.now() + 10_000;
80
+ while (performance.now() < lockDeadline) {
81
+ t.signal.throwIfAborted();
82
+ const [rows] = await admin.query<any[]>(`SELECT COUNT(*) n FROM performance_schema.data_lock_waits w
83
+ JOIN performance_schema.data_locks l ON l.ENGINE_LOCK_ID=w.REQUESTING_ENGINE_LOCK_ID AND l.ENGINE=w.ENGINE
84
+ WHERE l.OBJECT_SCHEMA=? AND l.OBJECT_NAME='bz_jobs'`, [database]);
85
+ if (Number(rows[0].n) > 0) { waitingOnSql = true; break; }
86
+ await delay(10);
87
+ }
88
+ assert.equal(waitingOnSql, true, 'the real boot timer must reach an UPDATE blocked inside MySQL');
89
+ t.diagnostic(`real MySQL row-lock wait observed in ${Math.round(performance.now() - startedAt)}ms`);
90
+ await assert.rejects(kernel.close(10), /boot recovery drain timed out/);
91
+ assert.equal(closes, 0, 'timing out cannot close the pool that owns the blocked UPDATE');
92
+ assert.ok(recoveryPool);
93
+ await recoveryPool.query('SELECT 1');
94
+
95
+ const firstClose = kernel.close(5_000), secondClose = kernel.close(5_000);
96
+ await lockConnection.rollback(); lockConnection.release(); lockConnection = undefined;
97
+ await Promise.all([firstClose, secondClose]);
98
+ await kernel.close(0);
99
+ assert.equal(closes, 1);
100
+ const [jobs] = await admin.query<any[]>(`SELECT status FROM \`${database}\`.bz_jobs WHERE job_id=?`, ['synthetic-orphan']);
101
+ assert.equal(jobs[0].status, 'queued');
102
+ const [audits] = await admin.query<any[]>(`SELECT COUNT(*) n FROM \`${database}\`.bz_audit WHERE job_id=? AND event='recovered'`, ['synthetic-orphan']);
103
+ assert.equal(Number(audits[0].n), 1);
104
+ await assert.rejects(recoveryPool.query('SELECT 1'));
105
+ } catch (error) {
106
+ failure = error;
107
+ throw error;
108
+ } finally {
109
+ const cleanupErrors: unknown[] = [];
110
+ const cleanup = async (action: () => Promise<unknown>): Promise<boolean> => {
111
+ try { await action(); return true; }
112
+ catch (error) { cleanupErrors.push(error); return false; }
113
+ };
114
+ if (lockConnection) {
115
+ const connection = lockConnection;
116
+ lockConnection = undefined;
117
+ if (await cleanup(() => connection.rollback())) connection.release();
118
+ else connection.destroy();
119
+ }
120
+ // Each cleanup step must run even if an earlier one fails. A second normal
121
+ // drain via shutdown may finish late SQL; never force-close its pool or drop
122
+ // the schema while that SQL is still in flight.
123
+ let drained = await cleanup(async () => { await kernel?.close(10_000); });
124
+ if (server) drained = await cleanup(() => server!.shutdown('test')) || drained;
125
+ if (created && drained) await cleanup(() => admin.query(`DROP DATABASE \`${database}\``));
126
+ if (created && !drained) t.diagnostic(`cleanup could not drain runtime; retained disposable schema ${database}`);
127
+ await cleanup(() => admin.end());
128
+ await cleanup(() => rm(dir, { recursive: true, force: true }));
129
+ t.signal.removeEventListener('abort', releaseTestLockOnAbort);
130
+ if (cleanupErrors.length) throw new AggregateError(failure === undefined ? cleanupErrors : [failure, ...cleanupErrors], 'Synthetic boot recovery test cleanup failed');
131
+ }
132
+ });
@@ -0,0 +1,157 @@
1
+ import assert from 'node:assert/strict';
2
+ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { setTimeout as delay } from 'node:timers/promises';
6
+ import test from 'node:test';
7
+ import type { AppConfig } from '../core/config/config';
8
+ import type { Job } from '../core/contracts/types';
9
+ import { JsonlStore } from '../infrastructure/state/state-jsonl';
10
+ import { createBailingHubKernel } from './kernel';
11
+
12
+ function gate() {
13
+ let release!: () => void;
14
+ const promise = new Promise<void>(resolve => { release = resolve; });
15
+ return { promise, release };
16
+ }
17
+
18
+ async function fixture(mode: 'standalone' | 'managed') {
19
+ const dir = await mkdtemp(join(tmpdir(), 'kernel-boot-recovery-'));
20
+ const cfg: AppConfig = {
21
+ root: process.cwd(), runtimeRoot: dir, env: 'development',
22
+ server: { host: '127.0.0.1', port: 0, token: '' }, brand: { name: 'Synthetic recovery test' },
23
+ displayTz: 'Asia/Shanghai', displayTzLabel: '北京时间', auditRetentionDays: 0, alerts: null,
24
+ metrics: { enabled: false, token: '', scrapeTimeoutMs: 1000 }, bootstrapAdmin: null,
25
+ concurrency: 1, killSwitchFile: join(dir, '.paused'), claudeBin: 'synthetic-unused',
26
+ defaultProfile: 'readonly', brainDir: join(dir, 'brain'),
27
+ state: { backend: 'jsonl', jsonlPath: join(dir, 'jobs.jsonl'),
28
+ mysql: { host: '', port: 3306, database: '', user: '', password: '', connectionLimit: 2 } },
29
+ projects: {}, llmCredentials: {},
30
+ executor: { hubUrl: '', token: '', executorId: 'synthetic', targets: [], waitMs: 100, concurrency: 1, labels: [] },
31
+ };
32
+ // No adapter is installed for this orphan: recovery can durably requeue it
33
+ // without invoking a model, business API, or other external side effect.
34
+ const orphan: Job = {
35
+ job_id: 'synthetic-orphan', request_id: 'synthetic-recovery', status: 'running', target: 'synthetic-uninstalled',
36
+ source: 'test', profile: 'readonly', project: '', input_preview: '', metadata: {},
37
+ created_at: new Date().toISOString(), updated_at: new Date().toISOString(),
38
+ };
39
+ await writeFile(cfg.state.jsonlPath, JSON.stringify({ kind: 'job', job: orphan }) + '\n');
40
+ const kernel = createBailingHubKernel({ instanceKey: `boot:${mode}`, config: cfg, schedulerMode: mode,
41
+ bootstrapLocalAdmin: false, logger: { log() {}, warn() {}, error() {} } });
42
+ let exits = 0;
43
+ const server = mode === 'standalone' ? kernel.createStandaloneServer({ exit: () => { exits++; } }) : undefined;
44
+ return {
45
+ kernel, cfg, server,
46
+ exits: () => exits,
47
+ async start() {
48
+ if (server) await server.start();
49
+ else {
50
+ await kernel.initialize();
51
+ await delay(2_050);
52
+ await kernel.tick();
53
+ }
54
+ },
55
+ async dispose() {
56
+ await kernel.close(2_000);
57
+ if (server) await server.shutdown('test');
58
+ await rm(dir, { recursive: true, force: true });
59
+ },
60
+ };
61
+ }
62
+
63
+ for (const mode of ['standalone', 'managed'] as const) {
64
+ test(`Kernel ${mode} boot recovery: query and late audit finish before resources close; timeout is retryable`, { timeout: 10_000 }, async t => {
65
+ const h = await fixture(mode);
66
+ const queryEntered = gate(), queryRelease = gate(), auditEntered = gate(), auditRelease = gate(), recoveryFinished = gate();
67
+ const events: string[] = [];
68
+ const list = JsonlStore.prototype.listJobsByStatus;
69
+ const audit = JsonlStore.prototype.appendAudit;
70
+ const update = JsonlStore.prototype.updateJobIfStatus;
71
+ const close = JsonlStore.prototype.close;
72
+ t.mock.method(JsonlStore.prototype, 'listJobsByStatus', async function (this: JsonlStore, ...args: Parameters<typeof list>) {
73
+ if (args[0].includes('queued') && args[0].includes('running')) {
74
+ events.push('query:start'); queryEntered.release(); await queryRelease.promise;
75
+ events.push('query:end');
76
+ }
77
+ return await list.apply(this, args);
78
+ });
79
+ t.mock.method(JsonlStore.prototype, 'appendAudit', async function (this: JsonlStore, ...args: Parameters<typeof audit>) {
80
+ if (args[0].event === 'recovered') { auditEntered.release(); await auditRelease.promise; }
81
+ await audit.apply(this, args);
82
+ if (args[0].event === 'recovered') events.push('audit:written');
83
+ });
84
+ t.mock.method(JsonlStore.prototype, 'updateJobIfStatus', async function (this: JsonlStore, ...args: Parameters<typeof update>) {
85
+ const value = await update.apply(this, args);
86
+ if (args[0] === 'synthetic-orphan' && args[2].status === 'queued') {
87
+ events.push('orphan:requeued'); recoveryFinished.release();
88
+ }
89
+ return value;
90
+ });
91
+ t.mock.method(JsonlStore.prototype, 'close', async function (this: JsonlStore) {
92
+ events.push('resources:close'); await close.call(this);
93
+ });
94
+ try {
95
+ await h.start();
96
+ await queryEntered.promise;
97
+ await assert.rejects(h.kernel.close(5), /(?:boot recovery|managed maintenance) drain timed out/);
98
+ assert.equal(events.includes('resources:close'), false, 'a blocked recovery query still owns its store');
99
+ queryRelease.release(); await auditEntered.promise;
100
+ await assert.rejects(h.kernel.close(5), /(?:boot recovery|managed maintenance) drain timed out/);
101
+ assert.equal(events.includes('resources:close'), false, 'late recovery audit and requeue must settle too');
102
+ const firstClose = h.kernel.close(2_000), secondClose = h.kernel.close(2_000);
103
+ auditRelease.release();
104
+ await Promise.all([firstClose, secondClose]);
105
+ await recoveryFinished.promise;
106
+ await h.kernel.close(0);
107
+ assert.deepEqual(events, ['query:start', 'query:end', 'audit:written', 'orphan:requeued', 'resources:close']);
108
+ const journal = (await readFile(h.cfg.state.jsonlPath, 'utf8')).trim().split('\n').map(line => JSON.parse(line));
109
+ assert.equal(journal.filter(row => row.kind === 'job').at(-1).job.status, 'queued');
110
+ assert.equal(journal.filter(row => row.kind === 'audit' && row.entry.event === 'recovered').length, 1);
111
+ } finally {
112
+ queryRelease.release(); auditRelease.release();
113
+ // The baseline closes too early; allow its detached work to finish before
114
+ // removing the fixture so the red test does not leave background writes.
115
+ await recoveryFinished.promise;
116
+ await h.dispose();
117
+ }
118
+ });
119
+ }
120
+
121
+ test('Kernel standalone boot recovery: failure settles before close and does not prevent an idempotent retry', { timeout: 10_000 }, async t => {
122
+ const h = await fixture('standalone'), entered = gate(), release = gate(), finished = gate();
123
+ let closed = 0;
124
+ const original = JsonlStore.prototype.listJobsByStatus, originalClose = JsonlStore.prototype.close;
125
+ t.mock.method(JsonlStore.prototype, 'listJobsByStatus', async function (this: JsonlStore, ...args: Parameters<typeof original>) {
126
+ if (args[0].includes('queued') && args[0].includes('running')) {
127
+ entered.release(); await release.promise; finished.release(); throw new Error('synthetic recovery query failed');
128
+ }
129
+ return await original.apply(this, args);
130
+ });
131
+ t.mock.method(JsonlStore.prototype, 'close', async function (this: JsonlStore) { closed++; await originalClose.call(this); });
132
+ const errors = t.mock.method(console, 'error', () => {});
133
+ try {
134
+ await h.start(); await entered.promise;
135
+ await assert.rejects(h.kernel.close(5), /boot recovery drain timed out/);
136
+ assert.equal(closed, 0);
137
+ release.release(); await h.kernel.close(2_000); await h.kernel.close(0);
138
+ assert.equal(closed, 1);
139
+ assert.equal(errors.mock.callCount(), 1, 'failed recovery remains observable through its existing error log');
140
+ } finally { release.release(); await finished.promise; await h.dispose(); }
141
+ });
142
+
143
+ test('Kernel standalone close before the boot timer fires cancels recovery permanently', { timeout: 10_000 }, async t => {
144
+ const h = await fixture('standalone');
145
+ let recoveryQueries = 0;
146
+ const original = JsonlStore.prototype.listJobsByStatus;
147
+ t.mock.method(JsonlStore.prototype, 'listJobsByStatus', async function (this: JsonlStore, ...args: Parameters<typeof original>) {
148
+ if (args[0].includes('queued') && args[0].includes('running')) recoveryQueries++;
149
+ return await original.apply(this, args);
150
+ });
151
+ try {
152
+ await h.start(); await h.kernel.close(2_000); await delay(2_050);
153
+ assert.equal(recoveryQueries, 0);
154
+ await h.server!.shutdown('test');
155
+ assert.equal(h.exits(), 1);
156
+ } finally { await h.dispose(); }
157
+ });
package/src/app/kernel.ts CHANGED
@@ -17,9 +17,10 @@ import { createRuntimeContextHelpers } from './runtime-context';
17
17
  import {
18
18
  createManagedRuntimeMaintenanceFor,
19
19
  initializeRuntimeLifecycleFor,
20
- scheduleBootRecoveryFor,
20
+ startBootRecoveryFor,
21
21
  startRuntimeSchedulersFor,
22
22
  type ManagedRuntimeMaintenance,
23
+ type RuntimeBootRecovery,
23
24
  type RuntimeLifecycleDeps,
24
25
  type RuntimeSchedulers,
25
26
  } from './runtime-lifecycle';
@@ -391,7 +392,7 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
391
392
  queue: composition.queue,
392
393
  isPaused,
393
394
  metrics,
394
- readiness: () => checkReadinessFor(cfg, composition.cfgStore),
395
+ readiness: () => checkReadinessFor(cfg, composition.cfgStore, composition.store),
395
396
  operationalStatus: () => {
396
397
  const audit = edition.auditFailures.snapshot();
397
398
  return { audit_write_failures: audit.total, last_audit_failure_at: audit.lastFailureAt };
@@ -409,7 +410,7 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
409
410
  let initialized = false;
410
411
  let initializePromise: Promise<void> | null = null;
411
412
  let schedulers: RuntimeSchedulers | null = null;
412
- let bootRecoveryTimer: ReturnType<typeof setTimeout> | null = null;
413
+ let bootRecovery: RuntimeBootRecovery | null = null;
413
414
  let managedMaintenance: ManagedRuntimeMaintenance | null = null;
414
415
  let closing = false;
415
416
  let closed = false;
@@ -490,12 +491,15 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
490
491
  if (!initializedWithinBudget) throw new Error(`Kernel ${instanceKey} initialization drain timed out`);
491
492
  }
492
493
  schedulers?.stop();
494
+ bootRecovery?.stop();
493
495
  if (schedulers?.drain && !await schedulers.drain(remainingDrainMs())) {
494
496
  throw new Error(`Kernel ${instanceKey} persisted evidence maintenance drain timed out`);
495
497
  }
496
498
  schedulers = null;
497
- if (bootRecoveryTimer) clearTimeout(bootRecoveryTimer);
498
- bootRecoveryTimer = null;
499
+ if (bootRecovery && !await bootRecovery.drain(remainingDrainMs())) {
500
+ throw new Error(`Kernel ${instanceKey} boot recovery drain timed out`);
501
+ }
502
+ bootRecovery = null;
499
503
  if (managedMaintenance) {
500
504
  const maintenanceDrained = await managedMaintenance.stop(remainingDrainMs());
501
505
  if (!maintenanceDrained) throw new Error(`Kernel ${instanceKey} managed maintenance drain timed out`);
@@ -561,8 +565,8 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
561
565
  return schedulers;
562
566
  },
563
567
  scheduleBootRecovery: () => {
564
- bootRecoveryTimer ??= scheduleBootRecoveryFor(lifecycleDeps);
565
- return bootRecoveryTimer;
568
+ bootRecovery ??= startBootRecoveryFor(lifecycleDeps);
569
+ return bootRecovery.timer;
566
570
  },
567
571
  closeRuntime: () => close(),
568
572
  logger,
@@ -576,7 +580,7 @@ export function createBailingHubKernel(input: CreateBailingHubKernelInputV1): Ba
576
580
  initialize,
577
581
  handle,
578
582
  tick,
579
- readiness: () => checkReadinessFor(cfg, composition.cfgStore),
583
+ readiness: () => checkReadinessFor(cfg, composition.cfgStore, composition.store),
580
584
  close,
581
585
  createStandaloneServer,
582
586
  isClosing: () => closing || closed,
@@ -0,0 +1,120 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { randomBytes } from 'node:crypto';
4
+ import { mkdtempSync, rmSync } from 'node:fs';
5
+ import { createServer } from 'node:http';
6
+ import { tmpdir } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { createBailingHubKernel } from './kernel';
9
+ import { createPool, type RowDataPacket } from 'mysql2/promise';
10
+ import type { AppConfig } from '../core/config/config';
11
+ import { BAILINGHUB_CORE_ARTIFACT_V1 as artifact } from '../kernel-api/v1/artifact';
12
+ import { migrateBailingHubCoreSchema } from '../infrastructure/schema/core-schema-migrator';
13
+ import { ConfigStore } from '../infrastructure/config/configstore';
14
+ import { MysqlStore } from '../infrastructure/state/state-mysql';
15
+ import { checkReadinessFor } from './readiness';
16
+
17
+ const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
18
+
19
+ test('readiness validates both real MySQL resources without mutating legacy or corrupt ledgers', { skip: !enabled, timeout: 120_000 }, async t => {
20
+ const prefix = `ready_${randomBytes(8).toString('hex')}`;
21
+ const names = [`${prefix}_state`, `${prefix}_config`];
22
+ const base = { host: '127.0.0.1', port: Number(process.env.BAILING_USAGE_TEST_MYSQL_PORT ?? 16307), user: 'root', password: '', connectionLimit: 2 };
23
+ const admin = createPool(base); const pools = names.map(database => createPool({ ...base, database }));
24
+ const created: string[] = [];
25
+ const state = new MysqlStore({ ...base, database: names[0]! }, { get: async () => pools[0]!, close: async () => {} });
26
+ const config = new ConfigStore({ ...base, database: names[1]! }, { get: async () => pools[1]!, close: async () => {} });
27
+ const sharedConfig = new ConfigStore({ ...base, database: names[0]! }, { get: async () => pools[0]!, close: async () => {} });
28
+ const cfg = { root: '/not-a-migration-directory', state: { backend: 'mysql', mysql: { ...base, database: names[0] } } } as AppConfig;
29
+ const latest = artifact.migrations.at(-1)!;
30
+ const ledger = async (index: number) => (await pools[index]!.query<RowDataPacket[]>('SELECT filename,checksum_sha256,applied_at FROM bz_schema_migrations ORDER BY filename'))[0];
31
+ try {
32
+ for (const name of names) {
33
+ assert.match(name, new RegExp(`^${prefix}_(state|config)$`));
34
+ await admin.query(`CREATE DATABASE \`${name}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`); created.push(name);
35
+ await migrateBailingHubCoreSchema({ mysql: { ...base, database: name }, logger: { log() {}, warn() {} } });
36
+ }
37
+ await state.init(); await config.init(); await sharedConfig.init();
38
+ await t.test('complete shared and split databases are ready', async () => {
39
+ assert.equal((await checkReadinessFor(cfg, config, state)).ready, true);
40
+ assert.equal((await checkReadinessFor(cfg, sharedConfig, state)).ready, true);
41
+ });
42
+ for (const [index, role] of ['state', 'configuration'].entries()) {
43
+ await t.test(`missing latest migration on ${role} returns not-ready`, async () => {
44
+ const before = await ledger(index); const row = before.find(item => item.filename === latest.filename)!;
45
+ await pools[index]!.query('DELETE FROM bz_schema_migrations WHERE filename=?', [latest.filename]);
46
+ const report = await checkReadinessFor(cfg, config, state);
47
+ assert.equal(report.ready, false); assert.deepEqual(report.checks.migrations, { status: 'pending', pending: 1 });
48
+ assert.equal((await ledger(index)).length, before.length - 1, 'readiness must not apply a migration');
49
+ await pools[index]!.query('INSERT INTO bz_schema_migrations(filename,checksum_sha256,applied_at) VALUES (?,?,?)', [row.filename, row.checksum_sha256, row.applied_at]);
50
+ assert.deepEqual(await ledger(index), before);
51
+ });
52
+ for (const checksum of [null, '0'.repeat(64)]) {
53
+ await t.test(`${role} ${checksum === null ? 'NULL' : 'conflicting'} checksum fails without backfill`, async () => {
54
+ await pools[index]!.query('UPDATE bz_schema_migrations SET checksum_sha256=? WHERE filename=?', [checksum, latest.filename]);
55
+ const before = await ledger(index); const report = await checkReadinessFor(cfg, config, state);
56
+ assert.equal(report.ready, false); assert.equal(report.checks.migrations.status, 'failed');
57
+ assert.deepEqual(await ledger(index), before, 'readiness cannot repair the ledger');
58
+ await pools[index]!.query('UPDATE bz_schema_migrations SET checksum_sha256=? WHERE filename=?', [latest.checksumSha256, latest.filename]);
59
+ });
60
+ }
61
+ await t.test(`${role} unknown future record fails without dropping it`, async () => {
62
+ await pools[index]!.query('INSERT INTO bz_schema_migrations(filename,checksum_sha256) VALUES (?,?)', ['999_synthetic_future.sql', '0'.repeat(64)]);
63
+ const before = await ledger(index); const report = await checkReadinessFor(cfg, config, state);
64
+ assert.equal(report.ready, false); assert.equal(report.checks.migrations.status, 'failed'); assert.deepEqual(await ledger(index), before);
65
+ await pools[index]!.query('DELETE FROM bz_schema_migrations WHERE filename=?', ['999_synthetic_future.sql']);
66
+ });
67
+ }
68
+ await t.test('JSONL state still checks configuration; missing checksum column requires explicit migrator', async () => {
69
+ const jsonl = { ...cfg, state: { ...cfg.state, backend: 'jsonl' as const } };
70
+ assert.equal((await checkReadinessFor(jsonl, config)).ready, true);
71
+ await pools[1]!.query('ALTER TABLE bz_schema_migrations DROP COLUMN checksum_sha256');
72
+ assert.equal((await checkReadinessFor(jsonl, config)).ready, false);
73
+ const [columns] = await pools[1]!.query<RowDataPacket[]>('SHOW COLUMNS FROM bz_schema_migrations');
74
+ assert.equal(columns.some(row => row.Field === 'checksum_sha256'), false, 'probe must not add the checksum column');
75
+ const repaired = await migrateBailingHubCoreSchema({ mysql: { ...base, database: names[1]! }, logger: { log() {}, warn() {} } });
76
+ assert.equal(repaired.checksumBackfilledFiles.length, artifact.migrations.length); assert.deepEqual(repaired.appliedFiles, []);
77
+ assert.equal((await checkReadinessFor(jsonl, config)).ready, true);
78
+ });
79
+ await t.test('Kernel.readiness and real /health/ready expose the same ledger decision', async () => {
80
+ const dir = mkdtempSync(join(tmpdir(), 'readiness-kernel-'));
81
+ const runtime: AppConfig = { root: process.cwd(), runtimeRoot: dir, env: 'development',
82
+ server: { host: '127.0.0.1', port: 0, token: '' }, brand: { name: 'Synthetic readiness test' },
83
+ displayTz: 'Asia/Shanghai', displayTzLabel: '北京时间', auditRetentionDays: 0, alerts: null,
84
+ metrics: { enabled: false, token: '', scrapeTimeoutMs: 1000 }, bootstrapAdmin: null,
85
+ concurrency: 1, killSwitchFile: join(dir, '.paused'), claudeBin: 'synthetic-unused', defaultProfile: 'readonly', brainDir: join(dir, 'brain'),
86
+ state: { backend: 'mysql', jsonlPath: join(dir, 'jobs.jsonl'), mysql: { ...base, database: names[0]! } }, projects: {}, llmCredentials: {},
87
+ executor: { hubUrl: '', token: '', executorId: 'synthetic', targets: [], waitMs: 100, concurrency: 1, labels: [] } };
88
+ const kernel = createBailingHubKernel({ instanceKey: prefix, config: runtime, schedulerMode: 'managed', bootstrapLocalAdmin: false,
89
+ logger: { log() {}, warn() {}, error() {} } });
90
+ const server = createServer((req, res) => { void kernel.handle(req, res, new URL(req.url ?? '/', 'http://local')).catch(() => { res.statusCode = 500; res.end(); }); });
91
+ try {
92
+ await kernel.initialize();
93
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
94
+ const address = server.address(); assert.ok(address && typeof address !== 'string');
95
+ const url = `http://127.0.0.1:${address.port}/health/ready`;
96
+ assert.equal((await kernel.readiness()).ready, true); assert.equal((await fetch(url)).status, 200);
97
+ await pools[0]!.query('UPDATE bz_schema_migrations SET checksum_sha256=NULL WHERE filename=?', [latest.filename]);
98
+ assert.equal((await kernel.readiness()).ready, false);
99
+ const failed = await fetch(url); assert.equal(failed.status, 503);
100
+ const body = await failed.json() as { status: string; checks: { migrations: { status: string } } };
101
+ assert.equal(body.status, 'not_ready'); assert.equal(body.checks.migrations.status, 'failed');
102
+ assert.doesNotMatch(JSON.stringify(body), /password|127\.0\.0\.1|checksum_sha256/);
103
+ await pools[0]!.query('UPDATE bz_schema_migrations SET checksum_sha256=? WHERE filename=?', [latest.checksumSha256, latest.filename]);
104
+ assert.equal((await kernel.readiness()).ready, true); assert.equal((await fetch(url)).status, 200);
105
+ } finally {
106
+ server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve()));
107
+ await kernel.close(); rmSync(dir, { recursive: true, force: true });
108
+ }
109
+ });
110
+ await t.test('both existing pools remain usable after repeated readiness calls', async () => {
111
+ for (let i = 0; i < 3; i++) assert.equal((await checkReadinessFor(cfg, config, state)).ready, true);
112
+ for (const pool of pools) await pool.query('SELECT 1');
113
+ });
114
+ } finally {
115
+ for (const pool of pools) await pool.end();
116
+ for (const name of created) { assert.match(name, new RegExp(`^${prefix}_(state|config)$`)); await admin.query(`DROP DATABASE \`${name}\``); }
117
+ const [left] = await admin.query<RowDataPacket[]>('SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME LIKE ?', [`${prefix}_%`]);
118
+ assert.equal(left.length, 0); t.diagnostic(`cleaned ${created.length} random schemas; no leftovers`); await admin.end();
119
+ }
120
+ });
@@ -1,37 +1,122 @@
1
1
  import test from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
- import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
4
- import { tmpdir } from 'node:os';
5
- import { join } from 'node:path';
3
+ import type { Pool } from 'mysql2/promise';
6
4
  import type { AppConfig } from '../core/config/config';
7
5
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
6
+ import type { SchemaReadinessDatabase } from '../core/contracts/schema-readiness';
7
+ import { BAILINGHUB_CORE_ARTIFACT_V1 as artifact } from '../kernel-api/v1/artifact';
8
+ import { MysqlStore } from '../infrastructure/state/state-mysql';
8
9
  import { checkReadinessFor } from './readiness';
9
10
 
10
- test('checkReadinessFor: MySQL 可达且迁移齐全才 ready', async () => {
11
- const root = mkdtempSync(join(tmpdir(), 'bailing-ready-'));
12
- try {
13
- mkdirSync(join(root, 'sql'));
14
- writeFileSync(join(root, 'sql', '001_init.sql'), 'SELECT 1;');
15
- const cfg = { root, state: { backend: 'mysql' } } as unknown as AppConfig;
16
- const store = {
17
- db: { query: async () => [[]] },
18
- observability: { listSchemaMigrations: async () => ['001_init.sql'] },
19
- } as unknown as ConfigStoreContract;
20
- assert.equal((await checkReadinessFor(cfg, store)).ready, true);
21
- (store.observability.listSchemaMigrations as () => Promise<string[]>) = async () => [];
22
- const pending = await checkReadinessFor(cfg, store);
23
- assert.equal(pending.ready, false);
24
- assert.deepEqual(pending.checks.migrations, { status: 'pending', pending: 1 });
25
- } finally {
26
- rmSync(root, { recursive: true, force: true });
11
+ const cfg = (backend: 'mysql' | 'jsonl' = 'mysql') => ({ root: '/not-the-installed-artifact', state: { backend } }) as AppConfig;
12
+ const rows = () => artifact.migrations.map(file => ({ filename: file.filename, checksum_sha256: file.checksumSha256 }));
13
+ function database(payload: unknown = rows(), fail?: 'connection' | 'ledger') {
14
+ const queries: string[] = [];
15
+ const db: SchemaReadinessDatabase = { query: async sql => {
16
+ queries.push(sql);
17
+ assert.ok(sql === 'SELECT 1' || sql === 'SELECT filename, checksum_sha256 FROM bz_schema_migrations ORDER BY filename', 'only fixed read-only queries');
18
+ if (fail === 'connection' || (fail === 'ledger' && sql !== 'SELECT 1')) throw new Error('mysql://secret@internal SQL error');
19
+ return [sql === 'SELECT 1' ? [{ one: 1 }] : payload, []];
20
+ } };
21
+ return { db, queries };
22
+ }
23
+ const config = (db: SchemaReadinessDatabase) => ({ db }) as ConfigStoreContract;
24
+ const state = (db: SchemaReadinessDatabase) => ({ schemaReadinessDb: db });
25
+
26
+ test('shared actual pool is checked once; installed artifact does not depend on cfg.root', async () => {
27
+ const { db, queries } = database();
28
+ assert.deepEqual(await checkReadinessFor(cfg(), config(db), state(db)), {
29
+ ready: true, checks: { state_backend: 'ok', database: 'ok', migrations: { status: 'ok', pending: 0 } },
30
+ });
31
+ assert.equal(queries.length, 2);
32
+ });
33
+
34
+ for (const missing of ['state', 'configuration']) {
35
+ test(`split MySQL: missing migration on ${missing} prevents ready`, async () => {
36
+ const stateDb = database(missing === 'state' ? rows().slice(0, -1) : rows());
37
+ const configDb = database(missing === 'configuration' ? rows().slice(0, -1) : rows());
38
+ const report = await checkReadinessFor(cfg(), config(configDb.db), state(stateDb.db));
39
+ assert.equal(report.ready, false);
40
+ assert.deepEqual(report.checks.migrations, { status: 'pending', pending: 1 });
41
+ assert.equal(stateDb.queries.length, 2); assert.equal(configDb.queries.length, 2);
42
+ });
43
+ }
44
+
45
+ test('pure JSONL skips SQL; JSONL state with a MySQL config still checks configuration', async () => {
46
+ assert.equal((await checkReadinessFor(cfg('jsonl'), null)).checks.database, 'skipped');
47
+ const incomplete = database(rows().slice(0, -1));
48
+ const report = await checkReadinessFor(cfg('jsonl'), config(incomplete.db));
49
+ assert.equal(report.ready, false); assert.equal(report.checks.migrations.pending, 1);
50
+ assert.equal(incomplete.queries.length, 2);
51
+ });
52
+
53
+ test('custom MySQL store without an actual probe fails closed; no fallback connection', async () => {
54
+ const { db, queries } = database();
55
+ const report = await checkReadinessFor(cfg(), config(db), {});
56
+ assert.equal(report.ready, false); assert.equal(report.checks.database, 'failed'); assert.equal(queries.length, 0);
57
+ });
58
+
59
+ test('existing MysqlStore pool is reused across probes, never closed or reacquired by readiness', async () => {
60
+ const { db } = database(); let gets = 0; let closes = 0;
61
+ const store = new MysqlStore({} as AppConfig['state']['mysql'], { get: async () => { gets++; return db as Pool; }, close: async () => { closes++; } });
62
+ await store.init();
63
+ for (let index = 0; index < 3; index++) assert.equal((await checkReadinessFor(cfg(), config(db), store)).ready, true);
64
+ assert.equal(gets, 1); assert.equal(closes, 0); assert.equal(store.schemaReadinessDb, db);
65
+ await store.close(); assert.equal(closes, 1);
66
+ });
67
+
68
+ for (const value of [null, '', ' ', '0'.repeat(64), 'invalid', undefined, 123]) {
69
+ test(`missing/malformed/conflicting checksum (${String(value)}) is not ready and is never backfilled`, async () => {
70
+ const payload: Array<Record<string, unknown>> = rows(); payload[0] = { ...payload[0], checksum_sha256: value };
71
+ const original = structuredClone(payload); const { db } = database(payload);
72
+ const report = await checkReadinessFor(cfg(), config(db), state(db));
73
+ assert.equal(report.ready, false); assert.equal(report.checks.migrations.status, 'failed'); assert.deepEqual(payload, original);
74
+ });
75
+ }
76
+
77
+ test('unknown future and duplicate migration rows fail closed', async () => {
78
+ for (const payload of [[...rows(), { filename: '999_future.sql', checksum_sha256: '0'.repeat(64) }], [...rows(), rows()[0]]]) {
79
+ const { db } = database(payload);
80
+ assert.equal((await checkReadinessFor(cfg(), config(db), state(db))).checks.migrations.status, 'failed');
81
+ }
82
+ });
83
+
84
+ test('retired history is optional, never pending; a present retired record must match its checksum', async () => {
85
+ const retired = artifact.retiredMigrations[0]; assert.ok(retired);
86
+ for (const checksum of [retired.checksumSha256, '0'.repeat(64), null]) {
87
+ const { db } = database([...rows(), { filename: retired.filename, checksum_sha256: checksum }]);
88
+ const report = await checkReadinessFor(cfg(), config(db), state(db));
89
+ assert.equal(report.ready, checksum === retired.checksumSha256); assert.equal(report.checks.migrations.pending, 0);
27
90
  }
28
91
  });
29
92
 
30
- test('checkReadinessFor: 数据库异常只输出稳定状态', async () => {
31
- const cfg = { root: process.cwd(), state: { backend: 'mysql' } } as unknown as AppConfig;
32
- const store = { db: { query: async () => { throw new Error('mysql://secret@internal'); } } } as unknown as ConfigStoreContract;
33
- assert.deepEqual(await checkReadinessFor(cfg, store), {
34
- ready: false,
35
- checks: { state_backend: 'ok', database: 'failed', migrations: { status: 'failed', pending: 0 } },
93
+ test('checksum normalization matches the migrator; invalid ledger shapes fail closed', async () => {
94
+ const upper = rows().map(row => ({ ...row, checksum_sha256: ` ${row.checksum_sha256.toUpperCase()} ` }));
95
+ const valid = database(upper).db; assert.equal((await checkReadinessFor(cfg(), config(valid), state(valid))).ready, true);
96
+ for (const payload of [undefined, {}, [null], [['invalid']], [{ filename: 1, checksum_sha256: '0'.repeat(64) }]]) {
97
+ const { db } = database(payload === undefined ? null : payload);
98
+ assert.equal((await checkReadinessFor(cfg(), config(db), state(db))).ready, false);
99
+ }
100
+ });
101
+
102
+ for (const fault of ['connection', 'ledger'] as const) {
103
+ test(`unreachable DB or absent ledger/checksum column (${fault}) exposes stable states only`, async () => {
104
+ const { db } = database(rows(), fault);
105
+ const report = await checkReadinessFor(cfg(), config(db), state(db));
106
+ assert.equal(report.ready, false); assert.equal(report.checks.database, fault === 'connection' ? 'failed' : 'ok');
107
+ assert.equal(report.checks.migrations.status, 'failed'); assert.doesNotMatch(JSON.stringify(report), /secret|internal|SQL/);
36
108
  });
109
+ }
110
+
111
+ test('adapter getter failure is contained without leaking connection details', async () => {
112
+ const broken = { get schemaReadinessDb(): SchemaReadinessDatabase { throw new Error('mysql://secret@internal'); } };
113
+ const { db } = database(); const report = await checkReadinessFor(cfg(), config(db), broken);
114
+ assert.equal(report.ready, false); assert.doesNotMatch(JSON.stringify(report), /secret|internal/);
115
+ });
116
+
117
+ test('pending counts distinct missing files across distinct pools without skipping either probe', async () => {
118
+ const first = database(rows().slice(0, -1)); const second = database(rows().slice(0, -1));
119
+ const report = await checkReadinessFor(cfg(), config(first.db), state(second.db));
120
+ assert.equal(report.ready, false); assert.equal(report.checks.migrations.pending, 1);
121
+ assert.equal(first.queries.length, 2); assert.equal(second.queries.length, 2);
37
122
  });