@apralabs/apra-fleet 0.3.6 → 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 (826) hide show
  1. package/README.md +378 -252
  2. package/dist/agents/backlog-groomer.md +303 -0
  3. package/dist/agents/ci-watcher.md +13 -1
  4. package/dist/agents/deployer.md +66 -13
  5. package/dist/agents/doer.md +67 -8
  6. package/dist/agents/harvester.md +22 -3
  7. package/dist/agents/integ-test-runner.md +166 -60
  8. package/dist/agents/kb-reconciler.md +216 -0
  9. package/dist/agents/plan-reviewer.md +88 -18
  10. package/dist/agents/planner.md +182 -19
  11. package/dist/agents/regression-test-runner.md +234 -0
  12. package/dist/agents/reviewer.md +125 -9
  13. package/dist/agents/schemas/backlog-groomer-input.json +35 -0
  14. package/dist/agents/schemas/backlog-groomer-output.json +164 -0
  15. package/dist/agents/schemas/doer-output.json +63 -3
  16. package/dist/agents/schemas/harvester-output.json +59 -2
  17. package/dist/agents/schemas/integ-test-runner-output.json +34 -0
  18. package/dist/agents/schemas/kb-reconciler-output.json +87 -0
  19. package/dist/agents/schemas/planner-output.json +65 -0
  20. package/dist/agents/schemas/regression-test-runner-input.json +15 -0
  21. package/dist/agents/schemas/regression-test-runner-output.json +50 -0
  22. package/dist/agents/schemas/reviewer-output.json +108 -7
  23. package/dist/cli/agent-transform.d.ts +1 -0
  24. package/dist/cli/agent-transform.d.ts.map +1 -1
  25. package/dist/cli/agent-transform.js +77 -0
  26. package/dist/cli/agent-transform.js.map +1 -1
  27. package/dist/cli/auth.d.ts +3 -0
  28. package/dist/cli/auth.d.ts.map +1 -1
  29. package/dist/cli/auth.js +181 -5
  30. package/dist/cli/auth.js.map +1 -1
  31. package/dist/cli/config.d.ts +5 -1
  32. package/dist/cli/config.d.ts.map +1 -1
  33. package/dist/cli/config.js +7 -1
  34. package/dist/cli/config.js.map +1 -1
  35. package/dist/cli/dolt-install.d.ts +91 -0
  36. package/dist/cli/dolt-install.d.ts.map +1 -0
  37. package/dist/cli/dolt-install.js +334 -0
  38. package/dist/cli/dolt-install.js.map +1 -0
  39. package/dist/cli/install-guard.d.ts +29 -0
  40. package/dist/cli/install-guard.d.ts.map +1 -0
  41. package/dist/cli/install-guard.js +153 -0
  42. package/dist/cli/install-guard.js.map +1 -0
  43. package/dist/cli/install.d.ts +45 -3
  44. package/dist/cli/install.d.ts.map +1 -1
  45. package/dist/cli/install.js +736 -109
  46. package/dist/cli/install.js.map +1 -1
  47. package/dist/cli/join.d.ts +12 -0
  48. package/dist/cli/join.d.ts.map +1 -0
  49. package/dist/cli/join.js +87 -0
  50. package/dist/cli/join.js.map +1 -0
  51. package/dist/cli/kb-commit.d.ts +12 -0
  52. package/dist/cli/kb-commit.d.ts.map +1 -0
  53. package/dist/cli/kb-commit.js +53 -0
  54. package/dist/cli/kb-commit.js.map +1 -0
  55. package/dist/cli/kb-directives.d.ts +17 -0
  56. package/dist/cli/kb-directives.d.ts.map +1 -0
  57. package/dist/cli/kb-directives.js +146 -0
  58. package/dist/cli/kb-directives.js.map +1 -0
  59. package/dist/cli/kb-import.d.ts +13 -0
  60. package/dist/cli/kb-import.d.ts.map +1 -0
  61. package/dist/cli/kb-import.js +56 -0
  62. package/dist/cli/kb-import.js.map +1 -0
  63. package/dist/cli/register-member.d.ts +2 -0
  64. package/dist/cli/register-member.d.ts.map +1 -0
  65. package/dist/cli/register-member.js +193 -0
  66. package/dist/cli/register-member.js.map +1 -0
  67. package/dist/cli/restart.d.ts +2 -0
  68. package/dist/cli/restart.d.ts.map +1 -0
  69. package/dist/cli/restart.js +7 -0
  70. package/dist/cli/restart.js.map +1 -0
  71. package/dist/cli/spoke.d.ts +35 -0
  72. package/dist/cli/spoke.d.ts.map +1 -0
  73. package/dist/cli/spoke.js +212 -0
  74. package/dist/cli/spoke.js.map +1 -0
  75. package/dist/cli/start.d.ts +2 -0
  76. package/dist/cli/start.d.ts.map +1 -0
  77. package/dist/cli/start.js +92 -0
  78. package/dist/cli/start.js.map +1 -0
  79. package/dist/cli/status.d.ts +2 -0
  80. package/dist/cli/status.d.ts.map +1 -0
  81. package/dist/cli/status.js +83 -0
  82. package/dist/cli/status.js.map +1 -0
  83. package/dist/cli/stop.d.ts +2 -0
  84. package/dist/cli/stop.d.ts.map +1 -0
  85. package/dist/cli/stop.js +51 -0
  86. package/dist/cli/stop.js.map +1 -0
  87. package/dist/cli/uninstall.d.ts.map +1 -1
  88. package/dist/cli/uninstall.js +120 -9
  89. package/dist/cli/uninstall.js.map +1 -1
  90. package/dist/cli/update.d.ts.map +1 -1
  91. package/dist/cli/update.js +10 -1
  92. package/dist/cli/update.js.map +1 -1
  93. package/dist/cli/watch.d.ts +53 -4
  94. package/dist/cli/watch.d.ts.map +1 -1
  95. package/dist/cli/watch.js +118 -17
  96. package/dist/cli/watch.js.map +1 -1
  97. package/dist/cli/workflow-assets.d.ts +37 -0
  98. package/dist/cli/workflow-assets.d.ts.map +1 -0
  99. package/dist/cli/workflow-assets.js +144 -0
  100. package/dist/cli/workflow-assets.js.map +1 -0
  101. package/dist/cli/workflow.d.ts +75 -0
  102. package/dist/cli/workflow.d.ts.map +1 -0
  103. package/dist/cli/workflow.js +397 -0
  104. package/dist/cli/workflow.js.map +1 -0
  105. package/dist/commands/kb-server.d.ts +8 -0
  106. package/dist/commands/kb-server.d.ts.map +1 -0
  107. package/dist/commands/kb-server.js +221 -0
  108. package/dist/commands/kb-server.js.map +1 -0
  109. package/dist/hub-service/activity.d.ts +30 -0
  110. package/dist/hub-service/activity.d.ts.map +1 -0
  111. package/dist/hub-service/activity.js +20 -0
  112. package/dist/hub-service/activity.js.map +1 -0
  113. package/dist/hub-service/audit-log.d.ts +19 -0
  114. package/dist/hub-service/audit-log.d.ts.map +1 -0
  115. package/dist/hub-service/audit-log.js +13 -0
  116. package/dist/hub-service/audit-log.js.map +1 -0
  117. package/dist/hub-service/db/pool.d.ts +19 -0
  118. package/dist/hub-service/db/pool.d.ts.map +1 -0
  119. package/dist/hub-service/db/pool.js +53 -0
  120. package/dist/hub-service/db/pool.js.map +1 -0
  121. package/dist/hub-service/enrollment.d.ts +29 -0
  122. package/dist/hub-service/enrollment.d.ts.map +1 -0
  123. package/dist/hub-service/enrollment.js +48 -0
  124. package/dist/hub-service/enrollment.js.map +1 -0
  125. package/dist/hub-service/envelope-routes.d.ts +46 -0
  126. package/dist/hub-service/envelope-routes.d.ts.map +1 -0
  127. package/dist/hub-service/envelope-routes.js +94 -0
  128. package/dist/hub-service/envelope-routes.js.map +1 -0
  129. package/dist/hub-service/handlers/installers.d.ts +14 -0
  130. package/dist/hub-service/handlers/installers.d.ts.map +1 -0
  131. package/dist/hub-service/handlers/installers.js +8 -0
  132. package/dist/hub-service/handlers/installers.js.map +1 -0
  133. package/dist/hub-service/http-server.d.ts +31 -0
  134. package/dist/hub-service/http-server.d.ts.map +1 -0
  135. package/dist/hub-service/http-server.js +711 -0
  136. package/dist/hub-service/http-server.js.map +1 -0
  137. package/dist/hub-service/hub-jwt.d.ts +30 -0
  138. package/dist/hub-service/hub-jwt.d.ts.map +1 -0
  139. package/dist/hub-service/hub-jwt.js +105 -0
  140. package/dist/hub-service/hub-jwt.js.map +1 -0
  141. package/dist/hub-service/jwt-revocation.d.ts +20 -0
  142. package/dist/hub-service/jwt-revocation.d.ts.map +1 -0
  143. package/dist/hub-service/jwt-revocation.js +18 -0
  144. package/dist/hub-service/jwt-revocation.js.map +1 -0
  145. package/dist/hub-service/machines.d.ts +16 -0
  146. package/dist/hub-service/machines.d.ts.map +1 -0
  147. package/dist/hub-service/machines.js +14 -0
  148. package/dist/hub-service/machines.js.map +1 -0
  149. package/dist/hub-service/main.d.ts +3 -0
  150. package/dist/hub-service/main.d.ts.map +1 -0
  151. package/dist/hub-service/main.js +64 -0
  152. package/dist/hub-service/main.js.map +1 -0
  153. package/dist/hub-service/member-tokens.d.ts +11 -0
  154. package/dist/hub-service/member-tokens.d.ts.map +1 -0
  155. package/dist/hub-service/member-tokens.js +49 -0
  156. package/dist/hub-service/member-tokens.js.map +1 -0
  157. package/dist/hub-service/member-view.d.ts +20 -0
  158. package/dist/hub-service/member-view.d.ts.map +1 -0
  159. package/dist/hub-service/member-view.js +76 -0
  160. package/dist/hub-service/member-view.js.map +1 -0
  161. package/dist/hub-service/members.d.ts +44 -0
  162. package/dist/hub-service/members.d.ts.map +1 -0
  163. package/dist/hub-service/members.js +25 -0
  164. package/dist/hub-service/members.js.map +1 -0
  165. package/dist/hub-service/presence.d.ts +40 -0
  166. package/dist/hub-service/presence.d.ts.map +1 -0
  167. package/dist/hub-service/presence.js +44 -0
  168. package/dist/hub-service/presence.js.map +1 -0
  169. package/dist/hub-service/project-view.d.ts +12 -0
  170. package/dist/hub-service/project-view.d.ts.map +1 -0
  171. package/dist/hub-service/project-view.js +34 -0
  172. package/dist/hub-service/project-view.js.map +1 -0
  173. package/dist/hub-service/projects.d.ts +48 -0
  174. package/dist/hub-service/projects.d.ts.map +1 -0
  175. package/dist/hub-service/projects.js +80 -0
  176. package/dist/hub-service/projects.js.map +1 -0
  177. package/dist/hub-service/relay-queue.d.ts +115 -0
  178. package/dist/hub-service/relay-queue.d.ts.map +1 -0
  179. package/dist/hub-service/relay-queue.js +148 -0
  180. package/dist/hub-service/relay-queue.js.map +1 -0
  181. package/dist/hub-service/session-jwt.d.ts +10 -0
  182. package/dist/hub-service/session-jwt.d.ts.map +1 -0
  183. package/dist/hub-service/session-jwt.js +69 -0
  184. package/dist/hub-service/session-jwt.js.map +1 -0
  185. package/dist/hub-service/usage.d.ts +40 -0
  186. package/dist/hub-service/usage.d.ts.map +1 -0
  187. package/dist/hub-service/usage.js +25 -0
  188. package/dist/hub-service/usage.js.map +1 -0
  189. package/dist/hub-service/users.d.ts +56 -0
  190. package/dist/hub-service/users.d.ts.map +1 -0
  191. package/dist/hub-service/users.js +72 -0
  192. package/dist/hub-service/users.js.map +1 -0
  193. package/dist/hub-service/workspaces.d.ts +20 -0
  194. package/dist/hub-service/workspaces.d.ts.map +1 -0
  195. package/dist/hub-service/workspaces.js +10 -0
  196. package/dist/hub-service/workspaces.js.map +1 -0
  197. package/dist/index.js +254 -132
  198. package/dist/index.js.map +1 -1
  199. package/dist/os/linux.d.ts +14 -0
  200. package/dist/os/linux.d.ts.map +1 -1
  201. package/dist/os/linux.js +80 -4
  202. package/dist/os/linux.js.map +1 -1
  203. package/dist/os/os-commands.d.ts +15 -0
  204. package/dist/os/os-commands.d.ts.map +1 -1
  205. package/dist/os/windows.d.ts +36 -0
  206. package/dist/os/windows.d.ts.map +1 -1
  207. package/dist/os/windows.js +74 -18
  208. package/dist/os/windows.js.map +1 -1
  209. package/dist/paths.d.ts +23 -0
  210. package/dist/paths.d.ts.map +1 -1
  211. package/dist/paths.js +29 -0
  212. package/dist/paths.js.map +1 -1
  213. package/dist/providers/agy.d.ts +20 -2
  214. package/dist/providers/agy.d.ts.map +1 -1
  215. package/dist/providers/agy.js +259 -21
  216. package/dist/providers/agy.js.map +1 -1
  217. package/dist/providers/claude.d.ts +16 -2
  218. package/dist/providers/claude.d.ts.map +1 -1
  219. package/dist/providers/claude.js +283 -16
  220. package/dist/providers/claude.js.map +1 -1
  221. package/dist/providers/codex.d.ts +13 -2
  222. package/dist/providers/codex.d.ts.map +1 -1
  223. package/dist/providers/codex.js +36 -6
  224. package/dist/providers/codex.js.map +1 -1
  225. package/dist/providers/copilot.d.ts +13 -2
  226. package/dist/providers/copilot.d.ts.map +1 -1
  227. package/dist/providers/copilot.js +34 -7
  228. package/dist/providers/copilot.js.map +1 -1
  229. package/dist/providers/email/headers.d.ts +15 -0
  230. package/dist/providers/email/headers.d.ts.map +1 -0
  231. package/dist/providers/email/headers.js +42 -0
  232. package/dist/providers/email/headers.js.map +1 -0
  233. package/dist/providers/email/index.d.ts +18 -0
  234. package/dist/providers/email/index.d.ts.map +1 -0
  235. package/dist/providers/email/index.js +60 -0
  236. package/dist/providers/email/index.js.map +1 -0
  237. package/dist/providers/email/provider.d.ts +49 -0
  238. package/dist/providers/email/provider.d.ts.map +1 -0
  239. package/dist/providers/email/provider.js +2 -0
  240. package/dist/providers/email/provider.js.map +1 -0
  241. package/dist/providers/email/sendgrid.d.ts +12 -0
  242. package/dist/providers/email/sendgrid.d.ts.map +1 -0
  243. package/dist/providers/email/sendgrid.js +67 -0
  244. package/dist/providers/email/sendgrid.js.map +1 -0
  245. package/dist/providers/email/smtp.d.ts +65 -0
  246. package/dist/providers/email/smtp.d.ts.map +1 -0
  247. package/dist/providers/email/smtp.js +373 -0
  248. package/dist/providers/email/smtp.js.map +1 -0
  249. package/dist/providers/gemini.d.ts +13 -2
  250. package/dist/providers/gemini.d.ts.map +1 -1
  251. package/dist/providers/gemini.js +49 -5
  252. package/dist/providers/gemini.js.map +1 -1
  253. package/dist/providers/index.d.ts +1 -0
  254. package/dist/providers/index.d.ts.map +1 -1
  255. package/dist/providers/index.js +3 -0
  256. package/dist/providers/index.js.map +1 -1
  257. package/dist/providers/none.d.ts +61 -0
  258. package/dist/providers/none.d.ts.map +1 -0
  259. package/dist/providers/none.js +124 -0
  260. package/dist/providers/none.js.map +1 -0
  261. package/dist/providers/opencode.d.ts +14 -2
  262. package/dist/providers/opencode.d.ts.map +1 -1
  263. package/dist/providers/opencode.js +104 -4
  264. package/dist/providers/opencode.js.map +1 -1
  265. package/dist/providers/provider.d.ts +156 -1
  266. package/dist/providers/provider.d.ts.map +1 -1
  267. package/dist/providers/provider.js +54 -0
  268. package/dist/providers/provider.js.map +1 -1
  269. package/dist/services/agent-provisioner.d.ts +3 -3
  270. package/dist/services/agent-provisioner.d.ts.map +1 -1
  271. package/dist/services/agent-provisioner.js +11 -7
  272. package/dist/services/agent-provisioner.js.map +1 -1
  273. package/dist/services/auth-socket.d.ts.map +1 -1
  274. package/dist/services/auth-socket.js +2 -0
  275. package/dist/services/auth-socket.js.map +1 -1
  276. package/dist/services/budget-awareness.d.ts +130 -0
  277. package/dist/services/budget-awareness.d.ts.map +1 -0
  278. package/dist/services/budget-awareness.js +129 -0
  279. package/dist/services/budget-awareness.js.map +1 -0
  280. package/dist/services/cloud/lifecycle.d.ts.map +1 -1
  281. package/dist/services/cloud/lifecycle.js +3 -0
  282. package/dist/services/cloud/lifecycle.js.map +1 -1
  283. package/dist/services/cloud/task-wrapper.d.ts +18 -0
  284. package/dist/services/cloud/task-wrapper.d.ts.map +1 -1
  285. package/dist/services/cloud/task-wrapper.js +157 -0
  286. package/dist/services/cloud/task-wrapper.js.map +1 -1
  287. package/dist/services/cloud-sync.d.ts +35 -0
  288. package/dist/services/cloud-sync.d.ts.map +1 -0
  289. package/dist/services/cloud-sync.js +90 -0
  290. package/dist/services/cloud-sync.js.map +1 -0
  291. package/dist/services/context-admission.d.ts +82 -0
  292. package/dist/services/context-admission.d.ts.map +1 -0
  293. package/dist/services/context-admission.js +136 -0
  294. package/dist/services/context-admission.js.map +1 -0
  295. package/dist/services/event-bus.d.ts +27 -0
  296. package/dist/services/event-bus.d.ts.map +1 -0
  297. package/dist/services/event-bus.js +20 -0
  298. package/dist/services/event-bus.js.map +1 -0
  299. package/dist/services/file-chunker.d.ts +38 -0
  300. package/dist/services/file-chunker.d.ts.map +1 -0
  301. package/dist/services/file-chunker.js +63 -0
  302. package/dist/services/file-chunker.js.map +1 -0
  303. package/dist/services/file-transfer-relay.d.ts +55 -0
  304. package/dist/services/file-transfer-relay.d.ts.map +1 -0
  305. package/dist/services/file-transfer-relay.js +115 -0
  306. package/dist/services/file-transfer-relay.js.map +1 -0
  307. package/dist/services/github-app.d.ts.map +1 -1
  308. package/dist/services/github-app.js +12 -2
  309. package/dist/services/github-app.js.map +1 -1
  310. package/dist/services/http-transport.d.ts +25 -0
  311. package/dist/services/http-transport.d.ts.map +1 -0
  312. package/dist/services/http-transport.js +371 -0
  313. package/dist/services/http-transport.js.map +1 -0
  314. package/dist/services/hub-client.d.ts +69 -0
  315. package/dist/services/hub-client.d.ts.map +1 -0
  316. package/dist/services/hub-client.js +217 -0
  317. package/dist/services/hub-client.js.map +1 -0
  318. package/dist/services/jwt.d.ts +17 -0
  319. package/dist/services/jwt.d.ts.map +1 -0
  320. package/dist/services/jwt.js +70 -0
  321. package/dist/services/jwt.js.map +1 -0
  322. package/dist/services/knowledge/audn.d.ts +37 -0
  323. package/dist/services/knowledge/audn.d.ts.map +1 -0
  324. package/dist/services/knowledge/audn.js +219 -0
  325. package/dist/services/knowledge/audn.js.map +1 -0
  326. package/dist/services/knowledge/file-hash.d.ts +11 -0
  327. package/dist/services/knowledge/file-hash.d.ts.map +1 -0
  328. package/dist/services/knowledge/file-hash.js +123 -0
  329. package/dist/services/knowledge/file-hash.js.map +1 -0
  330. package/dist/services/knowledge/http-provider.d.ts +46 -0
  331. package/dist/services/knowledge/http-provider.d.ts.map +1 -0
  332. package/dist/services/knowledge/http-provider.js +254 -0
  333. package/dist/services/knowledge/http-provider.js.map +1 -0
  334. package/dist/services/knowledge/kb-providers.d.ts +15 -0
  335. package/dist/services/knowledge/kb-providers.d.ts.map +1 -0
  336. package/dist/services/knowledge/kb-providers.js +92 -0
  337. package/dist/services/knowledge/kb-providers.js.map +1 -0
  338. package/dist/services/knowledge/kb-scope-input.d.ts +5 -0
  339. package/dist/services/knowledge/kb-scope-input.d.ts.map +1 -0
  340. package/dist/services/knowledge/kb-scope-input.js +11 -0
  341. package/dist/services/knowledge/kb-scope-input.js.map +1 -0
  342. package/dist/services/knowledge/kb-service.d.ts +3 -0
  343. package/dist/services/knowledge/kb-service.d.ts.map +1 -0
  344. package/dist/services/knowledge/kb-service.js +2 -0
  345. package/dist/services/knowledge/kb-service.js.map +1 -0
  346. package/dist/services/knowledge/path-validation.d.ts +2 -0
  347. package/dist/services/knowledge/path-validation.d.ts.map +1 -0
  348. package/dist/services/knowledge/path-validation.js +13 -0
  349. package/dist/services/knowledge/path-validation.js.map +1 -0
  350. package/dist/services/knowledge/pre-init.d.ts +14 -0
  351. package/dist/services/knowledge/pre-init.d.ts.map +1 -0
  352. package/dist/services/knowledge/pre-init.js +147 -0
  353. package/dist/services/knowledge/pre-init.js.map +1 -0
  354. package/dist/services/knowledge/project-slug.d.ts +2 -0
  355. package/dist/services/knowledge/project-slug.d.ts.map +1 -0
  356. package/dist/services/knowledge/project-slug.js +49 -0
  357. package/dist/services/knowledge/project-slug.js.map +1 -0
  358. package/dist/services/knowledge/sqlite-provider.d.ts +147 -0
  359. package/dist/services/knowledge/sqlite-provider.d.ts.map +1 -0
  360. package/dist/services/knowledge/sqlite-provider.js +1646 -0
  361. package/dist/services/knowledge/sqlite-provider.js.map +1 -0
  362. package/dist/services/knowledge/types.d.ts +163 -0
  363. package/dist/services/knowledge/types.d.ts.map +1 -0
  364. package/dist/services/knowledge/types.js +9 -0
  365. package/dist/services/knowledge/types.js.map +1 -0
  366. package/dist/services/known-sessions.d.ts +8 -0
  367. package/dist/services/known-sessions.d.ts.map +1 -0
  368. package/dist/services/known-sessions.js +40 -0
  369. package/dist/services/known-sessions.js.map +1 -0
  370. package/dist/services/member-home.d.ts +89 -0
  371. package/dist/services/member-home.d.ts.map +1 -0
  372. package/dist/services/member-home.js +256 -0
  373. package/dist/services/member-home.js.map +1 -0
  374. package/dist/services/member-remote-url.d.ts +34 -0
  375. package/dist/services/member-remote-url.d.ts.map +1 -0
  376. package/dist/services/member-remote-url.js +39 -0
  377. package/dist/services/member-remote-url.js.map +1 -0
  378. package/dist/services/model-pricing.d.ts +36 -0
  379. package/dist/services/model-pricing.d.ts.map +1 -0
  380. package/dist/services/model-pricing.js +108 -0
  381. package/dist/services/model-pricing.js.map +1 -0
  382. package/dist/services/orphan-recovery.d.ts +59 -0
  383. package/dist/services/orphan-recovery.d.ts.map +1 -0
  384. package/dist/services/orphan-recovery.js +122 -0
  385. package/dist/services/orphan-recovery.js.map +1 -0
  386. package/dist/services/pending-responses.d.ts +23 -0
  387. package/dist/services/pending-responses.d.ts.map +1 -0
  388. package/dist/services/pending-responses.js +52 -0
  389. package/dist/services/pending-responses.js.map +1 -0
  390. package/dist/services/preflight-check.d.ts +56 -0
  391. package/dist/services/preflight-check.d.ts.map +1 -0
  392. package/dist/services/preflight-check.js +277 -0
  393. package/dist/services/preflight-check.js.map +1 -0
  394. package/dist/services/registry.d.ts +4 -1
  395. package/dist/services/registry.d.ts.map +1 -1
  396. package/dist/services/registry.js +3 -0
  397. package/dist/services/registry.js.map +1 -1
  398. package/dist/services/relay-context.d.ts +23 -0
  399. package/dist/services/relay-context.d.ts.map +1 -0
  400. package/dist/services/relay-context.js +8 -0
  401. package/dist/services/relay-context.js.map +1 -0
  402. package/dist/services/relay-executor.d.ts +68 -0
  403. package/dist/services/relay-executor.d.ts.map +1 -0
  404. package/dist/services/relay-executor.js +70 -0
  405. package/dist/services/relay-executor.js.map +1 -0
  406. package/dist/services/relay-request.d.ts +65 -0
  407. package/dist/services/relay-request.d.ts.map +1 -0
  408. package/dist/services/relay-request.js +129 -0
  409. package/dist/services/relay-request.js.map +1 -0
  410. package/dist/services/relay-strategy.d.ts +19 -0
  411. package/dist/services/relay-strategy.d.ts.map +1 -0
  412. package/dist/services/relay-strategy.js +111 -0
  413. package/dist/services/relay-strategy.js.map +1 -0
  414. package/dist/services/service-manager/index.d.ts +5 -0
  415. package/dist/services/service-manager/index.d.ts.map +1 -0
  416. package/dist/services/service-manager/index.js +66 -0
  417. package/dist/services/service-manager/index.js.map +1 -0
  418. package/dist/services/service-manager/linux.d.ts +10 -0
  419. package/dist/services/service-manager/linux.d.ts.map +1 -0
  420. package/dist/services/service-manager/linux.js +97 -0
  421. package/dist/services/service-manager/linux.js.map +1 -0
  422. package/dist/services/service-manager/macos.d.ts +10 -0
  423. package/dist/services/service-manager/macos.d.ts.map +1 -0
  424. package/dist/services/service-manager/macos.js +94 -0
  425. package/dist/services/service-manager/macos.js.map +1 -0
  426. package/dist/services/service-manager/types.d.ts +18 -0
  427. package/dist/services/service-manager/types.d.ts.map +1 -0
  428. package/dist/services/service-manager/types.js +5 -0
  429. package/dist/services/service-manager/types.js.map +1 -0
  430. package/dist/services/service-manager/windows.d.ts +10 -0
  431. package/dist/services/service-manager/windows.d.ts.map +1 -0
  432. package/dist/services/service-manager/windows.js +73 -0
  433. package/dist/services/service-manager/windows.js.map +1 -0
  434. package/dist/services/session-registry.d.ts +70 -0
  435. package/dist/services/session-registry.d.ts.map +1 -0
  436. package/dist/services/session-registry.js +91 -0
  437. package/dist/services/session-registry.js.map +1 -0
  438. package/dist/services/singleton.d.ts +15 -0
  439. package/dist/services/singleton.d.ts.map +1 -0
  440. package/dist/services/singleton.js +98 -0
  441. package/dist/services/singleton.js.map +1 -0
  442. package/dist/services/sprint-coordination.d.ts +168 -0
  443. package/dist/services/sprint-coordination.d.ts.map +1 -0
  444. package/dist/services/sprint-coordination.js +564 -0
  445. package/dist/services/sprint-coordination.js.map +1 -0
  446. package/dist/services/ssh.d.ts.map +1 -1
  447. package/dist/services/ssh.js +70 -3
  448. package/dist/services/ssh.js.map +1 -1
  449. package/dist/services/stall/log-path-resolver.d.ts +11 -8
  450. package/dist/services/stall/log-path-resolver.d.ts.map +1 -1
  451. package/dist/services/stall/log-path-resolver.js +17 -33
  452. package/dist/services/stall/log-path-resolver.js.map +1 -1
  453. package/dist/services/stall/stall-detector.d.ts +32 -0
  454. package/dist/services/stall/stall-detector.d.ts.map +1 -1
  455. package/dist/services/stall/stall-detector.js +187 -12
  456. package/dist/services/stall/stall-detector.js.map +1 -1
  457. package/dist/services/stall/stall-poller.d.ts +50 -0
  458. package/dist/services/stall/stall-poller.d.ts.map +1 -1
  459. package/dist/services/stall/stall-poller.js +268 -18
  460. package/dist/services/stall/stall-poller.js.map +1 -1
  461. package/dist/services/strategy.d.ts.map +1 -1
  462. package/dist/services/strategy.js +57 -7
  463. package/dist/services/strategy.js.map +1 -1
  464. package/dist/services/substitution-engine.d.ts +20 -0
  465. package/dist/services/substitution-engine.d.ts.map +1 -0
  466. package/dist/services/substitution-engine.js +92 -0
  467. package/dist/services/substitution-engine.js.map +1 -0
  468. package/dist/services/task-cleanup.d.ts.map +1 -1
  469. package/dist/services/task-cleanup.js +1 -9
  470. package/dist/services/task-cleanup.js.map +1 -1
  471. package/dist/services/token-issuer.d.ts +47 -0
  472. package/dist/services/token-issuer.d.ts.map +1 -0
  473. package/dist/services/token-issuer.js +63 -0
  474. package/dist/services/token-issuer.js.map +1 -0
  475. package/dist/services/tool-registry.d.ts +3 -0
  476. package/dist/services/tool-registry.d.ts.map +1 -0
  477. package/dist/services/tool-registry.js +225 -0
  478. package/dist/services/tool-registry.js.map +1 -0
  479. package/dist/services/user-config.d.ts +14 -0
  480. package/dist/services/user-config.d.ts.map +1 -1
  481. package/dist/services/user-config.js +55 -0
  482. package/dist/services/user-config.js.map +1 -1
  483. package/dist/services/vcs/github.d.ts.map +1 -1
  484. package/dist/services/vcs/github.js +32 -1
  485. package/dist/services/vcs/github.js.map +1 -1
  486. package/dist/services/vcs/types.d.ts +44 -0
  487. package/dist/services/vcs/types.d.ts.map +1 -1
  488. package/dist/services/version-check.d.ts +22 -0
  489. package/dist/services/version-check.d.ts.map +1 -0
  490. package/dist/services/version-check.js +103 -0
  491. package/dist/services/version-check.js.map +1 -0
  492. package/dist/skills/fleet-sprint-cli/SKILL.md +114 -0
  493. package/dist/skills/pm/beads.md +6 -0
  494. package/dist/skills/pm/cost.md +3 -0
  495. package/dist/skills/pm/doer-reviewer-loop.md +3 -0
  496. package/dist/skills/pm/fleet-addendum.md +6 -0
  497. package/dist/skills/pm/index.md +56 -0
  498. package/dist/skills/pm/kb-reconcile.md +132 -0
  499. package/dist/skills/pm/kb-review.md +109 -0
  500. package/dist/tools/check-status.d.ts +47 -0
  501. package/dist/tools/check-status.d.ts.map +1 -1
  502. package/dist/tools/check-status.js +250 -2
  503. package/dist/tools/check-status.js.map +1 -1
  504. package/dist/tools/child-id-allocator.d.ts +45 -0
  505. package/dist/tools/child-id-allocator.d.ts.map +1 -0
  506. package/dist/tools/child-id-allocator.js +62 -0
  507. package/dist/tools/child-id-allocator.js.map +1 -0
  508. package/dist/tools/cloud-control.d.ts +2 -2
  509. package/dist/tools/code-intelligence-codebase-memory.d.ts +11 -0
  510. package/dist/tools/code-intelligence-codebase-memory.d.ts.map +1 -0
  511. package/dist/tools/code-intelligence-codebase-memory.js +270 -0
  512. package/dist/tools/code-intelligence-codebase-memory.js.map +1 -0
  513. package/dist/tools/code-intelligence-freshness.d.ts +2 -0
  514. package/dist/tools/code-intelligence-freshness.d.ts.map +1 -0
  515. package/dist/tools/code-intelligence-freshness.js +26 -0
  516. package/dist/tools/code-intelligence-freshness.js.map +1 -0
  517. package/dist/tools/code-intelligence-gitnexus.d.ts +14 -0
  518. package/dist/tools/code-intelligence-gitnexus.d.ts.map +1 -0
  519. package/dist/tools/code-intelligence-gitnexus.js +475 -0
  520. package/dist/tools/code-intelligence-gitnexus.js.map +1 -0
  521. package/dist/tools/code-intelligence-kb-enrich.d.ts +2 -0
  522. package/dist/tools/code-intelligence-kb-enrich.d.ts.map +1 -0
  523. package/dist/tools/code-intelligence-kb-enrich.js +65 -0
  524. package/dist/tools/code-intelligence-kb-enrich.js.map +1 -0
  525. package/dist/tools/code-intelligence-reindex.d.ts +7 -0
  526. package/dist/tools/code-intelligence-reindex.d.ts.map +1 -0
  527. package/dist/tools/code-intelligence-reindex.js +106 -0
  528. package/dist/tools/code-intelligence-reindex.js.map +1 -0
  529. package/dist/tools/code-intelligence-telemetry.d.ts +5 -0
  530. package/dist/tools/code-intelligence-telemetry.d.ts.map +1 -0
  531. package/dist/tools/code-intelligence-telemetry.js +52 -0
  532. package/dist/tools/code-intelligence-telemetry.js.map +1 -0
  533. package/dist/tools/code-intelligence-tests.d.ts +2 -0
  534. package/dist/tools/code-intelligence-tests.d.ts.map +1 -0
  535. package/dist/tools/code-intelligence-tests.js +24 -0
  536. package/dist/tools/code-intelligence-tests.js.map +1 -0
  537. package/dist/tools/code-intelligence.d.ts +114 -0
  538. package/dist/tools/code-intelligence.d.ts.map +1 -0
  539. package/dist/tools/code-intelligence.js +124 -0
  540. package/dist/tools/code-intelligence.js.map +1 -0
  541. package/dist/tools/compose-permissions.d.ts +38 -4
  542. package/dist/tools/compose-permissions.d.ts.map +1 -1
  543. package/dist/tools/compose-permissions.js +295 -33
  544. package/dist/tools/compose-permissions.js.map +1 -1
  545. package/dist/tools/dolt-push-mutex.d.ts +44 -0
  546. package/dist/tools/dolt-push-mutex.d.ts.map +1 -0
  547. package/dist/tools/dolt-push-mutex.js +83 -0
  548. package/dist/tools/dolt-push-mutex.js.map +1 -0
  549. package/dist/tools/execute-command.d.ts +13 -1
  550. package/dist/tools/execute-command.d.ts.map +1 -1
  551. package/dist/tools/execute-command.js +108 -21
  552. package/dist/tools/execute-command.js.map +1 -1
  553. package/dist/tools/execute-prompt.d.ts +84 -12
  554. package/dist/tools/execute-prompt.d.ts.map +1 -1
  555. package/dist/tools/execute-prompt.js +1191 -88
  556. package/dist/tools/execute-prompt.js.map +1 -1
  557. package/dist/tools/get-member-model-pricing.d.ts +21 -0
  558. package/dist/tools/get-member-model-pricing.d.ts.map +1 -0
  559. package/dist/tools/get-member-model-pricing.js +29 -0
  560. package/dist/tools/get-member-model-pricing.js.map +1 -0
  561. package/dist/tools/kb-capture.d.ts +53 -0
  562. package/dist/tools/kb-capture.d.ts.map +1 -0
  563. package/dist/tools/kb-capture.js +130 -0
  564. package/dist/tools/kb-capture.js.map +1 -0
  565. package/dist/tools/kb-context.d.ts +17 -0
  566. package/dist/tools/kb-context.d.ts.map +1 -0
  567. package/dist/tools/kb-context.js +29 -0
  568. package/dist/tools/kb-context.js.map +1 -0
  569. package/dist/tools/kb-export.d.ts +19 -0
  570. package/dist/tools/kb-export.d.ts.map +1 -0
  571. package/dist/tools/kb-export.js +344 -0
  572. package/dist/tools/kb-export.js.map +1 -0
  573. package/dist/tools/kb-feedback.d.ts +23 -0
  574. package/dist/tools/kb-feedback.d.ts.map +1 -0
  575. package/dist/tools/kb-feedback.js +43 -0
  576. package/dist/tools/kb-feedback.js.map +1 -0
  577. package/dist/tools/kb-freshness-sweep.d.ts +14 -0
  578. package/dist/tools/kb-freshness-sweep.d.ts.map +1 -0
  579. package/dist/tools/kb-freshness-sweep.js +29 -0
  580. package/dist/tools/kb-freshness-sweep.js.map +1 -0
  581. package/dist/tools/kb-harvest.d.ts +20 -0
  582. package/dist/tools/kb-harvest.d.ts.map +1 -0
  583. package/dist/tools/kb-harvest.js +143 -0
  584. package/dist/tools/kb-harvest.js.map +1 -0
  585. package/dist/tools/kb-import.d.ts +44 -0
  586. package/dist/tools/kb-import.d.ts.map +1 -0
  587. package/dist/tools/kb-import.js +239 -0
  588. package/dist/tools/kb-import.js.map +1 -0
  589. package/dist/tools/kb-invalidate.d.ts +19 -0
  590. package/dist/tools/kb-invalidate.d.ts.map +1 -0
  591. package/dist/tools/kb-invalidate.js +34 -0
  592. package/dist/tools/kb-invalidate.js.map +1 -0
  593. package/dist/tools/kb-list.d.ts +32 -0
  594. package/dist/tools/kb-list.d.ts.map +1 -0
  595. package/dist/tools/kb-list.js +43 -0
  596. package/dist/tools/kb-list.js.map +1 -0
  597. package/dist/tools/kb-promote.d.ts +20 -0
  598. package/dist/tools/kb-promote.d.ts.map +1 -0
  599. package/dist/tools/kb-promote.js +20 -0
  600. package/dist/tools/kb-promote.js.map +1 -0
  601. package/dist/tools/kb-query.d.ts +35 -0
  602. package/dist/tools/kb-query.d.ts.map +1 -0
  603. package/dist/tools/kb-query.js +111 -0
  604. package/dist/tools/kb-query.js.map +1 -0
  605. package/dist/tools/kb-reconcile-prefilter.d.ts +14 -0
  606. package/dist/tools/kb-reconcile-prefilter.d.ts.map +1 -0
  607. package/dist/tools/kb-reconcile-prefilter.js +26 -0
  608. package/dist/tools/kb-reconcile-prefilter.js.map +1 -0
  609. package/dist/tools/kb-resolve-contradiction.d.ts +23 -0
  610. package/dist/tools/kb-resolve-contradiction.d.ts.map +1 -0
  611. package/dist/tools/kb-resolve-contradiction.js +37 -0
  612. package/dist/tools/kb-resolve-contradiction.js.map +1 -0
  613. package/dist/tools/kb-session-prime.d.ts +26 -0
  614. package/dist/tools/kb-session-prime.d.ts.map +1 -0
  615. package/dist/tools/kb-session-prime.js +392 -0
  616. package/dist/tools/kb-session-prime.js.map +1 -0
  617. package/dist/tools/kb-setup.d.ts +20 -0
  618. package/dist/tools/kb-setup.d.ts.map +1 -0
  619. package/dist/tools/kb-setup.js +49 -0
  620. package/dist/tools/kb-setup.js.map +1 -0
  621. package/dist/tools/kb-stats.d.ts +20 -0
  622. package/dist/tools/kb-stats.d.ts.map +1 -0
  623. package/dist/tools/kb-stats.js +115 -0
  624. package/dist/tools/kb-stats.js.map +1 -0
  625. package/dist/tools/list-members.d.ts.map +1 -1
  626. package/dist/tools/list-members.js +39 -7
  627. package/dist/tools/list-members.js.map +1 -1
  628. package/dist/tools/member-detail.d.ts +1 -1
  629. package/dist/tools/member-detail.d.ts.map +1 -1
  630. package/dist/tools/member-detail.js +16 -2
  631. package/dist/tools/member-detail.js.map +1 -1
  632. package/dist/tools/member-reservation.d.ts +29 -0
  633. package/dist/tools/member-reservation.d.ts.map +1 -0
  634. package/dist/tools/member-reservation.js +71 -0
  635. package/dist/tools/member-reservation.js.map +1 -0
  636. package/dist/tools/monitor-task.d.ts.map +1 -1
  637. package/dist/tools/monitor-task.js +21 -3
  638. package/dist/tools/monitor-task.js.map +1 -1
  639. package/dist/tools/provision-auth.d.ts.map +1 -1
  640. package/dist/tools/provision-auth.js +10 -3
  641. package/dist/tools/provision-auth.js.map +1 -1
  642. package/dist/tools/provision-vcs-auth.d.ts +7 -7
  643. package/dist/tools/provision-vcs-auth.js +1 -1
  644. package/dist/tools/provision-vcs-auth.js.map +1 -1
  645. package/dist/tools/register-member.d.ts +20 -5
  646. package/dist/tools/register-member.d.ts.map +1 -1
  647. package/dist/tools/register-member.js +174 -6
  648. package/dist/tools/register-member.js.map +1 -1
  649. package/dist/tools/remove-member.d.ts +1 -1
  650. package/dist/tools/remove-member.d.ts.map +1 -1
  651. package/dist/tools/remove-member.js +17 -3
  652. package/dist/tools/remove-member.js.map +1 -1
  653. package/dist/tools/report-status.d.ts +33 -0
  654. package/dist/tools/report-status.d.ts.map +1 -0
  655. package/dist/tools/report-status.js +45 -0
  656. package/dist/tools/report-status.js.map +1 -0
  657. package/dist/tools/respond-to-message.d.ts +21 -0
  658. package/dist/tools/respond-to-message.d.ts.map +1 -0
  659. package/dist/tools/respond-to-message.js +23 -0
  660. package/dist/tools/respond-to-message.js.map +1 -0
  661. package/dist/tools/send-email.d.ts +69 -0
  662. package/dist/tools/send-email.d.ts.map +1 -0
  663. package/dist/tools/send-email.js +177 -0
  664. package/dist/tools/send-email.js.map +1 -0
  665. package/dist/tools/send-files.d.ts +3 -0
  666. package/dist/tools/send-files.d.ts.map +1 -1
  667. package/dist/tools/send-files.js +88 -8
  668. package/dist/tools/send-files.js.map +1 -1
  669. package/dist/tools/send-message.d.ts +27 -0
  670. package/dist/tools/send-message.d.ts.map +1 -0
  671. package/dist/tools/send-message.js +46 -0
  672. package/dist/tools/send-message.js.map +1 -0
  673. package/dist/tools/setup-ssh-key.d.ts.map +1 -1
  674. package/dist/tools/setup-ssh-key.js +2 -0
  675. package/dist/tools/setup-ssh-key.js.map +1 -1
  676. package/dist/tools/shutdown-server.d.ts +2 -0
  677. package/dist/tools/shutdown-server.d.ts.map +1 -1
  678. package/dist/tools/shutdown-server.js +19 -0
  679. package/dist/tools/shutdown-server.js.map +1 -1
  680. package/dist/tools/update-member.d.ts +11 -8
  681. package/dist/tools/update-member.d.ts.map +1 -1
  682. package/dist/tools/update-member.js +36 -2
  683. package/dist/tools/update-member.js.map +1 -1
  684. package/dist/types.d.ts +16 -3
  685. package/dist/types.d.ts.map +1 -1
  686. package/dist/utils/agent-helpers.d.ts +2 -1
  687. package/dist/utils/agent-helpers.d.ts.map +1 -1
  688. package/dist/utils/agent-helpers.js +7 -2
  689. package/dist/utils/agent-helpers.js.map +1 -1
  690. package/dist/utils/pid-helpers.d.ts +15 -0
  691. package/dist/utils/pid-helpers.d.ts.map +1 -1
  692. package/dist/utils/pid-helpers.js +23 -0
  693. package/dist/utils/pid-helpers.js.map +1 -1
  694. package/dist/utils/process-utils.d.ts +3 -0
  695. package/dist/utils/process-utils.d.ts.map +1 -0
  696. package/dist/utils/process-utils.js +42 -0
  697. package/dist/utils/process-utils.js.map +1 -0
  698. package/dist/utils/prompt-errors.d.ts +2 -1
  699. package/dist/utils/prompt-errors.d.ts.map +1 -1
  700. package/dist/utils/prompt-errors.js +13 -3
  701. package/dist/utils/prompt-errors.js.map +1 -1
  702. package/dist/utils/session-caller.d.ts +28 -0
  703. package/dist/utils/session-caller.d.ts.map +1 -0
  704. package/dist/utils/session-caller.js +24 -0
  705. package/dist/utils/session-caller.js.map +1 -0
  706. package/dist/utils/work-folder-validation.d.ts +39 -0
  707. package/dist/utils/work-folder-validation.d.ts.map +1 -0
  708. package/dist/utils/work-folder-validation.js +60 -0
  709. package/dist/utils/work-folder-validation.js.map +1 -0
  710. package/dist/utils/workspace-trust.d.ts +24 -0
  711. package/dist/utils/workspace-trust.d.ts.map +1 -0
  712. package/dist/utils/workspace-trust.js +35 -0
  713. package/dist/utils/workspace-trust.js.map +1 -0
  714. package/dist/workflows/auto-sprint.js +994 -91
  715. package/package.json +40 -9
  716. package/packages/apra-fleet-client/package.json +26 -0
  717. package/packages/apra-fleet-client/src/client/api.mjs +510 -0
  718. package/packages/apra-fleet-client/src/client/client.mjs +146 -0
  719. package/packages/apra-fleet-client/src/client/errors.mjs +71 -0
  720. package/packages/apra-fleet-client/src/client/factory.mjs +65 -0
  721. package/packages/apra-fleet-client/src/client/server-resolution.mjs +265 -0
  722. package/packages/apra-fleet-client/src/client/transport.mjs +327 -0
  723. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +303 -0
  724. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +101 -0
  725. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +151 -0
  726. package/packages/apra-fleet-se/apra-pm/agents/doer.md +259 -0
  727. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +188 -0
  728. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +332 -0
  729. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +216 -0
  730. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +201 -0
  731. package/packages/apra-fleet-se/apra-pm/agents/planner.md +322 -0
  732. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +234 -0
  733. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +275 -0
  734. package/packages/apra-fleet-se/apra-pm/agents/schemas/backlog-groomer-input.json +35 -0
  735. package/packages/apra-fleet-se/apra-pm/agents/schemas/backlog-groomer-output.json +164 -0
  736. package/packages/apra-fleet-se/apra-pm/agents/schemas/ci-watcher-input.json +26 -0
  737. package/packages/apra-fleet-se/apra-pm/agents/schemas/ci-watcher-output.json +18 -0
  738. package/packages/apra-fleet-se/apra-pm/agents/schemas/deployer-input.json +19 -0
  739. package/packages/apra-fleet-se/apra-pm/agents/schemas/deployer-output.json +17 -0
  740. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-input.json +25 -0
  741. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +82 -0
  742. package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-input.json +31 -0
  743. package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-output.json +75 -0
  744. package/packages/apra-fleet-se/apra-pm/agents/schemas/integ-test-runner-input.json +20 -0
  745. package/packages/apra-fleet-se/apra-pm/agents/schemas/integ-test-runner-output.json +61 -0
  746. package/packages/apra-fleet-se/apra-pm/agents/schemas/kb-reconciler-output.json +87 -0
  747. package/packages/apra-fleet-se/apra-pm/agents/schemas/plan-reviewer-input.json +15 -0
  748. package/packages/apra-fleet-se/apra-pm/agents/schemas/plan-reviewer-output.json +30 -0
  749. package/packages/apra-fleet-se/apra-pm/agents/schemas/planner-output.json +65 -0
  750. package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-input.json +15 -0
  751. package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-output.json +50 -0
  752. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-input.json +25 -0
  753. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +135 -0
  754. package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +402 -0
  755. package/packages/apra-fleet-se/apra-pm/skills/pm/beads.md +148 -0
  756. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +157 -0
  757. package/packages/apra-fleet-se/apra-pm/skills/pm/doer-reviewer-loop.md +300 -0
  758. package/packages/apra-fleet-se/apra-pm/skills/pm/fleet-addendum.md +127 -0
  759. package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +56 -0
  760. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-reconcile.md +132 -0
  761. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-review.md +109 -0
  762. package/packages/apra-fleet-se/apra-pm/skills/pm/simple-sprint.md +65 -0
  763. package/packages/apra-fleet-se/apra-pm/skills/pm/sprint.md +327 -0
  764. package/packages/apra-fleet-se/apra-pm/skills/pm/worktrees.md +92 -0
  765. package/packages/apra-fleet-se/apra-pm/version.json +3 -0
  766. package/packages/apra-fleet-se/bin/cli.mjs +864 -0
  767. package/packages/apra-fleet-se/bin/serve.mjs +395 -0
  768. package/packages/apra-fleet-se/fleet-sprint/conflict-ladder.mjs +178 -0
  769. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +940 -0
  770. package/packages/apra-fleet-se/fleet-sprint/dispatch-safety-guard.mjs +177 -0
  771. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +191 -0
  772. package/packages/apra-fleet-se/fleet-sprint/docs/coach-role-design.md +23 -0
  773. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-manual-recovery-verified.md +256 -0
  774. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +1482 -0
  775. package/packages/apra-fleet-se/fleet-sprint/docs/escalate-to-llm-design.md +908 -0
  776. package/packages/apra-fleet-se/fleet-sprint/docs/fleet-sprint-diagram.md +94 -0
  777. package/packages/apra-fleet-se/fleet-sprint/docs/shared-orchestrator-reservation-design.md +399 -0
  778. package/packages/apra-fleet-se/fleet-sprint/docs/stabilization-log.md +1125 -0
  779. package/packages/apra-fleet-se/fleet-sprint/dolt-literal-guard.mjs +72 -0
  780. package/packages/apra-fleet-se/fleet-sprint/dolt-settle.mjs +972 -0
  781. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +1310 -0
  782. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +616 -0
  783. package/packages/apra-fleet-se/fleet-sprint/full-db-fetch-guard.mjs +118 -0
  784. package/packages/apra-fleet-se/fleet-sprint/runner.js +10747 -0
  785. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +114 -0
  786. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +350 -0
  787. package/packages/apra-fleet-se/fleet-sprint/sprint-lock.mjs +140 -0
  788. package/packages/apra-fleet-se/fleet-sprint/sprint-progress.mjs +101 -0
  789. package/packages/apra-fleet-se/fleet-sprint/vcs-module.mjs +435 -0
  790. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/azure-devops.mjs +68 -0
  791. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +53 -0
  792. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/dolt.mjs +146 -0
  793. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/generic-git.mjs +176 -0
  794. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +235 -0
  795. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +218 -0
  796. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +942 -0
  797. package/packages/apra-fleet-se/package.json +29 -0
  798. package/packages/apra-fleet-se/workflow.json +1 -0
  799. package/packages/apra-fleet-workflow/package.json +30 -0
  800. package/packages/apra-fleet-workflow/src/viewer/command-output-cap.mjs +112 -0
  801. package/packages/apra-fleet-workflow/src/viewer/debounced-writer.mjs +153 -0
  802. package/packages/apra-fleet-workflow/src/viewer/html-utils.mjs +31 -0
  803. package/packages/apra-fleet-workflow/src/viewer/index.mjs +1439 -0
  804. package/packages/apra-fleet-workflow/src/viewer/lean-state.mjs +237 -0
  805. package/packages/apra-fleet-workflow/src/viewer/run-state-paths.mjs +130 -0
  806. package/packages/apra-fleet-workflow/src/viewer/run-title.mjs +60 -0
  807. package/packages/apra-fleet-workflow/src/viewer/sprint-state-paths.mjs +29 -0
  808. package/packages/apra-fleet-workflow/src/workflow/engine.mjs +200 -0
  809. package/packages/apra-fleet-workflow/src/workflow/errors.mjs +146 -0
  810. package/packages/apra-fleet-workflow/src/workflow/index.mjs +1727 -0
  811. package/packages/apra-fleet-workflow/src/workflow/journal.mjs +291 -0
  812. package/packages/apra-fleet-workflow/src/workflow/pricing.mjs +99 -0
  813. package/packages/apra-fleet-workflow/src/workflow/vetting.mjs +111 -0
  814. package/scripts/agy-transcript-reader.js +1 -0
  815. package/scripts/fleet-statusline.sh +17 -13
  816. package/skills/fleet/SKILL.md +37 -2
  817. package/skills/fleet/beads.md +14 -7
  818. package/skills/fleet/knowledge-agent.md +66 -0
  819. package/skills/fleet/permissions.md +76 -2
  820. package/skills/fleet/profiles/base-dev.json +11 -1
  821. package/skills/fleet/profiles/base-reviewer.json +9 -1
  822. package/skills/fleet/profiles/node.json +2 -2
  823. package/skills/fleet/profiles/tag-kb-reconciler.json +20 -0
  824. package/version.json +1 -1
  825. package/scripts/agy-settings-merge.js +0 -27
  826. /package/{dist → packages/apra-fleet-se/apra-pm}/agents/_shared/GRAPH-SEMANTICS.md +0 -0
