@apralabs/apra-fleet 0.4.1 → 0.4.2

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 (276) hide show
  1. package/README.md +16 -8
  2. package/dist/agents/backlog-groomer.md +17 -21
  3. package/dist/agents/ci-watcher.md +3 -0
  4. package/dist/agents/deployer.md +22 -44
  5. package/dist/agents/doer.md +131 -132
  6. package/dist/agents/harvester.md +20 -32
  7. package/dist/agents/integ-test-runner.md +81 -113
  8. package/dist/agents/kb-reconciler.md +31 -42
  9. package/dist/agents/plan-reviewer.md +32 -44
  10. package/dist/agents/planner.md +51 -63
  11. package/dist/agents/regression-test-runner.md +65 -80
  12. package/dist/agents/reviewer.md +56 -83
  13. package/dist/agents/schemas/integ-test-runner-output.json +1 -1
  14. package/dist/agents/schemas/regression-test-runner-output.json +4 -17
  15. package/dist/cli/auth.d.ts.map +1 -1
  16. package/dist/cli/auth.js +1 -2
  17. package/dist/cli/auth.js.map +1 -1
  18. package/dist/cli/config.d.ts +3 -3
  19. package/dist/cli/config.d.ts.map +1 -1
  20. package/dist/cli/config.js +4 -13
  21. package/dist/cli/config.js.map +1 -1
  22. package/dist/cli/install.d.ts.map +1 -1
  23. package/dist/cli/install.js +5 -39
  24. package/dist/cli/install.js.map +1 -1
  25. package/dist/cli/register-member.js +1 -1
  26. package/dist/cli/start.d.ts.map +1 -1
  27. package/dist/cli/start.js +7 -0
  28. package/dist/cli/start.js.map +1 -1
  29. package/dist/cli/uninstall.d.ts.map +1 -1
  30. package/dist/cli/uninstall.js +5 -3
  31. package/dist/cli/uninstall.js.map +1 -1
  32. package/dist/cli/watch.d.ts +26 -3
  33. package/dist/cli/watch.d.ts.map +1 -1
  34. package/dist/cli/watch.js +41 -9
  35. package/dist/cli/watch.js.map +1 -1
  36. package/dist/os/git-bash-candidates.d.ts +35 -0
  37. package/dist/os/git-bash-candidates.d.ts.map +1 -0
  38. package/dist/os/git-bash-candidates.js +46 -0
  39. package/dist/os/git-bash-candidates.js.map +1 -0
  40. package/dist/os/index.d.ts +13 -4
  41. package/dist/os/index.d.ts.map +1 -1
  42. package/dist/os/index.js +17 -2
  43. package/dist/os/index.js.map +1 -1
  44. package/dist/os/linux.js +1 -1
  45. package/dist/os/linux.js.map +1 -1
  46. package/dist/os/os-commands.d.ts +7 -0
  47. package/dist/os/os-commands.d.ts.map +1 -1
  48. package/dist/os/os-commands.js.map +1 -1
  49. package/dist/os/windows-gitbash.d.ts +93 -0
  50. package/dist/os/windows-gitbash.d.ts.map +1 -0
  51. package/dist/os/windows-gitbash.js +244 -0
  52. package/dist/os/windows-gitbash.js.map +1 -0
  53. package/dist/os/windows.d.ts.map +1 -1
  54. package/dist/os/windows.js +27 -5
  55. package/dist/os/windows.js.map +1 -1
  56. package/dist/providers/agy.d.ts +3 -2
  57. package/dist/providers/agy.d.ts.map +1 -1
  58. package/dist/providers/agy.js +11 -2
  59. package/dist/providers/agy.js.map +1 -1
  60. package/dist/providers/claude.d.ts +3 -2
  61. package/dist/providers/claude.d.ts.map +1 -1
  62. package/dist/providers/claude.js +22 -3
  63. package/dist/providers/claude.js.map +1 -1
  64. package/dist/providers/codex.d.ts +3 -2
  65. package/dist/providers/codex.d.ts.map +1 -1
  66. package/dist/providers/codex.js +5 -2
  67. package/dist/providers/codex.js.map +1 -1
  68. package/dist/providers/copilot.d.ts +3 -2
  69. package/dist/providers/copilot.d.ts.map +1 -1
  70. package/dist/providers/copilot.js +7 -2
  71. package/dist/providers/copilot.js.map +1 -1
  72. package/dist/providers/index.d.ts +0 -1
  73. package/dist/providers/index.d.ts.map +1 -1
  74. package/dist/providers/index.js +0 -3
  75. package/dist/providers/index.js.map +1 -1
  76. package/dist/providers/none.d.ts +3 -2
  77. package/dist/providers/none.d.ts.map +1 -1
  78. package/dist/providers/none.js +5 -2
  79. package/dist/providers/none.js.map +1 -1
  80. package/dist/providers/opencode.d.ts +3 -2
  81. package/dist/providers/opencode.d.ts.map +1 -1
  82. package/dist/providers/opencode.js +5 -2
  83. package/dist/providers/opencode.js.map +1 -1
  84. package/dist/providers/provider.d.ts +16 -7
  85. package/dist/providers/provider.d.ts.map +1 -1
  86. package/dist/providers/provider.js +2 -2
  87. package/dist/providers/provider.js.map +1 -1
  88. package/dist/services/agent-provisioner.js +2 -2
  89. package/dist/services/agent-provisioner.js.map +1 -1
  90. package/dist/services/cloud/activity.js +2 -2
  91. package/dist/services/cloud/activity.js.map +1 -1
  92. package/dist/services/context-admission.d.ts.map +1 -1
  93. package/dist/services/context-admission.js +9 -7
  94. package/dist/services/context-admission.js.map +1 -1
  95. package/dist/services/credential-cleanup.d.ts.map +1 -1
  96. package/dist/services/credential-cleanup.js +22 -3
  97. package/dist/services/credential-cleanup.js.map +1 -1
  98. package/dist/services/member-home.d.ts +1 -1
  99. package/dist/services/member-home.d.ts.map +1 -1
  100. package/dist/services/member-home.js +15 -12
  101. package/dist/services/member-home.js.map +1 -1
  102. package/dist/services/model-pricing.d.ts.map +1 -1
  103. package/dist/services/model-pricing.js +0 -5
  104. package/dist/services/model-pricing.js.map +1 -1
  105. package/dist/services/orphan-recovery.d.ts +6 -3
  106. package/dist/services/orphan-recovery.d.ts.map +1 -1
  107. package/dist/services/orphan-recovery.js +17 -14
  108. package/dist/services/orphan-recovery.js.map +1 -1
  109. package/dist/services/preflight-check.js +2 -2
  110. package/dist/services/preflight-check.js.map +1 -1
  111. package/dist/services/shell-probe.d.ts +131 -0
  112. package/dist/services/shell-probe.d.ts.map +1 -0
  113. package/dist/services/shell-probe.js +210 -0
  114. package/dist/services/shell-probe.js.map +1 -0
  115. package/dist/services/singleton.d.ts +2 -0
  116. package/dist/services/singleton.d.ts.map +1 -1
  117. package/dist/services/singleton.js +1 -1
  118. package/dist/services/singleton.js.map +1 -1
  119. package/dist/services/ssh.js +2 -2
  120. package/dist/services/ssh.js.map +1 -1
  121. package/dist/services/stall/find-log-file.d.ts.map +1 -1
  122. package/dist/services/stall/find-log-file.js +22 -16
  123. package/dist/services/stall/find-log-file.js.map +1 -1
  124. package/dist/services/stall/read-log-tail.d.ts.map +1 -1
  125. package/dist/services/stall/read-log-tail.js +6 -5
  126. package/dist/services/stall/read-log-tail.js.map +1 -1
  127. package/dist/services/stall/stall-poller.d.ts.map +1 -1
  128. package/dist/services/stall/stall-poller.js +35 -42
  129. package/dist/services/stall/stall-poller.js.map +1 -1
  130. package/dist/services/strategy.d.ts +9 -0
  131. package/dist/services/strategy.d.ts.map +1 -1
  132. package/dist/services/strategy.js +40 -6
  133. package/dist/services/strategy.js.map +1 -1
  134. package/dist/services/user-config.js +1 -1
  135. package/dist/services/user-config.js.map +1 -1
  136. package/dist/services/vcs/azure-devops.d.ts +1 -1
  137. package/dist/services/vcs/azure-devops.d.ts.map +1 -1
  138. package/dist/services/vcs/azure-devops.js +105 -10
  139. package/dist/services/vcs/azure-devops.js.map +1 -1
  140. package/dist/services/vcs/bitbucket.d.ts.map +1 -1
  141. package/dist/services/vcs/bitbucket.js +16 -0
  142. package/dist/services/vcs/bitbucket.js.map +1 -1
  143. package/dist/services/vcs/github.d.ts.map +1 -1
  144. package/dist/services/vcs/github.js +24 -0
  145. package/dist/services/vcs/github.js.map +1 -1
  146. package/dist/services/vcs/types.d.ts +123 -2
  147. package/dist/services/vcs/types.d.ts.map +1 -1
  148. package/dist/skills/fleet-sprint-cli/SKILL.md +2 -1
  149. package/dist/skills/pm/SKILL.md +0 -1
  150. package/dist/skills/pm/cost.md +0 -1
  151. package/dist/skills/pm/fleet-addendum.md +0 -1
  152. package/dist/tools/check-status.js +3 -3
  153. package/dist/tools/check-status.js.map +1 -1
  154. package/dist/tools/cloud-control.js +2 -2
  155. package/dist/tools/cloud-control.js.map +1 -1
  156. package/dist/tools/compose-permissions.d.ts.map +1 -1
  157. package/dist/tools/compose-permissions.js +37 -24
  158. package/dist/tools/compose-permissions.js.map +1 -1
  159. package/dist/tools/execute-command.d.ts.map +1 -1
  160. package/dist/tools/execute-command.js +28 -12
  161. package/dist/tools/execute-command.js.map +1 -1
  162. package/dist/tools/execute-prompt.d.ts.map +1 -1
  163. package/dist/tools/execute-prompt.js +55 -18
  164. package/dist/tools/execute-prompt.js.map +1 -1
  165. package/dist/tools/list-members.d.ts.map +1 -1
  166. package/dist/tools/list-members.js +6 -2
  167. package/dist/tools/list-members.js.map +1 -1
  168. package/dist/tools/member-detail.d.ts.map +1 -1
  169. package/dist/tools/member-detail.js +5 -3
  170. package/dist/tools/member-detail.js.map +1 -1
  171. package/dist/tools/member-reservation.d.ts.map +1 -1
  172. package/dist/tools/member-reservation.js +13 -1
  173. package/dist/tools/member-reservation.js.map +1 -1
  174. package/dist/tools/monitor-task.d.ts.map +1 -1
  175. package/dist/tools/monitor-task.js +17 -2
  176. package/dist/tools/monitor-task.js.map +1 -1
  177. package/dist/tools/provision-auth.js +5 -5
  178. package/dist/tools/provision-auth.js.map +1 -1
  179. package/dist/tools/provision-vcs-auth.d.ts +5 -2
  180. package/dist/tools/provision-vcs-auth.d.ts.map +1 -1
  181. package/dist/tools/provision-vcs-auth.js +58 -52
  182. package/dist/tools/provision-vcs-auth.js.map +1 -1
  183. package/dist/tools/register-member.d.ts +18 -12
  184. package/dist/tools/register-member.d.ts.map +1 -1
  185. package/dist/tools/register-member.js +42 -4
  186. package/dist/tools/register-member.js.map +1 -1
  187. package/dist/tools/remove-member.js +2 -2
  188. package/dist/tools/remove-member.js.map +1 -1
  189. package/dist/tools/revoke-vcs-auth.js +2 -2
  190. package/dist/tools/revoke-vcs-auth.js.map +1 -1
  191. package/dist/tools/setup-ssh-key.d.ts.map +1 -1
  192. package/dist/tools/setup-ssh-key.js +2 -1
  193. package/dist/tools/setup-ssh-key.js.map +1 -1
  194. package/dist/tools/stop-prompt.js +2 -2
  195. package/dist/tools/stop-prompt.js.map +1 -1
  196. package/dist/tools/update-agent-cli.js +2 -2
  197. package/dist/tools/update-agent-cli.js.map +1 -1
  198. package/dist/tools/update-member.d.ts +18 -12
  199. package/dist/tools/update-member.d.ts.map +1 -1
  200. package/dist/tools/update-member.js +18 -1
  201. package/dist/tools/update-member.js.map +1 -1
  202. package/dist/types.d.ts +11 -1
  203. package/dist/types.d.ts.map +1 -1
  204. package/dist/utils/agent-helpers.d.ts +36 -0
  205. package/dist/utils/agent-helpers.d.ts.map +1 -1
  206. package/dist/utils/agent-helpers.js +39 -1
  207. package/dist/utils/agent-helpers.js.map +1 -1
  208. package/dist/utils/platform.d.ts +7 -0
  209. package/dist/utils/platform.d.ts.map +1 -1
  210. package/dist/utils/platform.js +11 -1
  211. package/dist/utils/platform.js.map +1 -1
  212. package/dist/utils/workspace-trust.d.ts.map +1 -1
  213. package/dist/utils/workspace-trust.js +5 -1
  214. package/dist/utils/workspace-trust.js.map +1 -1
  215. package/dist/workflows/auto-sprint.js +4 -17
  216. package/package.json +2 -2
  217. package/packages/apra-fleet-client/src/client/api.mjs +92 -3
  218. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +17 -21
  219. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +3 -0
  220. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +22 -44
  221. package/packages/apra-fleet-se/apra-pm/agents/doer.md +131 -132
  222. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +20 -32
  223. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +81 -113
  224. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +31 -42
  225. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +32 -44
  226. package/packages/apra-fleet-se/apra-pm/agents/planner.md +51 -63
  227. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +65 -80
  228. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +56 -83
  229. package/packages/apra-fleet-se/apra-pm/agents/schemas/integ-test-runner-output.json +1 -1
  230. package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-output.json +4 -17
  231. package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +0 -1
  232. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +0 -1
  233. package/packages/apra-fleet-se/apra-pm/skills/pm/fleet-addendum.md +0 -1
  234. package/packages/apra-fleet-se/bin/cli.mjs +132 -3
  235. package/packages/apra-fleet-se/bin/serve.mjs +36 -1
  236. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +151 -33
  237. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +22 -7
  238. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-manual-recovery-verified.md +10 -8
  239. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +9 -4
  240. package/packages/apra-fleet-se/fleet-sprint/docs/escalate-to-llm-design.md +2 -2
  241. package/packages/apra-fleet-se/fleet-sprint/docs/shared-orchestrator-reservation-design.md +12 -12
  242. package/packages/apra-fleet-se/fleet-sprint/docs/stabilization-log.md +14 -4
  243. package/packages/apra-fleet-se/fleet-sprint/dolt-settle.mjs +275 -99
  244. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +67 -16
  245. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +41 -0
  246. package/packages/apra-fleet-se/fleet-sprint/runner.js +1140 -209
  247. package/packages/apra-fleet-se/fleet-sprint/se-os-commands.mjs +134 -0
  248. package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +154 -0
  249. package/packages/apra-fleet-se/fleet-sprint/se-windows-gitbash.mjs +97 -0
  250. package/packages/apra-fleet-se/fleet-sprint/se-windows.mjs +143 -0
  251. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +2 -1
  252. package/packages/apra-fleet-se/fleet-sprint/vcs-module.mjs +51 -0
  253. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/azure-devops.mjs +657 -12
  254. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/dolt.mjs +33 -4
  255. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +60 -43
  256. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +205 -2
  257. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/shell-helpers.mjs +164 -0
  258. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +92 -37
  259. package/packages/apra-fleet-workflow/src/viewer/index.mjs +167 -1
  260. package/packages/apra-fleet-workflow/src/workflow/index.mjs +435 -31
  261. package/skills/fleet/SKILL.md +20 -9
  262. package/skills/fleet/auth-azdevops.md +44 -5
  263. package/skills/fleet/auth-bitbucket.md +3 -3
  264. package/skills/fleet/auth-github.md +2 -2
  265. package/skills/fleet/beads-conflict-resolution.md +141 -0
  266. package/skills/fleet/beads.md +16 -12
  267. package/skills/fleet/onboarding.md +4 -4
  268. package/skills/fleet/permissions.md +6 -6
  269. package/skills/fleet/skill-matrix.md +1 -1
  270. package/skills/fleet/troubleshooting.md +2 -1
  271. package/version.json +1 -1
  272. package/dist/providers/gemini.d.ts +0 -52
  273. package/dist/providers/gemini.d.ts.map +0 -1
  274. package/dist/providers/gemini.js +0 -236
  275. package/dist/providers/gemini.js.map +0 -1
  276. package/packages/apra-fleet-se/fleet-sprint/docs/coach-role-design.md +0 -23
