@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
@@ -3,44 +3,127 @@ import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { v4 as uuid } from 'uuid';
5
5
  import { z } from 'zod';
6
+ import { knownRepoRemoteUrl } from '../services/member-remote-url.js';
6
7
  import { getStrategy } from '../services/strategy.js';
7
8
  import { getOsCommands } from '../os/index.js';
8
9
  import { getProvider } from '../providers/index.js';
9
- import { getAgentOS, touchAgent } from '../utils/agent-helpers.js';
10
+ import { getAgentOS, touchAgent, getStoredPid } from '../utils/agent-helpers.js';
10
11
  import { updateAgent } from '../services/registry.js';
11
12
  import { memberIdentifier, resolveMember } from '../utils/resolve-member.js';
12
- import { isRetryable, authErrorAdvice } from '../utils/prompt-errors.js';
13
+ import { isRetryable, authErrorAdvice, workspaceNotTrustedAdvice } from '../utils/prompt-errors.js';
13
14
  import { buildAuthEnvPrefix } from '../utils/auth-env.js';
14
15
  import { writeStatusline } from '../services/statusline.js';
15
16
  import { getModelOverride } from '../services/user-config.js';
16
17
  import { ensureCloudReady } from '../services/cloud/lifecycle.js';
17
18
  import { getStallDetector, resolveSessionLogPath } from '../services/stall/index.js';
18
- import { provisionAgents, remoteAgentsDir } from '../services/agent-provisioner.js';
19
+ import { getCachedMemberPathContext } from '../services/member-home.js';
20
+ import { provisionAgents, remoteAgentsDir, loadCanonicalAgentSet } from '../services/agent-provisioner.js';
19
21
  import { escapeWindowsArg, escapeDoubleQuoted } from '../os/os-commands.js';
20
22
  import { resolveTilde } from './execute-command.js';
21
23
  import { clearStoredPid } from '../utils/agent-helpers.js';
22
- import { tryKillPid } from '../utils/pid-helpers.js';
23
- import { LogScope, maskSecrets, truncateForLog } from '../utils/log-helpers.js';
24
+ import { tryKillPid, isPidAlive } from '../utils/pid-helpers.js';
25
+ import { recoverOrphanedDispatch, isRemoteProcessAlive } from '../services/orphan-recovery.js';
26
+ import { seedWorkspaceTrust } from '../utils/workspace-trust.js';
27
+ import { durableOutputPath } from '../os/linux.js';
28
+ import { LogScope, logLine, logWarn, maskSecrets, truncateForLog } from '../utils/log-helpers.js';
24
29
  import { getLogPreviewChars } from '../services/user-config.js';
30
+ import { validateSubstitutionKeys, applySubstitutions } from '../services/substitution-engine.js';
31
+ import { sessionRegistry } from '../services/session-registry.js';
32
+ import { getTokenIssuer } from '../services/token-issuer.js';
33
+ import { resolveExpectedDemand, checkContextAdmission, recordSessionUsage } from '../services/context-admission.js';
34
+ import { recordKnownSession, isKnownSession } from '../services/known-sessions.js';
35
+ import { resolveBudgetScope, evaluateBudget, recordAndEvaluate } from '../services/budget-awareness.js';
36
+ import { sendMessage } from './send-message.js';
37
+ import { registerPending } from '../services/pending-responses.js';
38
+ import { isMaxTurnsResponse } from '../providers/provider.js';
39
+ import { preflightCheck } from '../services/preflight-check.js';
25
40
  export const executePromptSchema = z.object({
26
41
  ...memberIdentifier,
27
42
  prompt: z.string().describe('The prompt to send to the LLM on the remote member'),
28
- resume: z.boolean().default(true).describe('Resume the previous session if one exists (default: true)'),
29
- timeout_s: z.number().default(300).describe('Inactivity timeout in seconds — the command is killed after this many seconds without any stdout/stderr output (default: 300s / 5 minutes)'),
30
- max_total_s: z.number().optional().describe('Hard ceiling in seconds — the command is killed after this total elapsed time regardless of activity. If omitted, there is no total time limit.'),
43
+ session_id: z.string().optional().describe('Shorthand for explicit session resume. Equivalent to resume: "<session_id>". If provided, takes precedence over resume.'),
44
+ resume: z.union([z.boolean(), z.string()]).default(true).describe('Session-resume control (default: true). ' +
45
+ 'true = best-effort resume of the member\'s stored last session (a stale/unknown stored session transparently falls back to a fresh session). ' +
46
+ 'false = always start a fresh session. ' +
47
+ 'A session-id STRING = EXPLICIT resume of exactly that session, preferred over the member\'s stored session -- the caller asserts this prompt depends on that session\'s prior context, so an unknown/expired id is a TERMINAL error ' +
48
+ '(structured {isError, reason: "session_not_found"}, NO LLM call, and NO fresh-session fallback) rather than a silent wrong-context dispatch.'),
49
+ timeout_s: z.number().default(300).describe('Inactivity timeout in seconds -- the command is killed after this many seconds without any stdout/stderr output (default: 300s / 5 minutes)'),
50
+ max_total_s: z.number().optional().describe('Hard ceiling in seconds -- the command is killed after this total elapsed time regardless of activity. If omitted, there is no total time limit.'),
31
51
  max_turns: z.number().min(1).max(500).optional().describe('Max turns for claude -p (default: 50)'),
32
- dangerously_skip_permissions: z.boolean().default(false).describe('DEPRECATED: use update_member(unattended="dangerous") instead. This field is ignored and will be removed in a future version.'),
33
- model: z.string().optional().describe('Model tier ("cheap", "standard", "premium") or a specific model ID for power users. Prefer tier names — the server resolves them to the correct model per provider. If omitted, defaults to the standard tier. Applies to both new and resumed sessions.'),
34
- });
35
- function buildFailureMessage(agentName, result, provider) {
52
+ model: z.string().optional().describe('Model tier ("cheap", "standard", "premium") or a specific model ID for power users. Prefer tier names -- the server resolves them to the correct model per provider. If omitted, defaults to the standard tier. Applies to both new and resumed sessions.'),
53
+ substitutions: z.record(z.string(), z.string()).optional().describe('Optional map of token name to replacement value. ' +
54
+ 'When provided, every occurrence of {{name}} in the prompt is replaced before the prompt is staged on the member. ' +
55
+ 'Keys must match [A-Za-z_][A-Za-z0-9_]*. Missing tokens cause the call to fail with no CLI invoked. ' +
56
+ 'Extra keys are silently ignored. Values are never logged.'),
57
+ agent: z.string().optional().describe('Optional agent name to activate. ' +
58
+ 'For Claude: invokes claude --agent <name>. ' +
59
+ 'For Gemini: prepends @<name> to the prompt on every dispatch. ' +
60
+ 'For AGY: prepends @<name> to the prompt on every dispatch (same as Gemini). ' +
61
+ 'Substitution runs before the @<name> prepend. ' +
62
+ 'Agent file must exist at the provider-specific path on the member: ' +
63
+ 'Claude: <workFolder>/.claude/agents/<name>.md or ~/.claude/agents/<name>.md; ' +
64
+ 'Gemini: <workFolder>/.gemini/agents/<name>.md or ~/.gemini/agents/<name>.md; ' +
65
+ 'AGY: <workFolder>/.gemini/antigravity-cli/agents/<name>.md or ~/.gemini/antigravity-cli/agents/<name>.md; ' +
66
+ 'OpenCode: <workFolder>/.opencode/agents/<name>.md or ~/.config/opencode/agents/<name>.md -- ' +
67
+ 'the call is rejected with a clear error if neither is present.'),
68
+ sprint_id: z.string().optional().describe('Opaque identity of the sprint issuing this dispatch. ' +
69
+ 'When provided, the server-side member-reservation check (see reservedBy below) ' +
70
+ 'compares this value directly against the reservation instead of falling back to ' +
71
+ 'this server process\'s APRA_FLEET_SPRINT_ID env var -- the same per-call value ' +
72
+ 'the caller passed to member_reservation reserve/release. Callers that never set a ' +
73
+ 'reservation, or that reserved and dispatch in the same process, should omit this; ' +
74
+ 'omitting it preserves the pre-existing env-var-based behavior exactly.'),
75
+ expected_context_tokens: z.number().positive().optional().describe('Optional estimate of how many tokens this dispatch will add ' +
76
+ 'to the target session\'s context. When set (or context_size is set), the server ' +
77
+ 'compares it against the session\'s remaining context-window headroom BEFORE ' +
78
+ 'invoking the LLM: too little headroom rejects the call with ' +
79
+ '{reason: "insufficient_context_headroom", detail: {demand, headroom, window}} and no ' +
80
+ 'spawn; a fit that lands inside the safety margin still proceeds but attaches a ' +
81
+ 'structured contextWarning. Wins over context_size when both are set. Omitting both ' +
82
+ 'fields disables the check entirely -- pre-existing behavior is unchanged.'),
83
+ context_size: z.enum(['S', 'M', 'L']).optional().describe('Optional size-bucket shorthand for expected_context_tokens: ' +
84
+ 'S/M/L map to configured token estimates (fleet defaults, overridable via ' +
85
+ 'config.json\'s contextAdmission.sizeBucketTokens). Ignored when expected_context_tokens ' +
86
+ 'is also set. The auto-sprint engine supplies this from the dispatched task\'s size ' +
87
+ 'metadata.'),
88
+ }).strict();
89
+ function buildFailureMessage(agentName, result, provider, parsed) {
36
90
  const output = result.stderr || result.stdout;
37
- const category = provider.classifyError(output);
91
+ // apra-fleet-p4f.2: prefer the already-parsed structured signal over the
92
+ // stderr/stdout regex scan -- a max_turns-exhausted transcript can still
93
+ // have auth-like noise in stderr (a stale warning, an unrelated retry
94
+ // message, etc.) that would otherwise misclassify it as an auth failure.
95
+ const category = isMaxTurnsResponse(parsed) ? 'max_turns' : provider.classifyError(output);
96
+ if (category === 'max_turns') {
97
+ return `[FAIL] Prompt on "${agentName}" was stopped after exhausting its turn limit (max_turns), not a genuine failure -- the model ran out of turns before finishing:
98
+ ${output}`;
99
+ }
38
100
  return category === 'auth'
39
101
  ? authErrorAdvice(agentName)
40
- : `❌ Prompt failed on "${agentName}":
102
+ : `[FAIL] Prompt failed on "${agentName}":
41
103
  ${output}`;
42
104
  }
43
105
  const SERVER_RETRY_DELAY_MS = 5000;
106
+ // A prompt written whole into a single remote exec command line can exceed
107
+ // the SSH exec channel's / Windows CreateProcess's command-line ceiling once
108
+ // the Windows path's UTF-16LE + base64 -EncodedCommand encoding (~2.67x
109
+ // inflation) is applied -- observed live (2026-07-30, fleet-win-dev1): a
110
+ // Review dispatch embedding full `bd show --json` output (description +
111
+ // acceptance criteria) for 5 beads produced a garbled "Unable to exec ..."
112
+ // response instead of real review output, because the encoded command line
113
+ // was too long for the remote shell to exec at all. Doer dispatches (small,
114
+ // just branch + bead ids) never hit this; only the larger Review-phase
115
+ // prompts do -- and only on Windows, where the encoding overhead is worst.
116
+ // Chunking keeps every single exec command line bounded regardless of total
117
+ // prompt size, on both OS paths (POSIX has a much higher real-world ceiling
118
+ // but shares the same underlying single-exec-command-line hazard).
119
+ const REMOTE_PROMPT_CHUNK_CHARS = 4000;
120
+ function chunkContent(content) {
121
+ const chunks = [];
122
+ for (let i = 0; i < content.length; i += REMOTE_PROMPT_CHUNK_CHARS) {
123
+ chunks.push(content.slice(i, i + REMOTE_PROMPT_CHUNK_CHARS));
124
+ }
125
+ return chunks.length > 0 ? chunks : [''];
126
+ }
44
127
  async function writePromptFile(agent, strategy, promptFilePath, content) {
45
128
  if (agent.agentType === 'local') {
46
129
  fs.writeFileSync(promptFilePath, content, 'utf-8');
@@ -49,24 +132,41 @@ async function writePromptFile(agent, strategy, promptFilePath, content) {
49
132
  const agentOs = getAgentOS(agent);
50
133
  const promptFileName = path.basename(promptFilePath);
51
134
  const remoteDir = path.dirname(promptFilePath);
135
+ const chunks = chunkContent(content);
52
136
  if (agentOs === 'windows') {
53
137
  const escapedFolder = escapeWindowsArg(remoteDir);
54
- const psScript = `New-Item -Path '${escapedFolder}' -ItemType Directory -Force | Out-Null; Set-Location "${escapedFolder}"; Set-Content -Path "${promptFileName}" -Value '${content.replace(/'/g, "''")}' -NoNewline -Encoding UTF8`;
55
- const encoded = Buffer.from(psScript, 'utf16le').toString('base64');
56
- await strategy.execCommand(`powershell -EncodedCommand ${encoded}`);
138
+ for (let i = 0; i < chunks.length; i++) {
139
+ const setup = i === 0 ? `New-Item -Path '${escapedFolder}' -ItemType Directory -Force | Out-Null; ` : '';
140
+ const cmdlet = i === 0 ? 'Set-Content' : 'Add-Content';
141
+ const psScript = `${setup}Set-Location "${escapedFolder}"; ${cmdlet} -Path "${promptFileName}" -Value '${chunks[i].replace(/'/g, "''")}' -NoNewline -Encoding UTF8`;
142
+ const encoded = Buffer.from(psScript, 'utf16le').toString('base64');
143
+ // eslint-disable-next-line no-await-in-loop -- each chunk must land before the next appends
144
+ await strategy.execCommand(`powershell -EncodedCommand ${encoded}`);
145
+ }
57
146
  }