@@ -0,0 +1,1727 @@
1
+ import Ajv from 'ajv';
2
+ import { EventEmitter } from 'events';
3
+ import { randomUUID } from 'crypto';
4
+ import { AsyncLocalStorage } from 'async_hooks';
5
+ import { calculateCost } from './pricing.mjs';
6
+ import { WorkflowError, MemberNotFoundError, AgentOutputError, AgentDispatchError, CommandError, FleetTransportError, BudgetExceededError, CancelledError } from './errors.mjs';
7
+ import { hashText, computeActivityKey } from './journal.mjs';
8
+
9
+ export { WorkflowError, MemberNotFoundError, AgentOutputError, AgentDispatchError, CommandError, FleetTransportError, BudgetExceededError, CancelledError } from './errors.mjs';
10
+
11
+ const ajv = new Ajv({ strict: false });
12
+
13
+ // --- Per-run execution context (apra-fleet-unw.9, F11) --------------------
14
+ //
15
+ // Before this change, `FleetWorkflow` kept its "current run" state --
16
+ // `args`, `currentPhase`, `currentGroup`, `budget` -- as plain mutable
17
+ // instance fields. `WorkflowEngine.executeFile()` mutated `this.wf.args` on
18
+ // every call, and `phase()`/`group()` mutated a single shared
19
+ // `currentPhase`/`currentGroup`. That's fine for exactly one execution at a
20
+ // time, but breaks as soon as:
21
+ // (a) two concurrent `executeFile()` calls run on the same `FleetWorkflow`
22
+ // instance -- their `args` and phase attribution stomp on each other, or
23
+ // (b) a single run's `parallel()` branches each call `phase()` with a
24
+ // different value -- every branch (and every activity emitted from any
25
+ // branch, including ones dispatched before the racing `phase()` call
26
+ // resolves) ends up labeled with whichever branch's `phase()` call
27
+ // happened to run last, not its own.
28
+ //
29
+ // `runStorage` (an AsyncLocalStorage) holds a small per-run store --
30
+ // `{ runId, args, phase, group, budget }` -- that is threaded automatically
31
+ // through the async call graph of a single `executeFile()` invocation:
32
+ // - `WorkflowEngine.executeFile()` creates a fresh store via
33
+ // `FleetWorkflow.runWithContext(args, entryFn)` and runs the whole script
34
+ // inside `runStorage.run(store, ...)`. Every `agent()`/`command()`/
35
+ // `phase()`/etc. call made anywhere inside that script -- including
36
+ // across `await` boundaries -- automatically sees that run's store via
37
+ // `runStorage.getStore()`, with no explicit threading required in the
38
+ // workflow script itself.
39
+ // - `parallel()` forks a *shallow copy* of the current store for each
40
+ // branch before invoking its processor. `phase`/`group` are copied by
41
+ // value, so a `phase()` call inside one branch only mutates that
42
+ // branch's own copy and can never leak into a sibling branch or the
43
+ // parent. `args`/`budget` are copied by reference, so budget spend is
44
+ // still aggregated for the whole run and `args` stays consistent.
45
+ // - Every activity/log/state event still carries the store's `runId`, so
46
+ // even though the shared `EventEmitter` on `FleetWorkflow` fans events
47
+ // out to a single global listener (the dashboard viewer subscribes
48
+ // once), events from concurrent runs remain distinguishable.
49
+ //
50
+ // Direct, non-`executeFile()` usage (e.g. calling `wf.agent()`/`wf.phase()`
51
+ // straight off a `FleetWorkflow` instance, as several unit tests do) is
52
+ // preserved unchanged: when there is no active `runStorage` store (i.e.
53
+ // `runStorage.getStore()` returns `undefined`), every primitive falls back
54
+ // to the legacy instance-level fields (`this.args`, `this.currentPhase`,
55
+ // `this.currentGroup`, `this.budget`), exactly as before this change.
56
+ const runStorage = new AsyncLocalStorage();
57
+
58
+ // --- Structured-output extraction (apra-fleet-unw.8) ---------------------
59
+ //
60
+ // The old extraction path used a single greedy regex,
61
+ // /\{[\s\S]*\}|\[[\s\S]*\]/, which grabs from the FIRST `{`/`[` to the LAST
62
+ // `}`/`]` in the whole reply. That fails as soon as a reply contains more
63
+ // than one JSON block, or trailing prose that happens to contain a brace --
64
+ // the regex swallows everything in between as one "candidate" and JSON.parse
65
+ // then throws on it. The functions below replace that with real bracket
66
+ // matching plus schema-directed candidate selection: prefer fenced ```json
67
+ // blocks; otherwise scan the raw text for every balanced top-level
68
+ // {...}/[...] span (tracking string state so braces inside string literals
69
+ // don't confuse the matcher); validate each candidate against the schema in
70
+ // the order found and return the first one that both parses and validates.
71
+ //
72
+ // NOTE (descoped, see agent() below for the full note): this is a
73
+ // client-side mitigation. The more robust fix -- enforcing the schema at the
74
+ // member/harness tool-call layer -- requires fleet-server changes.
75
+
76
+ const FENCED_JSON_RE = /```(?:json)?\s*\n([\s\S]*?)```/gi;
77
+
78
+ /**
79
+ * Extracts the contents of every fenced ```json (or bare ```) code block in
80
+ * `text`, in the order they appear.
81
+ * @param {string} text
82
+ * @returns {string[]}
83
+ */
84
+ function extractFencedJsonBlocks(text) {
85
+ const blocks = [];
86
+ let match;
87
+ FENCED_JSON_RE.lastIndex = 0;
88
+ while ((match = FENCED_JSON_RE.exec(text)) !== null) {
89
+ blocks.push(match[1].trim());
90
+ }
91
+ return blocks;
92
+ }
93
+
94
+ /**
95
+ * Given `text[start]` is `{` or `[`, scans forward tracking bracket nesting
96
+ * and JSON string state (so braces/brackets inside string literals are
97
+ * ignored) to find the index of the matching closing bracket. Returns -1 if
98
+ * the span never closes or the brackets are mismatched.
99
+ * @param {string} text
100
+ * @param {number} start
101
+ * @returns {number}
102
+ */
103
+ function findBalancedEnd(text, start) {
104
+ const closerFor = { '{': '}', '[': ']' };
105
+ const stack = [closerFor[text[start]]];
106
+ let inString = false;
107
+ let escaped = false;
108
+
109
+ for (let i = start + 1; i < text.length; i++) {
110
+ const ch = text[i];
111
+ if (inString) {
112
+ if (escaped) {
113
+ escaped = false;
114
+ } else if (ch === '\\') {
115
+ escaped = true;
116
+ } else if (ch === '"') {
117
+ inString = false;
118
+ }
119
+ continue;
120
+ }
121
+ if (ch === '"') {
122
+ inString = true;
123
+ continue;
124
+ }
125
+ if (ch === '{' || ch === '[') {
126
+ stack.push(closerFor[ch]);
127
+ continue;
128
+ }
129
+ if (ch === '}' || ch === ']') {
130
+ if (stack.length === 0) return -1;
131
+ const expected = stack.pop();
132
+ if (expected !== ch) return -1;
133
+ if (stack.length === 0) return i;
134
+ }
135
+ }
136
+ return -1;
137
+ }
138
+
139
+ /**
140
+ * Scans `text` for every balanced top-level JSON object/array span, using
141
+ * real bracket matching (not a greedy regex), in the order they appear.
142
+ * @param {string} text
143
+ * @returns {string[]}
144
+ */
145
+ function extractBalancedJsonCandidates(text) {
146
+ const candidates = [];
147
+ let i = 0;
148
+ while (i < text.length) {
149
+ const ch = text[i];
150
+ if (ch === '{' || ch === '[') {
151
+ const end = findBalancedEnd(text, i);
152
+ if (end !== -1) {
153
+ candidates.push(text.slice(i, end + 1));
154
+ i = end + 1;
155
+ continue;
156
+ }
157
+ }
158
+ i++;
159
+ }
160
+ return candidates;
161
+ }
162
+
163
+ /**
164
+ * Attempts to find a schema-valid JSON candidate in `text`. Prefers fenced
165
+ * ```json blocks; falls back to a balanced top-level bracket scan of the raw
166
+ * text. Every candidate found is parsed and validated in order; the first
167
+ * one that both parses and validates against `compiledSchema` wins. Returns
168
+ * `{ ok: true, parsed, raw }` on success, or `{ ok: false, attempts }` where
169
+ * `attempts` records why every candidate was rejected (parse error or ajv
170
+ * validation errors) for repair-prompt / error-reporting purposes.
171
+ * @param {string} text
172
+ * @param {import('ajv').ValidateFunction} compiledSchema
173
+ */
174
+ function extractStructuredOutput(text, compiledSchema) {
175
+ const fenced = extractFencedJsonBlocks(text);
176
+
177
+ const attempts = [];
178
+ const tryCandidate = (raw) => {
179
+ let parsed;
180
+ try {
181
+ parsed = JSON.parse(raw);
182
+ } catch (parseError) {
183
+ attempts.push({ raw, parseError });
184
+ return null;
185
+ }
186
+ if (compiledSchema(parsed)) {
187
+ return { ok: true, parsed, raw };
188
+ }
189
+ attempts.push({ raw, parsed, validationErrors: compiledSchema.errors ? [...compiledSchema.errors] : [] });
190
+ return null;
191
+ };
192
+
193
+ // Prefer fenced ```json blocks: try every fenced candidate first so the
194
+ // common case (a well-behaved reply whose only JSON lives in a fenced
195
+ // block) keeps picking the fenced block exactly as before.
196
+ for (const raw of fenced) {
197
+ const result = tryCandidate(raw);
198
+ if (result) return result;
199
+ }
200
+
201
+ // Fall through to a balanced-bracket scan when no fenced candidate
202
+ // parsed and validated -- either because there were no fenced blocks at
203
+ // all, or because every fenced block was something else entirely (e.g.
204
+ // a shell command the reply quotes for illustration) and the real
205
+ // schema-satisfying JSON lives outside the fences. Scan the text with
206
+ // the fenced spans blanked out so we don't re-try content already
207
+ // rejected above, and so a stray brace inside a non-JSON fenced block
208
+ // can't be mistaken for a balanced candidate.
209
+ const unfencedText = text.replace(FENCED_JSON_RE, (match) => ' '.repeat(match.length));
210
+ const balanced = extractBalancedJsonCandidates(unfencedText);
211
+ for (const raw of balanced) {
212
+ const result = tryCandidate(raw);
213
+ if (result) return result;
214
+ }
215
+
216
+ // Last-resort fallback: no bracketed candidate was found at all (e.g. a
217
+ // reply that is itself plain JSON with stray leading/trailing
218
+ // whitespace but somehow no `{`/`[` was detected as an opener -- should
219
+ // be rare given the scan above, but keeps behavior at least as good as
220
+ // the old single-shot JSON.parse(text) path).
221
+ if (fenced.length === 0 && balanced.length === 0) {
222
+ const result = tryCandidate(text.trim());
223
+ if (result) return result;
224
+ }
225
+
226
+ return { ok: false, attempts };
227
+ }
228
+
229
+ /**
230
+ * Summarizes why every extraction attempt failed, for both the repair-prompt
231
+ * re-ask and the final AgentOutputError message.
232
+ * @param {Array<{raw: string, parseError?: Error, validationErrors?: object[]}>} attempts
233
+ */
234
+ function summarizeExtractionAttempts(attempts) {
235
+ if (attempts.length === 0) {
236
+ return 'No JSON object or array was found in the response.';
237
+ }
238
+ return attempts
239
+ .map((a, idx) => {
240
+ if (a.parseError) {
241
+ return `Candidate ${idx + 1}: JSON parse error: ${a.parseError.message}`;
242
+ }
243
+ return `Candidate ${idx + 1}: schema validation failed: ${ajv.errorsText(a.validationErrors)}`;
244
+ })
245
+ .join('\n');
246
+ }
247
+
248
+ /**
249
+ * Builds the lean repair re-ask prompt sent to the SAME member after an
250
+ * invalid structured-output attempt. apra-fleet-02s.3: repair re-asks now
251
+ * force `resume: true` (see the payload construction below), so the member's
252
+ * session already has the original prompt/schema and its own invalid
253
+ * output in context -- re-embedding all of that here would just re-spend
254
+ * tokens re-sending what the resumed session already has. Only the
255
+ * validation errors plus a short corrected-JSON instruction are needed.
256
+ * @param {string} errorsText
257
+ */
258
+ function buildRepairPrompt(errorsText) {
259
+ return `Your previous response could not be used.\n\n` +
260
+ `Validation errors:\n${errorsText}\n\n` +
261
+ `Please respond again with corrected JSON only, strictly conforming to the schema from your previous instructions. ` +
262
+ `Do not include any commentary, explanation, or text outside the JSON.`;
263
+ }
264
+
265
+ /**
266
+ * @typedef {Object} AgentOptions
267
+ * @property {string} [label] - UI label for this run
268
+ * @property {string} [phase] - Workflow phase grouping
269
+ * @property {object} [schema] - JSON Schema for structured output. The dispatch-time
270
+ * `schema` passed here is the one actually ajv-validated against the member's
271
+ * response (see the compile/append/validate logic in agent() below) -- it is
272
+ * therefore authoritative at the member, per each persona's precedence clause
273
+ * ("if your dispatch prompt includes a JSON schema instruction, that schema is
274
+ * authoritative"). When `agentType` names a role that publishes its own output
275
+ * contract (apra-pm's role-owned schema design), callers MUST source this value
276
+ * from that role's published schema via their application-layer adapter (e.g.
277
+ * `contracts.mjs`'s `SCHEMAS.<name>` for auto-sprint) rather than authoring an
278
+ * independent, parallel definition here. Two independently-authored schemas for
279
+ * the same role is the double-specification hazard this single-source rule
280
+ * exists to prevent; the workflow layer itself stays generic and does not (and
281
+ * cannot) resolve or detect such drift -- see
282
+ * `docs/agent-schema-layering-proposal.md` (section 4, recommendation item 4;
283
+ * section 5.3) for the full rationale, and `docs/structured-errors-proposal.md`
284
+ * for the sibling design-doc pattern this cross-reference follows.
285
+ * @property {string} [model] - Overrides model for this call
286
+ * @property {string} [member_name] - Apra-fleet member to dispatch to
287
+ * @property {string} [member_id] - Specific member UUID
288
+ * @property {Record<string, string>} [substitutions] - Template substitutions for prompt
289
+ * @property {number} [timeout_s] - Execution timeout (server-side INACTIVITY timeout:
290
+ * resets on every output chunk from the member CLI)
291
+ * @property {number} [max_total_s] - Server-side HARD wall-clock ceiling for the dispatch,
292
+ * independent of activity. Also drives the derived client-side request timeout:
293
+ * deriveTimeoutMs (packages/apra-fleet-client/src/client/api.mjs) prefers max_total_s
294
+ * over timeout_s, so omitting it here caps the whole dispatch at timeout_s+grace
295
+ * client-side even when the caller intended a much larger total budget. Observed live
296
+ * (stabilization log Issue 10): this option was silently DROPPED from the payload, so a
297
+ * legitimate 15+ minute reviewer dispatch was client-timed-out at 930s while the remote
298
+ * session kept running.
299
+ * @property {number} [max_turns] - Max turns for conversational tools
300
+ * @property {'low'|'medium'|'high'|'xhigh'|'max'} [effort] - Effort parameter for fleet routing
301
+ * @property {string} [agentType] - Agent persona to activate on the member
302
+ * @property {boolean|string} [resume] - Resume the previous session on the member if one exists.
303
+ * A boolean `true` resumes the member's stored last session; a non-empty STRING resumes
304
+ * EXACTLY that session id (apra-fleet-eft.78.1 widened execute_prompt's resume input to
305
+ * boolean|session-id and made an explicit-id resume that cannot be resumed a TERMINAL
306
+ * error). The value is passed straight through to executePrompt's payload.resume.
307
+ * NOTE: the underlying ApraFleet client (packages/apra-fleet-client/src/client/api.mjs)
308
+ * defaults `resume` to `true` when omitted. The WORKFLOW layer overrides that: agent()
309
+ * explicitly sends `resume: false` unless the caller sets this option, so that
310
+ * workflow-authored prompts are self-contained by default and don't silently inherit
311
+ * state from a prior session. (F10 / apra-fleet-unw.3)
312
+ * @property {(sessionId: string, meta: { member?: string, agent?: string, usage?: object }) => void} [onSessionId]
313
+ * Optional best-effort callback invoked with the resumable session id that execute_prompt
314
+ * promoted into structuredContent.sessionId (apra-fleet-eft.78.1), on a non-error dispatch
315
+ * that actually produced one. Lets a caller (the auto-sprint engine's per-role round-resume
316
+ * registry, apra-fleet-eft.78.3) record each dispatch's session id per (role, cycle) so it
317
+ * can resume the same role's session across rounds via `resume: <id>`. Never fires when the
318
+ * provider returns no session id (a capability signal, not a provider-name check); a throwing
319
+ * callback is caught and never breaks the dispatch. (apra-fleet-eft.78.3)
320
+ * @property {number} [timeoutMs] - Client-side McpClient.request() timeout override (ms),
321
+ * passed through to ApraFleet.executePrompt. Not sent to the server. When omitted, a
322
+ * default is derived from timeout_s/max_total_s (see deriveTimeoutMs in
323
+ * packages/apra-fleet-client/src/client/api.mjs). (apra-fleet-unw.5)
324
+ * @property {AbortSignal} [signal] - Optional AbortSignal, passed through to
325
+ * ApraFleet.executePrompt / McpClient.request. Aborting rejects the pending client-side
326
+ * wait for a response; it cannot cancel a job already accepted by the remote fleet-server.
327
+ * Groundwork for the cooperative-stop work in apra-fleet-unw.10 -- no /stop UI wiring here.
328
+ * (apra-fleet-unw.5)
329
+ * @property {number} [schemaRetries] - Only meaningful when `schema` is set. Bounded number
330
+ * of repair re-asks to the SAME member after a parse/validation failure, before giving up
331
+ * and throwing AgentOutputError. Defaults to 2 (so up to 3 total dispatches: 1 original +
332
+ * 2 repairs). Each repair re-ask FORCES `resume: true` (apra-fleet-02s.3) so the member's
333
+ * session already has the original prompt/schema and its own invalid output in context --
334
+ * the re-ask itself is a lean reminder containing only the ajv validation/parse errors
335
+ * plus a corrected-JSON instruction, not a re-embedding of the full original prompt/output.
336
+ * Each attempt emits its own activity:start/activity:end pair and is cost-accounted
337
+ * individually. (apra-fleet-unw.8)
338
+ * @property {number} [busyWaitMs] - How long (ms) to keep waiting-and-retrying when the
339
+ * fleet server reports the member is busy ("execute_prompt is already running") before
340
+ * surfacing the busy AgentDispatchError. Defaults to 10 minutes. A busy member is
341
+ * almost always TRANSIENT-but-slow: observed live, a client-side transport drop
342
+ * orphans the in-flight remote session, which keeps running (and holding the member's
343
+ * one-dispatch-at-a-time lock) for however long its work takes -- minutes, not
344
+ * seconds -- then completes and releases the lock. A blind fixed backoff loses that
345
+ * race; polling until the lock actually frees wins it. Set 0 to disable (immediate
346
+ * throw, the pre-existing behavior). Each poll is a cheap re-dispatch attempt (the
347
+ * server rejects busy calls in milliseconds with no side effects).
348
+ * @property {number} [busyPollMs] - Poll interval (ms) for the busy-wait above. Default 15s.
349
+ * @property {string} [sprint_id] - Opaque sprint identity to pass straight through to
350
+ * execute_prompt's server-side reservation check (apra-fleet-eft.29.1). Callers that
351
+ * also reserve members via member_reservation (e.g. auto-sprint's
352
+ * createMemberReservationClient) should pass the SAME token here so a dispatch from
353
+ * the owning sprint is recognized as such even when the fleet server this call
354
+ * dispatches through is a pre-existing shared singleton with no per-sprint
355
+ * APRA_FLEET_SPRINT_ID of its own. Omit to preserve prior (env-var-only) behavior.
356
+ */
357
+
358
+ /**
359
+ * @typedef {Object} CommandOptions
360
+ * @property {string} [label] - UI label for this run
361
+ * @property {string} [phase] - Workflow phase grouping
362
+ * @property {string} [member_name] - Apra-fleet member to dispatch to
363
+ * @property {string} [member_id] - Specific member UUID
364
+ * @property {Record<string, string>} [substitutions] - Template substitutions for command
365
+ * @property {number} [timeout_s] - Execution timeout
366
+ * @property {boolean} [long_running] - Run as background task
367
+ * @property {number} [timeoutMs] - Client-side McpClient.request() timeout override (ms),
368
+ * passed through to ApraFleet.executeCommand. Not sent to the server. See AgentOptions
369
+ * .timeoutMs above for details. (apra-fleet-unw.5)
370
+ * @property {AbortSignal} [signal] - Optional AbortSignal, passed through to
371
+ * ApraFleet.executeCommand / McpClient.request. See AgentOptions.signal above for details.
372
+ * (apra-fleet-unw.5)
373
+ * @property {boolean} [failSoft] - When true, command() never throws for a
374
+ * command-level failure (CommandError / MemberNotFoundError /
375
+ * FleetTransportError); it instead resolves to
376
+ * `{ ok: boolean, output: string, error: string|null }`. A success also
377
+ * resolves to that shape (`{ ok: true, output: <text>, error: null }`)
378
+ * instead of the bare string, so callers don't have to branch on the
379
+ * return type. `CancelledError` (cooperative `requestStop()`) is never
380
+ * soft-caught -- it always throws, regardless of this option.
381
+ * (apra-fleet-unw.17)
382
+ */
383
+
384
+ export class FleetWorkflow extends EventEmitter {
385
+ /**
386
+ * @param {import('../fleet-client/api.mjs').ApraFleet} fleetApi
387
+ * @param {any} args
388
+ */
389
+ constructor(fleetApi, args = {}, logPrefix = '') {
390
+ super();
391
+ this.fleetApi = fleetApi;
392
+ this.args = args;
393
+ // (apra-fleet-20i.1.1) Optional per-run scenario label prepended to
394
+ // the [Workflow Log]/[Dispatch]/[Command] console.log lines below.
395
+ // Defaults to '' so existing callers get byte-identical output.
396
+ this.logPrefix = logPrefix;
397
+ this.currentPhase = null;
398
+ this.budget = {
399
+ total: null,
400
+ _spent: 0,
401
+ // apra-fleet-dv5.6: counts of dispatches priced via real
402
+ // per-member rates (get_member_model_pricing) vs. the
403
+ // tier-band/concrete-model fallback (pricing.mjs) -- see
404
+ // pricingSummary() and buildCostAnalysis() in runner.js.
405
+ _pricedReal: 0,
406
+ _pricedFallback: 0,
407
+ spent: () => this.budget._spent,
408
+ remaining: () => this.budget.total === null ? Infinity : (this.budget.total - this.budget._spent),
409
+ pricingSummary: () => ({ real: this.budget._pricedReal, fallback: this.budget._pricedFallback })
410
+ };
411
+ // apra-fleet-dv5.6: member_id/member_name -> MemberModelPricing (or
412
+ // `null` when real pricing is unavailable for that member), cached
413
+ // for the lifetime of a run (fresh per runWithContext() call, see
414
+ // `store.memberPricingCache` below) -- tier->model resolution is
415
+ // static for a run's duration, so this is a plain cache, not a TTL.
416
+ this._memberPricingCache = new Map();
417
+ // member_id/member_name we've already logged a "pricing unavailable"
418
+ // warning for (apra-fleet-dv5.6 acceptance criteria: log ONCE per
419
+ // member, not once per dispatch).
420
+ this._warnedPricingMembers = new Set();
421
+ // (apra-fleet-unw.10) runId -> AbortController for every currently
422
+ // active runWithContext() run. requestStop() aborts every entry in
423
+ // this map; agent()/command() default to the current run's
424
+ // controller.signal (via _currentSignal()) when the caller doesn't
425
+ // pass its own opts.signal. See runWithContext()/requestStop() below.
426
+ this._activeControllers = new Map();
427
+ }
428
+
429
+ // Returns the active per-run store (see runStorage above), or
430
+ // `undefined` when called outside of `WorkflowEngine.executeFile()` /
431
+ // `runWithContext()` -- e.g. direct `wf.method()` calls in unit tests.
432
+ _store() {
433
+ return runStorage.getStore();
434
+ }
435
+
436
+ // Effective phase: the current run's store.phase if one is active,
437
+ // otherwise the legacy instance-level `this.currentPhase`.
438
+ _currentPhase() {
439
+ const store = this._store();
440
+ return store ? store.phase : this.currentPhase;
441
+ }
442
+
443
+ _currentGroup() {
444
+ const store = this._store();
445
+ return store ? store.group : this.currentGroup;
446
+ }
447
+
448
+ _currentArgs() {
449
+ const store = this._store();
450
+ return store ? store.args : this.args;
451
+ }
452
+
453
+ _currentBudget() {
454
+ const store = this._store();
455
+ return store ? store.budget : this.budget;
456
+ }
457
+
458
+ // apra-fleet-dv5.6: same store-or-legacy-field pattern as the other
459
+ // _current*() accessors -- a fresh Map per run (see runWithContext()),
460
+ // or the legacy instance-level field for direct non-executeFile() usage.
461
+ _currentMemberPricingCache() {
462
+ const store = this._store();
463
+ return store ? store.memberPricingCache : this._memberPricingCache;
464
+ }
465
+
466
+ _currentRunId() {
467
+ const store = this._store();
468
+ return store ? store.runId : null;
469
+ }
470
+
471
+ // The active run's cooperative-cancellation AbortSignal (apra-fleet-
472
+ // unw.10), or `undefined` outside of a runWithContext() run / when the
473
+ // run's controller has no signal for some reason. agent()/command()
474
+ // fall back to this when the caller doesn't pass its own opts.signal.
475
+ _currentSignal() {
476
+ const store = this._store();
477
+ return store ? store.signal : undefined;
478
+ }
479
+
480
+ /**
481
+ * Cooperatively requests cancellation of every currently active run
482
+ * (every `runWithContext()` invocation -- i.e. every in-flight
483
+ * `WorkflowEngine.executeFile()` call -- on this `FleetWorkflow`
484
+ * instance). Aborts each run's `AbortController`, which rejects any
485
+ * in-flight `agent()`/`command()` dispatch that is using that run's
486
+ * signal (either implicitly, via `_currentSignal()`, or because the
487
+ * script never overrode `opts.signal`) with a client-side `AbortError`;
488
+ * `agent()`/`command()` re-wrap that as a typed `CancelledError` (see
489
+ * errors.mjs) so the run unwinds as a cancellation failure rather than a
490
+ * generic transport error.
491
+ *
492
+ * This is the mechanism the dashboard viewer's `/stop` endpoint uses
493
+ * (packages/apra-fleet-workflow/src/viewer/index.mjs) instead of the old
494
+ * `process.exit(1)` -- no state flush, mid-dispatch agents orphaned.
495
+ *
496
+ * NOTE: local/client-side cancellation only. A remote fleet member that
497
+ * already accepted a job may keep running to completion even after this
498
+ * run unwinds -- true server-side cancellation would require changes to
499
+ * the external apra-fleet MCP server and is out of scope here.
500
+ *
501
+ * @param {string} [reason]
502
+ */
503
+ requestStop(reason = 'Workflow run cancelled via requestStop()') {
504
+ for (const controller of this._activeControllers.values()) {
505
+ controller.abort(new CancelledError(`[Workflow Error] ${reason}`));
506
+ }
507
+ }
508
+
509
+ log(msg) {
510
+ console.log(`${this.logPrefix}[Workflow Log] ${msg}`);
511
+ this.emit('log', { phase: this._currentPhase(), msg, runId: this._currentRunId() });
512
+ }
513
+
514
+ group(title) {
515
+ const store = this._store();
516
+ if (store) {
517
+ store.group = title;
518
+ } else {
519
+ this.currentGroup = title;
520
+ }
521
+ console.log(`\n=== Group: ${title} ===`);
522
+ this.emit('group:start', { title, runId: this._currentRunId() });
523
+ }
524
+
525
+ endGroup() {
526
+ this.emit('group:end', { title: this._currentGroup(), runId: this._currentRunId() });
527
+ const store = this._store();
528
+ if (store) {
529
+ store.group = null;
530
+ } else {
531
+ this.currentGroup = null;
532
+ }
533
+ }
534
+
535
+ // NOTE: `title` set inside a `parallel()` branch only mutates that
536
+ // branch's own forked store copy (see `parallel()` below and the
537
+ // runStorage comment above this class) -- it never leaks to sibling
538
+ // branches or the parent run.
539
+ phase(title) {
540
+ const store = this._store();
541
+ if (store) {
542
+ store.phase = title;
543
+ } else {
544
+ this.currentPhase = title;
545
+ }
546
+ console.log(`--- Phase: ${title} ---`);
547
+ // Event payload deliberately kept as the bare `title` string (not an
548
+ // object) -- the dashboard viewer subscribes to this event and
549
+ // single-run rendering must stay byte-identical (apra-fleet-unw.9
550
+ // acceptance criteria #3). Concurrent-run disambiguation is carried
551
+ // on activity/log/state events instead, which already have an
552
+ // object payload.
553
+ this.emit('phase', title);
554
+ }
555
+
556
+
557
+ publishState(namespace, data) {
558
+ this.emit('state', { namespace, data, phase: this._currentPhase(), runId: this._currentRunId() });
559
+ }
560
+
561
+ // apra-fleet-dv5.6: fetches (and caches for the run) a member's real
562
+ // per-tier pricing via the get_member_model_pricing MCP tool. Never
563
+ // throws -- any failure (older fleet server without the tool,
564
+ // network/hub-relay error, member not found) degrades to `null`
565
+ // (meaning "use the tier-band/concrete-model fallback for this
566
+ // member"), logged ONCE per member rather than once per dispatch.
567
+ async _getMemberPricing(memberKey, opts) {
568
+ const cache = this._currentMemberPricingCache();
569
+ if (cache.has(memberKey)) return cache.get(memberKey);
570
+
571
+ const warnUnavailable = (reason) => {
572
+ if (!this._warnedPricingMembers.has(memberKey)) {
573
+ this._warnedPricingMembers.add(memberKey);
574
+ console.warn(`[Workflow] Real per-member pricing unavailable for member "${memberKey}" (${reason}) -- falling back to tier-band cost estimates for this member's dispatches.`);
575
+ }
576
+ };
577
+
578
+ try {
579
+ const res = await this.fleetApi.getMemberModelPricing({ member_id: opts.member_id, member_name: opts.member_name });
580
+ const text = res && res.content && res.content[0] ? res.content[0].text : null;
581
+ const parsed = text ? JSON.parse(text) : null;
582
+ if (!parsed || parsed.error || !parsed.pricing) {
583
+ warnUnavailable(parsed && parsed.error ? parsed.error : 'no pricing data returned');
584
+ cache.set(memberKey, null);
585
+ return null;
586
+ }
587
+ cache.set(memberKey, parsed.pricing);
588
+ return parsed.pricing;
589
+ } catch (err) {
590
+ warnUnavailable(err && err.message ? err.message : String(err));
591
+ cache.set(memberKey, null);
592
+ return null;
593
+ }
594
+ }
595
+
596
+ // apra-fleet-dv5.6: resolves the cost of one dispatch, preferring real
597
+ // per-member pricing over the pricing.mjs tier-band/concrete-model
598
+ // fallback whenever `opts.model` is a tier keyword AND real pricing is
599
+ // available for that member and tier. Falls back to calculateCost()
600
+ // (unchanged behavior) for: a literal (non-tier-keyword) model id, a
601
+ // dispatch with no member_id/member_name (shouldn't happen -- agent()
602
+ // requires one), or when real pricing is unavailable/doesn't cover this
603
+ // tier. Increments budget._pricedReal/_pricedFallback so
604
+ // buildCostAnalysis() (runner.js) can honestly report which source
605
+ // priced a run's total.
606
+ async _resolveCost(opts, usage, budget) {
607
+ const tier = opts.model;
608
+ if (tier === 'cheap' || tier === 'standard' || tier === 'premium') {
609
+ const memberKey = opts.member_id || opts.member_name;
610
+ if (memberKey) {
611
+ const realPricing = await this._getMemberPricing(memberKey, opts);
612
+ const entry = realPricing && realPricing[tier];
613
+ if (entry && typeof entry.promptPrice === 'number' && typeof entry.completionPrice === 'number') {
614
+ const pTokens = usage.input_tokens || 0;
615
+ const cTokens = usage.output_tokens || 0;
616
+ const cost = (pTokens / 1_000_000) * entry.promptPrice + (cTokens / 1_000_000) * entry.completionPrice;
617
+ budget._pricedReal++;
618
+ return cost;
619
+ }
620
+ }
621
+ }
622
+ const cost = calculateCost(opts.model, usage);
623
+ if (cost !== null) budget._pricedFallback++;
624
+ return cost;
625
+ }
626
+
627
+ /**
628
+ * @param {string} prompt
629
+ * @param {AgentOptions} [opts]
630
+ */
631
+ async agent(prompt, opts = {}) {
632
+ if (!opts.member_name && !opts.member_id) {
633
+ throw new Error(`[Workflow Error] agent() requires either member_name or member_id`);
634
+ }
635
+
636
+ const effectivePhase = opts.phase || this._currentPhase();
637
+ const runId = this._currentRunId();
638
+ if (effectivePhase) {
639
+ console.log(`${this.logPrefix}[Dispatch] phase: ${effectivePhase} | member: ${opts.member_name || opts.member_id} | label: ${opts.label || 'none'}`);
640
+ }
641
+
642
+ let compiledSchema = null;
643
+ if (opts.schema) {
644
+ try {
645
+ compiledSchema = ajv.compile(opts.schema);
646
+ } catch (err) {
647
+ throw new Error(`[Workflow Error] Invalid JSON Schema provided to agent(): ${err.message}`);
648
+ }
649
+ }
650
+
651
+ const initialPrompt = opts.schema
652
+ ? `${prompt}\n\nOnly provide your response strictly as per this JSON schema:\n${JSON.stringify(opts.schema, null, 2)}`
653
+ : prompt;
654
+
655
+ // Bounded schema-repair loop (apra-fleet-unw.8, F5). Non-schema
656
+ // calls always run exactly one iteration (maxRepairs = 0). For
657
+ // schema calls, a parse/validation failure re-dispatches to the SAME
658
+ // member with a self-contained repair prompt (see buildRepairPrompt
659
+ // above) instead of hard-throwing on the first bad reply -- one
660
+ // malformed JSON reply used to kill a whole multi-cycle sprint.
661
+ //
662
+ // DESCOPED: the more robust fix is enforcing the schema at the
663
+ // member/harness tool-call layer (e.g. a Claude-CLI-style structured
664
+ // tool call) so the member literally cannot emit non-conforming
665
+ // output. That requires fleet-server changes and is out of scope
666
+ // here; this client-side repair loop is the best available
667
+ // mitigation until that lands.
668
+ const maxRepairs = opts.schema ? (opts.schemaRetries ?? 2) : 0;
669
+
670
+ let currentPrompt = initialPrompt;
671
+ let lastActivityMeta = null;
672
+ const budget = this._currentBudget();
673
+
674
+ // (apra-fleet-unw.11, F6) Journal replay. `replayKey` is computed
675
+ // ONCE per logical agent() call (not per schema-repair attempt) from
676
+ // this run's monotonic activity sequence counter + call type +
677
+ // member + a hash of the fully-resolved initial prompt (including
678
+ // any appended schema instructions), so it's stable across repair
679
+ // attempts and deterministic across an uninterrupted-vs-resumed run
680
+ // of the SAME script with the SAME args. `store.activitySeq` is only
681
+ // non-null when the caller opted into journaling at all (see
682
+ // runWithContext()); a normal call with no journal/resumeJournal
683
+ // option never enters this block and never attaches
684
+ // sequence/replayKey to its activity events, so behavior/output are
685
+ // unchanged from before this feature existed.
686
+ const store = this._store();
687
+ let sequence = null;
688
+ let replayKey = null;
689
+ if (store && store.activitySeq) {
690
+ // (apra-fleet-unw2.14, N6) `sequence` is numeric at the top level
691
+ // and a hierarchical, scheduler-independent string inside a
692
+ // parallel() branch -- see _nextSequence()/parallel().
693
+ sequence = this._nextSequence(store);
694
+ replayKey = computeActivityKey({
695
+ sequence,
696
+ type: 'agent',
697
+ member: opts.member_name || opts.member_id,
698
+ textHash: hashText(initialPrompt)
699
+ });
700
+ }
701
+
702
+ const replay = store && store.replay;
703
+ if (replay && !replay.diverged && replayKey) {
704
+ const cached = replay.completedByKey.get(replayKey);
705
+ if (cached && cached.success) {
706
+ // Cache hit: return the journaled result WITHOUT dispatching
707
+ // to the fleet at all. Still emit activity:start/activity:end
708
+ // (marked `replayed: true`) so a listening dashboard/journal
709
+ // writer sees this step as part of the run.
710
+ const cachedActivityMeta = {
711
+ id: randomUUID(),
712
+ type: 'agent',
713
+ phase: effectivePhase,
714
+ runId,
715
+ label: (opts.label || prompt.split('\n')[0].substring(0, 50) + (prompt.length > 50 ? '...' : '')),
716
+ member: opts.member_name || opts.member_id,
717
+ model: opts.model || 'default',
718
+ repairAttempt: 0,
719
+ startTime: Date.now(),
720
+ sequence,
721
+ replayKey,
722
+ replayed: true
723
+ };
724
+ this.emit('activity:start', cachedActivityMeta);
725
+ // (apra-fleet-unw2.14, N18) INTENTIONAL: a replayed agent
726
+ // activity re-debits the run's budget using the journaled
727
+ // (cached) cost of the ORIGINAL dispatch. This is
728
+ // "total-spend-view" semantics: `budget.spent()` on a resumed
729
+ // run reflects the cumulative real cost of the whole logical
730
+ // run (original + resumed portions), NOT just what the resumed
731
+ // process dispatched live. That is deliberate -- a resume is a
732
+ // continuation of one run, and its budget ceiling must still
733
+ // account for money already spent before the crash, otherwise
734
+ // a run that crashed near its budget limit could resume and
735
+ // massively overspend. It is NOT the "fresh run starts at $0"
736
+ // model some callers might naively assume; that expectation is
737
+ // explicitly wrong here. (See the resumed-budget test in
738
+ // apra-fleet-workflow-journal.test.mjs.)
739
+ if (typeof cached.cost === 'number') {
740
+ budget._spent += cached.cost;
741
+ }
742
+ const cachedOutput = opts.schema ? JSON.parse(cached.output) : cached.output;
743
+ this.emit('activity:end', {
744
+ ...cachedActivityMeta,
745
+ duration: 0,
746
+ success: true,
747
+ usage: cached.usage ?? null,
748
+ cost: cached.cost ?? null,
749
+ output: cached.output,
750
+ replayed: true
751
+ });
752
+ return cachedOutput;
753
+ }
754
+ // First mismatch or first missing entry for this run: stop
755
+ // replay and switch to live execution from here onward (partial
756
+ // replay, not all-or-nothing).
757
+ replay.diverged = true;
758
+ const inParallel = !!(store && store.seqPrefix);
759
+ console.warn(this._divergenceWarning({ sequence, type: 'agent', member: opts.member_name || opts.member_id, inParallel }));
760
+ this.emit('journal:diverged', { runId, sequence, type: 'agent', replayKey, inParallel });
761
+ }
762
+
763
+ for (let attempt = 0; attempt <= maxRepairs; attempt++) {
764
+ if (budget.total !== null && budget.remaining() <= 0) {
765
+ throw new BudgetExceededError(
766
+ `[Workflow Error] Budget exceeded: spent $${budget._spent.toFixed(4)} of $${budget.total.toFixed(4)} total. Aborting agent() dispatch.`,
767
+ { details: { spent: budget._spent, total: budget.total, member: opts.member_name || opts.member_id } }
768
+ );
769
+ }
770
+
771
+ const isRepair = attempt > 0;
772
+ const activityMeta = {
773
+ id: randomUUID(),
774
+ type: 'agent',
775
+ phase: effectivePhase,
776
+ runId,
777
+ label: (opts.label || prompt.split('\n')[0].substring(0, 50) + (prompt.length > 50 ? '...' : ''))
778
+ + (isRepair ? ` [schema repair ${attempt}/${maxRepairs}]` : ''),
779
+ member: opts.member_name || opts.member_id,
780
+ model: opts.model || 'default',
781
+ repairAttempt: attempt,
782
+ startTime: Date.now(),
783
+ ...(replayKey !== null ? { sequence, replayKey } : {})
784
+ };
785
+ lastActivityMeta = activityMeta;
786
+ this.emit('activity:start', activityMeta);
787
+
788
+ const payload = {
789
+ prompt: currentPrompt,
790
+ model: opts.model,
791
+ member_name: opts.member_name,
792
+ member_id: opts.member_id,
793
+ substitutions: opts.substitutions,
794
+ timeout_s: opts.timeout_s,
795
+ max_total_s: opts.max_total_s,
796
+ max_turns: opts.max_turns,
797
+ effort: opts.effort,
798
+ agent: opts.agentType,
799
+ // apra-fleet-eft.29.1: pass-through opt-in, see AgentOptions.sprint_id above.
800
+ sprint_id: opts.sprint_id,
801
+ // F10: default to a self-contained (non-resumed) session for
802
+ // the INITIAL dispatch of a workflow-authored prompt. See
803
+ // AgentOptions.resume above and apra-fleet-unw.3.
804
+ // apra-fleet-02s.3: a schema-repair re-ask (isRepair===true)
805
+ // is a different case -- it now FORCES resume:true,
806
+ // regardless of opts.resume, so the member's session already
807
+ // has the original prompt/schema and its own invalid output
808
+ // in context; buildRepairPrompt() was shrunk accordingly to a
809
+ // lean reminder (validation errors only), since re-sending
810
+ // that context fresh every repair round would waste tokens.
811
+ resume: isRepair ? true : (opts.resume ?? false),
812
+ // apra-fleet-unw.5: opts pass-through only, no control-flow change here.
813
+ timeoutMs: opts.timeoutMs,
814
+ // apra-fleet-unw.10: defaults to the active run's cooperative
815
+ // -cancellation signal (set up by runWithContext()/
816
+ // requestStop()) when the caller doesn't supply its own.
817
+ signal: opts.signal ?? this._currentSignal()
818
+ };
819
+
820
+ try {
821
+ let result = await this.fleetApi.executePrompt(payload);
822
+
823
+ // Busy-wait (see AgentOptions.busyWaitMs): a busy member is
824
+ // transient-but-slow -- an orphaned prior session can hold
825
+ // the per-member dispatch lock for minutes before finishing.
826
+ // Poll (cheap, side-effect-free re-dispatch) until the lock
827
+ // frees or the budget runs out, instead of failing the whole
828
+ // step on the first busy rejection.
829
+ const busyWaitMs = opts.busyWaitMs ?? 600000;
830
+ const busyPollMs = opts.busyPollMs ?? 15000;
831
+ if (busyWaitMs > 0) {
832
+ const busyDeadline = Date.now() + busyWaitMs;
833
+ while (
834
+ result && result.structuredContent && result.structuredContent.isError
835
+ && result.structuredContent.reason === 'busy'
836
+ && Date.now() < busyDeadline
837
+ && !(payload.signal && payload.signal.aborted)
838
+ ) {
839
+ console.error(`[Agent Busy-Wait] member '${opts.member_name || opts.member_id}' is busy (a prior dispatch still holds its lock); retrying in ${Math.round(busyPollMs / 1000)}s (up to ${Math.round((busyDeadline - Date.now()) / 1000)}s left)...`);
840
+ await new Promise((resolve) => setTimeout(resolve, busyPollMs));
841
+ result = await this.fleetApi.executePrompt(payload);
842
+ }
843
+ }
844
+
845
+ // execute_prompt's dispatch-level structuredContent (added
846
+ // alongside the display text -- see src/tools/execute-prompt.ts)
847
+ // reports real per-call token usage AND classifies dispatch
848
+ // failures (busy member, non-zero CLI exit, transport
849
+ // exception) distinctly from a genuine LLM response. Prefer it;
850
+ // fall back to result.usage directly for older servers that
851
+ // predate this field.
852
+ const structured = result && result.structuredContent;
853
+ const reportedUsage = (structured && structured.usage) || result.usage;
854
+
855
+ // apra-fleet-unw.4: never fabricate usage. If the fleet result
856
+ // didn't report real token usage, both usage and cost are
857
+ // explicitly null -- the viewer renders "n/a" and excludes the
858
+ // activity from cost totals rather than showing fiction. This
859
+ // applies per-attempt: every repair dispatch is accounted
860
+ // individually, exactly like the original attempt.
861
+ const hasRealUsage = !!(reportedUsage && typeof reportedUsage.total_tokens === 'number');
862
+ result.usage = hasRealUsage ? reportedUsage : null;
863
+
864
+ const cost = hasRealUsage ? await this._resolveCost(opts, result.usage, budget) : null;
865
+ if (cost !== null) {
866
+ budget._spent += cost;
867
+ }
868
+ const duration = Date.now() - activityMeta.startTime;
869
+
870
+ // Dispatch-level failure (busy member, non-zero exit, transport
871
+ // exception): the text is never the LLM's actual answer, so
872
+ // feeding it to the schema/JSON extractor below would always
873
+ // fail and misreport as "LLM failed to return parseable JSON".
874
+ // Surface it as a typed, distinctly-classified error instead,
875
+ // and never retry it through the bounded schema-repair loop --
876
+ // repair re-asks the SAME prompt with "here's why your JSON was
877
+ // invalid" framing, which cannot fix a dispatch failure and
878
+ // both wastes attempts and produces a misleading error message.
879
+ // The caller's own top-level retry (e.g. the streak-dispatch
880
+ // "retrying once" wrapper in apra-fleet-se's runner.js) still
881
+ // applies on top of this.
882
+ if (structured && structured.isError) {
883
+ const text = result && result.content && result.content.length > 0 ? result.content[0].text : '';
884
+ console.error(`[Agent API Error]`, text);
885
+ // apra-fleet-202.3: a dispatch that FAILED (isError) but still
886
+ // reported real input/output tokens really did consume that
887
+ // spend -- carry its usage/cost onto the activity record (as
888
+ // the empty-response failure path below already does) so the
889
+ // dashboard's per-activity totalTokens/totalCost tally
890
+ // includes it instead of silently dropping it. budget._spent
891
+ // was already bumped above (drives the harvester cost-
892
+ // analysis via spent()), and this failed activity was never
893
+ // previously recorded with a cost, so neither total is
894
+ // double-counted. When the provider reported no usage at all,
895
+ // result.usage is null and cost is null -- the viewer then
896
+ // tallies it as an unknown-cost activity rather than fiction.
897
+ this.emit('activity:end', { ...activityMeta, error: text, duration, usage: result.usage, cost, success: false });
898
+ throw new AgentDispatchError(`[Workflow Error] Agent dispatch failed (${structured.reason || 'unknown'}): ${text}`, { details: { text, reason: structured.reason, member: opts.member_name || opts.member_id } });
899
+ }
900
+
901
+ // apra-fleet-eft.78.3: surface the resumable session id
902
+ // (promoted into structuredContent.sessionId by execute_prompt
903
+ // in apra-fleet-eft.78.1) to the caller via an optional callback,
904
+ // WITHOUT changing agent()'s string/parsed return contract. The
905
+ // auto-sprint engine uses this to record each dispatch's session
906
+ // per (role, cycle) so it can resume the same role's session
907
+ // across rounds within a cycle (runner.js's round-session
908
+ // registry). Fired only on a non-error dispatch that actually
909
+ // produced a session id; a provider that does not support resume
910
+ // returns no sessionId, so the callback never fires and the
911
+ // engine falls back to a fresh session (a capability signal, not
912
+ // a provider-name check). Best-effort: a throwing callback must
913
+ // never break the dispatch.
914
+ if (
915
+ structured
916
+ && typeof structured.sessionId === 'string'
917
+ && structured.sessionId
918
+ && typeof opts.onSessionId === 'function'
919
+ ) {
920
+ try {
921
+ opts.onSessionId(structured.sessionId, { member: opts.member_name || opts.member_id, agent: opts.agentType, usage: result.usage });
922
+ } catch (cbErr) {
923
+ console.error(`[Agent onSessionId] callback threw (non-fatal): ${cbErr && cbErr.message ? cbErr.message : cbErr}`);
924
+ }
925
+ }
926
+
927
+ if (result && result.content && result.content.length > 0) {
928
+ const text = result.content[0].text;
929
+
930
+ // STOPGAP: the apra-fleet MCP server currently reports a
931
+ // missing member as a normal-looking success payload whose
932
+ // text happens to match this pattern, instead of a
933
+ // structured error (see docs/structured-errors-proposal.md).
934
+ // Until the server ships Option 1 (JSON-RPC error) or
935
+ // Option 2 (isError payload), this string-sniff is the only
936
+ // classifier available; keep it, but always surface it as a
937
+ // typed error rather than a silent `null` return. A missing
938
+ // member is not a schema problem, so it is never retried
939
+ // through the repair loop.
940
+ if (text.startsWith('Member "') && text.includes('" not found.')) {
941
+ console.error(`[Agent API Error]`, text);
942
+ this.emit('activity:end', { ...activityMeta, error: text, duration, success: false });
943
+ throw new MemberNotFoundError(`[Workflow Error] ${text}`, { details: { text, member: opts.member_name || opts.member_id } });
944
+ }
945
+
946
+ // Empty-response detection (observed live, apra-fleet-eft.14):
947
+ // the fleet server can return success (exit 0, isError
948
+ // absent) whose text is ONLY the display wrapper -- e.g.
949
+ // exactly "\u{1F4CB} Response from <member>:\n\n" with an empty
950
+ // parsed result (the member CLI produced no parseable
951
+ // output; the server-side log line for such a dispatch
952
+ // also lacks its usual in=/out= token counts). Feeding
953
+ // that to schema extraction misclassifies it as "LLM
954
+ // returned invalid JSON" (and its repair re-ask wastes a
955
+ // dispatch); for no-schema calls it silently becomes a
956
+ // garbage "successful" result. It is a DISPATCH-level
957
+ // failure: surface it typed so callers' existing
958
+ // AgentDispatchError handling (retry / degrade the
959
+ // round) applies.
960
+ //
961
+ // structuredContent.response (added alongside this text --
962
+ // see src/tools/execute-prompt.ts) carries the exact reply
963
+ // the server parsed, with no display wrapper to strip --
964
+ // prefer it when present (upgraded server) as a direct,
965
+ // reliable emptiness check and as the clean value to hand
966
+ // back to callers, instead of text-scraping the wrapper.
967
+ // Fall back to the wrapper-stripping regex for an
968
+ // older/not-yet-rebuilt server that predates this field.
969
+ const hasStructuredResponse = !!structured && typeof structured.response === 'string';
970
+ const cleanText = hasStructuredResponse
971
+ ? structured.response
972
+ : text
973
+ .replace(/^\u{1F4CB} Response from [^\n:]+:\s*/u, '')
974
+ .replace(/^Tokens: input=\d+ output=\d+\s*$/mu, '')
975
+ .replace(/^---\s*$/mu, '')
976
+ .replace(/^session: \S+\s*$/mu, '');
977
+ if (cleanText.trim() === '') {
978
+ const emptyMsg = `execute_prompt returned an empty response (display wrapper only, no LLM output) from member '${opts.member_name || opts.member_id}'.`;
979
+ console.error(`[Agent API Error]`, emptyMsg);
980
+ this.emit('activity:end', { ...activityMeta, error: emptyMsg, output: text, duration, usage: result.usage, cost, success: false });
981
+ throw new AgentDispatchError(`[Workflow Error] Agent dispatch failed (empty_response): ${emptyMsg}`, { details: { text, reason: 'empty_response', member: opts.member_name || opts.member_id } });
982
+ }
983
+
984
+ if (!opts.schema) {
985
+ this.emit('activity:end', { ...activityMeta, duration, success: true, usage: result.usage, cost, output: text });
986
+ return hasStructuredResponse ? structured.response : text;
987
+ }
988
+
989
+ const extraction = extractStructuredOutput(hasStructuredResponse ? structured.response : text, compiledSchema);
990
+ if (extraction.ok) {
991
+ this.emit('activity:end', { ...activityMeta, duration, success: true, usage: result.usage, cost, output: JSON.stringify(extraction.parsed, null, 2) });
992
+ return extraction.parsed;
993
+ }
994
+
995
+ const errorsText = summarizeExtractionAttempts(extraction.attempts);
996
+
997
+ if (attempt < maxRepairs) {
998
+ // Bounded repair: re-dispatch to the SAME member with
999
+ // a fresh, self-contained prompt (original prompt +
1000
+ // invalid output + ajv errors). This attempt is still
1001
+ // recorded as its own activity:end (success: false)
1002
+ // so the journal/dashboard show it as a distinct step
1003
+ // before the repair attempt that follows.
1004
+ const repairMsg = `Schema-invalid output, retrying (repair ${attempt + 1}/${maxRepairs}): ${errorsText}`;
1005
+ // apra-fleet-wei: this branch used to ONLY emit
1006
+ // activity:end (visible via /state, i.e. the
1007
+ // dashboard) with no console/text-log line at all --
1008
+ // only the terminal failure paths (member-not-found,
1009
+ // repairs-exhausted, dispatch errors) call
1010
+ // console.error. A caller watching just the workflow
1011
+ // log stream had no way to see an intermediate repair
1012
+ // attempt fail, even when it eventually recovers on a
1013
+ // later repair (as most of these do) -- the failure
1014
+ // was only ever visible by separately querying the
1015
+ // dashboard's structured activity data.
1016
+ console.error(`[Agent API Error]`, repairMsg);
1017
+ this.emit('activity:end', { ...activityMeta, error: repairMsg, output: text, duration, usage: result.usage, cost, success: false });
1018
+ currentPrompt = buildRepairPrompt(errorsText);
1019
+ continue;
1020
+ }
1021
+
1022
+ // Repairs exhausted -- surface a typed AgentOutputError.
1023
+ // Classify the message the same way the old single-shot
1024
+ // code did (parseable-JSON vs schema-compliance failure)
1025
+ // based on the final attempt, so existing callers keyed
1026
+ // off either phrase keep working.
1027
+ const allUnparseable = extraction.attempts.length === 0 || extraction.attempts.every((a) => a.parseError);
1028
+ const attemptCount = attempt + 1;
1029
+ const message = allUnparseable
1030
+ ? `[Workflow Error] LLM failed to return parseable JSON for structured output after ${attemptCount} attempt(s) (${maxRepairs} repair(s) exhausted).`
1031
+ : `[Workflow Error] LLM returned non-compliant JSON. Validation failed after ${attemptCount} attempt(s) (${maxRepairs} repair(s) exhausted): ${errorsText}`;
1032
+ const validationErrors = extraction.attempts
1033
+ .filter((a) => a.validationErrors)
1034
+ .flatMap((a) => a.validationErrors);
1035
+ // Preserve the underlying JSON.parse error on `.cause`
1036
+ // when the final attempt was unparseable, matching the
1037
+ // original single-shot contract that callers can inspect
1038
+ // `.cause` for the raw parse failure.
1039
+ const lastParseError = [...extraction.attempts].reverse().find((a) => a.parseError)?.parseError;
1040
+
1041
+ const err = new AgentOutputError(message, {
1042
+ details: {
1043
+ text,
1044
+ attempts: attemptCount,
1045
+ repairs: maxRepairs,
1046
+ errorsText,
1047
+ validationErrors: validationErrors.length > 0 ? validationErrors : undefined
1048
+ },
1049
+ cause: lastParseError
1050
+ });
1051
+ this.emit('activity:end', { ...activityMeta, error: err.message, output: text, duration, usage: result.usage, cost, success: false });
1052
+ throw err;
1053
+ }
1054
+
1055
+ this.emit('activity:end', { ...activityMeta, duration, success: false });
1056
+ throw new AgentOutputError(`[Workflow Error] agent() received an empty content response from the fleet API.`, { details: { result } });
1057
+ } catch (error) {
1058
+ console.error(`[Agent API Error]`, error.message || error);
1059
+ if (error instanceof WorkflowError) {
1060
+ // activity:end for typed errors was already emitted at
1061
+ // the throw site above (with the richer, attempt-scoped
1062
+ // metadata); don't double-emit here.
1063
+ throw error;
1064
+ }
1065
+ const duration = Date.now() - activityMeta.startTime;
1066
+ // apra-fleet-unw.10: a client-side AbortError (.code ===
1067
+ // 'ABORTED', from McpClient.request() reacting to the
1068
+ // signal above) means this dispatch was cooperatively
1069
+ // cancelled via requestStop() -- surface it as a typed
1070
+ // CancelledError, not a generic transport failure.
1071
+ if (error && error.code === 'ABORTED') {
1072
+ const cancelErr = new CancelledError(`[Workflow Error] agent() dispatch cancelled: ${error.message || error}`, { details: { payload }, cause: error });
1073
+ this.emit('activity:end', { ...activityMeta, error: cancelErr.message, duration, success: false, cancelled: true });
1074
+ throw cancelErr;
1075
+ }
1076
+ this.emit('activity:end', { ...activityMeta, error: error.message || error, duration, success: false });
1077
+ throw new FleetTransportError(`[Workflow Error] Transport failure while executing agent prompt: ${error.message || error}`, { details: { payload }, cause: error });
1078
+ }
1079
+ }
1080
+
1081
+ // Unreachable: the loop above always returns or throws. Kept as a
1082
+ // defensive guard in case maxRepairs computation is ever negative.
1083
+ throw new AgentOutputError(`[Workflow Error] agent() exhausted its dispatch loop without a result.`, { details: { activity: lastActivityMeta } });
1084
+ }
1085
+
1086
+ /**
1087
+ * @param {string} cmd
1088
+ * @param {CommandOptions} [opts]
1089
+ */
1090
+ async command(cmd, opts = {}) {
1091
+ // (apra-fleet-unw.17, A4) `opts.failSoft`: when set, a command
1092
+ // failure that would otherwise throw (a well-formed `isError`
1093
+ // result -> CommandError, a "Member not found" text sniff ->
1094
+ // MemberNotFoundError, or a transport-level rejection ->
1095
+ // FleetTransportError) is instead returned to the caller as
1096
+ // `{ ok: false, output: '', error: <message> }` -- and a success is
1097
+ // returned as `{ ok: true, output: <text>, error: null }` instead of
1098
+ // the bare string. This exists for callers like runner.js's
1099
+ // deploy.md/integ-test-playbook.md file-existence probes, which must
1100
+ // never let a transient/portability probe failure (e.g. a
1101
+ // node-not-on-PATH quirk on some member) kill the whole sprint --
1102
+ // the probe is best-effort; a failure just means "treat as not
1103
+ // found" (skip the dependent phase), not "abort everything".
1104
+ // Deliberately does NOT catch CancelledError (cooperative
1105
+ // requestStop() cancellation must still unwind the run even for a
1106
+ // failSoft caller -- swallowing that would defeat requestStop()).
1107
+ const failSoft = !!opts.failSoft;
1108
+ const softFail = (err) => {
1109
+ if (err instanceof CancelledError) throw err;
1110
+ if (!failSoft) throw err;
1111
+ return { ok: false, output: '', error: err.message };
1112
+ };
1113
+ if (!opts.member_name && !opts.member_id) {
1114
+ throw new Error(`[Workflow Error] command() requires either member_name or member_id`);
1115
+ }
1116
+
1117
+ const effectivePhase = opts.phase || this._currentPhase();
1118
+ const runId = this._currentRunId();
1119
+ if (!opts.silent) {
1120
+ console.log(`${this.logPrefix}[Command] phase: ${effectivePhase} | member: ${opts.member_name || opts.member_id} | label: ${opts.label || 'none'}`);
1121
+ }
1122
+
1123
+ let finalCmd = cmd;
1124
+ if (opts.substitutions) {
1125
+ for (const [key, value] of Object.entries(opts.substitutions)) {
1126
+ finalCmd = finalCmd.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), value);
1127
+ }
1128
+ }
1129
+
1130
+ // (apra-fleet-unw.11, F6) Journal replay -- see the matching, more
1131
+ // detailed comment in agent() above. `command()`'s activity events
1132
+ // already carry the raw, substituted command text (the `command`
1133
+ // field above), so the replay key hashes that same text rather than
1134
+ // requiring a second copy.
1135
+ const store = this._store();
1136
+ let sequence = null;
1137
+ let replayKey = null;
1138
+ if (store && store.activitySeq) {
1139
+ // (apra-fleet-unw2.14, N6) See agent()/_nextSequence(): numeric at
1140
+ // the top level, hierarchical/order-independent inside parallel().
1141
+ sequence = this._nextSequence(store);
1142
+ replayKey = computeActivityKey({
1143
+ sequence,
1144
+ type: 'command',
1145
+ member: opts.member_name || opts.member_id,
1146
+ textHash: hashText(finalCmd)
1147
+ });
1148
+ }
1149
+
1150
+ const replay = store && store.replay;
1151
+ if (replay && !replay.diverged && replayKey) {
1152
+ const cached = replay.completedByKey.get(replayKey);
1153
+ if (cached && cached.success) {
1154
+ // apra-fleet-unw2.13 (N5): reconstruct the shape the CURRENT
1155
+ // call would have gotten live -- a failSoft caller expects
1156
+ // `{ ok, output, error }`, a plain caller expects the raw
1157
+ // string. `cached.failSoft` is read from the journaled
1158
+ // `activity:end` record (see the `failSoft` field added to
1159
+ // `activityMeta` below), which reflects how the ORIGINAL run
1160
+ // shaped this same call. Since a resumed run replays the
1161
+ // same script in the same order with the same opts, this
1162
+ // should always agree with the current call's `failSoft`.
1163
+ //
1164
+ // OLD-FORMAT journals (written before this fix) have no
1165
+ // `failSoft` field at all -- `cached.failSoft` is then
1166
+ // `undefined`, and we cannot know how the original call was
1167
+ // shaped. We fall back to the pre-fix behavior of returning
1168
+ // the raw string (best-effort; a failSoft caller resuming
1169
+ // from an old journal will see `res.ok === undefined` exactly
1170
+ // as it did before this fix, until the journal is
1171
+ // regenerated by a fresh, non-resumed run).
1172
+ const cachedFailSoft = !!cached.failSoft;
1173
+ const cachedActivityMeta = {
1174
+ id: randomUUID(),
1175
+ type: 'command',
1176
+ phase: effectivePhase,
1177
+ runId,
1178
+ label: opts.label || finalCmd.substring(0, 60),
1179
+ member: opts.member_name || opts.member_id,
1180
+ command: finalCmd,
1181
+ startTime: Date.now(),
1182
+ sequence,
1183
+ replayKey,
1184
+ replayed: true,
1185
+ failSoft: cachedFailSoft
1186
+ };
1187
+ this.emit('activity:start', cachedActivityMeta);
1188
+ this.emit('activity:end', {
1189
+ ...cachedActivityMeta,
1190
+ duration: 0,
1191
+ success: true,
1192
+ output: cached.output,
1193
+ replayed: true
1194
+ });
1195
+ return cachedFailSoft ? { ok: true, output: cached.output, error: null } : cached.output;
1196
+ }
1197
+ replay.diverged = true;
1198
+ const inParallel = !!(store && store.seqPrefix);
1199
+ console.warn(this._divergenceWarning({ sequence, type: 'command', member: opts.member_name || opts.member_id, inParallel }));
1200
+ this.emit('journal:diverged', { runId, sequence, type: 'command', replayKey, inParallel });
1201
+ }
1202
+
1203
+ const activityMeta = {
1204
+ id: randomUUID(),
1205
+ type: 'command',
1206
+ phase: effectivePhase,
1207
+ runId,
1208
+ label: opts.label || finalCmd.substring(0, 60),
1209
+ member: opts.member_name || opts.member_id,
1210
+ command: finalCmd,
1211
+ startTime: Date.now(),
1212
+ // apra-fleet-unw2.13 (N5): journal the failSoft flag as part of
1213
+ // every activity:start/activity:end record for this call, so a
1214
+ // FUTURE resume of this journal can reconstruct the right return
1215
+ // shape from `cached.failSoft` above, instead of unconditionally
1216
+ // returning the raw string regardless of how the original call
1217
+ // was made.
1218
+ failSoft,
1219
+ ...(replayKey !== null ? { sequence, replayKey } : {})
1220
+ };
1221
+ this.emit('activity:start', activityMeta);
1222
+
1223
+ const payload = {
1224
+ command: finalCmd,
1225
+ member_name: opts.member_name,
1226
+ member_id: opts.member_id,
1227
+ timeout_s: opts.timeout_s,
1228
+ long_running: opts.long_running,
1229
+ // apra-fleet-unw.5: opts pass-through only, no control-flow change here.
1230
+ timeoutMs: opts.timeoutMs,
1231
+ // apra-fleet-unw.10: see the matching comment in agent() above.
1232
+ signal: opts.signal ?? this._currentSignal()
1233
+ };
1234
+
1235
+ try {
1236
+ const result = await this.fleetApi.executeCommand(payload);
1237
+ const outText = result.content && result.content.length > 0 ? result.content[0].text : '';
1238
+ // Servers new enough to send structuredContent give clean stdout
1239
+ // directly -- no "Exit code: N\n" prefix to strip, no risk of a
1240
+ // caller (e.g. parseBdJson() in fleet-sprint/runner.js) choking on
1241
+ // display formatting mixed into what should be raw command
1242
+ // output. Older servers (no structuredContent) fall back to the
1243
+ // legacy text field as-is, preserving prior behavior exactly.
1244
+ const cleanOutput = (result.structuredContent && typeof result.structuredContent.stdout === 'string')
1245
+ ? result.structuredContent.stdout
1246
+ : outText;
1247
+ const duration = Date.now() - activityMeta.startTime;
1248
+
1249
+ // STOPGAP: see the matching comment in agent() above and
1250
+ // docs/structured-errors-proposal.md -- the server currently
1251
+ // signals a missing member via plain response text rather than a
1252
+ // structured error. Surface it as a typed error, never `null`.
1253
+ if (outText.startsWith('Member "') && outText.includes('" not found.')) {
1254
+ console.error(`[Command API Error]`, outText);
1255
+ this.emit('activity:end', { ...activityMeta, error: outText, duration, success: false });
1256
+ throw new MemberNotFoundError(`[Workflow Error] ${outText}`, { details: { text: outText, member: opts.member_name || opts.member_id } });
1257
+ }
1258
+
1259
+ if (result.isError) {
1260
+ const err = new CommandError(`[Command Failed] ${outText}`, { details: { text: outText, command: finalCmd } });
1261
+ this.emit('activity:end', { ...activityMeta, error: err.message, duration, success: false });
1262
+ throw err;
1263
+ }
1264
+
1265
+ // `result.isError` is an MCP-transport-level flag only -- it does
1266
+ // NOT reflect the exit code of the underlying process the server
1267
+ // ran. A `bd`/git/etc. invocation that exits non-zero (e.g. a
1268
+ // malformed argument) still comes back with isError unset, so
1269
+ // without this check it was reported as success:true both to
1270
+ // callers and to the dashboard viewer's activity badge. Older
1271
+ // servers with no structuredContent.exitCode are left exactly as
1272
+ // before (exitCode undefined skips this branch).
1273
+ const exitCode = result.structuredContent && typeof result.structuredContent.exitCode === 'number'
1274
+ ? result.structuredContent.exitCode
1275
+ : null;
1276
+ if (exitCode !== null && exitCode !== 0) {
1277
+ const err = new CommandError(`[Command Failed] Exit code ${exitCode}: ${outText}`, { details: { text: outText, command: finalCmd, exitCode } });
1278
+ this.emit('activity:end', { ...activityMeta, error: err.message, duration, success: false });
1279
+ throw err;
1280
+ }
1281
+
1282
+ this.emit('activity:end', { ...activityMeta, duration, success: true, output: outText });
1283
+ return failSoft ? { ok: true, output: cleanOutput, error: null } : cleanOutput;
1284
+ } catch (error) {
1285
+ console.error(`[Command API Error]`, error.message || error);
1286
+ if (error instanceof WorkflowError) {
1287
+ // activity:end for typed errors was already emitted at the
1288
+ // throw site above (see the matching comment in agent()'s
1289
+ // catch); don't double-emit here.
1290
+ return softFail(error);
1291
+ }
1292
+ const duration = Date.now() - activityMeta.startTime;
1293
+ // apra-fleet-unw.10: see the matching comment in agent() above.
1294
+ if (error && error.code === 'ABORTED') {
1295
+ const cancelErr = new CancelledError(`[Workflow Error] command() dispatch cancelled: ${error.message || error}`, { details: { payload }, cause: error });
1296
+ this.emit('activity:end', { ...activityMeta, error: cancelErr.message, duration, success: false, cancelled: true });
1297
+ throw cancelErr;
1298
+ }
1299
+ this.emit('activity:end', { ...activityMeta, error: error.message || error, duration, success: false });
1300
+ return softFail(new FleetTransportError(`[Workflow Error] Transport failure while executing command: ${error.message || error}`, { details: { payload }, cause: error }));
1301
+ }
1302
+ }
1303
+
1304
+ /**
1305
+ * Executes the given async processor function for each item sequentially.
1306
+ *
1307
+ * `sequential(items, processor, opts)` is the single-processor primitive:
1308
+ * exactly one `processor(item, index, items)` function is applied to every
1309
+ * item, in order. It does NOT accept a variadic list of per-stage
1310
+ * processors -- that old `sequential(items, ...stages)` form silently
1311
+ * dropped every stage after the first (F7). Extra positional arguments
1312
+ * now throw a TypeError instead of being swallowed. For a genuine
1313
+ * multi-stage pipeline where each stage's output feeds the next, use
1314
+ * `pipeline(items, ...stages)`.
1315
+ */
1316
+ async sequential(items, processor, opts = {}, ...rest) {
1317
+ if (rest.length > 0) {
1318
+ throw new TypeError(
1319
+ `sequential(items, processor, opts) accepts at most 3 arguments, got ${3 + rest.length}. ` +
1320
+ `sequential() no longer accepts a variadic list of per-stage processors -- use pipeline(items, ...stages) for multi-stage flows.`
1321
+ );
1322
+ }
1323
+ if (typeof processor !== 'function') {
1324
+ throw new TypeError(
1325
+ `sequential(items, processor, opts): the 2nd argument must be a single processor function, got ${processor === null ? 'null' : typeof processor}. ` +
1326
+ `The old sequential(items, ...stages) multi-stage form is no longer supported -- use pipeline(items, ...stages) instead.`
1327
+ );
1328
+ }
1329
+ if (opts === null || typeof opts !== 'object' || Array.isArray(opts)) {
1330
+ throw new TypeError(`sequential(items, processor, opts): the 3rd argument must be a plain options object, got ${opts === null ? 'null' : typeof opts}.`);
1331
+ }
1332
+
1333
+ const results = [];
1334
+ for (let i = 0; i < items.length; i++) {
1335
+ try {
1336
+ const res = await processor(items[i], i, items);
1337
+ results.push(res);
1338
+ } catch (err) {
1339
+ this.log(`[Sequential Error] item ${i} failed at a stage: ${err.message}`);
1340
+ if (!opts.continueOnError) {
1341
+ // Fail-fast: rethrow without discarding results already
1342
+ // collected for prior items. Attach them to the error so
1343
+ // callers can recover partial progress.
1344
+ err.partialResults = results.slice();
1345
+ throw err;
1346
+ }
1347
+ results.push(null);
1348
+ }
1349
+ }
1350
+ return results;
1351
+ }
1352
+
1353
+ /**
1354
+ * Executes a chain of stage functions for each item, sequentially, where
1355
+ * each stage receives the previous stage's result for that item (the
1356
+ * first stage receives the raw item). This is the documented multi-stage
1357
+ * form that `sequential(items, ...stages)` used to provide before it was
1358
+ * narrowed to a single-processor primitive (see `sequential()` above).
1359
+ *
1360
+ * Failure semantics mirror `sequential()`: by default a stage error
1361
+ * aborts the whole pipeline run and rethrows with `err.partialResults`
1362
+ * populated; pass `{ continueOnError: true }` as a trailing plain-object
1363
+ * argument to instead record `null` for the failed item and continue
1364
+ * with the rest.
1365
+ */
1366
+ async pipeline(items, ...stagesAndOpts) {
1367
+ let opts = {};
1368
+ let stages = stagesAndOpts;
1369
+ if (stagesAndOpts.length > 0 && typeof stagesAndOpts[stagesAndOpts.length - 1] !== 'function') {
1370
+ opts = stagesAndOpts[stagesAndOpts.length - 1];
1371
+ stages = stagesAndOpts.slice(0, -1);
1372
+ if (opts === null || typeof opts !== 'object' || Array.isArray(opts)) {
1373
+ throw new TypeError(`pipeline(items, ...stages, [opts]): the trailing non-function argument must be a plain options object, got ${opts === null ? 'null' : typeof opts}.`);
1374
+ }
1375
+ }
1376
+ if (stages.length === 0) {
1377
+ throw new TypeError('pipeline(items, ...stages): at least one stage function is required.');
1378
+ }
1379
+ stages.forEach((stage, idx) => {
1380
+ if (typeof stage !== 'function') {
1381
+ throw new TypeError(`pipeline(items, ...stages): stage ${idx + 1} must be a function, got ${stage === null ? 'null' : typeof stage}.`);
1382
+ }
1383
+ });
1384
+
1385
+ const results = [];
1386
+ for (let i = 0; i < items.length; i++) {
1387
+ try {
1388
+ let value = items[i];
1389
+ for (const stage of stages) {
1390
+ value = await stage(value, i, items);
1391
+ }
1392
+ results.push(value);
1393
+ } catch (err) {
1394
+ this.log(`[Pipeline Error] item ${i} failed at a stage: ${err.message}`);
1395
+ if (!opts.continueOnError) {
1396
+ err.partialResults = results.slice();
1397
+ throw err;
1398
+ }
1399
+ results.push(null);
1400
+ }
1401
+ }
1402
+ return results;
1403
+ }
1404
+
1405
+ /**
1406
+ * Executes the given async processor function for each item in parallel.
1407
+ *
1408
+ * (apra-fleet-unw.9, F11) Each branch runs against its own shallow-copied
1409
+ * fork of the current run's store (see runStorage comment above): `phase`
1410
+ * and `group` are copied by value, so a `phase()` call made inside one
1411
+ * branch's processor mutates only that branch's copy and can never leak
1412
+ * into a sibling branch (or into activities dispatched from a sibling
1413
+ * branch that happens to still be in flight) -- this is the exact F11
1414
+ * "concurrent branches inherit whichever phase() was called last" bug.
1415
+ * `args`/`budget`/`runId` are copied by reference so they stay shared and
1416
+ * consistent across every branch of the same run. When `parallel()` is
1417
+ * called outside of any active run store (legacy direct-call usage),
1418
+ * branches simply run without forking anything, matching prior behavior.
1419
+ *
1420
+ * (apra-fleet-unw2.14, N6) When journaling is active, each branch fork
1421
+ * ALSO gets its OWN activity sub-sequence rooted at a deterministic,
1422
+ * scheduler-independent prefix. Before this, every branch shared the
1423
+ * run's single `activitySeq` counter, so the sequence number a given
1424
+ * agent()/command() call received depended on which branch's call
1425
+ * happened to increment the shared counter next -- non-deterministic
1426
+ * across runs. A resumed multi-streak run then computed different
1427
+ * sequence numbers than the journaled run, missed the replay cache, and
1428
+ * re-executed everything live (re-dispatching doers whose work already
1429
+ * happened). Now the prefix is `<parentPrefix><barrierIndex>:<i>:` where
1430
+ * `barrierIndex` numbers this parallel() barrier at the parent level (in
1431
+ * program order, assigned SYNCHRONOUSLY before any branch runs) and `i`
1432
+ * is the branch's STATIC index in `items` -- neither depends on runtime
1433
+ * completion/scheduling order. Each branch's own fresh `activitySeq`
1434
+ * then counts only that branch's calls, in the branch's own program
1435
+ * order. The result: identical replay keys for a given logical call site
1436
+ * regardless of how branches interleave. See journal.mjs
1437
+ * computeActivityKey for the full semantics.
1438
+ */
1439
+ async parallel(items, processor, opts = {}) {
1440
+ const parentStore = this._store();
1441
+ // Assign this barrier's index SYNCHRONOUSLY, in program order, before
1442
+ // any branch is scheduled -- so it can never race with a sibling
1443
+ // parallel() call at the same store level. Only meaningful when
1444
+ // journaling is active (parallelSeq is null otherwise).
1445
+ const barrierIndex = (parentStore && parentStore.parallelSeq)
1446
+ ? parentStore.parallelSeq.value++
1447
+ : null;
1448
+ return Promise.all(items.map((item, i) => {
1449
+ const runBranch = async () => {
1450
+ try {
1451
+ return await processor(item, i, items);
1452
+ } catch (err) {
1453
+ this.log(`[Parallel Error] item ${i} failed: ${err.message}`);
1454
+ if (!opts.continueOnError) {
1455
+ throw err;
1456
+ }
1457
+ return null;
1458
+ }
1459
+ };
1460
+ if (parentStore) {
1461
+ const branchStore = { ...parentStore };
1462
+ // Journaling active: give this branch its OWN hierarchical
1463
+ // sub-sequence so its replay keys are order-independent. The
1464
+ // prefix is fixed by the branch's static array index `i` and
1465
+ // the barrier index computed above -- not by scheduling.
1466
+ if (parentStore.activitySeq) {
1467
+ branchStore.seqPrefix = `${parentStore.seqPrefix || ''}${barrierIndex}:${i}:`;
1468
+ branchStore.activitySeq = { value: 0 };
1469
+ branchStore.parallelSeq = { value: 0 };
1470
+ }
1471
+ return runStorage.run(branchStore, runBranch);
1472
+ }
1473
+ return runBranch();
1474
+ }));
1475
+ }
1476
+
1477
+ /**
1478
+ * (apra-fleet-unw2.14, N6) Computes the replay `sequence` component for
1479
+ * the next agent()/command() call in the current store, advancing the
1480
+ * store's local activity counter. At the top level this returns a plain
1481
+ * number (`0`,`1`,...); inside a `parallel()` branch it returns the
1482
+ * hierarchical, scheduler-independent string
1483
+ * `<seqPrefix><localSeq>` (e.g. `0:1:0`). Returns `null` when journaling
1484
+ * is not active for this run (so no replay-key machinery runs at all).
1485
+ * @param {object|undefined} store
1486
+ * @returns {number|string|null}
1487
+ */
1488
+ _nextSequence(store) {
1489
+ if (!store || !store.activitySeq) return null;
1490
+ const local = store.activitySeq.value++;
1491
+ return store.seqPrefix ? `${store.seqPrefix}${local}` : local;
1492
+ }
1493
+
1494
+ /**
1495
+ * (apra-fleet-unw2.14, N6) Builds the human-facing replay-divergence
1496
+ * warning, distinguishing a divergence detected INSIDE a `parallel()`
1497
+ * region from a sequential one. The two carry very different severity for
1498
+ * a human debugging a resume:
1499
+ *
1500
+ * - A SEQUENTIAL divergence is the suspicious case: the run's top-level
1501
+ * flow no longer matches the journal, which almost always means the
1502
+ * workflow script itself changed (a call added/removed/reordered, a
1503
+ * prompt/command edited, non-deterministic args) between the recording
1504
+ * and the resume. Everything from here on re-runs live.
1505
+ *
1506
+ * - A PARALLEL-region divergence is (post-N6) far less alarming: keys
1507
+ * inside `parallel()` are now scheduler-independent, so a divergence
1508
+ * here is NOT caused by branch interleaving. It usually means either
1509
+ * (a) the journal was written by a pre-N6 build (old shared global
1510
+ * counter -- see computeActivityKey's OLD-FORMAT note; regenerate the
1511
+ * journal to fix), or (b) a branch is internally non-deterministic
1512
+ * (dispatches a different number/order of calls across runs) or the
1513
+ * set/order of parallel branches changed.
1514
+ * @param {{ sequence: number|string, type: string, member?: string, inParallel: boolean }} parts
1515
+ * @returns {string}
1516
+ */
1517
+ _divergenceWarning({ sequence, type, member, inParallel }) {
1518
+ const base = `[Journal] Replay divergence at sequence ${sequence} (${type}, member: ${member}) -- switching to live execution from this point onward.`;
1519
+ if (inParallel) {
1520
+ return base + ' This divergence is INSIDE a parallel() region; branch interleaving is NOT the cause (replay keys are order-independent since apra-fleet-unw2.14/N6). Likely a pre-N6 (old-format) journal, an internally non-deterministic branch, or a changed set/order of parallel branches -- regenerate the journal from a fresh run if it predates N6.';
1521
+ }
1522
+ return base + ' This is a SEQUENTIAL (top-level) divergence: the run no longer matches the journal, most likely because the workflow script or its args changed between recording and resume.';
1523
+ }
1524
+
1525
+ async transform(label, func, context) {
1526
+ const id = randomUUID();
1527
+ const activityMeta = {
1528
+ id, type: 'transform', label, phase: this._currentPhase(), runId: this._currentRunId(), startTime: Date.now()
1529
+ };
1530
+ this.emit('activity:start', activityMeta);
1531
+
1532
+ const transformationFn = func || ((data) => data); // pass as-is default
1533
+
1534
+ try {
1535
+ let result = await transformationFn(context);
1536
+ const duration = Date.now() - activityMeta.startTime;
1537
+
1538
+ let stringifiedOutput = result;
1539
+ if (typeof result !== 'string' && result !== undefined && result !== null) {
1540
+ try { stringifiedOutput = JSON.stringify(result, null, 2); } catch(e) {}
1541
+ }
1542
+
1543
+ let stringifiedInput = context;
1544
+ if (typeof context !== 'string' && context !== undefined && context !== null) {
1545
+ try { stringifiedInput = JSON.stringify(context, null, 2); } catch(e) {}
1546
+ }
1547
+
1548
+ this.emit('activity:end', { ...activityMeta, duration, success: true, input: stringifiedInput, output: stringifiedOutput });
1549
+ return result;
1550
+ } catch (e) {
1551
+ const duration = Date.now() - activityMeta.startTime;
1552
+ let stringifiedInput = context;
1553
+ if (typeof context !== 'string' && context !== undefined && context !== null) {
1554
+ try { stringifiedInput = JSON.stringify(context, null, 2); } catch(e) {}
1555
+ }
1556
+
1557
+ this.emit('activity:end', { ...activityMeta, duration, success: false, error: e.message, input: stringifiedInput });
1558
+ const err = new Error(`[Workflow Error] Transform failed: ${e.message}`);
1559
+ throw err;
1560
+ }
1561
+ }
1562
+
1563
+ async workflow(nameOrRef, args = {}) {
1564
+ // Run another script inline. Needs script runner logic.
1565
+ throw new Error("Nested workflows not yet implemented");
1566
+ }
1567
+
1568
+ // Shared primitive bindings (agent/command/parallel/etc.) used by both
1569
+ // the legacy `createContext()` and the per-run `runWithContext()` below.
1570
+ // The primitives themselves are always bound to `this` -- they don't
1571
+ // capture `args`/`phase`/`budget` directly; instead they look those up
1572
+ // dynamically via `this._store()`/`this._current*()` at call time (see
1573
+ // the runStorage comment above this class), so the SAME bound functions
1574
+ // correctly resolve to whichever run (or the legacy instance-level
1575
+ // fields) is active when they're actually invoked.
1576
+ _bindPrimitives() {
1577
+ return {
1578
+ agent: this.agent.bind(this),
1579
+ command: this.command.bind(this),
1580
+ sequential: this.sequential.bind(this),
1581
+ pipeline: this.pipeline.bind(this),
1582
+ parallel: this.parallel.bind(this),
1583
+ transform: this.transform.bind(this),
1584
+ nullTransform: () => null,
1585
+ log: this.log.bind(this),
1586
+ phase: this.phase.bind(this),
1587
+ publishState: this.publishState.bind(this),
1588
+ workflow: this.workflow.bind(this),
1589
+ group: this.group.bind(this),
1590
+ endGroup: this.endGroup.bind(this)
1591
+ };
1592
+ }
1593
+
1594
+ // A helper to inject the workflow globals into a user script context.
1595
+ //
1596
+ // Legacy / direct-call form: NOT run-scoped. `args`/`budget` here are the
1597
+ // legacy instance-level fields (`this.args`/`this.budget`), exactly as
1598
+ // before apra-fleet-unw.9 -- preserved for existing direct `wf.method()`
1599
+ // callers and tests that never go through `WorkflowEngine.executeFile()`.
1600
+ // For per-run isolation (the fix for the concurrent-execution bug this
1601
+ // context object exists to prevent), use `runWithContext()` instead,
1602
+ // which `WorkflowEngine.executeFile()` calls internally.
1603
+ createContext(args = this.args) {
1604
+ return {
1605
+ ...this._bindPrimitives(),
1606
+ args,
1607
+ budget: this.budget
1608
+ };
1609
+ }
1610
+
1611
+ /**
1612
+ * Runs `entryFn(context)` inside a fresh, isolated per-run store (see the
1613
+ * runStorage comment above this class): its own `args`, `phase`, `group`,
1614
+ * and `budget` accounting, plus a unique `runId` carried on every
1615
+ * activity/log/state event emitted during the run. Concurrent calls to
1616
+ * `runWithContext()` (e.g. two overlapping `WorkflowEngine.executeFile()`
1617
+ * calls) on the SAME `FleetWorkflow` instance no longer corrupt each
1618
+ * other's `args` or phase attribution -- each gets its own store, and
1619
+ * `runStorage` (an `AsyncLocalStorage`) threads it automatically through
1620
+ * every `await` inside `entryFn`.
1621
+ *
1622
+ * The `FleetWorkflow`'s `EventEmitter` remains shared (a dashboard viewer
1623
+ * subscribes to it once, globally); every event carries the originating
1624
+ * run's `runId` so concurrent runs' events stay distinguishable there.
1625
+ *
1626
+ * @param {any} args - Arguments for this run, exposed as `context.args`.
1627
+ * @param {(context: object) => Promise<any>} entryFn - The workflow
1628
+ * script's entry point (`main`/`run`/`default`), called with this run's
1629
+ * context object.
1630
+ * @param {{ runId?: string, journalEnabled?: boolean, replay?: {completedByKey: Map<string,object>, diverged: boolean} }} [opts] -
1631
+ * (apra-fleet-unw.10) `runId`: optional caller-supplied run id, so
1632
+ * `WorkflowEngine.executeFile()` can know the run's id up front (to
1633
+ * attach it to the `end` event it emits from its own try/finally)
1634
+ * without this method having to report it back out-of-band. Defaults
1635
+ * to a fresh UUID when omitted, matching the pre-unw.10 behavior for
1636
+ * any other/legacy caller.
1637
+ * (apra-fleet-unw.11, F6) `journalEnabled`/`replay`: journal/resume
1638
+ * wiring from `WorkflowEngine.executeFile()`. `journalEnabled` gates
1639
+ * the per-run activity sequence counter (`store.activitySeq`) that
1640
+ * `agent()`/`command()` use to compute deterministic replay keys --
1641
+ * when omitted/false, that counter is never created and
1642
+ * `agent()`/`command()` never compute or attach replay-related fields
1643
+ * to their activity events, so behavior/output is unchanged from
1644
+ * before this feature existed. `replay` (only meaningful when
1645
+ * `journalEnabled` is true) is the loaded journal's
1646
+ * `completedByKey`/`diverged` state (see journal.mjs `loadJournal()`);
1647
+ * `diverged` is mutated in place by `agent()`/`command()` the first
1648
+ * time a call's replay key isn't found as a completed/successful
1649
+ * record in the journal, permanently switching the rest of the run to
1650
+ * live execution (partial replay, Claude-CLI style).
1651
+ */
1652
+ async runWithContext(args, entryFn, opts = {}) {
1653
+ const runId = opts.runId || randomUUID();
1654
+ const budget = {
1655
+ total: null,
1656
+ _spent: 0,
1657
+ _pricedReal: 0,
1658
+ _pricedFallback: 0,
1659
+ spent: () => budget._spent,
1660
+ remaining: () => budget.total === null ? Infinity : (budget.total - budget._spent),
1661
+ pricingSummary: () => ({ real: budget._pricedReal, fallback: budget._pricedFallback })
1662
+ };
1663
+ // (apra-fleet-unw.10) Per-run AbortController backing cooperative
1664
+ // cancellation: agent()/command() default to `store.signal` (via
1665
+ // _currentSignal()) so requestStop() can abort every in-flight and
1666
+ // future dispatch of THIS run without the workflow script having to
1667
+ // thread a signal through itself. Tracked in `_activeControllers` for
1668
+ // the lifetime of the run only -- removed in `finally` below so a
1669
+ // late requestStop() call after the run has already finished is a
1670
+ // no-op instead of leaking controllers across runs.
1671
+ const controller = new AbortController();
1672
+ this._activeControllers.set(runId, controller);
1673
+ const store = {
1674
+ runId,
1675
+ args,
1676
+ phase: null,
1677
+ group: null,
1678
+ budget,
1679
+ signal: controller.signal,
1680
+ // (apra-fleet-unw.11, F6 / apra-fleet-unw2.14, N6) Per-run
1681
+ // activity sequencing for deterministic replay keys.
1682
+ //
1683
+ // `activitySeq` is a monotonic counter scoped to THIS store level
1684
+ // (the run's top-level flow, or -- after a `parallel()` fork -- a
1685
+ // single branch). At the top level it produces plain numeric
1686
+ // sequences 0,1,2,... in program order, exactly as before N6.
1687
+ //
1688
+ // `seqPrefix` is the hierarchical path prefix prepended to a
1689
+ // call's local sequence to form its replay key's `sequence`
1690
+ // component. It is empty ('') at the top level -- so top-level
1691
+ // keys stay numeric and backward-compatible -- and is extended by
1692
+ // `parallel()` per branch (see parallel() below) to
1693
+ // `<barrierIndex>:<branchIndex>:`, making every in-branch key
1694
+ // scheduler-INDEPENDENT (order of branch interleaving no longer
1695
+ // affects the key). See journal.mjs computeActivityKey for the
1696
+ // full semantics/limitations.
1697
+ //
1698
+ // `parallelSeq` numbers the `parallel()` barriers entered AT this
1699
+ // store level, in program order, so two sequential parallel()
1700
+ // calls at the same level get distinct barrier prefixes even if
1701
+ // no agent()/command() ran between them.
1702
+ //
1703
+ // All three are `null` unless journaling was requested for this
1704
+ // run at all (a normal, non-journaled run never enters any of the
1705
+ // replay-key code paths).
1706
+ activitySeq: opts.journalEnabled ? { value: 0 } : null,
1707
+ seqPrefix: '',
1708
+ parallelSeq: opts.journalEnabled ? { value: 0 } : null,
1709
+ replay: opts.journalEnabled ? (opts.replay || null) : null,
1710
+ // apra-fleet-dv5.6: fresh per run, shared by reference across
1711
+ // parallel() branches (like `budget` above) so a member's
1712
+ // pricing is only fetched once per run regardless of how many
1713
+ // branches dispatch to it.
1714
+ memberPricingCache: new Map()
1715
+ };
1716
+ const context = {
1717
+ ...this._bindPrimitives(),
1718
+ args,
1719
+ budget
1720
+ };
1721
+ try {
1722
+ return await runStorage.run(store, () => entryFn(context));
1723
+ } finally {
1724
+ this._activeControllers.delete(runId);
1725
+ }
1726
+ }
1727
+ }