@@ -56,6 +56,7 @@
56
56
  // =============================================================================
57
57
 
58
58
  import { DoltDivergedError, DoltSyncError, DoltBinaryUnavailableError } from './errors.mjs';
59
+ import { getSeCommands } from './se-os-commands.mjs';
59
60
 
60
61
  /** Must equal src/cli/dolt-install.ts's DOLT_VERSION byte-for-byte -- a
61
62
  * drift-guard test (dolt-settle.test.mjs) asserts this against that file's
@@ -122,12 +123,22 @@ export function resolveDoltAsset(platform, arch) {
122
123
  return { assetName, url: `${DOLT_RELEASE_BASE}/${assetName}`, archiveType, binaryName };
123
124
  }
124
125
 
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"';
126
+ /**
127
+ * The member-side fleet-managed dolt path, resolved with the MEMBER's own
128
+ * shell dialect (never the orchestrator's homedir/platform) via
129
+ * se-os-commands.mjs's getSeCommands(). The binary filename is still
130
+ * OS-dependent (dolt.exe on either Windows dialect, dolt everywhere else --
131
+ * the same OS-vs-shell distinction resolveDoltAsset's platform-branched
132
+ * asset selection stays on), decided off the resolved primitive's `.shell`
133
+ * identifier rather than a `platform === 'win32'` check, so this function
134
+ * carries no platform branch of its own (apra-fleet-7dir.16).
135
+ * @param {{ os?: string, shell?: string }|string} target
136
+ * @returns {string} a double-quoted, shell-dialect-correct path
137
+ */
138
+ function memberDoltPath(target) {
139
+ const seCmds = getSeCommands(target);
140
+ const binaryName = seCmds.shell === 'posix' ? 'dolt' : 'dolt.exe';
141
+ return `"${seCmds.homePath(`.apra-fleet/bin/${binaryName}`)}"`;
131
142
  }