58
147
  else {
59
- const b64 = Buffer.from(content).toString('base64');
60
148
  const escapedFolder = escapeDoubleQuoted(remoteDir);
61
- await strategy.execCommand(`mkdir -p "${escapedFolder}" && cd "${escapedFolder}" && echo '${b64}' | base64 -d > ${promptFileName}`);
149
+ for (let i = 0; i < chunks.length; i++) {
150
+ const b64 = Buffer.from(chunks[i]).toString('base64');
151
+ const redirect = i === 0 ? '>' : '>>';
152
+ const mkdirPrefix = i === 0 ? `mkdir -p "${escapedFolder}" && ` : '';
153
+ // eslint-disable-next-line no-await-in-loop -- each chunk must land before the next appends
154
+ await strategy.execCommand(`${mkdirPrefix}cd "${escapedFolder}" && echo '${b64}' | base64 -d ${redirect} ${promptFileName}`);
155
+ }
62
156
  }
63
157
  }
64
- async function deletePromptFile(agent, strategy, promptFilePath) {
158
+ async function deletePromptFile(agent, strategy, promptFilePath, extraPaths = []) {
65
159
  if (agent.agentType === 'local') {
66
160
  try {
67
161
  fs.unlinkSync(promptFilePath);
68
162
  }
69
163
  catch { /* ignore */ }
164
+ for (const p of extraPaths) {
165
+ try {
166
+ fs.unlinkSync(p);
167
+ }
168
+ catch { /* ignore */ }
169
+ }
70
170
  return;
71
171
  }
72
172
  const agentOs = getAgentOS(agent);
@@ -80,7 +180,10 @@ async function deletePromptFile(agent, strategy, promptFilePath) {
80
180
  }
81
181
  else {
82
182
  const escapedFolder = escapeDoubleQuoted(remoteDir);
83
- await strategy.execCommand(`cd "${escapedFolder}" && rm -f ${promptFileName}`).catch(() => { });
183
+ // apra-fleet-6z8.1: the durable stdout mirror is cleaned up in the SAME
184
+ // round trip as the prompt file -- no extra exec per dispatch.
185
+ const extras = extraPaths.map(p => ` "${escapeDoubleQuoted(p)}"`).join('');
186
+ await strategy.execCommand(`cd "${escapedFolder}" && rm -f ${promptFileName}${extras}`).catch(() => { });
84
187
  }
85
188
  }
86
189
  export function resolveModelForTier(agent, tier, provider) {
@@ -91,7 +194,29 @@ export function resolveModelForTier(agent, tier, provider) {
91
194
  }
92
195
  return provider.modelForTier(tier);
93
196
  }
197
+ /**
198
+ * apra-fleet-b4g.6: the auto-harvest dispatch (below) is a server-internal
199
+ * kb_harvest call, not an LLM-supplied repo_remote_url like the other kb_*
200
+ * tools' hot paths (apra-fleet-b4g.1). Re-exported from
201
+ * services/member-remote-url.ts, which documents the no-guessing rule and is
202
+ * shared with member_detail (the fleet-sprint engine's only source for it).
203
+ */
204
+ export { knownRepoRemoteUrl };
94
205
  const SECURE_TOKEN_RE = /\{\{secure\.[a-zA-Z0-9_-]{1,64}\}\}/;
206
+ /**
207
+ * The sprint id this server process dispatches on behalf of, or undefined when
208
+ * run outside a sprint (e.g. a manual cli.mjs invocation). Sourced from
209
+ * APRA_FLEET_SPRINT_ID, which the auto-sprint spawner stamps into the per-sprint
210
+ * server's environment (apra-fleet-eft.10.3). Read on every dispatch so a
211
+ * reservation set/cleared mid-run is observed without a restart.
212
+ */
213
+ export function currentSprintId() {
214
+ const raw = process.env.APRA_FLEET_SPRINT_ID;
215
+ if (typeof raw !== 'string')
216
+ return undefined;
217
+ const trimmed = raw.trim();
218
+ return trimmed.length > 0 ? trimmed : undefined;
219
+ }
95
220
  export const inFlightAgents = new Set();
96
221
  // Member ids whose remote agent files (planner.md, doer.md, _shared/, schemas/, ...)
97
222
  // have already been probed/refreshed this server process uptime -- the #336
@@ -128,17 +253,200 @@ async function ensureAgentFilesProvisioned(agent) {
128
253
  }
129
254
  }
130
255
  // All exit paths from executePrompt clear busy state via the finally block (inFlightAgents.delete + writeStatusline):
