@apralabs/apra-fleet 0.4.0 → 0.4.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 (427) hide show
  1. package/README.md +145 -7
  2. package/dist/agents/backlog-groomer.md +17 -1
  3. package/dist/agents/ci-watcher.md +13 -1
  4. package/dist/agents/deployer.md +15 -3
  5. package/dist/agents/doer.md +35 -1
  6. package/dist/agents/harvester.md +22 -3
  7. package/dist/agents/integ-test-runner.md +18 -2
  8. package/dist/agents/kb-reconciler.md +216 -0
  9. package/dist/agents/plan-reviewer.md +14 -1
  10. package/dist/agents/planner.md +88 -5
  11. package/dist/agents/regression-test-runner.md +19 -1
  12. package/dist/agents/reviewer.md +104 -3
  13. package/dist/agents/schemas/doer-output.json +63 -3
  14. package/dist/agents/schemas/harvester-output.json +59 -2
  15. package/dist/agents/schemas/integ-test-runner-output.json +2 -2
  16. package/dist/agents/schemas/kb-reconciler-output.json +87 -0
  17. package/dist/agents/schemas/planner-output.json +65 -0
  18. package/dist/agents/schemas/reviewer-output.json +105 -8
  19. package/dist/cli/install.d.ts +1 -0
  20. package/dist/cli/install.d.ts.map +1 -1
  21. package/dist/cli/install.js +136 -5
  22. package/dist/cli/install.js.map +1 -1
  23. package/dist/cli/join.js +1 -1
  24. package/dist/cli/join.js.map +1 -1
  25. package/dist/cli/kb-commit.d.ts +12 -0
  26. package/dist/cli/kb-commit.d.ts.map +1 -0
  27. package/dist/cli/kb-commit.js +53 -0
  28. package/dist/cli/kb-commit.js.map +1 -0
  29. package/dist/cli/kb-directives.d.ts +17 -0
  30. package/dist/cli/kb-directives.d.ts.map +1 -0
  31. package/dist/cli/kb-directives.js +146 -0
  32. package/dist/cli/kb-directives.js.map +1 -0
  33. package/dist/cli/kb-import.d.ts +13 -0
  34. package/dist/cli/kb-import.d.ts.map +1 -0
  35. package/dist/cli/kb-import.js +56 -0
  36. package/dist/cli/kb-import.js.map +1 -0
  37. package/dist/cli/uninstall.d.ts.map +1 -1
  38. package/dist/cli/uninstall.js +11 -0
  39. package/dist/cli/uninstall.js.map +1 -1
  40. package/dist/cli/watch.d.ts +53 -4
  41. package/dist/cli/watch.d.ts.map +1 -1
  42. package/dist/cli/watch.js +118 -17
  43. package/dist/cli/watch.js.map +1 -1
  44. package/dist/commands/kb-server.d.ts +8 -0
  45. package/dist/commands/kb-server.d.ts.map +1 -0
  46. package/dist/commands/kb-server.js +221 -0
  47. package/dist/commands/kb-server.js.map +1 -0
  48. package/dist/index.js +77 -2
  49. package/dist/index.js.map +1 -1
  50. package/dist/os/linux.d.ts +1 -0
  51. package/dist/os/linux.d.ts.map +1 -1
  52. package/dist/os/linux.js +18 -1
  53. package/dist/os/linux.js.map +1 -1
  54. package/dist/os/os-commands.d.ts +5 -0
  55. package/dist/os/os-commands.d.ts.map +1 -1
  56. package/dist/os/windows.d.ts +35 -0
  57. package/dist/os/windows.d.ts.map +1 -1
  58. package/dist/os/windows.js +67 -31
  59. package/dist/os/windows.js.map +1 -1
  60. package/dist/providers/agy.d.ts +12 -1
  61. package/dist/providers/agy.d.ts.map +1 -1
  62. package/dist/providers/agy.js +134 -9
  63. package/dist/providers/agy.js.map +1 -1
  64. package/dist/providers/claude.d.ts +11 -1
  65. package/dist/providers/claude.d.ts.map +1 -1
  66. package/dist/providers/claude.js +47 -19
  67. package/dist/providers/claude.js.map +1 -1
  68. package/dist/providers/codex.d.ts +11 -1
  69. package/dist/providers/codex.d.ts.map +1 -1
  70. package/dist/providers/codex.js +29 -6
  71. package/dist/providers/codex.js.map +1 -1
  72. package/dist/providers/copilot.d.ts +11 -1
  73. package/dist/providers/copilot.d.ts.map +1 -1
  74. package/dist/providers/copilot.js +26 -6
  75. package/dist/providers/copilot.js.map +1 -1
  76. package/dist/providers/email/headers.d.ts +15 -0
  77. package/dist/providers/email/headers.d.ts.map +1 -0
  78. package/dist/providers/email/headers.js +42 -0
  79. package/dist/providers/email/headers.js.map +1 -0
  80. package/dist/providers/email/index.d.ts +18 -0
  81. package/dist/providers/email/index.d.ts.map +1 -0
  82. package/dist/providers/email/index.js +60 -0
  83. package/dist/providers/email/index.js.map +1 -0
  84. package/dist/providers/email/provider.d.ts +49 -0
  85. package/dist/providers/email/provider.d.ts.map +1 -0
  86. package/dist/providers/email/provider.js +2 -0
  87. package/dist/providers/email/provider.js.map +1 -0
  88. package/dist/providers/email/sendgrid.d.ts +12 -0
  89. package/dist/providers/email/sendgrid.d.ts.map +1 -0
  90. package/dist/providers/email/sendgrid.js +67 -0
  91. package/dist/providers/email/sendgrid.js.map +1 -0
  92. package/dist/providers/email/smtp.d.ts +65 -0
  93. package/dist/providers/email/smtp.d.ts.map +1 -0
  94. package/dist/providers/email/smtp.js +373 -0
  95. package/dist/providers/email/smtp.js.map +1 -0
  96. package/dist/providers/gemini.d.ts +11 -1
  97. package/dist/providers/gemini.d.ts.map +1 -1
  98. package/dist/providers/gemini.js +38 -4
  99. package/dist/providers/gemini.js.map +1 -1
  100. package/dist/providers/none.d.ts +11 -1
  101. package/dist/providers/none.d.ts.map +1 -1
  102. package/dist/providers/none.js +21 -0
  103. package/dist/providers/none.js.map +1 -1
  104. package/dist/providers/opencode.d.ts +11 -1
  105. package/dist/providers/opencode.d.ts.map +1 -1
  106. package/dist/providers/opencode.js +55 -4
  107. package/dist/providers/opencode.js.map +1 -1
  108. package/dist/providers/provider.d.ts +77 -0
  109. package/dist/providers/provider.d.ts.map +1 -1
  110. package/dist/providers/provider.js +44 -0
  111. package/dist/providers/provider.js.map +1 -1
  112. package/dist/services/agent-provisioner.d.ts.map +1 -1
  113. package/dist/services/agent-provisioner.js +3 -6
  114. package/dist/services/agent-provisioner.js.map +1 -1
  115. package/dist/services/cloud/lifecycle.d.ts.map +1 -1
  116. package/dist/services/cloud/lifecycle.js +3 -0
  117. package/dist/services/cloud/lifecycle.js.map +1 -1
  118. package/dist/services/cloud/task-wrapper.d.ts +18 -0
  119. package/dist/services/cloud/task-wrapper.d.ts.map +1 -1
  120. package/dist/services/cloud/task-wrapper.js +157 -0
  121. package/dist/services/cloud/task-wrapper.js.map +1 -1
  122. package/dist/services/github-app.d.ts.map +1 -1
  123. package/dist/services/github-app.js +11 -2
  124. package/dist/services/github-app.js.map +1 -1
  125. package/dist/services/knowledge/audn.d.ts +37 -0
  126. package/dist/services/knowledge/audn.d.ts.map +1 -0
  127. package/dist/services/knowledge/audn.js +219 -0
  128. package/dist/services/knowledge/audn.js.map +1 -0
  129. package/dist/services/knowledge/file-hash.d.ts +11 -0
  130. package/dist/services/knowledge/file-hash.d.ts.map +1 -0
  131. package/dist/services/knowledge/file-hash.js +123 -0
  132. package/dist/services/knowledge/file-hash.js.map +1 -0
  133. package/dist/services/knowledge/http-provider.d.ts +46 -0
  134. package/dist/services/knowledge/http-provider.d.ts.map +1 -0
  135. package/dist/services/knowledge/http-provider.js +254 -0
  136. package/dist/services/knowledge/http-provider.js.map +1 -0
  137. package/dist/services/knowledge/kb-providers.d.ts +15 -0
  138. package/dist/services/knowledge/kb-providers.d.ts.map +1 -0
  139. package/dist/services/knowledge/kb-providers.js +92 -0
  140. package/dist/services/knowledge/kb-providers.js.map +1 -0
  141. package/dist/services/knowledge/kb-scope-input.d.ts +5 -0
  142. package/dist/services/knowledge/kb-scope-input.d.ts.map +1 -0
  143. package/dist/services/knowledge/kb-scope-input.js +11 -0
  144. package/dist/services/knowledge/kb-scope-input.js.map +1 -0
  145. package/dist/services/knowledge/kb-service.d.ts +3 -0
  146. package/dist/services/knowledge/kb-service.d.ts.map +1 -0
  147. package/dist/services/knowledge/kb-service.js +2 -0
  148. package/dist/services/knowledge/kb-service.js.map +1 -0
  149. package/dist/services/knowledge/path-validation.d.ts +2 -0
  150. package/dist/services/knowledge/path-validation.d.ts.map +1 -0
  151. package/dist/services/knowledge/path-validation.js +13 -0
  152. package/dist/services/knowledge/path-validation.js.map +1 -0
  153. package/dist/services/knowledge/pre-init.d.ts +14 -0
  154. package/dist/services/knowledge/pre-init.d.ts.map +1 -0
  155. package/dist/services/knowledge/pre-init.js +147 -0
  156. package/dist/services/knowledge/pre-init.js.map +1 -0
  157. package/dist/services/knowledge/project-slug.d.ts +2 -0
  158. package/dist/services/knowledge/project-slug.d.ts.map +1 -0
  159. package/dist/services/knowledge/project-slug.js +49 -0
  160. package/dist/services/knowledge/project-slug.js.map +1 -0
  161. package/dist/services/knowledge/sqlite-provider.d.ts +147 -0
  162. package/dist/services/knowledge/sqlite-provider.d.ts.map +1 -0
  163. package/dist/services/knowledge/sqlite-provider.js +1646 -0
  164. package/dist/services/knowledge/sqlite-provider.js.map +1 -0
  165. package/dist/services/knowledge/types.d.ts +163 -0
  166. package/dist/services/knowledge/types.d.ts.map +1 -0
  167. package/dist/services/knowledge/types.js +9 -0
  168. package/dist/services/knowledge/types.js.map +1 -0
  169. package/dist/services/member-home.d.ts +89 -0
  170. package/dist/services/member-home.d.ts.map +1 -0
  171. package/dist/services/member-home.js +256 -0
  172. package/dist/services/member-home.js.map +1 -0
  173. package/dist/services/member-remote-url.d.ts +34 -0
  174. package/dist/services/member-remote-url.d.ts.map +1 -0
  175. package/dist/services/member-remote-url.js +39 -0
  176. package/dist/services/member-remote-url.js.map +1 -0
  177. package/dist/services/orphan-recovery.d.ts +5 -2
  178. package/dist/services/orphan-recovery.d.ts.map +1 -1
  179. package/dist/services/orphan-recovery.js +19 -8
  180. package/dist/services/orphan-recovery.js.map +1 -1
  181. package/dist/services/preflight-check.d.ts +56 -0
  182. package/dist/services/preflight-check.d.ts.map +1 -0
  183. package/dist/services/preflight-check.js +277 -0
  184. package/dist/services/preflight-check.js.map +1 -0
  185. package/dist/services/stall/log-path-resolver.d.ts +11 -8
  186. package/dist/services/stall/log-path-resolver.d.ts.map +1 -1
  187. package/dist/services/stall/log-path-resolver.js +17 -40
  188. package/dist/services/stall/log-path-resolver.js.map +1 -1
  189. package/dist/services/stall/stall-detector.d.ts +32 -0
  190. package/dist/services/stall/stall-detector.d.ts.map +1 -1
  191. package/dist/services/stall/stall-detector.js +149 -6
  192. package/dist/services/stall/stall-detector.js.map +1 -1
  193. package/dist/services/stall/stall-poller.d.ts +34 -0
  194. package/dist/services/stall/stall-poller.d.ts.map +1 -1
  195. package/dist/services/stall/stall-poller.js +134 -2
  196. package/dist/services/stall/stall-poller.js.map +1 -1
  197. package/dist/services/strategy.d.ts.map +1 -1
  198. package/dist/services/strategy.js +2 -2
  199. package/dist/services/strategy.js.map +1 -1
  200. package/dist/services/tool-registry.d.ts.map +1 -1
  201. package/dist/services/tool-registry.js +87 -1
  202. package/dist/services/tool-registry.js.map +1 -1
  203. package/dist/services/vcs/github.d.ts.map +1 -1
  204. package/dist/services/vcs/github.js +32 -1
  205. package/dist/services/vcs/github.js.map +1 -1
  206. package/dist/services/version-check.d.ts +22 -0
  207. package/dist/services/version-check.d.ts.map +1 -0
  208. package/dist/services/version-check.js +103 -0
  209. package/dist/services/version-check.js.map +1 -0
  210. package/dist/skills/fleet-sprint-cli/SKILL.md +13 -2
  211. package/dist/skills/pm/beads.md +6 -0
  212. package/dist/skills/pm/fleet-addendum.md +6 -0
  213. package/dist/skills/pm/index.md +56 -0
  214. package/dist/skills/pm/kb-reconcile.md +132 -0
  215. package/dist/skills/pm/kb-review.md +109 -0
  216. package/dist/tools/check-status.d.ts +47 -0
  217. package/dist/tools/check-status.d.ts.map +1 -1
  218. package/dist/tools/check-status.js +242 -0
  219. package/dist/tools/check-status.js.map +1 -1
  220. package/dist/tools/child-id-allocator.d.ts +2 -2
  221. package/dist/tools/code-intelligence-codebase-memory.d.ts +11 -0
  222. package/dist/tools/code-intelligence-codebase-memory.d.ts.map +1 -0
  223. package/dist/tools/code-intelligence-codebase-memory.js +270 -0
  224. package/dist/tools/code-intelligence-codebase-memory.js.map +1 -0
  225. package/dist/tools/code-intelligence-freshness.d.ts +2 -0
  226. package/dist/tools/code-intelligence-freshness.d.ts.map +1 -0
  227. package/dist/tools/code-intelligence-freshness.js +26 -0
  228. package/dist/tools/code-intelligence-freshness.js.map +1 -0
  229. package/dist/tools/code-intelligence-gitnexus.d.ts +14 -0
  230. package/dist/tools/code-intelligence-gitnexus.d.ts.map +1 -0
  231. package/dist/tools/code-intelligence-gitnexus.js +475 -0
  232. package/dist/tools/code-intelligence-gitnexus.js.map +1 -0
  233. package/dist/tools/code-intelligence-kb-enrich.d.ts +2 -0
  234. package/dist/tools/code-intelligence-kb-enrich.d.ts.map +1 -0
  235. package/dist/tools/code-intelligence-kb-enrich.js +65 -0
  236. package/dist/tools/code-intelligence-kb-enrich.js.map +1 -0
  237. package/dist/tools/code-intelligence-reindex.d.ts +7 -0
  238. package/dist/tools/code-intelligence-reindex.d.ts.map +1 -0
  239. package/dist/tools/code-intelligence-reindex.js +106 -0
  240. package/dist/tools/code-intelligence-reindex.js.map +1 -0
  241. package/dist/tools/code-intelligence-telemetry.d.ts +5 -0
  242. package/dist/tools/code-intelligence-telemetry.d.ts.map +1 -0
  243. package/dist/tools/code-intelligence-telemetry.js +52 -0
  244. package/dist/tools/code-intelligence-telemetry.js.map +1 -0
  245. package/dist/tools/code-intelligence-tests.d.ts +2 -0
  246. package/dist/tools/code-intelligence-tests.d.ts.map +1 -0
  247. package/dist/tools/code-intelligence-tests.js +24 -0
  248. package/dist/tools/code-intelligence-tests.js.map +1 -0
  249. package/dist/tools/code-intelligence.d.ts +114 -0
  250. package/dist/tools/code-intelligence.d.ts.map +1 -0
  251. package/dist/tools/code-intelligence.js +124 -0
  252. package/dist/tools/code-intelligence.js.map +1 -0
  253. package/dist/tools/compose-permissions.d.ts +26 -0
  254. package/dist/tools/compose-permissions.d.ts.map +1 -1
  255. package/dist/tools/compose-permissions.js +244 -33
  256. package/dist/tools/compose-permissions.js.map +1 -1
  257. package/dist/tools/execute-command.d.ts +2 -0
  258. package/dist/tools/execute-command.d.ts.map +1 -1
  259. package/dist/tools/execute-command.js +86 -16
  260. package/dist/tools/execute-command.js.map +1 -1
  261. package/dist/tools/execute-prompt.d.ts +13 -1
  262. package/dist/tools/execute-prompt.d.ts.map +1 -1
  263. package/dist/tools/execute-prompt.js +257 -45
  264. package/dist/tools/execute-prompt.js.map +1 -1
  265. package/dist/tools/kb-capture.d.ts +53 -0
  266. package/dist/tools/kb-capture.d.ts.map +1 -0
  267. package/dist/tools/kb-capture.js +130 -0
  268. package/dist/tools/kb-capture.js.map +1 -0
  269. package/dist/tools/kb-context.d.ts +17 -0
  270. package/dist/tools/kb-context.d.ts.map +1 -0
  271. package/dist/tools/kb-context.js +29 -0
  272. package/dist/tools/kb-context.js.map +1 -0
  273. package/dist/tools/kb-export.d.ts +19 -0
  274. package/dist/tools/kb-export.d.ts.map +1 -0
  275. package/dist/tools/kb-export.js +344 -0
  276. package/dist/tools/kb-export.js.map +1 -0
  277. package/dist/tools/kb-feedback.d.ts +23 -0
  278. package/dist/tools/kb-feedback.d.ts.map +1 -0
  279. package/dist/tools/kb-feedback.js +43 -0
  280. package/dist/tools/kb-feedback.js.map +1 -0
  281. package/dist/tools/kb-freshness-sweep.d.ts +14 -0
  282. package/dist/tools/kb-freshness-sweep.d.ts.map +1 -0
  283. package/dist/tools/kb-freshness-sweep.js +29 -0
  284. package/dist/tools/kb-freshness-sweep.js.map +1 -0
  285. package/dist/tools/kb-harvest.d.ts +20 -0
  286. package/dist/tools/kb-harvest.d.ts.map +1 -0
  287. package/dist/tools/kb-harvest.js +143 -0
  288. package/dist/tools/kb-harvest.js.map +1 -0
  289. package/dist/tools/kb-import.d.ts +44 -0
  290. package/dist/tools/kb-import.d.ts.map +1 -0
  291. package/dist/tools/kb-import.js +239 -0
  292. package/dist/tools/kb-import.js.map +1 -0
  293. package/dist/tools/kb-invalidate.d.ts +19 -0
  294. package/dist/tools/kb-invalidate.d.ts.map +1 -0
  295. package/dist/tools/kb-invalidate.js +34 -0
  296. package/dist/tools/kb-invalidate.js.map +1 -0
  297. package/dist/tools/kb-list.d.ts +32 -0
  298. package/dist/tools/kb-list.d.ts.map +1 -0
  299. package/dist/tools/kb-list.js +43 -0
  300. package/dist/tools/kb-list.js.map +1 -0
  301. package/dist/tools/kb-promote.d.ts +20 -0
  302. package/dist/tools/kb-promote.d.ts.map +1 -0
  303. package/dist/tools/kb-promote.js +20 -0
  304. package/dist/tools/kb-promote.js.map +1 -0
  305. package/dist/tools/kb-query.d.ts +35 -0
  306. package/dist/tools/kb-query.d.ts.map +1 -0
  307. package/dist/tools/kb-query.js +111 -0
  308. package/dist/tools/kb-query.js.map +1 -0
  309. package/dist/tools/kb-reconcile-prefilter.d.ts +14 -0
  310. package/dist/tools/kb-reconcile-prefilter.d.ts.map +1 -0
  311. package/dist/tools/kb-reconcile-prefilter.js +26 -0
  312. package/dist/tools/kb-reconcile-prefilter.js.map +1 -0
  313. package/dist/tools/kb-resolve-contradiction.d.ts +23 -0
  314. package/dist/tools/kb-resolve-contradiction.d.ts.map +1 -0
  315. package/dist/tools/kb-resolve-contradiction.js +37 -0
  316. package/dist/tools/kb-resolve-contradiction.js.map +1 -0
  317. package/dist/tools/kb-session-prime.d.ts +26 -0
  318. package/dist/tools/kb-session-prime.d.ts.map +1 -0
  319. package/dist/tools/kb-session-prime.js +392 -0
  320. package/dist/tools/kb-session-prime.js.map +1 -0
  321. package/dist/tools/kb-setup.d.ts +20 -0
  322. package/dist/tools/kb-setup.d.ts.map +1 -0
  323. package/dist/tools/kb-setup.js +49 -0
  324. package/dist/tools/kb-setup.js.map +1 -0
  325. package/dist/tools/kb-stats.d.ts +20 -0
  326. package/dist/tools/kb-stats.d.ts.map +1 -0
  327. package/dist/tools/kb-stats.js +115 -0
  328. package/dist/tools/kb-stats.js.map +1 -0
  329. package/dist/tools/member-detail.d.ts.map +1 -1
  330. package/dist/tools/member-detail.js +8 -0
  331. package/dist/tools/member-detail.js.map +1 -1
  332. package/dist/tools/monitor-task.d.ts.map +1 -1
  333. package/dist/tools/monitor-task.js +21 -3
  334. package/dist/tools/monitor-task.js.map +1 -1
  335. package/dist/tools/provision-auth.d.ts.map +1 -1
  336. package/dist/tools/provision-auth.js +10 -3
  337. package/dist/tools/provision-auth.js.map +1 -1
  338. package/dist/tools/register-member.d.ts +3 -0
  339. package/dist/tools/register-member.d.ts.map +1 -1
  340. package/dist/tools/register-member.js +30 -1
  341. package/dist/tools/register-member.js.map +1 -1
  342. package/dist/tools/remove-member.d.ts.map +1 -1
  343. package/dist/tools/remove-member.js +17 -3
  344. package/dist/tools/remove-member.js.map +1 -1
  345. package/dist/tools/report-status.d.ts.map +1 -1
  346. package/dist/tools/report-status.js +2 -1
  347. package/dist/tools/report-status.js.map +1 -1
  348. package/dist/tools/send-email.d.ts +69 -0
  349. package/dist/tools/send-email.d.ts.map +1 -0
  350. package/dist/tools/send-email.js +177 -0
  351. package/dist/tools/send-email.js.map +1 -0
  352. package/dist/tools/setup-ssh-key.d.ts.map +1 -1
  353. package/dist/tools/setup-ssh-key.js +2 -0
  354. package/dist/tools/setup-ssh-key.js.map +1 -1
  355. package/dist/tools/update-member.d.ts +3 -0
  356. package/dist/tools/update-member.d.ts.map +1 -1
  357. package/dist/tools/update-member.js +25 -1
  358. package/dist/tools/update-member.js.map +1 -1
  359. package/dist/types.d.ts +1 -0
  360. package/dist/types.d.ts.map +1 -1
  361. package/dist/utils/prompt-errors.js +1 -1
  362. package/dist/utils/prompt-errors.js.map +1 -1
  363. package/dist/utils/session-caller.d.ts +28 -0
  364. package/dist/utils/session-caller.d.ts.map +1 -0
  365. package/dist/utils/session-caller.js +24 -0
  366. package/dist/utils/session-caller.js.map +1 -0
  367. package/dist/utils/work-folder-validation.d.ts +39 -0
  368. package/dist/utils/work-folder-validation.d.ts.map +1 -0
  369. package/dist/utils/work-folder-validation.js +60 -0
  370. package/dist/utils/work-folder-validation.js.map +1 -0
  371. package/dist/workflows/auto-sprint.js +546 -6
  372. package/package.json +7 -4
  373. package/packages/apra-fleet-client/src/client/api.mjs +118 -4
  374. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +17 -1
  375. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +13 -1
  376. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +15 -3
  377. package/packages/apra-fleet-se/apra-pm/agents/doer.md +35 -1
  378. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +22 -3
  379. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +18 -2
  380. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +216 -0
  381. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +14 -1
  382. package/packages/apra-fleet-se/apra-pm/agents/planner.md +88 -5
  383. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +19 -1
  384. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +104 -3
  385. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +63 -3
  386. package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-output.json +59 -2
  387. package/packages/apra-fleet-se/apra-pm/agents/schemas/integ-test-runner-output.json +2 -2
  388. package/packages/apra-fleet-se/apra-pm/agents/schemas/kb-reconciler-output.json +87 -0
  389. package/packages/apra-fleet-se/apra-pm/agents/schemas/planner-output.json +65 -0
  390. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +105 -8
  391. package/packages/apra-fleet-se/apra-pm/skills/pm/beads.md +6 -0
  392. package/packages/apra-fleet-se/apra-pm/skills/pm/fleet-addendum.md +6 -0
  393. package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +56 -0
  394. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-reconcile.md +132 -0
  395. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-review.md +109 -0
  396. package/packages/apra-fleet-se/bin/cli.mjs +7 -0
  397. package/packages/apra-fleet-se/bin/serve.mjs +14 -2
  398. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +31 -5
  399. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +1 -1
  400. package/packages/apra-fleet-se/fleet-sprint/docs/coach-role-design.md +23 -151
  401. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-manual-recovery-verified.md +256 -0
  402. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +1482 -0
  403. package/packages/apra-fleet-se/fleet-sprint/docs/escalate-to-llm-design.md +908 -0
  404. package/packages/apra-fleet-se/fleet-sprint/docs/shared-orchestrator-reservation-design.md +399 -0
  405. package/packages/apra-fleet-se/fleet-sprint/dolt-settle.mjs +972 -0
  406. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +167 -101
  407. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +50 -6
  408. package/packages/apra-fleet-se/fleet-sprint/runner.js +1416 -116
  409. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +13 -2
  410. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +350 -0
  411. package/packages/apra-fleet-se/fleet-sprint/sprint-progress.mjs +101 -0
  412. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +30 -17
  413. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +62 -2
  414. package/packages/apra-fleet-se/package.json +1 -0
  415. package/packages/apra-fleet-workflow/src/viewer/index.mjs +127 -13
  416. package/packages/apra-fleet-workflow/src/viewer/run-title.mjs +60 -0
  417. package/packages/apra-fleet-workflow/src/workflow/index.mjs +8 -4
  418. package/skills/fleet/knowledge-agent.md +66 -0
  419. package/skills/fleet/permissions.md +28 -4
  420. package/skills/fleet/profiles/base-dev.json +10 -1
  421. package/skills/fleet/profiles/base-reviewer.json +8 -1
  422. package/skills/fleet/profiles/tag-kb-reconciler.json +20 -0
  423. package/version.json +1 -1
  424. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-tier2-runbook.md +0 -127
  425. package/packages/apra-fleet-se/fleet-sprint/dolt-recovery-path-b.mjs +0 -339
  426. package/packages/apra-fleet-se/fleet-sprint/dolt-recovery-tier2.mjs +0 -360
  427. package/packages/apra-fleet-se/fleet-sprint/dolt-recovery.mjs +0 -363