132
143
 
133
144
  // ---------------------------------------------------------------------------
@@ -144,34 +155,38 @@ function memberDoltPath(platform) {
144
155
  // can avoid backticks entirely simply does).
145
156
  // - `cmd 2>$null || fallback` parses in bash but is a hard parse ERROR in
146
157
  // PowerShell 5.1, so no single "works everywhere" probe string exists.
158
+ //
159
+ // memberDoltPath/invokeBinary/escapeSqlForShell all resolve their dialect via
160
+ // se-os-commands.mjs's getSeCommands({ os, shell }) rather than a bare
161
+ // `platform === 'win32'` check (apra-fleet-7dir.16/.20), so a Windows member
162
+ // whose registered shell is Git-for-Windows bash gets the bash dialect for
163
+ // all three instead of being force-assumed PowerShell.
147
164
  // ---------------------------------------------------------------------------
148
165
 
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}`;
166
+ /**
167
+ * Invoke an executable at a quoted path with arguments, in the member's
168
+ * actual shell dialect.
169
+ * @param {{ os?: string, shell?: string }|string} target
170
+ * @param {string} quotedPath
171
+ * @param {string} args
172
+ */
173
+ function invokeBinary(target, quotedPath, args) {
174
+ return getSeCommands(target).shell === 'powershell' ? `& ${quotedPath} ${args}` : `${quotedPath} ${args}`;
152
175
  }
153
176
 
154
177
  /**
155
178
  * Escape a SQL string so it survives as ONE double-quoted argument in the
156
179
  * member's shell. Backticks and `$` are the dangerous characters in both
157
- * dialects, for opposite reasons.
180
+ * dialects, for opposite reasons. Delegates to se-os-commands.mjs's
181
+ * escapeSqlArg primitive (apra-fleet-7dir.20) rather than re-implementing the
182
+ * escaping here.
183
+ * @param {{ os?: string, shell?: string }|string} target bare platform string
184
+ * ('win32'|'linux'|'darwin', back-compat with every existing caller/test)
185
+ * or a { os, shell } record for full shell-dialect fidelity.
186
+ * @param {string} sql
158
187
  */
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, '\\"');
188
+ export function escapeSqlForShell(target, sql) {
189
+ return getSeCommands(target).escapeSqlArg(sql);
175
190
  }
176
191
 
177
192
  // ---------------------------------------------------------------------------
@@ -204,16 +219,25 @@ export async function resolveDoltStatus({ command, member, log = () => {} }) {
204
219
  // ---------------------------------------------------------------------------
205
220
 
206
221
  /** 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}'` });
222
+ async function probeDoltVersion({ command, member, doltPath, platform, shell = '' }) {
223
+ const res = await command(invokeBinary({ os: platform, shell }, doltPath, 'version'), { member_name: member, silent: true, failSoft: true, label: `settle: probe dolt version for '${member}'` });
209
224
  const text = String((res && (res.output || res.error)) || '');
210
225
  const match = text.match(/dolt version (\d+\.\d+\.\d+\S*)/i);
211
226
  return { ok: !!(res && res.ok !== false) && !!match, version: match ? match[1] : null, raw: text };
212
227
  }
213
228
 