131
- // (a) normal success: result.code === 0 → finally sets idle and removes agent from inFlight
132
- // (b) non-zero exit from execCommand: result.code !== 0 → finally sets idle and removes agent from inFlight
133
- // (c) exception in try block (auth, network, crash) → catch records error type; finally sets offline or idle
134
- // (d) AbortSignal/MCP client cancellation → abortHandler kills PID, execCommand resolves, finally clears
135
- // (e) stale session retry → retried without session ID; finally clears on success or failure
136
- // (f) server overload retry → retried after delay; finally clears on success or failure
137
- // (g) early returns before inFlightAgents.add: busy state never entered
256
+ // (a) normal success: result.code === 0 -> finally sets idle and removes agent from inFlight
257
+ // (b) non-zero exit from execCommand: result.code !== 0 -> finally sets idle and removes agent from inFlight
258
+ // (c) exception in try block (auth, network, crash) -> catch records error type; finally sets offline or idle
259
+ // (d) AbortSignal/MCP client cancellation -> abortHandler kills PID, execCommand resolves, finally clears
260
+ // (e) stale session retry -> retried without session ID; finally clears on success or failure
261
+ // (f) server overload retry -> retried after delay; finally clears on success or failure
262
+ // (g) early returns before inFlightAgents.add (busy-rejection, reservation
263
+ // conflict, no-LLM member): busy state never entered
264
+ // (h) preflight: the lock is claimed just before the preflight await (moved
265
+ // here from the interactive/subprocess split further below, to close the
266
+ // busy-check-to-lock-claim race window -- that split no longer calls
267
+ // .add() itself, it relies on the claim made here). Both the {ok: false}
268
+ // result path and preflightCheck() itself throwing release the lock
269
+ // explicitly inline, since both return/rethrow before reaching any
270
+ // finally block below
271
+ /**
272
+ * apra-fleet-idb: liveness probe for a busy-locked member's backing process.
273
+ * An inFlightAgents entry can outlive the process it was guarding -- a child
274
+ * reaped without its 'close'/'error' handler ever firing (e.g. a hung SSH
275
+ * channel that never signals exit, so clearStoredPid never runs), or an
276
+ * interactive member's underlying claude process dying/disconnecting after
277
+ * its session was registered -- permanently wedging the member: every future
278
+ * dispatch would keep returning busy even though fleet_status's own
279
+ * independent live-process check (src/tools/check-status.ts's
280
+ * fleetProcessCheck) would report idle. Returns the confirmed-dead pid (used
281
+ * only for the release warning) when the lock should self-heal, or undefined
282
+ * when the member is genuinely busy.
283
+ *
284
+ * Conservative on ambiguity, deliberately: NO captured pid at all (neither an
285
+ * interactive session pid nor a subprocess pid) is treated as still busy, not
286
+ * as evidence of staleness -- a dispatch that has not reached its pid-capture
287
+ * step yet must never be raced by a concurrent "self-heal" attempt. Only a
288
+ * DEFINITIVE dead-pid reading releases the lock.
289
+ */
290
+ async function findDeadLockPid(agent, workspaceId) {
291
+ // Interactive sessions are always local (register_member's interactive
292
+ // bootstrap is gated to isLocal members) -- the same local
293
+ // process.kill(pid, 0) probe the eft.28.1 dead-session guard uses further
294
+ // below applies directly here. Falls back to the durable lastKnownPid
295
+ // anchor exactly like that guard does, so a disconnected-then-reconnected
296
+ // session (pid lost on the live SessionState) is still checkable.
297
+ const session = sessionRegistry.get(workspaceId, agent.id);
298
+ const interactivePid = session?.pid ?? sessionRegistry.lastKnownPid(workspaceId, agent.id);
299
+ if (interactivePid !== undefined && !isPidAlive(interactivePid)) {
300
+ return interactivePid;
301
+ }
302
+ // Subprocess dispatch pid (local strategy or remote-over-SSH/relay). A
303
+ // remote pid lives in a DIFFERENT machine's pid namespace -- process.kill()
304
+ // -based isPidAlive is meaningless there (it would almost always read back
305
+ // ESRCH for a pid that simply does not exist on THIS machine, wrongly
306
+ // declaring a genuinely-alive remote session dead and racing a duplicate
307
+ // dispatch onto it). Probe it the same way orphan-recovery's lease-of-life
308
+ // gate does instead: a fresh, independent SSH round trip, never the
309
+ // (possibly wedged) channel that produced the stale lock.
310
+ const subprocessPid = getStoredPid(agent.id);
311
+ if (subprocessPid !== undefined) {
312
+ const alive = agent.agentType === 'local'
313
+ ? isPidAlive(subprocessPid)
314
+ : await isRemoteProcessAlive(getStrategy(agent), subprocessPid, getAgentOS(agent));
315
+ if (!alive)
316
+ return subprocessPid;
317
+ }
318
+ return undefined;
319
+ }
320
+ // apra-fleet-eft.28.1: how often the interactive wait re-checks that the
321
+ // target member's claude process is still alive. This is the dispatch-level
322
+ // liveness/no-progress bound -- the member's process can die AFTER the
323
+ // pre-dispatch liveness check above (e.g. mid-turn, right after send_message
324
+ // lands) with no further signal ever arriving, so the wait for
325
+ // respond_to_message must not be the sole backstop up to the full timeout_s
326
+ // (which can be 3600s). A short, fixed poll interval keeps the surfaced
327
+ // error well under the playbook's <10min budget regardless of how large
328
+ // timeout_s is.
329
+ const INTERACTIVE_LIVENESS_POLL_MS = 5000;
330
+ /** Raised by waitForInteractiveResponse when the member's claude process is
331
+ * confirmed dead while a response is still pending -- distinguished from a
332
+ * plain "nobody answered in time" timeout so the caller can surface a more
333
+ * actionable terminal error. */
334
+ class InteractiveSessionDiedError extends Error {
335
+ }
336
+ /**
337
+ * Waits for the member's respond_to_message reply, racing that wait against
338
+ * a periodic PID-liveness poll of the same session. Resolves/rejects as soon
339
+ * as either side settles -- a dead PID short-circuits the wait instead of
340
+ * letting it run out the full timeoutMs.
341
+ */
342
+ function waitForInteractiveResponse(agent, workspaceId, msgid, timeoutMs, scope) {
343
+ return new Promise((resolve, reject) => {
344
+ let settled = false;
345
+ const poller = setInterval(() => {
346
+ if (settled)
347
+ return;
348
+ const session = sessionRegistry.get(workspaceId, agent.id);
349
+ // apra-fleet-eft.50.1: fall back to the durable launch-pid anchor when the
350
+ // live session lost its pid on a reconnect, so this in-flight poll can
351
+ // still detect a dead persistent process on a retry that reused the
352
+ // reconnected session -- not only when the session still carries its pid.
353
+ const pid = session?.pid ?? sessionRegistry.lastKnownPid(workspaceId, agent.id);
354
+ if (pid !== undefined && !isPidAlive(pid)) {
355
+ settled = true;
356
+ clearInterval(poller);
357
+ scope.info(`[interactive] member process pid=${pid} died while awaiting a response -- aborting wait`);
358
+ sessionRegistry.unregister(workspaceId, agent.id);
359
+ reject(new InteractiveSessionDiedError(`member claude process (pid ${pid}) died while waiting for a response`));
360
+ }
361
+ }, INTERACTIVE_LIVENESS_POLL_MS);
362
+ registerPending(msgid, timeoutMs).then((res) => {
363
+ if (settled)
364
+ return;
365
+ settled = true;
366
+ clearInterval(poller);
367
+ resolve(res);
368
+ }, (err) => {
369
+ if (settled)
370
+ return;
371
+ settled = true;
372
+ clearInterval(poller);
373
+ reject(err);
374
+ });
375
+ });
376
+ }
377
+ /**
378
+ * Interactive routing (apra-fleet-2xs.8): pushes the prompt to a connected
379
+ * member's live session via send_message and waits for that member to call
380
+ * respond_to_message with the matching reply_to. No subprocess, no SSH, no
381
+ * prompt file, no stall detector on a log file -- the session is a
382
+ * long-lived interactive process, not something this call spawns or owns.
383
+ */
384
+ async function executePromptInteractive(agent, renderedPrompt, input, workspaceId, heuristicWarningSuffix) {
385
+ const timeoutS = input.timeout_s ?? 300;
386
+ const scope = new LogScope('execute_prompt', `[interactive] timeout=${timeoutS}s ${truncateForLog(maskSecrets(input.prompt))}`, agent);
387
+ const sendResult = await sendMessage({ member_id: agent.id, content: renderedPrompt }, workspaceId);
388
+ const parsed = JSON.parse(sendResult);
389
+ if (parsed.error) {
390
+ scope.abort(`send failed: ${parsed.error}`);
391
+ return `[FAIL] Failed to deliver prompt to "${agent.friendlyName}" (interactive session): ${parsed.error}`;
392
+ }
393
+ try {
394
+ const response = await waitForInteractiveResponse(agent, workspaceId, parsed.msgid, timeoutS * 1000, scope);
395
+ scope.ok('interactive response received');
396
+ let output = `[RESULT] Response from ${agent.friendlyName}:\n\n${response}`;
397
+ if (heuristicWarningSuffix)
398
+ output += heuristicWarningSuffix;
399
+ return output;
400
+ }
401
+ catch (err) {
402
+ if (err instanceof InteractiveSessionDiedError) {
403
+ scope.abort(err.message);
404
+ return `[ERROR] "${agent.friendlyName}"'s interactive claude process died while this dispatch was waiting for a response (${err.message}). The prompt was delivered but nothing will ever answer it -- re-launch the member (re-run register_member) before retrying.`;
405
+ }
406
+ scope.abort(`interactive timeout: ${err.message}`);
407
+ // apra-fleet-eft.74.2: self-heal on interactive-route timeout. A session
408
+ // with no verifiable live pid that just timed out is a phantom channel
409
+ // (the eft.74 wedge): re-routing the NEXT execute_prompt to it would
410
+ // silently re-burn the full timeout_s, forever (observed 5x 900s). Evict
411
+ // it here so the next dispatch finds no interactive session and falls back
412
+ // to the subprocess path. A session that DOES have a verifiably live pid is
413
+ // left registered -- the member is alive, merely slow, so a later dispatch
414
+ // may legitimately reach it interactively again.
415
+ const timedOutSession = sessionRegistry.get(workspaceId, agent.id);
416
+ const timedOutPid = timedOutSession?.pid ?? sessionRegistry.lastKnownPid(workspaceId, agent.id);
417
+ const hasVerifiableLivePid = timedOutPid !== undefined && isPidAlive(timedOutPid);
418
+ if (!hasVerifiableLivePid) {
419
+ sessionRegistry.unregister(workspaceId, agent.id);
420
+ scope.info(`[interactive] timed-out session for "${agent.friendlyName}" has no verifiable live pid (pid=${timedOutPid ?? 'none'}) -- evicting so the next dispatch falls back to subprocess`);
421
+ }
422
+ return `[FAIL] Timed out waiting for "${agent.friendlyName}" to respond (interactive session, ${timeoutS}s). The prompt was delivered; the member may still respond late, but this call has given up waiting.`;
423
+ }
424
+ }
138
425
  export async function executePrompt(input, extra) {
139
426
  if (SECURE_TOKEN_RE.test(input.prompt)) {
140
427
  return 'error: execute_prompt prompt contains {{secure.NAME}} token. Secrets must never be passed to LLM prompts. Use execute_command with {{secure.NAME}} instead.';
141
428
  }
429
+ // Validate substitution keys before any I/O or member resolution.
430
+ if (input.substitutions !== undefined) {
431
+ const keyCheck = validateSubstitutionKeys('execute_prompt', input.substitutions);
432
+ if (!keyCheck.ok)
433
+ return keyCheck.error;
434
+ }
435
+ // Apply substitutions to the prompt string (or emit heuristic warning when omitted).
436
+ let renderedPrompt = input.prompt;
437
+ let heuristicWarningSuffix = '';
438
+ if (input.substitutions !== undefined) {
439
+ const result = applySubstitutions('execute_prompt', [{ label: 'prompt', content: input.prompt }], input.substitutions);
440
+ if (!result.ok)
441
+ return result.error;
442
+ renderedPrompt = result.outputs[0];
443
+ }
444
+ else {
445
+ const warnResult = applySubstitutions('execute_prompt', [{ label: 'prompt', content: input.prompt }], undefined);
446
+ if (warnResult.ok && warnResult.warning) {
447
+ heuristicWarningSuffix = `\n\n[WARN] ${warnResult.warning}`;
448
+ }
449
+ }
142
450
  const promptFileName = `.fleet-task.md`;
143
451
  const agentOrError = resolveMember(input.member_id, input.member_name);
144
452
  if (typeof agentOrError === 'string')
@@ -148,15 +456,247 @@ export async function executePrompt(input, extra) {
148
456
  agent = await ensureCloudReady(agentOrError); // auto-start if stopped
149
457
  }
150
458
  catch (err) {
151
- return `❌ Failed to execute prompt on "${agentOrError.friendlyName}": ${err.message}`;
459
+ return `[FAIL] Failed to execute prompt on "${agentOrError.friendlyName}": ${err.message}`;
460
+ }
461
+ // Server-side member reservation enforcement (apra-fleet-eft.10.3): a member
462
+ // reserved by a DIFFERENT sprint may not be dispatched to. Mirrors the
463
+ // inFlightAgents busy-rejection error path -- the error names the owning
464
+ // sprint. A dispatch from the owning sprint (matching APRA_FLEET_SPRINT_ID)
465
+ // or against an unreserved member proceeds unchanged, so behavior with no
466
+ // reservations is identical to before. Checked before any busy state is
467
+ // entered, closing the manual-CLI bypass the ledger alone could not.
468
+ //
469
+ // apra-fleet-eft.29.1: currentSprintId() alone (APRA_FLEET_SPRINT_ID on
470
+ // THIS server process) is only correct when the launcher spawns a private
471
+ // per-sprint server and stamps its env -- it is not for the eft.7.1
472
+ // CLI/shared-fleet-server path, where cli.mjs attaches to an existing,
473
+ // long-lived HTTP singleton it never spawns and so can never stamp. There,
474
+ // APRA_FLEET_SPRINT_ID is unset (or stale from a different run), so a
475
+ // member reserved by ITS OWN owning sprint was rejected as if from another
476
+ // sprint. Prefer the per-call `sprint_id` -- the exact same opaque token
477
+ // the caller already passed to member_reservation reserve/release (see
478
+ // createMemberReservationClient / sprintMutexId in
479
+ // packages/apra-fleet-se/fleet-sprint/runner.js) -- and fall back to
480
+ // currentSprintId() only when the caller omits it, so existing
481
+ // env-var-based callers/tests are unaffected.
482
+ const owningSprint = agent.reservedBy ?? null;
483
+ const dispatchSprintId = input.sprint_id ?? currentSprintId();
484
+ if (owningSprint && owningSprint !== dispatchSprintId) {
485
+ return {
486
+ text: `[-] Member "${agent.friendlyName}" is reserved by sprint "${owningSprint}" and cannot accept a dispatch from another sprint. Wait for that sprint to release it, or force-release the reservation to recover.`,
487
+ structuredContent: { isError: true, reason: 'reserved' },
488
+ };
152
489
  }
153
490
  if (inFlightAgents.has(agent.id)) {
154
- return `❌ execute_prompt is already running for "${agent.friendlyName}". Wait for the current call to finish before sending another.`;
491
+ // apra-fleet-idb: before honoring the busy rejection, verify the locked
492
+ // session actually still has a live backing process -- see
493
+ // findDeadLockPid's docstring for the full rationale. This is what keeps
494
+ // fleet_status (which decides busy/idle from its own independent live
495
+ // process check) and this dispatch gate from ever disagreeing: a stale
496
+ // lock self-heals here instead of permanently wedging the member.
497
+ const staleLockPid = await findDeadLockPid(agent, getTokenIssuer().workspaceId());
498
+ if (staleLockPid !== undefined) {
499
+ logWarn('busy_lock', `orphaned busy-lock for "${agent.friendlyName}" -- locked pid=${staleLockPid} is confirmed dead; releasing the stale lock and proceeding with this dispatch instead of rejecting it as busy`, agent);
500
+ inFlightAgents.delete(agent.id);
501
+ getStallDetector().remove(agent.id);
502
+ writeStatusline(new Map([[agent.id, 'idle']]));
503
+ }
504
+ else {
505
+ return {
506
+ text: `[FAIL] execute_prompt is already running for "${agent.friendlyName}". Wait for the current call to finish before sending another.`,
507
+ structuredContent: { isError: true, reason: 'busy' },
508
+ };
509
+ }
155
510
  }
511
+ // No-LLM members (apra-fleet-us9.14) are plain command executors -- neither
512
+ // execute_prompt mode applies (there is no LLM to prompt in either a
513
+ // subprocess or an interactive session). Rejected here, before any busy
514
+ // state is entered, rather than relying on NoneProvider's methods to throw
515
+ // deeper in either dispatch path.
516
+ if (agent.llmProvider === 'none') {
517
+ return `[FAIL] "${agent.friendlyName}" has no LLM provider (llm_provider: "none") -- it is a plain command executor. Use execute_command instead.`;
518
+ }
519
+ // Claim the busy lock BEFORE the preflight await, not after (as it
520
+ // originally was further below at the interactive/subprocess split).
521
+ // preflightCheck can take up to ~30s on a cache miss; leaving the busy-check
522
+ // (line ~546) and the lock claim ~150 lines apart left a window where two
523
+ // near-simultaneous dispatches to the same member could both pass the busy
524
+ // check (neither had claimed the lock yet), both await preflight, and both
525
+ // proceed to double-dispatch. Every return path from here to the
526
+ // interactive/subprocess split below (currently only the preflight-failure
527
+ // return immediately following) must release this lock explicitly, since
528
+ // it now returns AFTER the lock is claimed instead of before.
156
529
  inFlightAgents.add(agent.id);
530
+ // Peek at session state early so the preflight check can skip interactive
531
+ // members whose dispatch routes through a live MCP push channel, not SSH.
532
+ const earlyWorkspaceId = getTokenIssuer().workspaceId();
533
+ const earlySession = sessionRegistry.get(earlyWorkspaceId, agent.id);
534
+ const isChannelCapable = !!earlySession?.channelCapable;
535
+ // Pre-dispatch readiness check (apra-fleet preflight-check): verify
536
+ // connectivity and LLM auth BEFORE the expensive prompt dispatch
537
+ // (writePromptFile + CLI invocation). Catches expired OAuth, missing
538
+ // credentials, and offline members in <1s instead of burning a full
539
+ // round trip. Local members and interactive sessions are excluded
540
+ // (local shares this machine's credentials; interactive sessions have
541
+ // their own liveness probes). The check is cached for 60s so
542
+ // back-to-back dispatches do not add latency.
543
+ if (agent.agentType !== 'local' && !isChannelCapable) {
544
+ let preflight;
545
+ try {
546
+ preflight = await preflightCheck(agent);
547
+ }
548
+ catch (err) {
549
+ // preflightCheck's own synchronous prologue (getStrategy/getProvider)
550
+ // and its internal exec calls are not fully guarded -- if it throws
551
+ // instead of resolving {ok: false}, the lock claimed above would
552
+ // otherwise leak forever (no pid captured yet for findDeadLockPid's
553
+ // stale-lock self-heal to recognize). Release and propagate unchanged
554
+ // -- this preserves the exact same exception the caller would have
555
+ // seen before the lock was claimed this early.
556
+ inFlightAgents.delete(agent.id);
557
+ throw err;
558
+ }
559
+ if (!preflight.ok) {
560
+ // R2-F5: use preflight-specific reason codes so fleet-sprint can
561
+ // distinguish pre-dispatch failures from in-dispatch ones and avoid
562
+ // inappropriate self-heal loops (e.g. re-provisioning auth when the
563
+ // member is simply offline).
564
+ const preflightReason = preflight.code === 'offline' ? 'preflight_offline'
565
+ : preflight.code === 'auth_expired' ? 'preflight_auth_expired'
566
+ : preflight.code === 'auth_missing' ? 'preflight_auth_missing'
567
+ : 'dispatch_failed';
568
+ // Release the lock claimed above -- this return happens before the
569
+ // interactive/subprocess split's own add+finally cleanup ever runs.
570
+ inFlightAgents.delete(agent.id);
571
+ return {
572
+ text: `[FAIL] Pre-dispatch check failed for "${agent.friendlyName}": ${preflight.reason}`,
573
+ structuredContent: {
574
+ isError: true,
575
+ reason: preflightReason,
576
+ },
577
+ };
578
+ }
579
+ }
580
+ // Interactive routing (apra-fleet-2xs.8/us9.8, docs/cloud-fleet-architecture.md
581
+ // section 6): if this member has a live MCP session connected right now,
582
+ // route via send_message + wait-for-response instead of spawning a
583
+ // subprocess. Decided tier-2-locally against THIS machine's session
584
+ // registry only (never caller/hub-side state, per apra-fleet-2xs.8's own
585
+ // scope note) -- so behavior is unaffected by whether execute_prompt is
586
+ // invoked directly (Phase 1) or relayed through a future hub. Falls
587
+ // through to the unchanged subprocess/SSH path below for every member
588
+ // without a live session (the common case today, and always for members
589
+ // that never opt into an interactive session).
590
+ //
591
+ // Gated by capability, not provider name (apra-fleet-cqa, eft.74 follow-up):
592
+ // mode (b) -- server-push mid-session prompt injection -- was POC-proven on
593
+ // Claude via the provider-branded `notifications/claude/channel` capability
594
+ // (apra-fleet-us9.9's survey, docs/interactive-injection-provider-survey.md),
595
+ // but the routing decision itself must be provider-agnostic: whatever the
596
+ // provider, a session is only an interactive-routing candidate if it
597
+ // actually declared that capability at MCP initialize time (recorded as
598
+ // SessionState.channelCapable below). Gemini/Codex are confirmed [FAIL]
599
+ // today (no equivalent push mechanism) and so never end up channelCapable in
600
+ // practice, but that is a fact about what each provider adapter currently
601
+ // advertises, not a name-based pre-filter here -- any provider that
602
+ // implements the same MCP channel capability is picked up automatically. A
603
+ // member CAN still have a live sessionRegistry entry (registerMcpEndpoint
604
+ // gives it basic MCP tool access, apra-fleet-fnz.1-3) without that meaning
605
+ // it can receive or act on this push -- routing to it anyway would silently
606
+ // spend the full timeout_s waiting for a response that can never arrive.
607
+ // R2-F3: re-query session registry after the preflight await (10-20s) so
608
+ // interactive routing sees sessions that became channelCapable during that
609
+ // window, rather than using the stale pre-preflight snapshot.
610
+ const workspaceId = getTokenIssuer().workspaceId();
611
+ const rawSession = sessionRegistry.get(workspaceId, agent.id);
612
+ // apra-fleet-eft.74.1: interactive routing requires the EXPLICIT channel
613
+ // opt-in handshake, not mere JWT registration. A plain subprocess
614
+ // connect-back (a Doer that opened an MCP tool-access session with a member
615
+ // JWT but never declared the `claude/channel` capability) registers a live
616
+ // `server` here, yet can never receive the `notifications/claude/channel`
617
+ // push -- routing to it would enqueue a message nothing reads and burn the
618
+ // full timeout_s on every later dispatch (the eft.74 wedge). Only a
619
+ // channel-capable session is an interactive-routing candidate; anything else
620
+ // (including that Doer's live tool session, which must be left untouched)
621
+ // falls through to the unchanged subprocess path below.
622
+ let interactiveSession = rawSession?.channelCapable ? rawSession : undefined;
623
+ // apra-fleet-eft.50.1: resolve the pid to test FRESH on every dispatch
624
+ // (never cached from a prior attempt) and fall back to the durable
625
+ // launch-pid anchor when this reused session lost its own pid on a
626
+ // reconnect. This is what re-arms the dead-session guard on a retry attempt
627
+ // 2+ exactly as on attempt 1: the specific eft.50 ordering (attempt 1 fails
628
+ // clean, attempt 2 targets a now-dead reconnected session) used to slip
629
+ // through here because the reconnected SessionState had pid=undefined, so the
630
+ // check below was skipped and the caller hung on the dead channel.
631
+ const interactivePid = interactiveSession?.pid
632
+ ?? sessionRegistry.lastKnownPid(workspaceId, agent.id);
633
+ if (interactiveSession?.server && interactivePid !== undefined && !isPidAlive(interactivePid)) {
634
+ // apra-fleet-eft.28.1/eft.28.5: never reuse a persistent interactive
635
+ // session whose underlying member claude process has already died. Before
636
+ // eft.28.1, a dead launch-time process (e.g. it crashed before ever
637
+ // producing a plan) left a `server` entry in sessionRegistry that looked
638
+ // reusable -- send_message would happily enqueue to it, but nothing would
639
+ // ever call respond_to_message, so the caller silently burned the full
640
+ // timeout_s (observed up to 3600s in apra-fleet-eft.28) with zero
641
+ // fleet-server log output and no watchdog coverage.
642
+ //
643
+ // eft.28.5 changes what happens once the death is detected: instead of
644
+ // surfacing a terminal dispatch_failed error that forces a manual
645
+ // register_member, EVICT the dead session and FALL THROUGH to a fresh
646
+ // non-interactive (subprocess) dispatch below -- i.e. re-dispatch fresh
647
+ // instead of blocking on waitForInteractiveResponse. The bug in
648
+ // apra-fleet-eft.28 was precisely that a dead session was reused "rather
649
+ // than detecting its death and spawning a fresh dispatch"; this does the
650
+ // spawning. If the fresh subprocess dispatch itself cannot start it
651
+ // returns its own terminal error, so nothing ever hangs.
652
+ //
653
+ // The liveness check now fires for connect-back interactive sessions too:
654
+ // http-transport carries the launch-time pid forward across re-registration
655
+ // (eft.28.5), so `pid` is no longer undefined for a member that registered
656
+ // via register_member and then connected back -- the exact real-fleet
657
+ // repro that evaded eft.28.1.
658
+ //
659
+ // apra-fleet-eft.50.1: eft.28.5's carry-forward still lost the pid when a
660
+ // reconnect happened AFTER the prior SessionState was already unregistered
661
+ // (priorPid lookup found nothing), so a retry attempt 2+ reused a
662
+ // pid=undefined session and hung. `interactivePid` above now back-stops
663
+ // that with sessionRegistry.lastKnownPid, the durable per-member launch-pid
664
+ // anchor, so this guard re-arms on EVERY dispatch attempt that reuses an
665
+ // interactive session, not just the first. It stays undefined only for
666
+ // sessions that never had a captured PID at all (e.g. tests, or a provider
667
+ // that never went through register_member's local spawn path); those are
668
+ // left to the pre-existing interactive behavior, unchanged.
669
+ const deadScope = new LogScope('execute_prompt', `[interactive] session liveness check pid=${interactivePid}`, agent);
670
+ sessionRegistry.unregister(workspaceId, agent.id);
671
+ deadScope.info(`member claude process (pid ${interactivePid}) for "${agent.friendlyName}" is dead -- evicting the stale interactive session and re-dispatching fresh (non-interactive)`);
672
+ interactiveSession = undefined;
673
+ }
674
+ if (interactiveSession?.server) {
675
+ // Lock already claimed above, before the preflight await -- do not
676
+ // re-add here (Set.add would be a harmless no-op, but keeping a second
677
+ // add site invites the lock and its release to drift out of sync).
678
+ writeStatusline(new Map([[agent.id, 'busy']]));
679
+ try {
680
+ return await executePromptInteractive(agent, renderedPrompt, input, workspaceId, heuristicWarningSuffix);
681
+ }
682
+ finally {
683
+ inFlightAgents.delete(agent.id);
684
+ writeStatusline(new Map([[agent.id, 'idle']]));
685
+ }
686
+ }
687
+ // Lock already claimed above, before the preflight await.
157
688
  await ensureAgentFilesProvisioned(agent);
158
689
  const stallDetector = getStallDetector();
159
690
  let clearedByStall = false;
691
+ // apra-fleet-3c9.1: a CONFIRMED stall must not only kill the remote pid but
692
+ // also cancel the in-flight strategy.execCommand() promise. Before this, the
693
+ // client kept waiting out its full deriveTimeoutMs deadline after the
694
+ // server-side work had already died (the 60.5-min hung dispatch in
695
+ // apra-fleet-3c9). onStall aborts this controller; its signal is merged into
696
+ // the signal handed to every execCommand below (see dispatchSignal), so a
697
+ // confirmed stall settles the pending dispatch immediately and surfaces a
698
+ // typed 'stalled' error instead of hanging.
699
+ const stallAbortController = new AbortController();
160
700
  stallDetector.add(agent.id, {
161
701
  sessionId: null,
162
702
  logFilePath: null,
@@ -174,6 +714,21 @@ export async function executePrompt(input, extra) {
174
714
  // a new execute_prompt that may have already claimed the member.
175
715
  inFlightAgents.delete(agent.id);
176
716
  clearedByStall = true;
717
+ // apra-fleet-6z8.2: a CONFIRMED stall means the remote turn made no
718
+ // progress of any kind for the whole threshold. Clearing bookkeeping
719
+ // alone left that wedged process running indefinitely on the member --
720
+ // burning its LLM session, holding its work folder, and colliding with
721
+ // whatever dispatch takes the member next. Kill the tracked pid too.
722
+ // Best-effort and never awaited: onStall is a fire-and-forget callback
723
+ // from the poll loop, and tryKillPid already swallows its own errors.
724
+ void tryKillPid(agent, strategy, cmds).catch(() => { });
725
+ // apra-fleet-3c9.1: killing the remote pid alone left the pending
726
+ // execCommand promise still awaiting its full deadline. Abort it now so
727
+ // the dispatch settles promptly and returns a typed 'stalled' error.
728
+ try {
729
+ stallAbortController.abort();
730
+ }
731
+ catch { /* best-effort */ }
177
732
  },
178
733
  });
179
734
  const tmpDir = agent.agentType === 'local' ? os.tmpdir() : '/tmp';
@@ -209,14 +764,51 @@ export async function executePrompt(input, extra) {
209
764
  else {
210
765
  resolvedModel = tiers[resolvedModel] ?? resolvedModel;
211
766
  }
212
- const deprecationWarning = input.dangerously_skip_permissions
213
- ? '⚠️ DEPRECATION: dangerously_skip_permissions is deprecated and ignored. Use update_member(unattended="dangerous") instead.\n\n'
214
- : '';
215
767
  const scope = new LogScope('execute_prompt', `[${resolvedModel}] resume=${input.resume} timeout=${input.timeout_s ?? 300}s ${truncateForLog(maskSecrets(input.prompt), getLogPreviewChars())}`, agent);
216
- const resuming = !!(input.resume && agent.sessionId && provider.supportsResume());
217
- const mintedId = (provider.name === 'claude' || provider.name === 'gemini' || provider.name === 'agy')
218
- ? (resuming ? agent.sessionId : uuid())
219
- : (resuming ? agent.sessionId : undefined);
768
+ // Resume semantics (apra-fleet-eft.78.1). `resume` is boolean | string:
769
+ // - true -> best-effort resume of the member's stored last session; a
770
+ // stale/unknown stored session transparently retries fresh.
771
+ // - false -> always a fresh session.
772
+ // - string -> EXPLICIT session-id resume: resume exactly this id, preferring
773
+ // it over agent.sessionId. The caller asserts the prompt depends
774
+ // on that session's context, so an unknown/expired id is a
775
+ // TERMINAL session_not_found (handled just below) and NO
776
+ // fresh-session fallback is ever applied (see the retry paths).
777
+ const explicitResumeId = (typeof input.session_id === 'string' && input.session_id.trim().length > 0)
778
+ ? input.session_id.trim()
779
+ : (typeof input.resume === 'string' && input.resume.length > 0 ? input.resume : undefined);
780
+ const resumeRequested = input.resume === true || explicitResumeId !== undefined;
781
+ const resumeTargetId = explicitResumeId ?? agent.sessionId;
782
+ // An explicit-id resume must never silently degrade to a fresh session: that
783
+ // is exactly the wrong-context dispatch this feature forbids. resume=true and
784
+ // resume=false keep their pre-existing transparent recovery.
785
+ const allowFreshSessionFallback = explicitResumeId === undefined;
786
+ const resuming = !!(resumeRequested && resumeTargetId && provider.supportsResume());
787
+ const isCallerMinted = provider.sessionIdStrategy().type === 'caller-minted';
788
+ const mintedId = isCallerMinted
789
+ ? (resuming ? resumeTargetId : uuid())
790
+ : (resuming ? resumeTargetId : undefined);
791
+ // Terminal session-not-found gate for explicit-id resumes (apra-fleet-eft.78.1).
792
+ // Checked BEFORE any spawn (writePromptFile / the LLM invocation): if the
793
+ // caller named a session the server has never issued for this member -- and it
794
+ // is not the member's currently-stored session -- there is no context to
795
+ // resume. Reject with a structured session_not_found and make NO LLM call,
796
+ // so an orchestrator can rebuild a self-contained prompt and re-dispatch fresh
797
+ // deliberately, rather than getting a silent blank-session response.
798
+ if (explicitResumeId !== undefined) {
799
+ const resumable = provider.supportsResume()
800
+ && (isKnownSession(agent.id, explicitResumeId) || explicitResumeId === agent.sessionId);
801
+ if (!resumable) {
802
+ scope.abort(`explicit resume rejected -- session "${explicitResumeId}" is unknown/expired (no LLM call)`);
803
+ inFlightAgents.delete(agent.id);
804
+ stallDetector.remove(agent.id);
805
+ writeStatusline(new Map([[agent.id, 'idle']]));
806
+ return {
807
+ text: `[FAIL] execute_prompt on "${agent.friendlyName}" rejected -- session "${explicitResumeId}" cannot be resumed (unknown or expired). No LLM call was made. Rebuild the context and re-dispatch with a full, self-contained prompt (resume=false), or resume=true for best-effort recovery.`,
808
+ structuredContent: { isError: true, reason: 'session_not_found', sessionId: explicitResumeId },
809
+ };
810
+ }
811
+ }
220
812
  const promptOpts = {
221
813
  folder: resolvedWorkFolder,
222
814
  promptFile: promptFileName,
@@ -227,26 +819,192 @@ export async function executePrompt(input, extra) {
227
819
  tier: resolvedTier,
228
820
  maxTurns: input.max_turns,
229
821
  inv: scope.getInv(),
822
+ agentName: input.agent,
230
823
  };
824
+ // apra-fleet issue #390: session log paths live on the MEMBER's machine, under
825
+ // the MEMBER's home directory, joined with the MEMBER's OS convention. Before
826
+ // this, every remote member got a HUB-home path (os.homedir()) joined with the
827
+ // HUB's path convention -- a path that can never exist on the member, which
828
+ // silently disabled stall detection for Claude/Gemini and manufactured
829
+ // false-positive stall kills for AGY/OpenCode.
830
+ //
831
+ // This resolution is deliberately SYNCHRONOUS (cached probe result, else the
832
+ // member's known login username's default home): the dispatch path must not
833
+ // add a remote round trip, and a wrong guess here can only cost detection
834
+ // fidelity, never cause a kill. The kill-capable directory poll in
835
+ // stall-poller.ts uses the probe-backed async resolver instead.
836
+ const memberPathCtx = getCachedMemberPathContext(agent);
837
+ const activePreSpawnSid = resuming ? resumeTargetId : (isCallerMinted ? mintedId : undefined);
838
+ let resolvedLogPath = null;
839
+ if (activePreSpawnSid) {
840
+ try {
841
+ resolvedLogPath = resolveSessionLogPath(agent.llmProvider ?? 'claude', activePreSpawnSid, resolvedWorkFolder, memberPathCtx.homeDir, memberPathCtx.targetOs);
842
+ }
843
+ catch {
844
+ resolvedLogPath = null;
845
+ }
846
+ }
847
+ stallDetector.update(agent.id, {
848
+ sessionId: activePreSpawnSid,
849
+ logFilePath: resolvedLogPath,
850
+ provisional: !resolvedLogPath,
851
+ });
231
852
  const claudeCmd = authPrefix + cmds.buildAgentPromptCommand(provider, promptOpts);
853
+ // apra-fleet-6z8.1: the per-invocation durable stdout mirror the unix prompt
854
+ // wrapper tees to (see durableOutputPath / buildAgentPromptCommand). Windows
855
+ // members have no such companion tee, so recovery is skipped for them.
856
+ const durablePath = getAgentOS(agent) === 'windows' ? undefined : durableOutputPath(scope.getInv());
857
+ const dispatchStartedAt = Date.now();
232
858
  const timeoutMs = (input.timeout_s ?? 300) * 1000;
233
859
  const maxTotalMs = input.max_total_s !== undefined ? input.max_total_s * 1000 : undefined;
860
+ // apra-fleet-y8q.1: every retry below (dispatch-exception, stale-session,
861
+ // server-overloaded) re-dispatches with a FRESH session but used to reuse the
862
+ // SAME full timeoutMs/maxTotalMs as the original attempt -- so a single
863
+ // dispatch could burn up to ~2x max_total_s server-side (original attempt +
864
+ // one full-budget retry), well past what the client's deriveTimeoutMs()
865
+ // (packages/apra-fleet-client/src/client/api.mjs) budgets for the whole
866
+ // tools/call (max_total_s*1000 + a fixed grace margin). That let the
867
+ // client's hard timeout fire before the server's own retry-and-report path
868
+ // ever got a chance, hiding a clean typed server error behind a raw client
869
+ // transport timeout. Share ONE deadline budget across the original attempt
870
+ // and any single retry: cap a retry's maxTotalMs (and its inactivity
871
+ // timeoutMs, so it can't independently outlast the shared ceiling) to
872
+ // whatever remains of max_total_s since dispatchStartedAt, and skip the
873
+ // retry entirely once that budget is exhausted -- so total wall-clock time
874
+ // for this call never exceeds max_total_s, which is exactly what the client
875
+ // is prepared to wait for. When max_total_s is absent there is no hard
876
+ // ceiling to share, so retries keep their full timeout_s (unchanged,
877
+ // pre-existing behavior).
878
+ function retryBudget() {
879
+ if (maxTotalMs === undefined)
880
+ return { timeoutMs, maxTotalMs: undefined, exhausted: false };
881
+ const remaining = Math.max(0, maxTotalMs - (Date.now() - dispatchStartedAt));
882
+ return { timeoutMs: Math.min(timeoutMs, remaining), maxTotalMs: remaining, exhausted: remaining <= 0 };
883
+ }
884
+ // Agent file validation -- verify named agent exists before any CLI invocation
885
+ if (input.agent) {
886
+ const dirs = provider.agentDirectories(input.agent);
887
+ let agentFound = false;
888
+ if (agent.agentType === 'local') {
889
+ const projPath = path.join(resolvedWorkFolder, dirs.project);
890
+ const userPath = path.join(os.homedir(), dirs.home);
891
+ agentFound = fs.existsSync(projPath) || fs.existsSync(userPath);
892
+ if (!agentFound) {
893
+ inFlightAgents.delete(agent.id);
894
+ stallDetector.remove(agent.id);
895
+ writeStatusline(new Map([[agent.id, 'idle']]));
896
+ return `execute_prompt: agent "${input.agent}" not found.\n\nExpected at:\n ${projPath.replace(/\\/g, '/')}\n ${userPath.replace(/\\/g, '/')}`;
897
+ }
898
+ }
899
+ else {
900
+ // Canonical PM role agents (planner/doer/reviewer/plan-reviewer/...) are
901
+ // already guaranteed present in ~/dirs.home by
902
+ // ensureAgentFilesProvisioned() above (ln ~576, which ran provisionAgents()
903
+ // for this exact member earlier in this same call) -- trust that instead
904
+ // of re-probing the remote here. This also SIDESTEPS the bug this check
905
+ // used to have: the old code hand-rolled a POSIX-only
906
+ // `test -f ... || test -f ...` command run via strategy.execCommand(),
907
+ // which throws a PowerShell parser error (not a POSIX shell) on every
908
+ // Windows remote -- a nonzero exit that this check misread as "agent not
909
+ // found" even when the file genuinely existed (apra-fleet P0 bug, fleet-
910
+ // sprint via a Windows remote member always failed plan-review with
911
+ // "agent 'plan-reviewer' not found").
912
+ const canonicalRelPath = `${input.agent}.md`;
913
+ agentFound = remoteAgentsDir(provider.name) !== null
914
+ && loadCanonicalAgentSet(provider.name).some((f) => f.relPath === canonicalRelPath);
915
+ if (!agentFound) {
916
+ // Not part of the canonical PM set (e.g. a project-local custom
917
+ // agent) -- fall back to a REAL existence probe, built platform-aware
918
+ // via this repo's own getOsCommands() abstraction (src/os/*.ts,
919
+ // already used the same way by list-members.ts/member-detail.ts for
920
+ // credential-file checks) instead of a single hardcoded shell dialect.
921
+ const cmds = getOsCommands(getAgentOS(agent));
922
+ const projPath = `${resolvedWorkFolder}/${dirs.project}`;
923
+ const userPath = `~/${dirs.home}`;
924
+ const [projResult, userResult] = await Promise.all([
925
+ strategy.execCommand(cmds.credentialFileCheck(projPath), 10000),
926
+ strategy.execCommand(cmds.credentialFileCheck(userPath), 10000),
927
+ ]);
928
+ agentFound = projResult.stdout.includes('found') || userResult.stdout.includes('found');
929
+ }
930
+ if (!agentFound) {
931
+ inFlightAgents.delete(agent.id);
932
+ stallDetector.remove(agent.id);
933
+ writeStatusline(new Map([[agent.id, 'idle']]));
934
+ return `execute_prompt: agent "${input.agent}" not found on "${agent.friendlyName}".\n\nExpected at:\n ${resolvedWorkFolder}/${dirs.project}\n ~/${dirs.home}`;
935
+ }
936
+ }
937
+ }
938
+ // Context-headroom admission control (apra-fleet-eft.81.1): a declared
939
+ // demand is checked against this session's remaining headroom BEFORE any
940
+ // CLI is spawned. No declared demand (both fields omitted) means this
941
+ // block is skipped entirely -- pre-existing behavior is unchanged.
942
+ const contextDemand = resolveExpectedDemand(input.expected_context_tokens, input.context_size);
943
+ let contextWarning;
944
+ if (contextDemand !== undefined) {
945
+ const admission = checkContextAdmission({
946
+ provider: provider.name,
947
+ resolvedModel,
948
+ sessionId: mintedId,
949
+ demand: contextDemand,
950
+ });
951
+ if (!admission.allowed) {
952
+ scope.abort(`insufficient context headroom: demand=${admission.detail.demand} headroom=${admission.detail.headroom} window=${admission.detail.window}`);
953
+ inFlightAgents.delete(agent.id);
954
+ stallDetector.remove(agent.id);
955
+ writeStatusline(new Map([[agent.id, 'idle']]));
956
+ return {
957
+ text: `[FAIL] execute_prompt on "${agent.friendlyName}" rejected -- insufficient context headroom (demand=${admission.detail.demand}, headroom=${admission.detail.headroom}, window=${admission.detail.window}). Start a fresh session, shrink the task, or split it.`,
958
+ structuredContent: { isError: true, reason: 'insufficient_context_headroom', detail: admission.detail },
959
+ };
960
+ }
961
+ if (admission.warning) {
962
+ contextWarning = { message: admission.warning, detail: admission.detail };
963
+ }
964
+ }
965
+ // Usage/budget admission (apra-fleet-eft.80.2): when a budget is configured
966
+ // for this member (or its workspace), a hard-threshold crossing rejects the
967
+ // NEW dispatch BEFORE any LLM is spawned -- never killing an in-flight call.
968
+ // No configured budget (the common case) means resolveBudgetScope returns
969
+ // undefined and this block is skipped entirely -- behavior is unchanged.
970
+ const budgetScope = resolveBudgetScope([agent.id, workspaceId]);
971
+ if (budgetScope) {
972
+ const preBudget = await evaluateBudget({ scope: budgetScope, agent, provider });
973
+ if (preBudget?.exhausted) {
974
+ scope.abort(`budget exhausted: scope=${budgetScope} spent=${preBudget.block.spent} budget=${preBudget.block.budget} source=${preBudget.block.source}`);
975
+ inFlightAgents.delete(agent.id);
976
+ stallDetector.remove(agent.id);
977
+ writeStatusline(new Map([[agent.id, 'idle']]));
978
+ return {
979
+ text: `[FAIL] execute_prompt on "${agent.friendlyName}" rejected -- budget exhausted (scope=${budgetScope}, spent=${preBudget.block.spent}, budget=${preBudget.block.budget} ${preBudget.block.unit}, source=${preBudget.block.source}). No LLM call was made; raise or reset the budget to resume.`,
980
+ structuredContent: { isError: true, reason: 'budget_exhausted', budgetUsage: preBudget.block },
981
+ };
982
+ }
983
+ }
234
984
  // Kill any leftover session from a previous (possibly zombie) execute_prompt call
235
985
  await tryKillPid(agent, strategy, cmds);
236
- // Write the prompt to the unique prompt file before execution
237
- await writePromptFile(agent, strategy, promptFilePath, input.prompt);
986
+ // Write the rendered prompt (with substitutions applied) to the prompt file before execution
987
+ await writePromptFile(agent, strategy, promptFilePath, renderedPrompt);
988
+ // apra-fleet-6z8.1: remembered for the lease-of-life gate below -- the pid
989
+ // outlives the SSH channel that reported it, and is the only way to tell a
990
+ // fabricated "exit 0 / empty" close apart from a real one.
991
+ let capturedPid;
238
992
  const onPidCaptured = (pid) => {
993
+ capturedPid = pid;
239
994
  scope.info(`pid=${pid}`);
240
995
  if (mintedId) {
996
+ let logPath = null;
241
997
  try {
242
- const logPath = resolveSessionLogPath(agent.llmProvider ?? 'claude', mintedId, agent.workFolder);
243
- stallDetector.update(agent.id, {
244
- sessionId: mintedId,
245
- logFilePath: logPath,
246
- provisional: false,
247
- });
998
+ logPath = resolveSessionLogPath(agent.llmProvider ?? 'claude', mintedId, resolvedWorkFolder, memberPathCtx.homeDir, memberPathCtx.targetOs);
248
999
  }
249
- catch { /* copilot/codex: no log path resolution */ }
1000
+ catch {
1001
+ logPath = null;
1002
+ }
1003
+ stallDetector.update(agent.id, {
1004
+ sessionId: mintedId,
1005
+ logFilePath: logPath,
1006
+ provisional: !logPath,
1007
+ });
250
1008
  }
251
1009
  };
252
1010
  const abortHandler = () => {
@@ -254,61 +1012,313 @@ export async function executePrompt(input, extra) {
254
1012
  tryKillPid(agent, strategy, cmds).catch(() => { });
255
1013
  };
256
1014
  extra?.signal?.addEventListener('abort', abortHandler);
1015
+ // apra-fleet-3c9.1: the signal handed to execCommand fires on EITHER the MCP
1016
+ // client's cancellation OR a confirmed stall (stallAbortController). Merging
1017
+ // them means a stall aborts the pending dispatch exactly as a client cancel
1018
+ // would, while a live (non-stalled) dispatch -- whose controller is never
1019
+ // aborted -- is left completely untouched.
1020
+ const dispatchSignal = extra?.signal
1021
+ ? AbortSignal.any([extra.signal, stallAbortController.signal])
1022
+ : stallAbortController.signal;
257
1023
  // Mark agent as busy in statusline
258
1024
  writeStatusline(new Map([[agent.id, 'busy']]));
259
1025
  let _epExitCode = 'error';
260
1026
  let _epError;
261
1027
  let _epUsage;
262
1028
  let _epOffline = false;
1029
+ // apra-fleet-6a7.1: gates the exit-0/empty-stdout workspace_not_trusted
1030
+ // self-heal-and-retry below to exactly one attempt per call, mirroring
1031
+ // runGitStep's authHealAttempted shape (fleet-sprint/runner.js:616) -- a
1032
+ // repeat trust failure after the heal is terminal, never looped.
1033
+ let trustHealAttempted = false;
263
1034
  try {
264
- let result = await strategy.execCommand(claudeCmd, timeoutMs, maxTotalMs, onPidCaptured, extra?.signal);
1035
+ let result;
1036
+ try {
1037
+ result = await strategy.execCommand(claudeCmd, timeoutMs, maxTotalMs, onPidCaptured, dispatchSignal);
1038
+ }
1039
+ catch (dispatchErr) {
1040
+ // apra-fleet-02s.1: a genuine command-execution exception (e.g. an
1041
+ // inactivity timeout, or any other error strategy.execCommand throws)
1042
+ // used to be unconditionally unretried here -- it bypasses both retry
1043
+ // mechanisms below, since those only fire on a non-throwing nonzero
1044
+ // exit, never on a thrown exception. Retry once with a fresh session
1045
+ // before giving up, mirroring the stale-session/server-overloaded
1046
+ // retries' bounded, single-attempt shape. Skip the retry if the client
1047
+ // itself cancelled the request -- there is nothing to recover from a
1048
+ // deliberate cancellation.
1049
+ if (extra?.signal?.aborted)
1050
+ throw dispatchErr;
1051
+ // apra-fleet-3c9.1: a stall-triggered abort is terminal. onStall already
1052
+ // killed the remote process and its session is gone, so retrying in a
1053
+ // fresh session would just re-dispatch onto a member we just tore down.
1054
+ // Let the exception surface to the outer catch, which classifies it as a
1055
+ // typed 'stalled' error instead of retrying or hanging.
1056
+ if (stallAbortController.signal.aborted)
1057
+ throw dispatchErr;
1058
+ // apra-fleet-eft.78.1: an explicit-id resume must NOT retry in a fresh
1059
+ // session (that would run a context-dependent delta prompt with no
1060
+ // context). Let the exception surface as dispatch_failed instead.
1061
+ if (!allowFreshSessionFallback)
1062
+ throw dispatchErr;
1063
+ // apra-fleet-y8q.1: no budget left to share with a retry (the original
1064
+ // attempt already consumed the whole max_total_s) -- retrying here would
1065
+ // just re-burn a fresh full budget past what the client is waiting for.
1066
+ // Let the original exception surface instead of retrying blind.
1067
+ const budget = retryBudget();
1068
+ if (budget.exhausted)
1069
+ throw dispatchErr;
1070
+ scope.info(`[${resolvedModel}] retrying -- dispatch exception: ${dispatchErr.message}`);
1071
+ await tryKillPid(agent, strategy, cmds);
1072
+ const freshOpts = { ...promptOpts, sessionId: isCallerMinted ? uuid() : undefined, resuming: false };
1073
+ const retryCmd = authPrefix + cmds.buildAgentPromptCommand(provider, freshOpts);
1074
+ result = await strategy.execCommand(retryCmd, budget.timeoutMs, budget.maxTotalMs, onPidCaptured, dispatchSignal);
1075
+ }
265
1076
  let parsed = provider.parseResponse(result);
266
1077
  if (parsed.usage)
267
1078
  _epUsage = parsed.usage;
268
- // Stale session retry — fresh session ID, no resume
269
- if (result.code !== 0 && input.resume && agent.sessionId) {
270
- scope.info(`[${resolvedModel}] retrying — stale session`);
271
- await tryKillPid(agent, strategy, cmds);
272
- const freshOpts = { ...promptOpts, sessionId: (provider.name === 'claude' || provider.name === 'gemini' || provider.name === 'agy') ? uuid() : undefined, resuming: false };
273
- const retryCmd = authPrefix + cmds.buildAgentPromptCommand(provider, freshOpts);
274
- result = await strategy.execCommand(retryCmd, timeoutMs, maxTotalMs, onPidCaptured, extra?.signal);
275
- parsed = provider.parseResponse(result);
276
- if (parsed.usage)
277
- _epUsage = parsed.usage;
278
- }
279
- // Server/overloaded error retry — single attempt after delay
280
- if (result.code !== 0 && isRetryable(provider.classifyError(result.stderr || result.stdout))) {
281
- scope.info(`[${resolvedModel}] retrying — server overloaded`);
282
- await tryKillPid(agent, strategy, cmds);
283
- await new Promise(r => setTimeout(r, SERVER_RETRY_DELAY_MS));
284
- const freshOpts = { ...promptOpts, sessionId: (provider.name === 'claude' || provider.name === 'gemini' || provider.name === 'agy') ? uuid() : undefined, resuming: false };
285
- const retryCmd = authPrefix + cmds.buildAgentPromptCommand(provider, freshOpts);
286
- result = await strategy.execCommand(retryCmd, timeoutMs, maxTotalMs, onPidCaptured, extra?.signal);
287
- parsed = provider.parseResponse(result);
288
- if (parsed.usage)
289
- _epUsage = parsed.usage;
1079
+ // apra-fleet-eft.40.3: workspace-not-trusted degrades composed permissions
1080
+ // (project-scoped allow entries silently dropped) without killing the CLI process --
1081
+ // from there, unattended -p cannot auto-approve or prompt, so tools get denied and
1082
+ // the turn eventually fails. Blindly falling through to the stale-session /
1083
+ // server-overloaded retries below just repeats the same degraded dispatch against a
1084
+ // workspace that is still untrusted, and can walk into eft.28's dead-session hang.
1085
+ // Classify and fail fast here, before either retry path, naming
1086
+ // ensureWorkspaceTrusted (apra-fleet-eft.40.1/40.2) as the remediation.
1087
+ if (result.code !== 0 && provider.classifyError(result.stderr || result.stdout) === 'workspace_not_trusted') {
1088
+ return {
1089
+ text: `[FAIL] ${workspaceNotTrustedAdvice(agent.friendlyName)}\n${result.stderr || result.stdout}`,
1090
+ structuredContent: { isError: true, reason: 'workspace_not_trusted' },
1091
+ };
1092
+ }
1093
+ // Stale session retry -- fresh session ID, no resume. apra-fleet-eft.78.1:
1094
+ // ONLY the best-effort resume=true mode gets this transparent retry-fresh
1095
+ // recovery. An explicit session-id resume (string) deliberately does NOT --
1096
+ // its caller asserted context dependence, so a not-found id is terminal.
1097
+ if (result.code !== 0 && input.resume === true && agent.sessionId) {
1098
+ // apra-fleet-y8q.1: share the remaining max_total_s budget with this
1099
+ // retry too -- skip it outright once exhausted (see retryBudget above).
1100
+ const staleBudget = retryBudget();
1101
+ if (!staleBudget.exhausted) {
1102
+ scope.info(`[${resolvedModel}] retrying -- stale session`);
1103
+ await tryKillPid(agent, strategy, cmds);
1104
+ const freshOpts = { ...promptOpts, sessionId: isCallerMinted ? uuid() : undefined, resuming: false };
1105
+ const retryCmd = authPrefix + cmds.buildAgentPromptCommand(provider, freshOpts);
1106
+ result = await strategy.execCommand(retryCmd, staleBudget.timeoutMs, staleBudget.maxTotalMs, onPidCaptured, dispatchSignal);
1107
+ parsed = provider.parseResponse(result);
1108
+ if (parsed.usage)
1109
+ _epUsage = parsed.usage;
1110
+ }
1111
+ }
1112
+ // Server/overloaded error retry -- single attempt after delay. Skipped for
1113
+ // an explicit-id resume (apra-fleet-eft.78.1): the retry starts a fresh
1114
+ // session, which would discard the exact context the caller asked to resume.
1115
+ if (result.code !== 0 && allowFreshSessionFallback && isRetryable(provider.classifyError(result.stderr || result.stdout))) {
1116
+ // apra-fleet-y8q.1: share the remaining max_total_s budget with this
1117
+ // retry too -- skip it outright once exhausted (see retryBudget above).
1118
+ const overloadBudget = retryBudget();
1119
+ if (!overloadBudget.exhausted) {
1120
+ scope.info(`[${resolvedModel}] retrying -- server overloaded`);
1121
+ await tryKillPid(agent, strategy, cmds);
1122
+ await new Promise(r => setTimeout(r, SERVER_RETRY_DELAY_MS));
1123
+ const freshOpts = { ...promptOpts, sessionId: isCallerMinted ? uuid() : undefined, resuming: false };
1124
+ const retryCmd = authPrefix + cmds.buildAgentPromptCommand(provider, freshOpts);
1125
+ result = await strategy.execCommand(retryCmd, overloadBudget.timeoutMs, overloadBudget.maxTotalMs, onPidCaptured, dispatchSignal);
1126
+ parsed = provider.parseResponse(result);
1127
+ if (parsed.usage)
1128
+ _epUsage = parsed.usage;
1129
+ }
290
1130
  }
291
1131
  _epExitCode = result.code;
292
1132
  if (result.code !== 0) {
293
- return buildFailureMessage(agent.friendlyName, result, provider);
1133
+ // apra-fleet-391: surface an auth failure as a STRUCTURED reason (not
1134
+ // just prose in `text`) so callers -- notably fleet-sprint's
1135
+ // isAuthDispatchError -- can key off it directly instead of regexing
1136
+ // the message string. Overloading 'nonzero_exit' for this case was
1137
+ // what made auth self-heal impossible to wire reliably upstream.
1138
+ const failureCategory = isMaxTurnsResponse(parsed)
1139
+ ? 'max_turns'
1140
+ : provider.classifyError(result.stderr || result.stdout);
1141
+ return {
1142
+ text: buildFailureMessage(agent.friendlyName, result, provider, parsed),
1143
+ structuredContent: {
1144
+ isError: true,
1145
+ reason: failureCategory === 'max_turns'
1146
+ ? 'max_turns_exhausted'
1147
+ : failureCategory === 'auth'
1148
+ ? 'auth'
1149
+ : failureCategory === 'server'
1150
+ ? 'server'
1151
+ : failureCategory === 'overloaded'
1152
+ ? 'overloaded'
1153
+ : failureCategory === 'workspace_not_trusted'
1154
+ ? 'workspace_not_trusted'
1155
+ : 'nonzero_exit',
1156
+ // apra-fleet-63x.1: a nonzero exit -- most commonly max_turns_exhausted,
1157
+ // where the CLI ran real turns and burned real tokens before hitting its
1158
+ // ceiling -- still has a REAL parsed usage figure sitting in _epUsage
1159
+ // (captured just above from `parsed.usage` regardless of exit code).
1160
+ // This branch used to return no `usage` field at all on any failure,
1161
+ // so FleetWorkflow.agent() (packages/apra-fleet-workflow/src/workflow/
1162
+ // index.mjs, apra-fleet-202.3) saw hasRealUsage=false and never priced
1163
+ // it, silently under-counting a sprint's tracked spend (observed: a
1164
+ // 10-hour run with dozens of max_turns exhaustions reporting
1165
+ // stats.totalCost of $0). Attach it here whenever it's available so
1166
+ // the caller can record the real partial cost instead of nothing.
1167
+ ...(_epUsage ? { usage: { input_tokens: _epUsage.input_tokens, output_tokens: _epUsage.output_tokens, total_tokens: _epUsage.input_tokens + _epUsage.output_tokens } } : {}),
1168
+ },
1169
+ };
1170
+ }
1171
+ // Exit 0 but the provider parser extracted NOTHING (no result text)
1172
+ // -- observed live (apra-fleet-eft.14, 2026-07-19 stabilization loop):
1173
+ // the claude CLI can die silently mid-turn (member-side session
1174
+ // transcript stops at a tool_result with no final assistant message)
1175
+ // and still exit 0 with EMPTY stdout, so parseResponse falls through
1176
+ // to its plain-text fallback with result: ''. Returning that as a
1177
+ // success used to hand callers a display wrapper with nothing inside,
1178
+ // which schema-extraction layers then misreported as "LLM returned
1179
+ // invalid JSON". Classify it at the source as a typed dispatch error
1180
+ // instead, with stderr's tail attached for diagnosis.
1181
+ //
1182
+ // apra-fleet-6z8.1 (lease-of-life gate): before declaring that, cross-check
1183
+ // whether the captured pid is STILL ALIVE via a fresh short exec. ssh.ts
1184
+ // substitutes code 0 when the channel closes without ever receiving an
1185
+ // 'exit' event, so "exit 0 + empty" is ALSO exactly what a torn-down
1186
+ // channel over a perfectly healthy, still-running turn looks like (live
1187
+ // evidence: pid 89858 running 2+ minutes past the close). Declaring
1188
+ // empty_response there orphans the CLI and invites a duplicate concurrent
1189
+ // dispatch of the same scope. A confirmed-dead pid keeps today's behavior
1190
+ // verbatim.
1191
+ if (!parsed.result || parsed.result.trim() === '') {
1192
+ const recovery = await recoverOrphanedDispatch({
1193
+ strategy,
1194
+ cmds,
1195
+ pid: capturedPid,
1196
+ durablePath,
1197
+ unsupported: getAgentOS(agent) === 'windows',
1198
+ os: getAgentOS(agent),
1199
+ maxWaitMs: maxTotalMs !== undefined ? Math.max(maxTotalMs - (Date.now() - dispatchStartedAt), 0) : undefined,
1200
+ scope,
1201
+ });
1202
+ if (recovery.status === 'timeout') {
1203
+ scope.info(`orphan recovery timed out after ${Math.round((recovery.waitedMs ?? 0) / 1000)}s -- pid killed`);
1204
+ return {
1205
+ text: `[FAIL] execute_prompt on "${agent.friendlyName}" lost its SSH channel while the member CLI (pid ${capturedPid}) was still running, and that process was still alive after the recovery window (${Math.round((recovery.waitedMs ?? 0) / 1000)}s). The process has been killed; no result was recovered. This is NOT an empty response -- do not treat it as a failed turn without checking the member's session transcript first.`,
1206
+ structuredContent: { isError: true, reason: 'orphan_recovery_timeout' },
1207
+ };
1208
+ }
1209
+ if (recovery.status === 'recovered' && recovery.stdout) {
1210
+ // Feed the durable output through the normal provider parse path,
1211
+ // exactly as if it had arrived on the original channel.
1212
+ const recoveredParsed = provider.parseResponse({ stdout: recovery.stdout, stderr: result.stderr ?? '', code: 0 });
1213
+ if (recoveredParsed.result && recoveredParsed.result.trim() !== '') {
1214
+ scope.info(`recovered the real result from the durable output file after a false-alarm empty_response (waited ${Math.round((recovery.waitedMs ?? 0) / 1000)}s)`);
1215
+ parsed = recoveredParsed;
1216
+ if (parsed.usage)
1217
+ _epUsage = parsed.usage;
1218
+ }
1219
+ }
1220
+ // apra-fleet-6a7.1: the code!==0 workspace_not_trusted classification
1221
+ // above (~line 1048) never sees this branch -- exit 0 + empty stdout is
1222
+ // a SEPARATE path, but live evidence (apra-fleet-2g2, fleet-win-dev1,
1223
+ // 2026-08-02) showed it can be caused by the exact same trust-gate
1224
+ // failure: exited 0, empty stdout, and the stderr tail contained the
1225
+ // exact matched phrase, so the code!==0 classifier never ran. Classify
1226
+ // it here too and -- unlike that path, which only advises a manual fix
1227
+ // -- self-heal via the same seedWorkspaceTrust/ensureWorkspaceTrusted
1228
+ // path compose_permissions already uses, then retry the dispatch
1229
+ // exactly once (gated by trustHealAttempted, mirroring runGitStep's
1230
+ // onAuthFailure shape: a repeat failure after the heal is terminal, not
1231
+ // looped).
1232
+ if ((!parsed.result || parsed.result.trim() === '')
1233
+ && allowFreshSessionFallback
1234
+ && provider.classifyError(result.stderr || result.stdout) === 'workspace_not_trusted'
1235
+ && !trustHealAttempted) {
1236
+ trustHealAttempted = true;
1237
+ scope.info(`[${resolvedModel}] exit-0/empty-stdout classified as workspace_not_trusted -- self-healing (seedWorkspaceTrust) once, then retrying the dispatch`);
1238
+ await seedWorkspaceTrust(agent, strategy, 'execute_prompt');
1239
+ const healBudget = retryBudget();
1240
+ if (!healBudget.exhausted) {
1241
+ await tryKillPid(agent, strategy, cmds);
1242
+ const freshOpts = { ...promptOpts, sessionId: isCallerMinted ? uuid() : undefined, resuming: false };
1243
+ const retryCmd = authPrefix + cmds.buildAgentPromptCommand(provider, freshOpts);
1244
+ result = await strategy.execCommand(retryCmd, healBudget.timeoutMs, healBudget.maxTotalMs, onPidCaptured, dispatchSignal);
1245
+ parsed = provider.parseResponse(result);
1246
+ if (parsed.usage)
1247
+ _epUsage = parsed.usage;
1248
+ }
1249
+ }
1250
+ if (!parsed.result || parsed.result.trim() === '') {
1251
+ const stderrTail = (result.stderr || '').trim().slice(-500);
1252
+ const trustClassified = provider.classifyError(result.stderr || result.stdout) === 'workspace_not_trusted';
1253
+ return {
1254
+ text: trustClassified
1255
+ ? `[FAIL] ${workspaceNotTrustedAdvice(agent.friendlyName)}\n${stderrTail}`
1256
+ : `[FAIL] execute_prompt on "${agent.friendlyName}" exited 0 but produced no parseable output (empty result -- the member CLI likely died mid-turn without printing its result envelope).${stderrTail ? `\n[stderr tail]\n${stderrTail}` : ''}`,
1257
+ structuredContent: { isError: true, reason: trustClassified ? 'workspace_not_trusted' : 'empty_response' },
1258
+ };
1259
+ }
294
1260
  }
295
1261
  // Session-id assertion: returned id must match the one we minted/resumed
296
- if (mintedId && parsed.sessionId && parsed.sessionId !== mintedId) {
297
- scope.info(`session-id mismatch: expected=${mintedId} got=${parsed.sessionId} -- not persisting`);
1262
+ const expectedSid = resuming ? resumeTargetId : (isCallerMinted ? mintedId : undefined);
1263
+ const isMismatch = expectedSid && parsed.sessionId && parsed.sessionId !== expectedSid;
1264
+ if (isMismatch) {
1265
+ scope.info(`session-id mismatch: expected=${expectedSid} got=${parsed.sessionId} -- not persisting`);
1266
+ if (!allowFreshSessionFallback && explicitResumeId !== undefined) {
1267
+ inFlightAgents.delete(agent.id);
1268
+ stallDetector.remove(agent.id);
1269
+ writeStatusline(new Map([[agent.id, 'idle']]));
1270
+ clearStoredPid(agent.id);
1271
+ if (parsed.sessionId) {
1272
+ recordKnownSession(agent.id, parsed.sessionId);
1273
+ }
1274
+ if (parsed.usage) {
1275
+ const prev = agent.tokenUsage ?? { input: 0, output: 0 };
1276
+ updateAgent(agent.id, {
1277
+ tokenUsage: {
1278
+ input: prev.input + parsed.usage.input_tokens,
1279
+ output: prev.output + parsed.usage.output_tokens,
1280
+ },
1281
+ });
1282
+ recordSessionUsage(parsed.sessionId ?? expectedSid, parsed.usage);
1283
+ if (budgetScope) {
1284
+ await recordAndEvaluate({ scope: budgetScope, agent, provider, tier: resolvedTier, usage: parsed.usage });
1285
+ }
1286
+ }
1287
+ return {
1288
+ text: `[FAIL] execute_prompt on "${agent.friendlyName}" failed -- resumed session mismatch. Expected session "${expectedSid}", but provider returned "${parsed.sessionId}".`,
1289
+ structuredContent: {
1290
+ isError: true,
1291
+ reason: 'session_not_found',
1292
+ sessionId: expectedSid,
1293
+ returnedSessionId: parsed.sessionId,
1294
+ ...(parsed.usage ? { usage: { ...parsed.usage, total_tokens: parsed.usage.input_tokens + parsed.usage.output_tokens } } : {}),
1295
+ },
1296
+ };
1297
+ }
298
1298
  touchAgent(agent.id, undefined);
299
1299
  }
300
1300
  else {
301
- touchAgent(agent.id, mintedId ?? parsed.sessionId);
1301
+ touchAgent(agent.id, parsed.sessionId ?? expectedSid);
302
1302
  }
303
- if (mintedId) {
1303
+ // apra-fleet-eft.78.1: mark the session this dispatch actually landed on as
1304
+ // known/resumable for this member, so a later explicit-id resume of it
1305
+ // passes the terminal session_not_found gate above instead of being
1306
+ // rejected as unknown.
1307
+ const finalSid = parsed.sessionId ?? expectedSid;
1308
+ if (finalSid) {
1309
+ recordKnownSession(agent.id, finalSid);
1310
+ let postLogPath = null;
304
1311
  try {
305
- stallDetector.update(agent.id, {
306
- sessionId: mintedId,
307
- logFilePath: resolveSessionLogPath(agent.llmProvider ?? 'claude', mintedId, agent.workFolder),
308
- provisional: false,
309
- });
1312
+ postLogPath = resolveSessionLogPath(agent.llmProvider ?? 'claude', finalSid, resolvedWorkFolder, memberPathCtx.homeDir, memberPathCtx.targetOs);
1313
+ }
1314
+ catch {
1315
+ postLogPath = null;
310
1316
  }
311
- catch { /* copilot/codex: no log path resolution */ }
1317
+ stallDetector.update(agent.id, {
1318
+ sessionId: finalSid,
1319
+ logFilePath: postLogPath,
1320
+ provisional: !postLogPath,
1321
+ });
312
1322
  }
313
1323
  clearStoredPid(agent.id);
314
1324
  if (parsed.usage) {
@@ -319,25 +1329,118 @@ export async function executePrompt(input, extra) {
319
1329
  output: prev.output + parsed.usage.output_tokens,
320
1330
  },
321
1331
  });
1332
+ // Per-session cumulative tracking for context-headroom admission
1333
+ // (apra-fleet-eft.81.1) -- separate from the per-member lifetime total
1334
+ // just above. Keyed by whichever session id this dispatch actually
1335
+ // landed on (the returned id, falling back to the minted/resumed one),
1336
+ // so the NEXT admission check on this same session sees this dispatch's
1337
+ // usage already accounted for.
1338
+ recordSessionUsage(parsed.sessionId ?? mintedId, parsed.usage);
1339
+ }
1340
+ // Usage/budget accounting (apra-fleet-eft.80.2): account this dispatch's
1341
+ // token usage against the scope's budget (self-metered only when the
1342
+ // provider has no native getUsage()), then attach the usage block to the
1343
+ // result when the warning band is crossed. Nothing is attached below the
1344
+ // band, and nothing happens at all when no budget is configured.
1345
+ let budgetUsage;
1346
+ if (budgetScope && parsed.usage) {
1347
+ const postBudget = await recordAndEvaluate({ scope: budgetScope, agent, provider, tier: resolvedTier, usage: parsed.usage });
1348
+ if (postBudget?.warned)
1349
+ budgetUsage = postBudget.block;
322
1350
  }
323
- let output = `${deprecationWarning}📋 Response from ${agent.friendlyName}:
1351
+ let output = `[RESULT] Response from ${agent.friendlyName}:
324
1352
 
325
1353
  ${parsed.result}`;
326
- if (parsed.usage)
327
- output += `
328
- Tokens: input=${parsed.usage.input_tokens} output=${parsed.usage.output_tokens}`;
329
1354
  if (parsed.sessionId)
330
1355
  output += `
331
1356
 
332
1357
  ---
333
1358
  session: ${parsed.sessionId}`;
334
- return output;
1359
+ // Auto-harvest learnings from session output (fire-and-forget)
1360
+ if (parsed.result) {
1361
+ // apra-fleet-tm7.2: always pass resolvedWorkFolder, local or remote.
1362
+ // getKbProviders(undefined) falls back to slugFor(process.cwd()) --
1363
+ // the FLEET SERVER's own cwd, not any generic 'default' -- so omitting
1364
+ // repo_path for remote members would silently route their harvested
1365
+ // learnings into the server's own repo KB (the exact defect apra-fleet-tm7
1366
+ // describes).
1367
+ //
1368
+ // apra-fleet-b4g.6: repo_remote_url (apra-fleet-b4g.1) is how a REMOTE
1369
+ // member's call reaches the SAME shared project KB a local clone would --
1370
+ // without it, resolvedWorkFolder is a path on the remote host that will
1371
+ // almost never exist on this (fleet server) machine, resolveProjectSlug's
1372
+ // git calls on it fail with ENOENT, and it falls through to the literal
1373
+ // 'default' slug, pooling every such member's harvest into one shared,
1374
+ // useless bucket (no cross-repo contamination, but no real routing
1375
+ // either). knownRepoRemoteUrl() forwards it whenever the member's own
1376
+ // registration record already carries a genuine URL. It deliberately does
1377
+ // NOT construct one from agent.gitRepos' bare "owner/repo" access-list
1378
+ // entries (see src/services/vcs/github.ts's own
1379
+ // https://github.com/${repo}.git construction for a DIFFERENT, narrower
1380
+ // purpose -- connectivity testing) or shell out to the member host to
1381
+ // discover it: guessing a URL that turns out wrong would route the
1382
+ // harvest into a KB slug that does not match the repo's real local-clone
1383
+ // slug, which is worse than today's honest 'default' degradation. When no
1384
+ // genuine URL is known, behaviour is unchanged from before this fix.
1385
+ // KB-TRUST PHASE 1 (apra-fleet-4wz.8): report the harvest counters. This is
1386
+ // the highest-volume KB writer and its result was previously discarded
1387
+ // entirely, so entries_rejected -- the fail-closed signal -- was invisible
1388
+ // on the one path that produces most of it. Rejections are EXPECTED to
1389
+ // dominate here: harvest's regex extraction frequently yields no file
1390
+ // paths at all, and an entry with no basis is refused by design. A high
1391
+ // rejected count is the invariant working, not a regression to tune away.
1392
+ void import('./kb-harvest.js')
1393
+ .then(({ kbHarvest }) => kbHarvest({
1394
+ repo_path: resolvedWorkFolder,
1395
+ repo_remote_url: knownRepoRemoteUrl(agent),
1396
+ session_transcript: parsed.result,
1397
+ session_id: parsed.sessionId,
1398
+ }))
1399
+ .then((raw) => {
1400
+ try {
1401
+ const r = JSON.parse(raw);
1402
+ if (r.entries_captured || r.entries_updated || r.entries_skipped || r.entries_rejected) {
1403
+ logLine('kb_harvest', `auto-harvest: captured=${r.entries_captured} updated=${r.entries_updated} skipped=${r.entries_skipped} rejected=${r.entries_rejected}`);
1404
+ }
1405
+ }
1406
+ catch {
1407
+ // A non-JSON payload is not worth failing a fire-and-forget harvest over.
1408
+ }
1409
+ })
1410
+ .catch((err) => logWarn('kb_harvest', `auto-harvest failed: ${err.message}`));
1411
+ }
1412
+ if (heuristicWarningSuffix)
1413
+ output += heuristicWarningSuffix;
1414
+ return {
1415
+ text: output,
1416
+ structuredContent: {
1417
+ response: parsed.result,
1418
+ ...(_epUsage ? { usage: { input_tokens: _epUsage.input_tokens, output_tokens: _epUsage.output_tokens, total_tokens: _epUsage.input_tokens + _epUsage.output_tokens } } : {}),
1419
+ ...(parsed.sessionId ? { sessionId: parsed.sessionId } : {}),
1420
+ ...(contextWarning ? { contextWarning } : {}),
1421
+ ...(budgetUsage ? { budgetUsage } : {}),
1422
+ },
1423
+ };
335
1424
  }
336
1425
  catch (err) {
1426
+ // apra-fleet-3c9.1: a confirmed stall aborted the in-flight execCommand (and
1427
+ // NOT the MCP client). Surface it as a typed 'stalled' error so the dispatch
1428
+ // settles here -- well under the client hard timeout -- instead of being
1429
+ // mislabeled dispatch_failed or waiting out the full deadline.
1430
+ if (stallAbortController.signal.aborted && !extra?.signal?.aborted) {
1431
+ _epError = 'dispatch aborted by confirmed stall';
1432
+ return {
1433
+ text: `[FAIL] execute_prompt on "${agent.friendlyName}" was aborted after a confirmed stall -- the remote turn made no progress for the stall threshold, its process was killed, and the in-flight dispatch was cancelled immediately rather than waiting out the client timeout.`,
1434
+ structuredContent: { isError: true, reason: 'stalled' },
1435
+ };
1436
+ }
337
1437
  // Only mark offline for genuine SSH/network connection failures, not for cancellations
338
1438
  _epOffline = !!(err.message && /ssh|network|econnrefused|ehostunreach|connection timed out/i.test(err.message));
339
1439
  _epError = err.message;
340
- return `❌ Failed to execute prompt on "${agent.friendlyName}": ${err.message}`;
1440
+ return {
1441
+ text: `[FAIL] Failed to execute prompt on "${agent.friendlyName}": ${err.message}`,
1442
+ structuredContent: { isError: true, reason: 'dispatch_failed' },
1443
+ };
341
1444
  }
342
1445
  finally {
343
1446
  extra?.signal?.removeEventListener('abort', abortHandler);
@@ -348,14 +1451,14 @@ session: ${parsed.sessionId}`;
348
1451
  scope.fail(`exit=${_epExitCode}${_epTok}`);
349
1452
  else
350
1453
  scope.ok(`exit=0${_epTok}`);
351
- // Skip if stall detector already cleared state — a new execute_prompt may have
1454
+ // Skip if stall detector already cleared state -- a new execute_prompt may have
352
1455
  // claimed inFlightAgents and set busy again; clobbering it here would be wrong.
353
1456
  if (!clearedByStall) {
354
1457
  writeStatusline(new Map([[agent.id, _epOffline ? 'offline' : 'idle']]));
355
1458
  inFlightAgents.delete(agent.id);
356
1459
  }
357
1460
  stallDetector.remove(agent.id);
358
- await deletePromptFile(agent, strategy, promptFilePath);
1461
+ await deletePromptFile(agent, strategy, promptFilePath, durablePath ? [durablePath] : []);
359
1462
  }
360
1463
  }
361
1464
  //# sourceMappingURL=execute-prompt.js.map