@@ -0,0 +1,972 @@
1
+ // Dolt conflict recovery: settle() -- see docs/dolt-sync-redesign.md for the
2
+ // full design. Short version: this module replaces the entire 3-tier
3
+ // Path A / Path B / Tier 2 recovery ladder (dolt-recovery.mjs,
4
+ // dolt-recovery-path-b.mjs, dolt-recovery-tier2.mjs) with ONE deterministic,
5
+ // zero-agent-dispatch function that is TOTAL over every row-level Dolt
6
+ // conflict shape this data model can produce -- no gates, no allowlist, no
7
+ // escalation, no LLM. The old ladder's Path A never actually ran in
8
+ // production (no sql() runtime was ever injected at its runner.js call
9
+ // site) and its LLM-driven Tier 2 had no code-guaranteed rollback (see
10
+ // apra-fleet-ga61, apra-fleet-5mqg). settleDoltConflicts() fixes both: it IS
11
+ // the sql runtime (driving the raw `dolt` CLI itself, not routing bd through
12
+ // it), and its teardown is a real `finally`, not a step an agent can abandon
13
+ // mid-procedure.
14
+ //
15
+ // -----------------------------------------------------------------------------
16
+ // Mechanics (every step live-verified -- see docs/dolt-manual-recovery-verified.md
17
+ // and docs/dolt-sync-redesign.md Parts 3/5/7 for the full evidence trail):
18
+ //
19
+ // 0. Resolve the REAL data dir/mode from `bd dolt status` -- never
20
+ // hardcoded. If the member is already in server mode, target that
21
+ // live server instead of spawning a second one.
22
+ // 1. Ensure a correctly-pinned `dolt` binary exists on the MEMBER at its
23
+ // own `~/.apra-fleet/bin`. Members never run `apra-fleet install`
24
+ // (they are pure SSH command targets, not apra-fleet installs) so
25
+ // nothing else on a member ever puts a pinned dolt there -- settle is
26
+ // self-sufficient: probe, and if missing/wrong-version, install it
27
+ // itself from the SAME pinned GitHub-release asset dolt-install.ts
28
+ // uses. If an existing binary can't be replaced because a stray dolt
29
+ // process holds the file, kill it (a legitimate self-heal -- nothing
30
+ // else ever launches a binary at this path) and retry once; only then
31
+ // fall back to whatever runnable dolt IS present, gated behind a
32
+ // functional preflight query.
33
+ // 2. Spawn a genuinely-detached ephemeral `dolt sql-server` against the
34
+ // resolved data dir. `Start-Process`/`schtasks` on Windows both die
35
+ // with the launching SSH session -- WMI `Win32_Process.Create` is what
36
+ // actually survives (session 0). POSIX: `nohup ... & disown`.
37
+ // 3. Drive the raw `dolt` CLI directly at the socket -- NEVER route `bd`
38
+ // through it (bd's own routing state, `.beads/metadata.json`, is never
39
+ // touched, which is what makes teardown unconditionally safe).
40
+ // `--no-tls` MUST precede `--host`/`--port` (order-sensitive parser);
41
+ // NEVER pass `--user`/`--password` (both are credential-prompt
42
+ // landmines -- omitting them authenticates silently as root/empty).
43
+ // 4. Re-open the merge, enumerate EVERY conflicted table (no allowlist),
44
+ // and resolve each one via the fixed per-table rulebook below, with a
45
+ // generic per-field last-writer-wins-by-`updated_at` fallback (falling
46
+ // back further to `--theirs` outright if a table has no `updated_at`
47
+ // column) for any table not named explicitly -- this is what makes the
48
+ // function TOTAL rather than gated.
49
+ // 5. Tear the server down FIRST (kill + verify port closed), THEN
50
+ // republish via `bd dolt pull`/`bd dolt push`. Embedded-mode `bd` must
51
+ // not race the server's exclusive chunk-journal lock -- republishing
52
+ // while the server is still up would hit that lock and fail or fall
53
+ // back read-only (design doc Part 7.2).
54
+ // 6. Guaranteed teardown in a real `finally`, regardless of outcome --
55
+ // the ephemeral-server class of state is undone on every exit path.
56
+ // =============================================================================
57
+
58
+ import { DoltDivergedError, DoltSyncError, DoltBinaryUnavailableError } from './errors.mjs';
59
+
60
+ /** Must equal src/cli/dolt-install.ts's DOLT_VERSION byte-for-byte -- a
61
+ * drift-guard test (dolt-settle.test.mjs) asserts this against that file's
62
+ * source text. Two executors of one pin (design doc Part 5.4): dolt-install.ts
63
+ * installs it in-process on the orchestrator; this module installs it over
64
+ * command() on members, since members never run `apra-fleet install`. */
65
+ export const DOLT_VERSION = 'v2.2.0';
66
+ const DOLT_RELEASE_BASE = `https://github.com/dolthub/dolt/releases/download/${DOLT_VERSION}`;
67
+
68
+ /** Default embedded dolt data dir -- used ONLY as a last-resort fallback
69
+ * when `bd dolt status` itself cannot be parsed. Every real call path
70
+ * resolves the data dir live (step 0); this constant existing at all is
71
+ * exactly the anti-pattern design doc Part 5 warns against, so it is never
72
+ * used silently -- resolveDoltStatus() logs loudly if it has to fall back
73
+ * to it. */
74
+ export const DEFAULT_EMBEDDED_DATA_DIR = '.beads/embeddeddolt';
75
+
76
+ export const RECOVERY_SQL_SERVER_HOST = '127.0.0.1';
77
+ export const DEFAULT_PORT_RANGE = Object.freeze({ start: 13300, end: 13400 });
78
+
79
+ /** Tables settle() has an explicit, named rulebook entry for. Anything else
80
+ * still gets resolved -- via the generic per-field-LWW-or-theirs fallback
81
+ * (resolveGenericTable) -- this list is NOT an allowlist/gate. */
82
+ const NAMED_RULEBOOK = Object.freeze({
83
+ issues: 'lww',
84
+ dependencies: 'lww',
85
+ labels: 'union',
86
+ comments: 'theirs',
87
+ events: 'theirs',
88
+ });
89
+
90
+ // ---------------------------------------------------------------------------
91
+ // Section 1: pinned-dolt asset resolution (mirrors src/cli/dolt-install.ts's
92
+ // resolveDoltAsset exactly -- kept as plain data here since dolt-settle.mjs
93
+ // cannot import the TypeScript module across the package boundary at
94
+ // runtime; the drift-guard test is what keeps these two in sync).
95
+ // ---------------------------------------------------------------------------
96
+
97
+ /**
98
+ * @param {string} platform - 'win32' | 'linux' | 'darwin'
99
+ * @param {string} arch - 'x64' | 'arm64'
100
+ * @returns {{ assetName: string, url: string, archiveType: 'zip'|'tar.gz', binaryName: string }}
101
+ */
102
+ export function resolveDoltAsset(platform, arch) {
103
+ const binaryName = platform === 'win32' ? 'dolt.exe' : 'dolt';
104
+ let assetName;
105
+ let archiveType;
106
+ if (platform === 'win32' && arch === 'x64') {
107
+ assetName = 'dolt-windows-amd64.zip';
108
+ archiveType = 'zip';
109
+ } else if (platform === 'linux' && arch === 'x64') {
110
+ assetName = 'dolt-linux-amd64.tar.gz';
111
+ archiveType = 'tar.gz';
112
+ } else if (platform === 'darwin' && arch === 'x64') {
113
+ assetName = 'dolt-darwin-amd64.tar.gz';
114
+ archiveType = 'tar.gz';
115
+ } else if (platform === 'darwin' && arch === 'arm64') {
116
+ assetName = 'dolt-darwin-arm64.tar.gz';
117
+ archiveType = 'tar.gz';
118
+ }
119
+ if (!assetName || !archiveType) {
120
+ throw new Error(`settle: unsupported platform/arch for pinned dolt install: ${platform}/${arch}`);
121
+ }
122
+ return { assetName, url: `${DOLT_RELEASE_BASE}/${assetName}`, archiveType, binaryName };
123
+ }
124
+
125
+ /** The member-side fleet-managed dolt path, resolved with the MEMBER's own
126
+ * shell (never the orchestrator's homedir/platform). */
127
+ function memberDoltPath(platform) {
128
+ return platform === 'win32'
129
+ ? '"$env:USERPROFILE\\.apra-fleet\\bin\\dolt.exe"'
130
+ : '"$HOME/.apra-fleet/bin/dolt"';
131
+ }
132
+
133
+ // ---------------------------------------------------------------------------
134
+ // Section 1b: shell dialect. Every command below is dispatched into the
135
+ // MEMBER's own shell -- PowerShell (5.1, so no `&&`/`||`) on Windows, bash on
136
+ // POSIX -- and the two disagree about things settle depends on. All of this
137
+ // was found by running settle against real members, not by reading docs:
138
+ //
139
+ // - Invoking a quoted absolute path needs PowerShell's call operator
140
+ // (`& "..."`); a leading `&` in bash is a syntax error outright.
141
+ // - Inside a double-quoted string, bash treats a backtick as command
142
+ // substitution while PowerShell treats it as its escape character, so a
143
+ // SQL identifier quote must be escaped differently for each (and SQL that
144
+ // can avoid backticks entirely simply does).
145
+ // - `cmd 2>$null || fallback` parses in bash but is a hard parse ERROR in
146
+ // PowerShell 5.1, so no single "works everywhere" probe string exists.
147
+ // ---------------------------------------------------------------------------
148
+
149
+ /** Invoke an executable at a quoted path with arguments, in the member's shell. */
150
+ function invokeBinary(platform, quotedPath, args) {
151
+ return platform === 'win32' ? `& ${quotedPath} ${args}` : `${quotedPath} ${args}`;
152
+ }
153
+
154
+ /**
155
+ * Escape a SQL string so it survives as ONE double-quoted argument in the
156
+ * member's shell. Backticks and `$` are the dangerous characters in both
157
+ * dialects, for opposite reasons.
158
+ */
159
+ export function escapeSqlForShell(platform, sql) {
160
+ const bq = String.fromCharCode(96);
161
+ if (platform === 'win32') {
162
+ // PowerShell: ` escapes; a literal backtick is a doubled backtick, a
163
+ // literal quote is `" and a literal $ is `$.
164
+ return String(sql)
165
+ .split(bq).join(bq + bq)
166
+ .replace(/\$/g, `${bq}$`)
167
+ .replace(/"/g, `${bq}"`);
168
+ }
169
+ // bash: backslash escapes inside double quotes.
170
+ return String(sql)
171
+ .replace(/\\/g, '\\\\')
172
+ .split(bq).join('\\' + bq)
173
+ .replace(/\$/g, '\\$')
174
+ .replace(/"/g, '\\"');
175
+ }
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // Section 2: `bd dolt status` parsing -- resolve the REAL data dir/mode.
179
+ // ---------------------------------------------------------------------------
180
+
181
+ /**
182
+ * @param {{ command: Function, member: string }} opts
183
+ * @returns {Promise<{ mode: 'embedded'|'server'|'unknown', dataDir: string|null, host: string|null, port: number|null, raw: string }>}
184
+ */
185
+ export async function resolveDoltStatus({ command, member, log = () => {} }) {
186
+ const res = await command('bd dolt status', { member_name: member, silent: true, failSoft: true, label: `settle: bd dolt status for '${member}'` });
187
+ const raw = String((res && (res.output || res.error)) || '');
188
+
189
+ const embeddedMatch = raw.match(/embedded[^\n]*\n\s*Data:\s*(.+)/i);
190
+ if (embeddedMatch) {
191
+ return { mode: 'embedded', dataDir: embeddedMatch[1].trim(), host: null, port: null, raw };
192
+ }
193
+ const serverMatch = raw.match(/server[^\n]*?(\d{1,3}(?:\.\d{1,3}){3}|localhost):(\d+)/i);
194
+ if (serverMatch) {
195
+ return { mode: 'server', dataDir: null, host: serverMatch[1], port: Number(serverMatch[2]), raw };
196
+ }
197
+ log(`[Dolt Settle] WARNING: could not parse 'bd dolt status' for member '${member}' -- falling back to default data dir '${DEFAULT_EMBEDDED_DATA_DIR}'. Raw: ${raw.slice(0, 300)}`);
198
+ return { mode: 'unknown', dataDir: DEFAULT_EMBEDDED_DATA_DIR, host: null, port: null, raw };
199
+ }
200
+
201
+ // ---------------------------------------------------------------------------
202
+ // Section 3: ensure a correctly-pinned dolt binary on the member (design doc
203
+ // Part 5.3/5.6).
204
+ // ---------------------------------------------------------------------------
205
+
206
+ /** Probe an existing binary at `doltPath` for exit-0 + parseable version. */
207
+ async function probeDoltVersion({ command, member, doltPath, platform }) {
208
+ const res = await command(invokeBinary(platform, doltPath, 'version'), { member_name: member, silent: true, failSoft: true, label: `settle: probe dolt version for '${member}'` });
209
+ const text = String((res && (res.output || res.error)) || '');
210
+ const match = text.match(/dolt version (\d+\.\d+\.\d+\S*)/i);
211
+ return { ok: !!(res && res.ok !== false) && !!match, version: match ? match[1] : null, raw: text };
212
+ }
213
+
214
+ /** Step 1b: install the pinned binary via remote shell from the same pinned
215
+ * asset URL resolveDoltAsset() computes. Bounded, single-attempt. */
216
+ async function installPinnedDolt({ command, member, platform, arch, doltPath, log }) {
217
+ const asset = resolveDoltAsset(platform, arch);
218
+ log(`[Dolt Settle] installing pinned dolt ${DOLT_VERSION} on member '${member}' from ${asset.url}`);
219
+
220
+ if (platform === 'win32') {
221
+ const script = [
222
+ 'New-Item -ItemType Directory -Force "$env:USERPROFILE\\.apra-fleet\\bin" | Out-Null',
223
+ `Invoke-WebRequest -Uri "${asset.url}" -OutFile "$env:TEMP\\dolt-settle.zip" -TimeoutSec 300`,
224
+ 'Expand-Archive -Force "$env:TEMP\\dolt-settle.zip" "$env:TEMP\\dolt-settle"',
225
+ `Get-ChildItem -Recurse -Filter "${asset.binaryName}" "$env:TEMP\\dolt-settle" | Select-Object -First 1 | Copy-Item -Force -Destination ${doltPath}`,
226
+ 'Remove-Item -Recurse -Force "$env:TEMP\\dolt-settle.zip","$env:TEMP\\dolt-settle" -ErrorAction SilentlyContinue',
227
+ ].join('; ');
228
+ return command(script, { member_name: member, silent: true, failSoft: true, timeout_s: 320, label: `settle: install pinned dolt on '${member}'` });
229
+ }
230
+
231
+ const script = [
232
+ 'mkdir -p "$HOME/.apra-fleet/bin"',
233
+ `curl -fL --max-time 300 "${asset.url}" -o /tmp/dolt-settle-${member}.tgz`,
234
+ `mkdir -p /tmp/dolt-settle-${member} && tar -xzf /tmp/dolt-settle-${member}.tgz -C /tmp/dolt-settle-${member}`,
235
+ `install -m 0755 "$(find /tmp/dolt-settle-${member} -type f -name ${asset.binaryName} | head -1)" "$HOME/.apra-fleet/bin/${asset.binaryName}"`,
236
+ `rm -rf /tmp/dolt-settle-${member}.tgz /tmp/dolt-settle-${member}`,
237
+ ].join(' && ');
238
+ return command(script, { member_name: member, silent: true, failSoft: true, timeout_s: 320, label: `settle: install pinned dolt on '${member}'` });
239
+ }
240
+
241
+ /** Is this install failure the "file is in use / can't be replaced" class
242
+ * (design doc Part 5.6), as opposed to a hard failure (network, unsupported
243
+ * platform, corrupted download) that must still throw? */
244
+ function isBinaryLockedError(output) {
245
+ const text = String(output || '');
246
+ // NOTE: deliberately no bare "Permission denied" -- that also matches an
247
+ // ordinary POSIX EACCES (wrong perms, non-lock cause), which would waste
248
+ // a kill-and-retry cycle on a failure the retry can never fix. ETXTBSY /
249
+ // EBUSY / "text file busy" already cover the real POSIX in-use case.
250
+ return /being used by another process|Access to the path .* is denied|ETXTBSY|EBUSY|text file busy/i.test(text);
251
+ }
252
+
253
+ /** Kill any process whose executable path is exactly the fleet-managed dolt
254
+ * path -- by construction the only thing that ever launches a binary there
255
+ * is settle/the installer, so this is always a legitimate self-heal, never
256
+ * collateral damage against an unrelated process. */
257
+ async function killProcessAtPath({ command, member, platform, doltPath, log }) {
258
+ log(`[Dolt Settle] attempting to kill any process locking '${doltPath}' on member '${member}' before retrying the pinned install.`);
259
+ if (platform === 'win32') {
260
+ return command(`Get-Process | Where-Object { $_.Path -eq ${doltPath} } | Stop-Process -Force -ErrorAction SilentlyContinue`, { member_name: member, silent: true, failSoft: true, label: `settle: kill locking dolt process on '${member}'` });
261
+ }
262
+ return command('pkill -f "\\.apra-fleet/bin/dolt" || true', { member_name: member, silent: true, failSoft: true, label: `settle: kill locking dolt process on '${member}'` });
263
+ }
264
+
265
+ /**
266
+ * Design doc Part 5.3/5.6: probe -> install if missing/wrong-version ->
267
+ * (if blocked) kill-and-retry-once -> (if still blocked) warn and fall back
268
+ * to whatever runnable dolt IS present, gated behind a functional preflight.
269
+ * Throws DoltBinaryUnavailableError only when NOTHING runnable is available
270
+ * after the full ladder, or the platform/arch is unsupported with no
271
+ * existing binary -- an ordinary operational failure, not an escalation.
272
+ *
273
+ * @returns {Promise<{ doltPath: string, version: string, pinned: boolean, warnings: string[] }>}
274
+ */
275
+ export async function ensurePinnedDolt({ command, member, platform, arch = 'x64', log = () => {} }) {
276
+ const doltPath = memberDoltPath(platform);
277
+ const warnings = [];
278
+
279
+ const initial = await probeDoltVersion({ command, member, doltPath, platform });
280
+ if (initial.ok && initial.version === DOLT_VERSION.replace(/^v/, '')) {
281
+ return { doltPath, version: initial.version, pinned: true, warnings };
282
+ }
283
+
284
+ // Missing, broken, or wrong version -- attempt the pinned install.
285
+ let install;
286
+ try {
287
+ install = await installPinnedDolt({ command, member, platform, arch, doltPath, log });
288
+ } catch (err) {
289
+ throw new DoltBinaryUnavailableError(
290
+ `[Dolt Settle] unsupported platform/arch for member '${member}' installing pinned dolt: ${err.message}`,
291
+ { member, probedPath: doltPath, probeOutput: err.message, repairCommand: `manually install dolt ${DOLT_VERSION} at ${doltPath} on ${member}` },
292
+ );
293
+ }
294
+
295
+ const installFailed = install && install.ok === false;
296
+ const installOutput = String((install && (install.error || install.output)) || '');
297
+
298
+ if (installFailed && isBinaryLockedError(installOutput)) {
299
+ // Kill-first, then retry once (Part 5.6 step 2).
300
+ await killProcessAtPath({ command, member, platform, doltPath, log });
301
+ const retry = await installPinnedDolt({ command, member, platform, arch, doltPath, log });
302
+ if (!(retry && retry.ok === false)) {
303
+ const reprobed = await probeDoltVersion({ command, member, doltPath, platform });
304
+ if (reprobed.ok) return { doltPath, version: reprobed.version, pinned: true, warnings };
305
+ }
306
+ // Still blocked after kill+retry -- warn and fall back (Part 5.6 step 3).
307
+ const fallback = await probeDoltVersion({ command, member, doltPath, platform });
308
+ if (fallback.ok) {
309
+ const warn = `[Dolt Settle] pin not enforced on '${member}': could not replace ${doltPath} (locked even after kill+retry); proceeding with dolt ${fallback.version} as a functionally-probed fallback. Landmines unverified on this version -- see docs/dolt-sync-redesign.md Part 5.6.`;
310
+ log(warn);
311
+ warnings.push(warn);
312
+ return { doltPath, version: fallback.version, pinned: false, warnings };
313
+ }
314
+ throw new DoltBinaryUnavailableError(
315
+ `[Dolt Settle] no usable dolt binary on member '${member}' after install+kill+retry: ${installOutput}`,
316
+ { member, probedPath: doltPath, probeOutput: installOutput, repairCommand: `manually free ${doltPath} on ${member} and re-run settle` },
317
+ );
318
+ }
319
+
320
+ if (installFailed) {
321
+ throw new DoltBinaryUnavailableError(
322
+ `[Dolt Settle] failed to install pinned dolt ${DOLT_VERSION} on member '${member}': ${installOutput}`,
323
+ { member, probedPath: doltPath, probeOutput: installOutput, repairCommand: `manually install dolt ${DOLT_VERSION} at ${doltPath} on ${member}` },
324
+ );
325
+ }
326
+
327
+ const reprobed = await probeDoltVersion({ command, member, doltPath, platform });
328
+ if (!reprobed.ok) {
329
+ throw new DoltBinaryUnavailableError(
330
+ `[Dolt Settle] pinned dolt install reported success but the binary still fails 'dolt version' on member '${member}' -- likely a corrupted download.`,
331
+ { member, probedPath: doltPath, probeOutput: reprobed.raw, repairCommand: `delete ${doltPath} on ${member} and re-run settle` },
332
+ );
333
+ }
334
+ return { doltPath, version: reprobed.version, pinned: true, warnings };
335
+ }
336
+
337
+ // ---------------------------------------------------------------------------
338
+ // Section 4: ephemeral sql-server spawn/teardown.
339
+ // ---------------------------------------------------------------------------
340
+
341
+ /** Genuinely-detached spawn -- WMI on Windows (Start-Process/schtasks both
342
+ * die with the launching SSH session, verified live), nohup+disown on
343
+ * POSIX. Returns the pid so teardown can target it precisely. */
344
+ export async function spawnEphemeralServer({ command, member, platform, doltPath, dataDir, host, port, log = () => {} }) {
345
+ log(`[Dolt Settle] starting ephemeral dolt sql-server for member '${member}' at ${host}:${port} --data-dir ${dataDir}`);
346
+
347
+ if (platform === 'win32') {
348
+ // The command line is assembled in PowerShell, from a DOUBLE-quoted
349
+ // $exe, so `$env:USERPROFILE` actually expands: passing the raw
350
+ // '$env:USERPROFILE\...' text inside WMI's single-quoted argument
351
+ // makes Win32_Process.Create fail with ReturnValue 9 / "path not
352
+ // found" (verified live on fleet-win-dev1). Paths are quoted inside
353
+ // the command line so a space in either survives.
354
+ const script = [
355
+ `$exe = ${doltPath}`,
356
+ `$cl = '"' + $exe + '" sql-server --host ${host} --port ${port} --data-dir ' + '"${dataDir}"'`,
357
+ '$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = $cl }',
358
+ 'if ($r.ReturnValue -ne 0) { throw "Win32_Process.Create failed with ReturnValue $($r.ReturnValue) for command line: $cl" }',
359
+ 'Write-Output "PID:$($r.ProcessId)"',
360
+ ].join('; ');
361
+ const res = await command(script, { member_name: member, silent: true, failSoft: true, label: `settle: spawn ephemeral sql-server on '${member}'` });
362
+ if (res && res.ok === false) {
363
+ throw new DoltSyncError(`[Dolt Settle] failed to spawn ephemeral sql-server for member '${member}': ${res.error}`, { member, doltOutput: res.error });
364
+ }
365
+ const pidMatch = String(res.output || '').match(/PID:(\d+)/);
366
+ if (!pidMatch) {
367
+ throw new DoltSyncError(`[Dolt Settle] spawned sql-server for member '${member}' but could not parse its PID from output: ${res.output}`, { member, doltOutput: res.output });
368
+ }
369
+ return { pid: Number(pidMatch[1]) };
370
+ }
371
+
372
+ // POSIX detachment, every piece of it verified live on fleet-lin-dev1
373
+ // because the obvious form does NOT work under the fleet's own bash
374
+ // wrapper (which backgrounds the command and `wait`s on it):
375
+ // - `( ... & )` -- a SUBSHELL the dispatching shell never waits on.
376
+ // A plain `nohup ... & echo PID; disown` left the dispatch hanging
377
+ // until its 300s inactivity timeout while the server was actually up
378
+ // and holding the data dir lock: a "spawn failure" that silently
379
+ // leaves a live orphan behind.
380
+ // - `setsid` -- own session, so it outlives the SSH session.
381
+ // - `< /dev/null` -- otherwise the server inherits the dispatch's stdin
382
+ // and the SSH channel never closes.
383
+ // - the pid comes from `pgrep` on the port, not `$!`: `$!` belongs to
384
+ // the subshell, not to the server we must be able to kill.
385
+ const logPath = `/tmp/dolt-settle-${member}-${port}.log`;
386
+ const matcher = `sql-server --host ${host} --port ${port}`;
387
+ // `setsid` does NOT exist on macOS (verified live on fleet-mac: the spawn
388
+ // silently produced no pid), so it is resolved at runtime and simply
389
+ // omitted where absent -- `nohup` inside the detached subshell is what
390
+ // actually keeps the server alive there.
391
+ const script = `SETSID=$(command -v setsid || true); ( $SETSID nohup ${doltPath} sql-server --host ${host} --port ${port} --data-dir ${dataDir} > ${logPath} 2>&1 < /dev/null & ) ; sleep 1; echo "PID:$(pgrep -f '${matcher}' | head -1)"`;
392
+ const res = await command(script, { member_name: member, silent: true, failSoft: true, label: `settle: spawn ephemeral sql-server on '${member}'` });
393
+ if (res && res.ok === false) {
394
+ throw new DoltSyncError(`[Dolt Settle] failed to spawn ephemeral sql-server for member '${member}': ${res.error}`, { member, doltOutput: res.error });
395
+ }
396
+ const pidMatch = String(res.output || '').match(/PID:(\d+)/);
397
+ if (!pidMatch) {
398
+ throw new DoltSyncError(`[Dolt Settle] spawned sql-server for member '${member}' but could not parse its PID from output: ${res.output}`, { member, doltOutput: res.output });
399
+ }
400
+ return { pid: Number(pidMatch[1]), logPath };
401
+ }
402
+
403
+ /** Bounded poll for the server to actually accept connections -- never
404
+ * sleep-and-hope. */
405
+ export async function waitForServerReady({ command, member, platform, host, port, log = () => {}, attempts = 10, intervalMs = 500 }) {
406
+ for (let i = 0; i < attempts; i += 1) {
407
+ const probe = platformAwareTcpProbe({ command, member, platform, host, port });
408
+ // eslint-disable-next-line no-await-in-loop -- intentional bounded poll
409
+ const res = await probe;
410
+ if (res) return true;
411
+ // eslint-disable-next-line no-await-in-loop -- intentional bounded poll
412
+ await new Promise((resolve) => { setTimeout(resolve, intervalMs); });
413
+ }
414
+ throw new DoltSyncError(`[Dolt Settle] ephemeral sql-server for member '${member}' never became reachable at ${host}:${port} after ${attempts} attempts.`, { member });
415
+ }
416
+
417
+ /**
418
+ * Is something listening on host:port on the member?
419
+ *
420
+ * Done in NODE, not in the member's shell, because no shell one-liner works
421
+ * everywhere -- all of this is live-verified, not assumed:
422
+ * - `cmd || fallback` is a hard PARSE ERROR in PowerShell 5.1
423
+ * (fleet-win-dev1), so no single string can cover both families.
424
+ * - `/dev/tcp` is a BASH feature and fleet-mac's shell is ZSH, where it does
425
+ * not exist -- the probe silently reported "nothing listening" while the
426
+ * server was up and logging "Server ready. Accepting connections."
427
+ * Every member necessarily has node (bd is npm-installed), and a single-quoted
428
+ * JS string survives both bash and PowerShell unchanged.
429
+ */
430
+ /**
431
+ * Wrap a JS snippet as a `node -e` argument for the member's shell.
432
+ *
433
+ * PowerShell 5.1's native-argument passing STRIPS the double quotes inside a
434
+ * single-quoted string, so `require("net")` arrived at node as
435
+ * `require(net)` and died with a SyntaxError (verified live on
436
+ * fleet-win-dev1). Backslash-escaping them is the documented workaround --
437
+ * and must NOT be applied on POSIX, where the backslashes would survive
438
+ * literally into the JS.
439
+ */
440
+ function nodeEval(platform, js) {
441
+ return `node -e '${platform === 'win32' ? js.replace(/"/g, '\\"') : js}'`;
442
+ }
443
+
444
+ function tcpProbeScript(platform, host, port, timeoutMs = 2000) {
445
+ return nodeEval(platform, `const net=require("net");const s=net.connect(${port},"${host}");const done=(v)=>{try{s.destroy()}catch(e){};console.log(v?"PROBE:True":"PROBE:False");process.exit(0)};s.on("connect",()=>done(true));s.on("error",()=>done(false));setTimeout(()=>done(false),${timeoutMs})`);
446
+ }
447
+
448
+ async function platformAwareTcpProbe({ command, member, platform, host, port }) {
449
+ const res = await command(tcpProbeScript(platform, host, port), { member_name: member, silent: true, failSoft: true, label: `settle: TCP probe for '${member}'` });
450
+ return /PROBE:True/i.test(String((res && res.output) || ''));
451
+ }
452
+
453
+ /** Kill the server + verify the port is actually closed. Best-effort by
454
+ * design (called from the happy path AND the unconditional `finally` --
455
+ * see settleDoltConflicts). */
456
+ async function killServerAndVerify({ command, member, platform, pid, host, port, log = () => {} }) {
457
+ // Kill the recorded pid AND, belt-and-braces, anything still bound to our
458
+ // ephemeral port: the recorded pid is resolved by a pattern match at spawn
459
+ // time, so a mis-resolved pid must not be able to leave the real server
460
+ // running (which would hold the data dir lock and wedge the republish).
461
+ // Both forms are scoped to settle's own port, never to dolt at large.
462
+ const matcher = `sql-server --host ${host} --port ${port}`;
463
+ if (platform === 'win32') {
464
+ await command(
465
+ `Stop-Process -Id ${pid} -Force -ErrorAction SilentlyContinue; Get-CimInstance Win32_Process -Filter "Name='dolt.exe'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -match '--port ${port}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`,
466
+ { member_name: member, silent: true, failSoft: true, label: `settle: kill ephemeral sql-server pid ${pid} on '${member}'` },
467
+ );
468
+ } else {
469
+ await command(`kill ${pid} 2>/dev/null; pkill -f '${matcher}' 2>/dev/null; true`, { member_name: member, silent: true, failSoft: true, label: `settle: kill ephemeral sql-server pid ${pid} on '${member}'` });
470
+ }
471
+ for (let i = 0; i < 6; i += 1) {
472
+ // eslint-disable-next-line no-await-in-loop -- bounded teardown-verify poll
473
+ const stillUp = await platformAwareTcpProbe({ command, member, platform, host, port });
474
+ if (!stillUp) {
475
+ log(`[Dolt Settle] torn down ephemeral sql-server (pid ${pid}) for member '${member}'; port ${port} confirmed closed.`);
476
+ return;
477
+ }
478
+ // eslint-disable-next-line no-await-in-loop -- bounded teardown-verify poll
479
+ await new Promise((resolve) => { setTimeout(resolve, 300); });
480
+ }
481
+ log(`[Dolt Settle] WARNING: sent kill to pid ${pid} on member '${member}' but port ${port} still appears open after 6 checks -- the supervisor orphan sweep is the backstop for this (design doc Part 3.3).`);
482
+ }
483
+
484
+ // ---------------------------------------------------------------------------
485
+ // Section 5: raw dolt CLI query runner -- the exact live-verified flag set.
486
+ // ---------------------------------------------------------------------------
487
+
488
+ /**
489
+ * Runs a query against the ephemeral server via the raw `dolt` CLI, using
490
+ * the exact live-verified flag set: `--no-tls` BEFORE `--host`/`--port`
491
+ * (order-sensitive), NEVER `--user`/`--password` (both trigger an
492
+ * interactive credential prompt that fails non-interactively -- see
493
+ * apra-fleet-ga61). `-r json` for parseable output. `USE beads;` is
494
+ * prepended automatically.
495
+ *
496
+ * @returns {Promise<object[]>} parsed rows (empty array for statements with no result set)
497
+ */
498
+ export async function runDoltSql({ command, member, platform, doltPath, host, port, query, log = () => {} }) {
499
+ // EVERY invocation is its own SQL SESSION -- `dolt sql -q` connects,
500
+ // runs, and disconnects -- so session-scoped state does NOT carry over
501
+ // between calls. `@@dolt_allow_commit_conflicts` is therefore set on each
502
+ // one, not once up front: without it DOLT_MERGE fails outright with
503
+ // "Merge conflict detected, @autocommit transaction rolled back"
504
+ // (verified live on fleet-lin-dev1). The conflict data itself IS durable
505
+ // -- it lives in the working set -- which is what lets the subsequent
506
+ // resolve/commit statements run in later sessions.
507
+ const preamble = 'USE beads; SET @@dolt_allow_commit_conflicts = 1;';
508
+ const fullQuery = escapeSqlForShell(platform, `${preamble} ${query}`);
509
+ const cmd = invokeBinary(platform, doltPath, `--no-tls --host=${host} --port=${port} sql -r json -q "${fullQuery}"`);
510
+ const res = await command(cmd, { member_name: member, silent: true, failSoft: true, label: `settle: dolt sql for '${member}'` });
511
+ if (res && res.ok === false) {
512
+ throw new DoltSyncError(`[Dolt Settle] dolt sql query failed for member '${member}': ${res.error}\nquery: ${query}`, { member, doltOutput: res.error });
513
+ }
514
+ return parseDoltJsonRows(res && res.output);
515
+ }
516
+
517
+ /**
518
+ * Parse the rows out of a `dolt sql -r json` batch.
519
+ *
520
+ * A multi-statement `-q` emits ONE JSON document PER STATEMENT, concatenated
521
+ * (`{}` for a statement with no result set, `{"rows": [...]}` for a SELECT),
522
+ * so a plain JSON.parse of the whole output throws and silently yielded []
523
+ * -- which made settle believe a genuinely conflicted clone had no conflicted
524
+ * tables at all, and then fail at DOLT_COMMIT with "the table(s) issues are
525
+ * in conflict". Verified live on fleet-lin-dev1. Every settle query carries a
526
+ * `USE beads; SET ...;` preamble, so this is the NORMAL shape, not an edge
527
+ * case: take the last row-bearing document.
528
+ *
529
+ * @param {string|null|undefined} output
530
+ * @returns {object[]}
531
+ */
532
+ export function parseDoltJsonRows(output) {
533
+ const raw = String(output || '').trim();
534
+ if (!raw) return [];
535
+ try {
536
+ const parsed = JSON.parse(raw);
537
+ if (Array.isArray(parsed)) return parsed;
538
+ if (Array.isArray(parsed && parsed.rows)) return parsed.rows;
539
+ } catch { /* the multi-document shape below is the common case */ }
540
+
541
+ let rows = [];
542
+ for (const line of raw.split('\n')) {
543
+ const text = line.trim();
544
+ if (!text.startsWith('{')) continue;
545
+ try {
546
+ const doc = JSON.parse(text);
547
+ if (Array.isArray(doc)) rows = doc;
548
+ else if (Array.isArray(doc.rows)) rows = doc.rows;
549
+ } catch { /* not a complete JSON document on this line */ }
550
+ }
551
+ return rows;
552
+ }
553
+
554
+ // ---------------------------------------------------------------------------
555
+ // Section 6: the settle rulebook -- TOTAL over every conflicted table.
556
+ // ---------------------------------------------------------------------------
557
+
558
+ async function tableColumns({ command, member, platform, doltPath, host, port, table }) {
559
+ const rows = await runDoltSql({
560
+ command, member, platform, doltPath, host, port,
561
+ query: `SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = '${table}';`,
562
+ });
563
+ return rows.map((r) => r.COLUMN_NAME || r.column_name).filter(Boolean);
564
+ }
565
+
566
+ /** The table's REAL uniqueness key, read live from information_schema -- never
567
+ * a hardcoded column list. Used by the set-union resolver to decide whether a
568
+ * `their_*` row is already present on our side. Falls back to the full column
569
+ * list (whole-row identity) when a table declares no PRIMARY KEY, which is
570
+ * still a correct -- if conservative -- set-union identity. */
571
+ async function tablePrimaryKey({ command, member, platform, doltPath, host, port, table }) {
572
+ const rows = await runDoltSql({
573
+ command, member, platform, doltPath, host, port,
574
+ query: `SELECT COLUMN_NAME FROM information_schema.key_column_usage WHERE TABLE_NAME = '${table}' AND CONSTRAINT_NAME = 'PRIMARY' ORDER BY ORDINAL_POSITION;`,
575
+ });
576
+ return rows.map((r) => r.COLUMN_NAME || r.column_name).filter(Boolean);
577
+ }
578
+
579
+ /** Generic per-field last-writer-wins-by-updated_at, applicable to ANY table
580
+ * that has an `updated_at` column -- this is what makes settle TOTAL rather
581
+ * than gated to a fixed table list. Falls back to a plain `--theirs`
582
+ * resolve for a table with no `updated_at` column. */
583
+ async function resolveLwwTable({ command, member, platform, doltPath, host, port, table, log }) {
584
+ const bq = String.fromCharCode(96); // backtick, built at runtime -- avoids a literal backslash-backtick sequence in source
585
+ const cols = await tableColumns({ command, member, platform, doltPath, host, port, table });
586
+ if (!cols.includes('updated_at')) {
587
+ log(`[Dolt Settle] table '${table}' has no updated_at column -- resolving via plain --theirs (no per-field merge possible).`);
588
+ await runDoltSql({ command, member, platform, doltPath, host, port, query: `CALL DOLT_CONFLICTS_RESOLVE('--theirs', '${table}');` });
589
+ return;
590
+ }
591
+ const pk = cols.includes('id') ? 'id' : cols[0];
592
+ const mutable = cols.filter((c) => c !== pk);
593
+ // TRUE per-field merge, against the BASE row -- not the design doc's
594
+ // original whole-row "recency wins every column" simplification, which the
595
+ // live disjoint-fields scenario disproved on fleet-lin-dev1: with A
596
+ // changing `status` and B changing `priority`, B's row was simply newer,
597
+ // so every column took B's value and A's status change was silently lost.
598
+ //
599
+ // Per field, in order:
600
+ // 1. we did not touch it (ours == base) -> take theirs
601
+ // 2. they did not touch it (theirs == base) -> take ours
602
+ // 3. BOTH changed it -> last-writer-wins on updated_at, tie to theirs
603
+ // (consistent with first-successful-pusher-wins: the remote already
604
+ // published)
605
+ // `<=>` is null-safe equality, so a NULL base (add/add, no base row) falls
606
+ // through to the LWW branch rather than matching everything.
607
+ const setClauses = mutable
608
+ .map((c) => ` t.${bq}${c}${bq} = CASE`
609
+ + ` WHEN c.our_${c} <=> c.base_${c} THEN c.their_${c}`
610
+ + ` WHEN c.their_${c} <=> c.base_${c} THEN c.our_${c}`
611
+ + ` WHEN c.their_updated_at >= c.our_updated_at THEN c.their_${c}`
612
+ + ` ELSE c.our_${c} END`)
613
+ .join(',\n ');
614
+ const updateSql = `
615
+ UPDATE ${bq}${table}${bq} t
616
+ JOIN dolt_conflicts_${table} c ON t.${bq}${pk}${bq} = c.our_${pk}
617
+ SET
618
+ ${setClauses},
619
+ t.updated_at = GREATEST(c.our_updated_at, c.their_updated_at)
620
+ WHERE t.${bq}${pk}${bq} IN (SELECT our_${pk} FROM dolt_conflicts_${table});
621
+ `;
622
+ await runDoltSql({ command, member, platform, doltPath, host, port, query: updateSql });
623
+
624
+ // Their-side-only rows (an add they made that we do not have) would be
625
+ // DROPPED by the --ours resolve below, so carry them over first.
626
+ const keyCols = (await tablePrimaryKey({ command, member, platform, doltPath, host, port, table })).length > 0
627
+ ? await tablePrimaryKey({ command, member, platform, doltPath, host, port, table })
628
+ : [pk];
629
+ await runDoltSql({ command, member, platform, doltPath, host, port, query: buildTheirMissingInsert(table, cols, keyCols) });
630
+
631
+ // --ours, NOT --theirs. The design doc flagged this as the one step to
632
+ // validate live, and the live run settled it: DOLT_CONFLICTS_RESOLVE
633
+ // rewrites the working-set row from the chosen side, so '--theirs' after
634
+ // the LWW UPDATE CLOBBERS the merged row (verified on fleet-lin-dev1: a
635
+ // row whose later updated_at was ours came back with their older value).
636
+ // '--ours' keeps the row the UPDATE just merged, which is the whole point
637
+ // of computing it.
638
+ await runDoltSql({ command, member, platform, doltPath, host, port, query: `CALL DOLT_CONFLICTS_RESOLVE('--ours', '${table}');` });
639
+ }
640
+
641
+ /**
642
+ * INSERT every `their_*` row from dolt_conflicts_<table> that is not already
643
+ * present on our side, keyed on `keyCols`. Shared by the LWW resolver (where
644
+ * it carries over their-side-only adds before an --ours resolve) and the
645
+ * set-union resolver (where it IS the union).
646
+ */
647
+ function buildTheirMissingInsert(table, cols, keyCols) {
648
+ const bq = String.fromCharCode(96);
649
+ const quote = (c) => `${bq}${c}${bq}`;
650
+ const insertCols = cols.map(quote).join(', ');
651
+ const selectCols = cols.map((c) => `c.their_${c}`).join(', ');
652
+ const notNullGuard = keyCols.map((c) => `c.their_${c} IS NOT NULL`).join(' AND ');
653
+ // NOTE: built by concatenation, not a template literal, purely so the
654
+ // source never contains a backtick immediately followed by 't' -- the
655
+ // repo's pre-commit PowerShell-escape guard flags that 2-char sequence.
656
+ const matchOnKey = keyCols.map((c) => 't.' + quote(c) + ` = c.their_${c}`).join(' AND ');
657
+ return `
658
+ INSERT INTO ${quote(table)} (${insertCols})
659
+ SELECT ${selectCols}
660
+ FROM dolt_conflicts_${table} c
661
+ WHERE ${notNullGuard}
662
+ AND NOT EXISTS (
663
+ SELECT 1 FROM ${quote(table)} t WHERE ${matchOnKey}
664
+ );
665
+ `;
666
+ }
667
+
668
+ /**
669
+ * Set-union for add/add conflicts (`labels`): BOTH sides' rows must survive,
670
+ * so a plain `--theirs`/`--ours` resolve is wrong on its own -- it keeps one
671
+ * side's row shape and drops the other side's added rows outright.
672
+ *
673
+ * Mechanism (design doc Part 3.2 step 4, "labels: set-union"): our side's rows
674
+ * are already in the working set by construction (they are what our clone
675
+ * committed), so the union reduces to inserting every `their_*` row from
676
+ * dolt_conflicts_<table> that is not already present on our side, keyed on the
677
+ * table's REAL uniqueness key -- read live from information_schema, never
678
+ * hardcoded (a schema change that renames/extends the key must not silently
679
+ * turn this into a no-op or a duplicate-row insert). The subsequent
680
+ * DOLT_CONFLICTS_RESOLVE only clears the conflict markers: the actual data
681
+ * reconciliation has already happened in the INSERT above.
682
+ *
683
+ * A table with no discoverable columns, or whose conflict view carries no
684
+ * `their_*` projection of the key, degrades to a plain `--theirs` resolve
685
+ * rather than issuing an INSERT it cannot construct correctly -- settle stays
686
+ * total either way.
687
+ */
688
+ async function resolveUnionTable({ command, member, platform, doltPath, host, port, table, log }) {
689
+ const cols = await tableColumns({ command, member, platform, doltPath, host, port, table });
690
+ if (cols.length === 0) {
691
+ log(`[Dolt Settle] table '${table}' set-union: could not read its columns from information_schema -- falling back to a plain --theirs resolve.`);
692
+ await runDoltSql({ command, member, platform, doltPath, host, port, query: `CALL DOLT_CONFLICTS_RESOLVE('--theirs', '${table}');` });
693
+ return;
694
+ }
695
+
696
+ const pkFromSchema = await tablePrimaryKey({ command, member, platform, doltPath, host, port, table });
697
+ const keyCols = pkFromSchema.length > 0 ? pkFromSchema : cols;
698
+ log(`[Dolt Settle] table '${table}' conflict: resolving as a set-union (both sides' rows kept; identity = ${keyCols.join(' + ')}).`);
699
+
700
+ await runDoltSql({ command, member, platform, doltPath, host, port, query: buildTheirMissingInsert(table, cols, keyCols) });
701
+ // --ours, not --theirs (same live finding as resolveLwwTable): the resolve
702
+ // rewrites the working-set row from the chosen side, so --theirs here
703
+ // would undo the union by dropping the rows only WE had. Their rows have
704
+ // just been inserted, so --ours is what actually keeps both sides.
705
+ await runDoltSql({ command, member, platform, doltPath, host, port, query: `CALL DOLT_CONFLICTS_RESOLVE('--ours', '${table}');` });
706
+ }
707
+
708
+ /** Plain theirs -- machine-local/config rows, and append-only tables
709
+ * (comments/events) where both sides already survive by construction. */
710
+ async function resolveTheirsTable({ command, member, platform, doltPath, host, port, table, log }) {
711
+ log(`[Dolt Settle] table '${table}' conflict: resolving --theirs.`);
712
+ await runDoltSql({ command, member, platform, doltPath, host, port, query: `CALL DOLT_CONFLICTS_RESOLVE('--theirs', '${table}');` });
713
+ }
714
+
715
+ /** Dispatch a single conflicted table to its rulebook entry, or the generic
716
+ * LWW fallback if it has no named entry -- this fallback is what makes
717
+ * settle total rather than an allowlist. */
718
+ async function resolveConflictedTable(ctx, table) {
719
+ const kind = NAMED_RULEBOOK[table] || 'lww';
720
+ if (kind === 'union') return resolveUnionTable({ ...ctx, table });
721
+ if (kind === 'theirs') return resolveTheirsTable({ ...ctx, table });
722
+ return resolveLwwTable({ ...ctx, table });
723
+ }
724
+
725
+ // ---------------------------------------------------------------------------
726
+ // Section 7: the orchestrator.
727
+ // ---------------------------------------------------------------------------
728
+
729
+ /**
730
+ * @typedef {Object} SettleOpts
731
+ * @property {(cmd: string, opts?: object) => Promise<{ok: boolean, output?: string, error?: string}>} command
732
+ * @property {(msg: string) => void} [log]
733
+ * @property {'win32'|'linux'|'darwin'} platform - the MEMBER's platform. REQUIRED -- never assume process.platform.
734
+ * @property {'x64'|'arm64'} [arch]
735
+ * @property {string} [remote]
736
+ * @property {string} [branch]
737
+ * @property {number} [portRangeStart]
738
+ * @property {number} [portRangeEnd]
739
+ */
740
+
741
+ /**
742
+ * Total, deterministic settle: resolves EVERY row-level Dolt conflict shape
743
+ * this data model can produce, no gates, no escalation. Only throws on a
744
+ * genuine operational failure (no usable dolt binary, server wouldn't
745
+ * start, a SQL statement errored for a reason unrelated to conflict
746
+ * content) -- callers treat that exactly like any other infra command
747
+ * failure (dolt-sync.mjs's existing degraded/fatal taxonomy), NOT as a
748
+ * ladder tier.
749
+ *
750
+ * @param {string} member
751
+ * @param {SettleOpts} opts
752
+ * @returns {Promise<{ ok: true, resolvedTables: string[], warnings: string[], doltVersionUsed: string }>}
753
+ */
754
+ export async function settleDoltConflicts(member, opts = {}) {
755
+ const {
756
+ command,
757
+ log = () => {},
758
+ platform,
759
+ arch = 'x64',
760
+ remote = 'origin',
761
+ branch = 'main',
762
+ portRangeStart = DEFAULT_PORT_RANGE.start,
763
+ portRangeEnd = DEFAULT_PORT_RANGE.end,
764
+ } = opts;
765
+
766
+ if (!member) throw new Error('settleDoltConflicts requires a member');
767
+ if (typeof command !== 'function') throw new Error('settleDoltConflicts requires an injected command() in opts');
768
+ if (!platform) throw new Error("settleDoltConflicts requires opts.platform ('win32'|'linux'|'darwin') -- the MEMBER's platform, never assumed");
769
+
770
+ let host = RECOVERY_SQL_SERVER_HOST;
771
+ let pid = null;
772
+ let port = null;
773
+ let weSpawnedTheServer = false;
774
+
775
+ try {
776
+ // Step 0: resolve the real data dir/mode -- never hardcoded.
777
+ const status = await resolveDoltStatus({ command, member, log });
778
+
779
+ // Step 1: ensure a correctly-pinned (or functionally-probed-fallback)
780
+ // dolt binary exists on the member.
781
+ const doltInfo = await ensurePinnedDolt({ command, member, platform, arch, log });
782
+ const warnings = [...doltInfo.warnings];
783
+
784
+ if (status.mode === 'server' && status.host && status.port) {
785
+ // Reuse the member's own already-live server rather than spawning
786
+ // a second one against the same data dir (design doc Part 3.5/7.2).
787
+ host = status.host;
788
+ port = status.port;
789
+ log(`[Dolt Settle] member '${member}' already has a live server at ${status.host}:${status.port} -- targeting it instead of spawning a second one.`);
790
+ } else {
791
+ const dataDir = status.dataDir || DEFAULT_EMBEDDED_DATA_DIR;
792
+ port = await pickFreePort({ command, member, platform, portRangeStart, portRangeEnd });
793
+
794
+ // A busy candidate port is SKIPPED, not killed-and-reused: pickFreePort
795
+ // only ever hands back a port nothing answers on (design doc Part 3.5,
796
+ // amended -- see pickFreePort's own docstring below for why). A
797
+ // stray already-listening server on/near our data dir is left for
798
+ // the supervisor's orphan sweep to reap; settle does not attempt to
799
+ // distinguish "genuinely orphaned residue" from "another concurrent
800
+ // settle legitimately in progress" inline, since getting that
801
+ // distinction wrong (killing a live settle) is worse than the
802
+ // bounded wait on the sweep.
803
+ const spawned = await spawnEphemeralServer({ command, member, platform, doltPath: doltInfo.doltPath, dataDir, host, port, log });
804
+ pid = spawned.pid;
805
+ weSpawnedTheServer = true;
806
+ await waitForServerReady({ command, member, platform, host, port, log });
807
+ }
808
+
809
+ // If not preflight-validated by the pin ladder, the fallback dolt
810
+ // must pass a harmless functional preflight before any real data is
811
+ // touched (Part 5.6 step 3). runDoltSql() already throws a
812
+ // DoltSyncError on any command failure (res.ok === false) and
813
+ // otherwise always returns an array (parseDoltJsonRows never returns
814
+ // a non-array) -- so that throw IS the gate; there is no reachable
815
+ // "succeeded but returned something unusable" case to additionally
816
+ // check here.
817
+ if (!doltInfo.pinned) {
818
+ await runDoltSql({ command, member, platform, doltPath: doltInfo.doltPath, host, port, query: 'SELECT 1;', log });
819
+ }
820
+
821
+ // Step 3/4: re-open the merge, enumerate every conflicted table.
822
+ const ctx = { command, member, platform, doltPath: doltInfo.doltPath, host, port, log };
823
+ await runDoltSql({ ...ctx, query: `CALL DOLT_MERGE('${remote}/${branch}');` });
824
+
825
+ // NOTE: `SELECT *`, not a backtick-quoted `table` column -- dolt_conflicts'
826
+ // only other column is num_conflicts, and avoiding the identifier quote
827
+ // keeps this one (very frequently issued) query free of the shell's
828
+ // backtick minefield entirely.
829
+ const conflictRows = await runDoltSql({ ...ctx, query: 'SELECT * FROM dolt_conflicts;' });
830
+ const tables = conflictRows.map((r) => r.table || r.TABLE).filter(Boolean);
831
+
832
+ if (tables.length === 0) {
833
+ log(`[Dolt Settle] no conflicted tables found for member '${member}' after DOLT_MERGE -- nothing to resolve (the clone may have already been fixed).`);
834
+ }
835
+
836
+ for (const table of tables) {
837
+ // eslint-disable-next-line no-await-in-loop -- sequential by design: each table's UPDATE must land before its own DOLT_CONFLICTS_RESOLVE
838
+ await resolveConflictedTable(ctx, table);
839
+ }
840
+
841
+ await runDoltSql({ ...ctx, query: `CALL DOLT_COMMIT('-m', 'settle: automated deterministic conflict resolution for ${member}');` });
842
+
843
+ const remaining = await runDoltSql({ ...ctx, query: 'SELECT COUNT(*) AS n FROM dolt_conflicts;' });
844
+ const remainingCount = Number((remaining[0] && (remaining[0].n ?? remaining[0].N)) || 0);
845
+ if (remainingCount !== 0) {
846
+ throw new DoltSyncError(`[Dolt Settle] ${remainingCount} conflict(s) still remain for member '${member}' after resolving every enumerated table -- refusing to commit/push a partially-resolved clone.`, { member });
847
+ }
848
+
849
+ // Step 5 (CORRECTED ORDER, design doc Part 7.2): tear the server down
850
+ // BEFORE republishing -- embedded bd must not race the server's
851
+ // exclusive chunk-journal lock on the same data dir.
852
+ if (weSpawnedTheServer && pid) {
853
+ await killServerAndVerify({ command, member, platform, pid, host, port, log });
854
+ pid = null;
855
+ }
856
+
857
+ const pull = await command('bd dolt pull', { member_name: member, silent: true, failSoft: true, label: `settle: post-resolve D-pull for '${member}'` });
858
+ if (pull && pull.ok === false) {
859
+ throw new DoltDivergedError(`[Dolt Settle] post-resolve pull still failed for member '${member}': ${pull.error}`, { member, doltOutput: pull.error, operation: 'settle-pull' });
860
+ }
861
+ const push = await command('bd dolt push', { member_name: member, silent: true, failSoft: true, label: `settle: post-resolve D-push for '${member}'` });
862
+ if (push && push.ok === false) {
863
+ throw new DoltDivergedError(`[Dolt Settle] resolved every conflict but the republishing push was still rejected for member '${member}': ${push.error}`, { member, doltOutput: push.error, operation: 'settle-push' });
864
+ }
865
+
866
+ log(`[Dolt Settle] SUCCEEDED for member '${member}': ${tables.length} table(s) resolved (${tables.join(', ') || 'none'}), republished.`);
867
+ return { ok: true, resolvedTables: tables, warnings, doltVersionUsed: doltInfo.version };
868
+ } finally {
869
+ // Guaranteed teardown -- covers every throw path above. On the happy
870
+ // path pid is already null (torn down before republish per 7.2).
871
+ if (weSpawnedTheServer && pid) {
872
+ await killServerAndVerify({ command, member, platform, pid, host, port, log }).catch((err) => {
873
+ log(`[Dolt Settle] WARNING: finally-block teardown failed for member '${member}': ${err.message}`);
874
+ });
875
+ }
876
+ }
877
+ }
878
+
879
+ // ---------------------------------------------------------------------------
880
+ // Section 8: the wiring seam -- what dolt-sync.mjs/runner.js actually hold.
881
+ // ---------------------------------------------------------------------------
882
+
883
+ /**
884
+ * Resolve the MEMBER's platform/arch (never the orchestrator's -- see design
885
+ * doc Part 5.3). Callers that already have registry metadata should pass
886
+ * `platform`/`arch` explicitly; this probe is the fallback for callers (like
887
+ * the sprint runner's sync brackets) that only hold a member name and a
888
+ * command(). Members necessarily have node, since `bd` is npm-installed.
889
+ *
890
+ * @returns {Promise<{ platform: 'win32'|'linux'|'darwin', arch: string }>}
891
+ */
892
+ export async function detectMemberPlatform({ command, member }) {
893
+ // Quote-free JS on purpose: PowerShell 5.1 mangles quotes inside native
894
+ // arguments, so a snippet with no quotes at all is the one form that
895
+ // survives every member shell unchanged.
896
+ const res = await command("node -e 'console.log(process.platform,process.arch)'", {
897
+ member_name: member, silent: true, failSoft: true, label: `settle: detect platform for '${member}'`,
898
+ });
899
+ const text = String((res && (res.output || res.error)) || '');
900
+ const match = text.match(/\b(win32|linux|darwin)\b\s+(\S+)/);
901
+ if (!match) {
902
+ throw new DoltSyncError(
903
+ `[Dolt Settle] could not detect the platform of member '${member}' -- settle refuses to assume the orchestrator's own platform. Raw: ${text.slice(0, 200)}`,
904
+ { member, doltOutput: text },
905
+ );
906
+ }
907
+ return { platform: match[1], arch: match[2] === 'arm64' ? 'arm64' : 'x64' };
908
+ }
909
+
910
+ /**
911
+ * Build the zero-argument settle callback the sync brackets hold at their
912
+ * divergence terminals (`opts.settle` in dolt-sync.mjs). This is the single
913
+ * seam that REPLACES buildDoltRecoveryLadder(): one deterministic function,
914
+ * no tiers, no agent/model threading, and -- unlike the old ladder -- a
915
+ * resolved promise IS a verified recovery, because settle republishes and
916
+ * verifies before returning.
917
+ *
918
+ * The member's platform is resolved lazily on first invocation (nothing is
919
+ * probed unless a divergence actually happens) and cached for the callback's
920
+ * lifetime.
921
+ *
922
+ * @param {string} member
923
+ * @param {{ command: Function, log?: Function, platform?: string, arch?: string }} opts
924
+ * @returns {() => Promise<{ ok: true, resolvedTables: string[], warnings: string[], doltVersionUsed: string }>}
925
+ */
926
+ export function buildSettleCallback(member, opts = {}) {
927
+ const { command, log = () => {}, platform, arch } = opts;
928
+ if (!member) throw new Error('buildSettleCallback requires a member');
929
+ if (typeof command !== 'function') throw new Error('buildSettleCallback requires an injected command() in opts');
930
+
931
+ let resolved = platform ? { platform, arch: arch || 'x64' } : null;
932
+ return async () => {
933
+ if (!resolved) resolved = await detectMemberPlatform({ command, member });
934
+ return settleDoltConflicts(member, { command, log, platform: resolved.platform, arch: resolved.arch });
935
+ };
936
+ }
937
+
938
+ /**
939
+ * Ephemeral port selection: find the first port in the range nothing is
940
+ * answering on. Deliberately ONE dispatch that scans member-side rather than
941
+ * one dispatch per candidate port -- a 100-port range would otherwise be 100
942
+ * SSH round trips.
943
+ *
944
+ * A port already answering is NOT reused even though it might be an orphaned
945
+ * settle server: per design doc Part 3.5, this is a DELIBERATE, accepted
946
+ * trade-off, not the originally-sketched "kill it, then spawn fresh" -- a
947
+ * same-data-dir orphan cannot be safely distinguished inline from another
948
+ * concurrent settle legitimately in progress without risking killing a live
949
+ * one, so settle always skips to the next free port and leaves reaping to the
950
+ * supervisor's orphan sweep (dolt-orphan-sweep.mjs). Consequence: if the
951
+ * orchestrator dies mid-settle, a fresh settle attempt against the SAME data
952
+ * dir can be blocked (lock held / falls back read-only) for up to the sweep's
953
+ * age threshold plus its run interval (~15 minutes with the current
954
+ * defaults) until the sweep reaps the orphan.
955
+ */
956
+ async function pickFreePort({ command, member, platform, portRangeStart, portRangeEnd }) {
957
+ // Same node-based probe as tcpProbeScript, scanning the range member-side
958
+ // in ONE dispatch: a round trip per candidate port would be 100 SSH
959
+ // sessions, and no shell one-liner is portable across PowerShell 5.1,
960
+ // bash and zsh (see tcpProbeScript for the live evidence).
961
+ const script = nodeEval(platform,
962
+ `const net=require("net");const host="${RECOVERY_SQL_SERVER_HOST}";`
963
+ + 'const free=(p)=>new Promise((r)=>{const s=net.connect(p,host);const done=(v)=>{try{s.destroy()}catch(e){};r(v)};'
964
+ + 's.on("connect",()=>done(false));s.on("error",()=>done(true));setTimeout(()=>done(true),500)});'
965
+ + `(async()=>{for(let p=${portRangeStart};p<${portRangeEnd};p++){if(await free(p)){console.log("FREEPORT:"+p);break}}})()`);
966
+ const res = await command(script, { member_name: member, silent: true, failSoft: true, label: `settle: pick a free ephemeral port for '${member}'` });
967
+ const match = String((res && res.output) || '').match(/FREEPORT:(\d+)/);
968
+ if (!match) {
969
+ throw new DoltSyncError(`[Dolt Settle] no free port in range [${portRangeStart}, ${portRangeEnd}) for member '${member}'.`, { member, doltOutput: (res && (res.output || res.error)) || '' });
970
+ }
971
+ return Number(match[1]);
972
+ }