214
229
  /** 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 }) {
230
+ * asset URL resolveDoltAsset() computes. Bounded, single-attempt.
231
+ * The PowerShell script body is kept byte-identical to today regardless of
232
+ * the member's registered shell -- it is `doltPath` (already the
233
+ * PowerShell-dialect `psDoltPath` form, resolved by the caller) that must
234
+ * stay in `$env:USERPROFILE...` form even for a gitbash member, since the
235
+ * dialect INSIDE the wrapped script is PowerShell, not the member's own
236
+ * shell (apra-fleet-7dir.21's NON-OBVIOUS constraint). Only the OUTER
237
+ * invocation is routed via getSeCommands(...).wrapPowerShellScript, which
238
+ * returns the script unchanged for a powershell member and a bash-invocable
239
+ * `-EncodedCommand` form for a gitbash member. */
240
+ async function installPinnedDolt({ command, member, platform, arch, doltPath, shell = '', log }) {
217
241
  const asset = resolveDoltAsset(platform, arch);
218
242
  log(`[Dolt Settle] installing pinned dolt ${DOLT_VERSION} on member '${member}' from ${asset.url}`);
219
243
 
@@ -225,7 +249,8 @@ async function installPinnedDolt({ command, member, platform, arch, doltPath, lo
225
249
  `Get-ChildItem -Recurse -Filter "${asset.binaryName}" "$env:TEMP\\dolt-settle" | Select-Object -First 1 | Copy-Item -Force -Destination ${doltPath}`,
226
250
  'Remove-Item -Recurse -Force "$env:TEMP\\dolt-settle.zip","$env:TEMP\\dolt-settle" -ErrorAction SilentlyContinue',
227
251
  ].join('; ');
228
- return command(script, { member_name: member, silent: true, failSoft: true, timeout_s: 320, label: `settle: install pinned dolt on '${member}'` });
252
+ const wrapped = getSeCommands({ os: platform, shell }).wrapPowerShellScript(script, 'dolt-settle installPinnedDolt');
253
+ return command(wrapped, { member_name: member, silent: true, failSoft: true, timeout_s: 320, label: `settle: install pinned dolt on '${member}'` });
229
254
  }
230
255
 
231
256
  const script = [
@@ -254,10 +279,12 @@ function isBinaryLockedError(output) {
254
279
  * path -- by construction the only thing that ever launches a binary there
255
280
  * is settle/the installer, so this is always a legitimate self-heal, never
256
281
  * collateral damage against an unrelated process. */
257
- async function killProcessAtPath({ command, member, platform, doltPath, log }) {
282
+ async function killProcessAtPath({ command, member, platform, doltPath, shell = '', log }) {
258
283
  log(`[Dolt Settle] attempting to kill any process locking '${doltPath}' on member '${member}' before retrying the pinned install.`);
259
284
  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}'` });
285
+ const script = `Get-Process | Where-Object { $_.Path -eq ${doltPath} } | Stop-Process -Force -ErrorAction SilentlyContinue`;
286
+ const wrapped = getSeCommands({ os: platform, shell }).wrapPowerShellScript(script, 'dolt-settle killProcessAtPath');
287
+ return command(wrapped, { member_name: member, silent: true, failSoft: true, label: `settle: kill locking dolt process on '${member}'` });
261
288
  }
262
289
  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
290
  }
@@ -270,21 +297,35 @@ async function killProcessAtPath({ command, member, platform, doltPath, log }) {
270
297
  * after the full ladder, or the platform/arch is unsupported with no
271
298
  * existing binary -- an ordinary operational failure, not an escalation.
272
299
  *
273
- * @returns {Promise<{ doltPath: string, version: string, pinned: boolean, warnings: string[] }>}
300
+ * @returns {Promise<{ doltPath: string, psDoltPath: string, version: string, pinned: boolean, warnings: string[] }>}
274
301
  */
275
- export async function ensurePinnedDolt({ command, member, platform, arch = 'x64', log = () => {} }) {
276
- const doltPath = memberDoltPath(platform);
302
+ export async function ensurePinnedDolt({ command, member, platform, arch = 'x64', shell = '', log = () => {} }) {
303
+ // `doltPath` is the member-shell-native invocation path (bash for a
304
+ // gitbash member, PowerShell otherwise) -- used for the version probe and
305
+ // (via the returned doltInfo) every later `dolt` invocation dispatched
306
+ // directly to the member's own shell (runDoltSql).
307
+ const doltPath = memberDoltPath({ os: platform, shell });
308
+ // `psDoltPath` is ALWAYS the PowerShell-dialect form (shell forced to ''),
309
+ // because installPinnedDolt/killProcessAtPath/spawnEphemeralServer embed
310
+ // it inside a raw PowerShell SCRIPT body, not a member-shell-dispatched
311
+ // command. The dialect INSIDE those wrapped scripts is always PowerShell
312
+ // even for a gitbash member -- only the OUTER invocation is now routed
313
+ // through getSeCommands(...).wrapPowerShellScript (apra-fleet-7dir.21/.22)
314
+ // -- so a gitbash member must still get the PowerShell-dialect path here,
315
+ // or a bare `$HOME/...` path would silently fail to expand inside those
316
+ // PowerShell script bodies.
317
+ const psDoltPath = memberDoltPath({ os: platform, shell: '' });
277
318
  const warnings = [];
278
319
 
279
- const initial = await probeDoltVersion({ command, member, doltPath, platform });
320
+ const initial = await probeDoltVersion({ command, member, doltPath, platform, shell });
280
321
  if (initial.ok && initial.version === DOLT_VERSION.replace(/^v/, '')) {
281
- return { doltPath, version: initial.version, pinned: true, warnings };
322
+ return { doltPath, psDoltPath, version: initial.version, pinned: true, warnings };
282
323
  }
283
324
 
284
325
  // Missing, broken, or wrong version -- attempt the pinned install.
285
326
  let install;
286
327
  try {
287
- install = await installPinnedDolt({ command, member, platform, arch, doltPath, log });
328
+ install = await installPinnedDolt({ command, member, platform, arch, doltPath: psDoltPath, shell, log });
288
329
  } catch (err) {
289
330
  throw new DoltBinaryUnavailableError(
290
331
  `[Dolt Settle] unsupported platform/arch for member '${member}' installing pinned dolt: ${err.message}`,
@@ -297,19 +338,19 @@ export async function ensurePinnedDolt({ command, member, platform, arch = 'x64'
297
338
 
298
339
  if (installFailed && isBinaryLockedError(installOutput)) {
299
340
  // 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 });
341
+ await killProcessAtPath({ command, member, platform, doltPath: psDoltPath, shell, log });
342
+ const retry = await installPinnedDolt({ command, member, platform, arch, doltPath: psDoltPath, shell, log });
302
343
  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 };
344
+ const reprobed = await probeDoltVersion({ command, member, doltPath, platform, shell });
345
+ if (reprobed.ok) return { doltPath, psDoltPath, version: reprobed.version, pinned: true, warnings };
305
346
  }
306
347
  // Still blocked after kill+retry -- warn and fall back (Part 5.6 step 3).
307
- const fallback = await probeDoltVersion({ command, member, doltPath, platform });
348
+ const fallback = await probeDoltVersion({ command, member, doltPath, platform, shell });
308
349
  if (fallback.ok) {
309
350
  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
351
  log(warn);
311
352
  warnings.push(warn);
312
- return { doltPath, version: fallback.version, pinned: false, warnings };
353
+ return { doltPath, psDoltPath, version: fallback.version, pinned: false, warnings };
313
354
  }
314
355
  throw new DoltBinaryUnavailableError(
315
356
  `[Dolt Settle] no usable dolt binary on member '${member}' after install+kill+retry: ${installOutput}`,
@@ -324,14 +365,14 @@ export async function ensurePinnedDolt({ command, member, platform, arch = 'x64'
324
365
  );
325
366
  }
326
367
 
327
- const reprobed = await probeDoltVersion({ command, member, doltPath, platform });
368
+ const reprobed = await probeDoltVersion({ command, member, doltPath, platform, shell });
328
369
  if (!reprobed.ok) {
329
370
  throw new DoltBinaryUnavailableError(
330
371
  `[Dolt Settle] pinned dolt install reported success but the binary still fails 'dolt version' on member '${member}' -- likely a corrupted download.`,
331
372
  { member, probedPath: doltPath, probeOutput: reprobed.raw, repairCommand: `delete ${doltPath} on ${member} and re-run settle` },
332
373
  );
333
374
  }
334
- return { doltPath, version: reprobed.version, pinned: true, warnings };
375
+ return { doltPath, psDoltPath, version: reprobed.version, pinned: true, warnings };
335
376
  }
336
377
 
337
378
  // ---------------------------------------------------------------------------
@@ -341,7 +382,7 @@ export async function ensurePinnedDolt({ command, member, platform, arch = 'x64'
341
382
  /** Genuinely-detached spawn -- WMI on Windows (Start-Process/schtasks both
342
383
  * die with the launching SSH session, verified live), nohup+disown on
343
384
  * POSIX. Returns the pid so teardown can target it precisely. */
344
- export async function spawnEphemeralServer({ command, member, platform, doltPath, dataDir, host, port, log = () => {} }) {
385
+ export async function spawnEphemeralServer({ command, member, platform, doltPath, dataDir, host, port, shell = '', log = () => {} }) {
345
386
  log(`[Dolt Settle] starting ephemeral dolt sql-server for member '${member}' at ${host}:${port} --data-dir ${dataDir}`);
346
387
 
347
388
  if (platform === 'win32') {
@@ -358,7 +399,8 @@ export async function spawnEphemeralServer({ command, member, platform, doltPath
358
399
  'if ($r.ReturnValue -ne 0) { throw "Win32_Process.Create failed with ReturnValue $($r.ReturnValue) for command line: $cl" }',
359
400
  'Write-Output "PID:$($r.ProcessId)"',
360
401
  ].join('; ');
361
- const res = await command(script, { member_name: member, silent: true, failSoft: true, label: `settle: spawn ephemeral sql-server on '${member}'` });
402
+ const wrapped = getSeCommands({ os: platform, shell }).wrapPowerShellScript(script, 'dolt-settle spawnEphemeralServer');
403
+ const res = await command(wrapped, { member_name: member, silent: true, failSoft: true, label: `settle: spawn ephemeral sql-server on '${member}'` });
362
404
  if (res && res.ok === false) {
363
405
  throw new DoltSyncError(`[Dolt Settle] failed to spawn ephemeral sql-server for member '${member}': ${res.error}`, { member, doltOutput: res.error });
364
406
  }
@@ -402,9 +444,9 @@ export async function spawnEphemeralServer({ command, member, platform, doltPath
402
444
 
403
445
  /** Bounded poll for the server to actually accept connections -- never
404
446
  * sleep-and-hope. */
405
- export async function waitForServerReady({ command, member, platform, host, port, log = () => {}, attempts = 10, intervalMs = 500 }) {
447
+ export async function waitForServerReady({ command, member, platform, shell = '', host, port, log = () => {}, attempts = 10, intervalMs = 500 }) {
406
448
  for (let i = 0; i < attempts; i += 1) {
407
- const probe = platformAwareTcpProbe({ command, member, platform, host, port });
449
+ const probe = platformAwareTcpProbe({ command, member, platform, shell, host, port });
408
450
  // eslint-disable-next-line no-await-in-loop -- intentional bounded poll
409
451
  const res = await probe;
410
452
  if (res) return true;
@@ -434,26 +476,33 @@ export async function waitForServerReady({ command, member, platform, host, port
434
476
  * single-quoted string, so `require("net")` arrived at node as
435
477
  * `require(net)` and died with a SyntaxError (verified live on
436
478
  * 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.
479
+ * and must NOT be applied on POSIX (or on a Windows member whose registered
480
+ * shell is Git-for-Windows bash, which runs `node` directly rather than
481
+ * through PowerShell's native-argument passing): the backslashes would
482
+ * survive literally into the JS. Dialect is resolved off the member's
483
+ * REGISTERED shell (getSeCommands) rather than platform, so this only
484
+ * escapes for the true powershell dialect (apra-fleet-7dir.22/.23).
485
+ * @param {{ os?: string, shell?: string }|string} target
486
+ * @param {string} js
439
487
  */
440
- function nodeEval(platform, js) {
441
- return `node -e '${platform === 'win32' ? js.replace(/"/g, '\\"') : js}'`;
488
+ function nodeEval(target, js) {
489
+ const needsPowerShellEscaping = getSeCommands(target).shell === 'powershell';
490
+ return `node -e '${needsPowerShellEscaping ? js.replace(/"/g, '\\"') : js}'`;
442
491
  }
443
492
 
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})`);
493
+ function tcpProbeScript(target, host, port, timeoutMs = 2000) {
494
+ return nodeEval(target, `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
495
  }
447
496
 
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}'` });
497
+ async function platformAwareTcpProbe({ command, member, platform, shell = '', host, port }) {
498
+ const res = await command(tcpProbeScript({ os: platform, shell }, host, port), { member_name: member, silent: true, failSoft: true, label: `settle: TCP probe for '${member}'` });
450
499
  return /PROBE:True/i.test(String((res && res.output) || ''));
451
500
  }
452
501
 
453
502
  /** Kill the server + verify the port is actually closed. Best-effort by
454
503
  * design (called from the happy path AND the unconditional `finally` --
455
504
  * see settleDoltConflicts). */
456
- async function killServerAndVerify({ command, member, platform, pid, host, port, log = () => {} }) {
505
+ async function killServerAndVerify({ command, member, platform, shell = '', pid, host, port, log = () => {} }) {
457
506
  // Kill the recorded pid AND, belt-and-braces, anything still bound to our
458
507
  // ephemeral port: the recorded pid is resolved by a pattern match at spawn
459
508
  // time, so a mis-resolved pid must not be able to leave the real server
@@ -461,8 +510,10 @@ async function killServerAndVerify({ command, member, platform, pid, host, port,
461
510
  // Both forms are scoped to settle's own port, never to dolt at large.
462
511
  const matcher = `sql-server --host ${host} --port ${port}`;
463
512
  if (platform === 'win32') {
513
+ const script = `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 }`;
514
+ const wrapped = getSeCommands({ os: platform, shell }).wrapPowerShellScript(script, 'dolt-settle killServerAndVerify');
464
515
  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 }`,
516
+ wrapped,
466
517
  { member_name: member, silent: true, failSoft: true, label: `settle: kill ephemeral sql-server pid ${pid} on '${member}'` },
467
518
  );
468
519
  } else {
@@ -470,7 +521,7 @@ async function killServerAndVerify({ command, member, platform, pid, host, port,
470
521
  }
471
522
  for (let i = 0; i < 6; i += 1) {
472
523
  // eslint-disable-next-line no-await-in-loop -- bounded teardown-verify poll
473
- const stillUp = await platformAwareTcpProbe({ command, member, platform, host, port });
524
+ const stillUp = await platformAwareTcpProbe({ command, member, platform, shell, host, port });
474
525
  if (!stillUp) {
475
526
  log(`[Dolt Settle] torn down ephemeral sql-server (pid ${pid}) for member '${member}'; port ${port} confirmed closed.`);
476
527
  return;
@@ -485,6 +536,91 @@ async function killServerAndVerify({ command, member, platform, pid, host, port,
485
536
  // Section 5: raw dolt CLI query runner -- the exact live-verified flag set.
486
537
  // ---------------------------------------------------------------------------
487
538
 
539
+ // apra-fleet-ka1u follow-up (bug #2): MSYS bash (Git for Windows -- the shell
540
+ // every gitbash member's command() dispatches through) SILENTLY TRUNCATES any
541
+ // `bash -c <string>` longer than this many characters, with no error at the
542
+ // truncation point itself -- the failure only surfaces later as a confusing
543
+ // "unexpected EOF while looking for matching '\"'" once the truncated string
544
+ // leaves an unterminated quote. Bisected empirically (byte-precise: 8186 ok,
545
+ // 8187 fails), identically for both the Git-bundled and the standalone MSYS
546
+ // bash on this class of Windows member. A live incident: resolveLwwTable()'s
547
+ // per-column CASE/SET UPDATE for a 53-column table (e.g. 'issues') built a
548
+ // 14,064-character query, well past the limit, and settle silently failed
549
+ // with no usable diagnostic. Kept well under the measured 8186 so escaping
550
+ // overhead (the preamble, and any character that doubles under
551
+ // escapeSqlForShell) can never push a chunk over the real limit.
552
+ const DOLT_SQL_INLINE_LIMIT = 6000;
553
+
554
+ /** Random-enough per-invocation suffix for a scratch SQL file name -- multiple
555
+ * concurrent settle calls on the same member must never collide. Not
556
+ * cryptographic; collision just needs to be practically impossible for one
557
+ * member's lifetime, not adversarially resistant. */
558
+ function randomFileSuffix() {
559
+ return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
560
+ }
561
+
562
+ /**
563
+ * Write `sql` to a scratch file on `member` in chunks that individually stay
564
+ * well under DOLT_SQL_INLINE_LIMIT (never one giant `-c` string, which is
565
+ * exactly the bug this exists to avoid), then return the file's path so the
566
+ * caller can pass it to `dolt sql -f <path>` instead of `-q "<query>"`.
567
+ * POSIX/gitbash writes under $HOME (both resolve it correctly; verified by
568
+ * runDoltSql's own pre-existing "$HOME/.apra-fleet/bin/dolt.exe" doltPath
569
+ * convention); PowerShell writes under $env:TEMP.
570
+ *
571
+ * @returns {Promise<string>} the scratch file's path, in the member's own dialect
572
+ */
573
+ async function writeDoltSqlScratchFile({ command, member, target, sql, log }) {
574
+ const seCommands = getSeCommands(target);
575
+ const isPowerShell = seCommands.shell === 'powershell';
576
+ const suffix = randomFileSuffix();
577
+ const filePath = isPowerShell
578
+ ? `$env:TEMP\\dolt-settle-${suffix}.sql`
579
+ : `$HOME/.apra-fleet-se-dolt-settle-${suffix}.sql`;
580
+
581
+ // Create/truncate the file first (a stale file from a killed prior
582
+ // attempt must never be silently appended to).
583
+ const createCmd = isPowerShell
584
+ ? `Set-Content -Path "${filePath}" -Value $null -NoNewline`
585
+ : `printf '' > "${filePath}"`;
586
+ const createRes = await command(createCmd, { member_name: member, silent: true, failSoft: true, label: `settle: create scratch SQL file for '${member}'` });
587
+ if (createRes && createRes.ok === false) {
588
+ throw new DoltSyncError(`[Dolt Settle] could not create scratch SQL file '${filePath}' for member '${member}': ${createRes.error}`, { member, doltOutput: createRes.error });
589
+ }
590
+
591
+ for (let offset = 0; offset < sql.length; offset += DOLT_SQL_INLINE_LIMIT) {
592
+ const chunk = sql.slice(offset, offset + DOLT_SQL_INLINE_LIMIT);
593
+ const escapedChunk = escapeSqlForShell(target, chunk);
594
+ const appendCmd = isPowerShell
595
+ ? `Add-Content -Path "${filePath}" -Value "${escapedChunk}" -NoNewline`
596
+ : `printf '%s' "${escapedChunk}" >> "${filePath}"`;
597
+ // eslint-disable-next-line no-await-in-loop -- each append MUST land
598
+ // before the next is issued (same file, sequential writes; a member's
599
+ // own shell has no ordering guarantee across concurrently-dispatched
600
+ // commands, only within one command() call's own execution).
601
+ const appendRes = await command(appendCmd, { member_name: member, silent: true, failSoft: true, label: `settle: append scratch SQL chunk for '${member}'` });
602
+ if (appendRes && appendRes.ok === false) {
603
+ throw new DoltSyncError(`[Dolt Settle] could not write scratch SQL file '${filePath}' for member '${member}': ${appendRes.error}`, { member, doltOutput: appendRes.error });
604
+ }
605
+ }
606
+ log(`[Dolt Settle] wrote ${sql.length}-char query to scratch file '${filePath}' for member '${member}' (${Math.ceil(sql.length / DOLT_SQL_INLINE_LIMIT)} chunk(s), staying under bash's ${DOLT_SQL_INLINE_LIMIT}-char -c limit).`);
607
+ return filePath;
608
+ }
609
+
610
+ /** Best-effort scratch-file cleanup -- never lets a delete failure surface as
611
+ * the query's own result; a leftover scratch file is a minor annoyance, not
612
+ * a correctness problem (the next writeDoltSqlScratchFile call for this
613
+ * member always creates/truncates its own uniquely-suffixed file anyway). */
614
+ async function cleanupDoltSqlScratchFile({ command, member, target, filePath, log }) {
615
+ const isPowerShell = getSeCommands(target).shell === 'powershell';
616
+ const rmCmd = isPowerShell ? `Remove-Item -Path "${filePath}" -ErrorAction SilentlyContinue` : `rm -f "${filePath}"`;
617
+ try {
618
+ await command(rmCmd, { member_name: member, silent: true, failSoft: true, label: `settle: remove scratch SQL file for '${member}'` });
619
+ } catch (err) {
620
+ log(`[Dolt Settle] WARNING: could not remove scratch SQL file '${filePath}' for member '${member}' (non-fatal): ${err && err.message ? err.message : err}`);
621
+ }
622
+ }
623
+
488
624
  /**
489
625
  * Runs a query against the ephemeral server via the raw `dolt` CLI, using
490
626
  * the exact live-verified flag set: `--no-tls` BEFORE `--host`/`--port`
@@ -495,7 +631,7 @@ async function killServerAndVerify({ command, member, platform, pid, host, port,
495
631
  *
496
632
  * @returns {Promise<object[]>} parsed rows (empty array for statements with no result set)
497
633
  */
498
- export async function runDoltSql({ command, member, platform, doltPath, host, port, query, log = () => {} }) {
634
+ export async function runDoltSql({ command, member, platform, doltPath, host, port, query, log = () => {}, shell = '' }) {
499
635
  // EVERY invocation is its own SQL SESSION -- `dolt sql -q` connects,
500
636
  // runs, and disconnects -- so session-scoped state does NOT carry over
501
637
  // between calls. `@@dolt_allow_commit_conflicts` is therefore set on each
@@ -504,10 +640,30 @@ export async function runDoltSql({ command, member, platform, doltPath, host, po
504
640
  // (verified live on fleet-lin-dev1). The conflict data itself IS durable
505
641
  // -- it lives in the working set -- which is what lets the subsequent
506
642
  // resolve/commit statements run in later sessions.
643
+ const target = { os: platform, shell };
507
644
  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}"`);
645
+ const rawFullQuery = `${preamble} ${query}`;
646
+ const fullQuery = escapeSqlForShell(target, rawFullQuery);
647
+
648
+ // apra-fleet-ka1u bug #2: never risk bash's silent >8186-char -c
649
+ // truncation. Below the limit, keep the exact live-verified -q "<query>"
650
+ // invocation byte-identical (no behavior change for the overwhelming
651
+ // majority of settle's queries, which are short). At/above it, write the
652
+ // RAW (pre-escaped) query to a chunked scratch file and run -f instead --
653
+ // dolt reads that file's contents literally, so it needs no shell
654
+ // escaping at all, sidestepping both the length limit and its escaping.
655
+ let scratchFilePath = null;
656
+ let cmd;
657
+ if (fullQuery.length >= DOLT_SQL_INLINE_LIMIT) {
658
+ scratchFilePath = await writeDoltSqlScratchFile({ command, member, target, sql: rawFullQuery, log });
659
+ cmd = invokeBinary(target, doltPath, `--no-tls --host=${host} --port=${port} sql -r json -f "${scratchFilePath}"`);
660
+ } else {
661
+ cmd = invokeBinary(target, doltPath, `--no-tls --host=${host} --port=${port} sql -r json -q "${fullQuery}"`);
662
+ }
510
663
  const res = await command(cmd, { member_name: member, silent: true, failSoft: true, label: `settle: dolt sql for '${member}'` });
664
+ if (scratchFilePath) {
665
+ await cleanupDoltSqlScratchFile({ command, member, target, filePath: scratchFilePath, log });
666
+ }
511
667
  if (res && res.ok === false) {
512
668
  throw new DoltSyncError(`[Dolt Settle] dolt sql query failed for member '${member}': ${res.error}\nquery: ${query}`, { member, doltOutput: res.error });
513
669
  }
@@ -555,9 +711,9 @@ export function parseDoltJsonRows(output) {
555
711
  // Section 6: the settle rulebook -- TOTAL over every conflicted table.
556
712
  // ---------------------------------------------------------------------------
557
713
 
558
- async function tableColumns({ command, member, platform, doltPath, host, port, table }) {
714
+ async function tableColumns({ command, member, platform, doltPath, host, port, table, shell }) {
559
715
  const rows = await runDoltSql({
560
- command, member, platform, doltPath, host, port,
716
+ command, member, platform, doltPath, host, port, shell,
561
717
  query: `SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_NAME = '${table}';`,
562
718
  });
563
719
  return rows.map((r) => r.COLUMN_NAME || r.column_name).filter(Boolean);
@@ -568,9 +724,9 @@ async function tableColumns({ command, member, platform, doltPath, host, port, t
568
724
  * `their_*` row is already present on our side. Falls back to the full column
569
725
  * list (whole-row identity) when a table declares no PRIMARY KEY, which is
570
726
  * still a correct -- if conservative -- set-union identity. */
571
- async function tablePrimaryKey({ command, member, platform, doltPath, host, port, table }) {
727
+ async function tablePrimaryKey({ command, member, platform, doltPath, host, port, table, shell }) {
572
728
  const rows = await runDoltSql({
573
- command, member, platform, doltPath, host, port,
729
+ command, member, platform, doltPath, host, port, shell,
574
730
  query: `SELECT COLUMN_NAME FROM information_schema.key_column_usage WHERE TABLE_NAME = '${table}' AND CONSTRAINT_NAME = 'PRIMARY' ORDER BY ORDINAL_POSITION;`,
575
731
  });
576
732
  return rows.map((r) => r.COLUMN_NAME || r.column_name).filter(Boolean);
@@ -580,12 +736,12 @@ async function tablePrimaryKey({ command, member, platform, doltPath, host, port
580
736
  * that has an `updated_at` column -- this is what makes settle TOTAL rather
581
737
  * than gated to a fixed table list. Falls back to a plain `--theirs`
582
738
  * resolve for a table with no `updated_at` column. */
583
- async function resolveLwwTable({ command, member, platform, doltPath, host, port, table, log }) {
739
+ async function resolveLwwTable({ command, member, platform, doltPath, host, port, table, log, shell = '' }) {
584
740
  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 });
741
+ const cols = await tableColumns({ command, member, platform, doltPath, host, port, table, shell });
586
742
  if (!cols.includes('updated_at')) {
587
743
  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}');` });
744
+ await runDoltSql({ command, member, platform, doltPath, host, port, shell, query: `CALL DOLT_CONFLICTS_RESOLVE('--theirs', '${table}');` });
589
745
  return;
590
746
  }
591
747
  const pk = cols.includes('id') ? 'id' : cols[0];
@@ -619,14 +775,14 @@ async function resolveLwwTable({ command, member, platform, doltPath, host, port
619
775
  t.updated_at = GREATEST(c.our_updated_at, c.their_updated_at)
620
776
  WHERE t.${bq}${pk}${bq} IN (SELECT our_${pk} FROM dolt_conflicts_${table});
621
777
  `;
622
- await runDoltSql({ command, member, platform, doltPath, host, port, query: updateSql });
778
+ await runDoltSql({ command, member, platform, doltPath, host, port, shell, query: updateSql });
623
779
 
624
780
  // Their-side-only rows (an add they made that we do not have) would be
625
781
  // 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 })
782
+ const keyCols = (await tablePrimaryKey({ command, member, platform, doltPath, host, port, table, shell })).length > 0
783
+ ? await tablePrimaryKey({ command, member, platform, doltPath, host, port, table, shell })
628
784
  : [pk];
629
- await runDoltSql({ command, member, platform, doltPath, host, port, query: buildTheirMissingInsert(table, cols, keyCols) });
785
+ await runDoltSql({ command, member, platform, doltPath, host, port, shell, query: buildTheirMissingInsert(table, cols, keyCols) });
630
786
 
631
787
  // --ours, NOT --theirs. The design doc flagged this as the one step to
632
788
  // validate live, and the live run settled it: DOLT_CONFLICTS_RESOLVE
@@ -635,7 +791,7 @@ async function resolveLwwTable({ command, member, platform, doltPath, host, port
635
791
  // row whose later updated_at was ours came back with their older value).
636
792
  // '--ours' keeps the row the UPDATE just merged, which is the whole point
637
793
  // of computing it.
638
- await runDoltSql({ command, member, platform, doltPath, host, port, query: `CALL DOLT_CONFLICTS_RESOLVE('--ours', '${table}');` });
794
+ await runDoltSql({ command, member, platform, doltPath, host, port, shell, query: `CALL DOLT_CONFLICTS_RESOLVE('--ours', '${table}');` });
639
795
  }
640
796
 
641
797
  /**
@@ -685,31 +841,31 @@ function buildTheirMissingInsert(table, cols, keyCols) {
685
841
  * rather than issuing an INSERT it cannot construct correctly -- settle stays
686
842
  * total either way.
687
843
  */
688
- async function resolveUnionTable({ command, member, platform, doltPath, host, port, table, log }) {
689
- const cols = await tableColumns({ command, member, platform, doltPath, host, port, table });
844
+ async function resolveUnionTable({ command, member, platform, doltPath, host, port, table, log, shell = '' }) {
845
+ const cols = await tableColumns({ command, member, platform, doltPath, host, port, table, shell });
690
846
  if (cols.length === 0) {
691
847
  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}');` });
848
+ await runDoltSql({ command, member, platform, doltPath, host, port, shell, query: `CALL DOLT_CONFLICTS_RESOLVE('--theirs', '${table}');` });
693
849
  return;
694
850
  }
695
851
 
696
- const pkFromSchema = await tablePrimaryKey({ command, member, platform, doltPath, host, port, table });
852
+ const pkFromSchema = await tablePrimaryKey({ command, member, platform, doltPath, host, port, table, shell });
697
853
  const keyCols = pkFromSchema.length > 0 ? pkFromSchema : cols;
698
854
  log(`[Dolt Settle] table '${table}' conflict: resolving as a set-union (both sides' rows kept; identity = ${keyCols.join(' + ')}).`);
699
855
 
700
- await runDoltSql({ command, member, platform, doltPath, host, port, query: buildTheirMissingInsert(table, cols, keyCols) });
856
+ await runDoltSql({ command, member, platform, doltPath, host, port, shell, query: buildTheirMissingInsert(table, cols, keyCols) });
701
857
  // --ours, not --theirs (same live finding as resolveLwwTable): the resolve
702
858
  // rewrites the working-set row from the chosen side, so --theirs here
703
859
  // would undo the union by dropping the rows only WE had. Their rows have
704
860
  // 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}');` });
861
+ await runDoltSql({ command, member, platform, doltPath, host, port, shell, query: `CALL DOLT_CONFLICTS_RESOLVE('--ours', '${table}');` });
706
862
  }
707
863
 
708
864
  /** Plain theirs -- machine-local/config rows, and append-only tables
709
865
  * (comments/events) where both sides already survive by construction. */
710
- async function resolveTheirsTable({ command, member, platform, doltPath, host, port, table, log }) {
866
+ async function resolveTheirsTable({ command, member, platform, doltPath, host, port, table, log, shell = '' }) {
711
867
  log(`[Dolt Settle] table '${table}' conflict: resolving --theirs.`);
712
- await runDoltSql({ command, member, platform, doltPath, host, port, query: `CALL DOLT_CONFLICTS_RESOLVE('--theirs', '${table}');` });
868
+ await runDoltSql({ command, member, platform, doltPath, host, port, shell, query: `CALL DOLT_CONFLICTS_RESOLVE('--theirs', '${table}');` });
713
869
  }
714
870
 
715
871
  /** Dispatch a single conflicted table to its rulebook entry, or the generic
@@ -732,6 +888,7 @@ async function resolveConflictedTable(ctx, table) {
732
888
  * @property {(msg: string) => void} [log]
733
889
  * @property {'win32'|'linux'|'darwin'} platform - the MEMBER's platform. REQUIRED -- never assume process.platform.
734
890
  * @property {'x64'|'arm64'} [arch]
891
+ * @property {string} [shell] - the MEMBER's registered shell ('gitbash' on a Windows member running Git-for-Windows bash, '' otherwise). Resolved via runner.js's resolveMemberTarget; drives memberDoltPath/invokeBinary/escapeSqlForShell's dialect through se-os-commands.mjs's getSeCommands (apra-fleet-7dir.16). Defaults to '' (PowerShell dialect on Windows), matching pre-shell-aware behavior when unknown.
735
892
  * @property {string} [remote]
736
893
  * @property {string} [branch]
737
894
  * @property {number} [portRangeStart]
@@ -757,6 +914,7 @@ export async function settleDoltConflicts(member, opts = {}) {
757
914
  log = () => {},
758
915
  platform,
759
916
  arch = 'x64',
917
+ shell = '',
760
918
  remote = 'origin',
761
919
  branch = 'main',
762
920
  portRangeStart = DEFAULT_PORT_RANGE.start,
@@ -778,7 +936,7 @@ export async function settleDoltConflicts(member, opts = {}) {
778
936
 
779
937
  // Step 1: ensure a correctly-pinned (or functionally-probed-fallback)
780
938
  // dolt binary exists on the member.
781
- const doltInfo = await ensurePinnedDolt({ command, member, platform, arch, log });
939
+ const doltInfo = await ensurePinnedDolt({ command, member, platform, arch, shell, log });
782
940
  const warnings = [...doltInfo.warnings];
783
941
 
784
942
  if (status.mode === 'server' && status.host && status.port) {
@@ -789,7 +947,7 @@ export async function settleDoltConflicts(member, opts = {}) {
789
947
  log(`[Dolt Settle] member '${member}' already has a live server at ${status.host}:${status.port} -- targeting it instead of spawning a second one.`);
790
948
  } else {
791
949
  const dataDir = status.dataDir || DEFAULT_EMBEDDED_DATA_DIR;
792
- port = await pickFreePort({ command, member, platform, portRangeStart, portRangeEnd });
950
+ port = await pickFreePort({ command, member, platform, shell, portRangeStart, portRangeEnd });
793
951
 
794
952
  // A busy candidate port is SKIPPED, not killed-and-reused: pickFreePort
795
953
  // only ever hands back a port nothing answers on (design doc Part 3.5,
@@ -800,10 +958,20 @@ export async function settleDoltConflicts(member, opts = {}) {
800
958
  // settle legitimately in progress" inline, since getting that
801
959
  // distinction wrong (killing a live settle) is worse than the
802
960
  // bounded wait on the sweep.
803
- const spawned = await spawnEphemeralServer({ command, member, platform, doltPath: doltInfo.doltPath, dataDir, host, port, log });
961
+ // spawnEphemeralServer embeds doltPath inside a raw PowerShell/WMI
962
+ // script body on Windows (Section 4). The script body itself must
963
+ // keep receiving the PowerShell-dialect path (psDoltPath)
964
+ // regardless of the member's actual registered shell -- the
965
+ // dialect INSIDE the wrapped script is always PowerShell -- but
966
+ // the OUTER invocation is now routed through
967
+ // getSeCommands(...).wrapPowerShellScript via `shell`
968
+ // (apra-fleet-7dir.22), so a gitbash member gets it via
969
+ // `powershell -EncodedCommand` from bash instead of the raw
970
+ // PowerShell text being handed directly to bash.
971
+ const spawned = await spawnEphemeralServer({ command, member, platform, doltPath: doltInfo.psDoltPath, dataDir, host, port, shell, log });
804
972
  pid = spawned.pid;
805
973
  weSpawnedTheServer = true;
806
- await waitForServerReady({ command, member, platform, host, port, log });
974
+ await waitForServerReady({ command, member, platform, shell, host, port, log });
807
975
  }
808
976
 
809
977
  // If not preflight-validated by the pin ladder, the fallback dolt
@@ -815,11 +983,11 @@ export async function settleDoltConflicts(member, opts = {}) {
815
983
  // "succeeded but returned something unusable" case to additionally
816
984
  // check here.
817
985
  if (!doltInfo.pinned) {
818
- await runDoltSql({ command, member, platform, doltPath: doltInfo.doltPath, host, port, query: 'SELECT 1;', log });
986
+ await runDoltSql({ command, member, platform, doltPath: doltInfo.doltPath, host, port, query: 'SELECT 1;', log, shell });
819
987
  }
820
988
 
821
989
  // Step 3/4: re-open the merge, enumerate every conflicted table.
822
- const ctx = { command, member, platform, doltPath: doltInfo.doltPath, host, port, log };
990
+ const ctx = { command, member, platform, doltPath: doltInfo.doltPath, host, port, log, shell };
823
991
  await runDoltSql({ ...ctx, query: `CALL DOLT_MERGE('${remote}/${branch}');` });
824
992
 
825
993
  // NOTE: `SELECT *`, not a backtick-quoted `table` column -- dolt_conflicts'
@@ -850,7 +1018,7 @@ export async function settleDoltConflicts(member, opts = {}) {
850
1018
  // BEFORE republishing -- embedded bd must not race the server's
851
1019
  // exclusive chunk-journal lock on the same data dir.
852
1020
  if (weSpawnedTheServer && pid) {
853
- await killServerAndVerify({ command, member, platform, pid, host, port, log });
1021
+ await killServerAndVerify({ command, member, platform, shell, pid, host, port, log });
854
1022
  pid = null;
855
1023
  }
856
1024
 
@@ -869,7 +1037,7 @@ export async function settleDoltConflicts(member, opts = {}) {
869
1037
  // Guaranteed teardown -- covers every throw path above. On the happy
870
1038
  // path pid is already null (torn down before republish per 7.2).
871
1039
  if (weSpawnedTheServer && pid) {
872
- await killServerAndVerify({ command, member, platform, pid, host, port, log }).catch((err) => {
1040
+ await killServerAndVerify({ command, member, platform, shell, pid, host, port, log }).catch((err) => {
873
1041
  log(`[Dolt Settle] WARNING: finally-block teardown failed for member '${member}': ${err.message}`);
874
1042
  });
875
1043
  }
@@ -920,18 +1088,23 @@ export async function detectMemberPlatform({ command, member }) {
920
1088
  * lifetime.
921
1089
  *
922
1090
  * @param {string} member
923
- * @param {{ command: Function, log?: Function, platform?: string, arch?: string }} opts
1091
+ * @param {{ command: Function, log?: Function, platform?: string, arch?: string, shell?: string }} opts
924
1092
  * @returns {() => Promise<{ ok: true, resolvedTables: string[], warnings: string[], doltVersionUsed: string }>}
925
1093
  */
926
1094
  export function buildSettleCallback(member, opts = {}) {
927
- const { command, log = () => {}, platform, arch } = opts;
1095
+ const { command, log = () => {}, platform, arch, shell = '' } = opts;
928
1096
  if (!member) throw new Error('buildSettleCallback requires a member');
929
1097
  if (typeof command !== 'function') throw new Error('buildSettleCallback requires an injected command() in opts');
930
1098
 
931
1099
  let resolved = platform ? { platform, arch: arch || 'x64' } : null;
932
1100
  return async () => {
933
1101
  if (!resolved) resolved = await detectMemberPlatform({ command, member });
934
- return settleDoltConflicts(member, { command, log, platform: resolved.platform, arch: resolved.arch });
1102
+ // `shell` is resolved once by the CALLER (runner.js's
1103
+ // resolveMemberTarget, via member_detail) and closed over here --
1104
+ // detectMemberPlatform only probes process.platform/arch on the
1105
+ // member, which carries no shell information, so it cannot supply
1106
+ // this itself (apra-fleet-7dir.16).
1107
+ return settleDoltConflicts(member, { command, log, platform: resolved.platform, arch: resolved.arch, shell });
935
1108
  };
936
1109
  }
937
1110
 
@@ -953,12 +1126,15 @@ export function buildSettleCallback(member, opts = {}) {
953
1126
  * age threshold plus its run interval (~15 minutes with the current
954
1127
  * defaults) until the sweep reaps the orphan.
955
1128
  */
956
- async function pickFreePort({ command, member, platform, portRangeStart, portRangeEnd }) {
1129
+ async function pickFreePort({ command, member, platform, shell = '', portRangeStart, portRangeEnd }) {
957
1130
  // Same node-based probe as tcpProbeScript, scanning the range member-side
958
1131
  // in ONE dispatch: a round trip per candidate port would be 100 SSH
959
1132
  // 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,
1133
+ // bash and zsh (see tcpProbeScript for the live evidence). Dialect is
1134
+ // resolved off the member's registered shell, not bare platform, so a
1135
+ // gitbash member takes the POSIX (unescaped) nodeEval branch just like
1136
+ // tcpProbeScript (apra-fleet-7dir.22).
1137
+ const script = nodeEval({ os: platform, shell },
962
1138
  `const net=require("net");const host="${RECOVERY_SQL_SERVER_HOST}";`
963
1139
  + 'const free=(p)=>new Promise((r)=>{const s=net.connect(p,host);const done=(v)=>{try{s.destroy()}catch(e){};r(v)};'
964
1140
  + 's.on("connect",()=>done(false));s.on("error",()=>done(true));setTimeout(()=>done(true),500)});'