@apralabs/apra-fleet 0.4.2 → 0.4.3

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 (370) hide show
  1. package/README.md +38 -5
  2. package/dist/agents/backlog-groomer.md +25 -0
  3. package/dist/agents/ci-watcher.md +11 -0
  4. package/dist/agents/deployer.md +37 -2
  5. package/dist/agents/doer.md +36 -12
  6. package/dist/agents/harvester.md +11 -0
  7. package/dist/agents/integ-test-runner.md +11 -0
  8. package/dist/agents/kb-reconciler.md +9 -0
  9. package/dist/agents/plan-reviewer.md +110 -22
  10. package/dist/agents/planner.md +125 -37
  11. package/dist/agents/regression-test-runner.md +11 -0
  12. package/dist/agents/reviewer.md +13 -2
  13. package/dist/agents/schemas/plan-reviewer-output.json +37 -0
  14. package/dist/cli/agent-transform.d.ts +83 -2
  15. package/dist/cli/agent-transform.d.ts.map +1 -1
  16. package/dist/cli/agent-transform.js +266 -21
  17. package/dist/cli/agent-transform.js.map +1 -1
  18. package/dist/cli/auth.d.ts.map +1 -1
  19. package/dist/cli/auth.js +28 -9
  20. package/dist/cli/auth.js.map +1 -1
  21. package/dist/cli/config.d.ts +7 -5
  22. package/dist/cli/config.d.ts.map +1 -1
  23. package/dist/cli/config.js +44 -34
  24. package/dist/cli/config.js.map +1 -1
  25. package/dist/cli/install.d.ts +33 -0
  26. package/dist/cli/install.d.ts.map +1 -1
  27. package/dist/cli/install.js +290 -23
  28. package/dist/cli/install.js.map +1 -1
  29. package/dist/cli/kb-directives.d.ts.map +1 -1
  30. package/dist/cli/kb-directives.js +2 -1
  31. package/dist/cli/kb-directives.js.map +1 -1
  32. package/dist/cli/register-member.d.ts.map +1 -1
  33. package/dist/cli/register-member.js +6 -2
  34. package/dist/cli/register-member.js.map +1 -1
  35. package/dist/commands/kb-server.d.ts +3 -0
  36. package/dist/commands/kb-server.d.ts.map +1 -1
  37. package/dist/commands/kb-server.js +43 -3
  38. package/dist/commands/kb-server.js.map +1 -1
  39. package/dist/index.js +3 -3
  40. package/dist/os/linux.d.ts +6 -0
  41. package/dist/os/linux.d.ts.map +1 -1
  42. package/dist/os/linux.js +35 -2
  43. package/dist/os/linux.js.map +1 -1
  44. package/dist/os/os-commands.d.ts +61 -2
  45. package/dist/os/os-commands.d.ts.map +1 -1
  46. package/dist/os/windows-gitbash.d.ts +5 -0
  47. package/dist/os/windows-gitbash.d.ts.map +1 -1
  48. package/dist/os/windows-gitbash.js +15 -0
  49. package/dist/os/windows-gitbash.js.map +1 -1
  50. package/dist/os/windows.d.ts +6 -0
  51. package/dist/os/windows.d.ts.map +1 -1
  52. package/dist/os/windows.js +46 -3
  53. package/dist/os/windows.js.map +1 -1
  54. package/dist/providers/agy.d.ts +115 -6
  55. package/dist/providers/agy.d.ts.map +1 -1
  56. package/dist/providers/agy.js +569 -53
  57. package/dist/providers/agy.js.map +1 -1
  58. package/dist/providers/claude.d.ts +81 -3
  59. package/dist/providers/claude.d.ts.map +1 -1
  60. package/dist/providers/claude.js +344 -10
  61. package/dist/providers/claude.js.map +1 -1
  62. package/dist/providers/codex.d.ts +4 -2
  63. package/dist/providers/codex.d.ts.map +1 -1
  64. package/dist/providers/codex.js +19 -2
  65. package/dist/providers/codex.js.map +1 -1
  66. package/dist/providers/copilot.d.ts +4 -2
  67. package/dist/providers/copilot.d.ts.map +1 -1
  68. package/dist/providers/copilot.js +20 -2
  69. package/dist/providers/copilot.js.map +1 -1
  70. package/dist/providers/none.d.ts +4 -2
  71. package/dist/providers/none.d.ts.map +1 -1
  72. package/dist/providers/none.js +17 -2
  73. package/dist/providers/none.js.map +1 -1
  74. package/dist/providers/opencode.d.ts +3 -1
  75. package/dist/providers/opencode.d.ts.map +1 -1
  76. package/dist/providers/opencode.js +22 -2
  77. package/dist/providers/opencode.js.map +1 -1
  78. package/dist/providers/provider.d.ts +201 -6
  79. package/dist/providers/provider.d.ts.map +1 -1
  80. package/dist/providers/provider.js +56 -0
  81. package/dist/providers/provider.js.map +1 -1
  82. package/dist/services/agy-project.d.ts +102 -0
  83. package/dist/services/agy-project.d.ts.map +1 -0
  84. package/dist/services/agy-project.js +356 -0
  85. package/dist/services/agy-project.js.map +1 -0
  86. package/dist/services/auth-socket.js +4 -4
  87. package/dist/services/auth-web.js +1 -1
  88. package/dist/services/cloud/lifecycle.d.ts.map +1 -1
  89. package/dist/services/cloud/lifecycle.js +33 -4
  90. package/dist/services/cloud/lifecycle.js.map +1 -1
  91. package/dist/services/credential-cleanup.d.ts.map +1 -1
  92. package/dist/services/credential-cleanup.js +35 -17
  93. package/dist/services/credential-cleanup.js.map +1 -1
  94. package/dist/services/exit-drain.d.ts +44 -0
  95. package/dist/services/exit-drain.d.ts.map +1 -0
  96. package/dist/services/exit-drain.js +52 -0
  97. package/dist/services/exit-drain.js.map +1 -0
  98. package/dist/services/github-app.d.ts.map +1 -1
  99. package/dist/services/github-app.js +32 -4
  100. package/dist/services/github-app.js.map +1 -1
  101. package/dist/services/http-transport.d.ts +1 -0
  102. package/dist/services/http-transport.d.ts.map +1 -1
  103. package/dist/services/http-transport.js +48 -1
  104. package/dist/services/http-transport.js.map +1 -1
  105. package/dist/services/knowledge/kb-config.d.ts +42 -0
  106. package/dist/services/knowledge/kb-config.d.ts.map +1 -0
  107. package/dist/services/knowledge/kb-config.js +54 -0
  108. package/dist/services/knowledge/kb-config.js.map +1 -0
  109. package/dist/services/knowledge/kb-providers.d.ts +7 -1
  110. package/dist/services/knowledge/kb-providers.d.ts.map +1 -1
  111. package/dist/services/knowledge/kb-providers.js +191 -17
  112. package/dist/services/knowledge/kb-providers.js.map +1 -1
  113. package/dist/services/knowledge/require-sqlite-project.d.ts +32 -0
  114. package/dist/services/knowledge/require-sqlite-project.d.ts.map +1 -0
  115. package/dist/services/knowledge/require-sqlite-project.js +38 -0
  116. package/dist/services/knowledge/require-sqlite-project.js.map +1 -0
  117. package/dist/services/model-pricing.d.ts.map +1 -1
  118. package/dist/services/model-pricing.js +7 -3
  119. package/dist/services/model-pricing.js.map +1 -1
  120. package/dist/services/secret-token.d.ts +38 -0
  121. package/dist/services/secret-token.d.ts.map +1 -0
  122. package/dist/services/secret-token.js +51 -0
  123. package/dist/services/secret-token.js.map +1 -0
  124. package/dist/services/service-manager/types.d.ts +3 -1
  125. package/dist/services/service-manager/types.d.ts.map +1 -1
  126. package/dist/services/service-manager/windows.d.ts +14 -2
  127. package/dist/services/service-manager/windows.d.ts.map +1 -1
  128. package/dist/services/service-manager/windows.js +65 -7
  129. package/dist/services/service-manager/windows.js.map +1 -1
  130. package/dist/services/ssh.d.ts.map +1 -1
  131. package/dist/services/ssh.js +58 -2
  132. package/dist/services/ssh.js.map +1 -1
  133. package/dist/services/stall/read-log-tail.d.ts.map +1 -1
  134. package/dist/services/stall/read-log-tail.js +20 -10
  135. package/dist/services/stall/read-log-tail.js.map +1 -1
  136. package/dist/services/stall/stall-detector.d.ts +53 -4
  137. package/dist/services/stall/stall-detector.d.ts.map +1 -1
  138. package/dist/services/stall/stall-detector.js +212 -34
  139. package/dist/services/stall/stall-detector.js.map +1 -1
  140. package/dist/services/strategy.d.ts.map +1 -1
  141. package/dist/services/strategy.js +79 -2
  142. package/dist/services/strategy.js.map +1 -1
  143. package/dist/services/substitution-engine.js +2 -2
  144. package/dist/services/substitution-engine.js.map +1 -1
  145. package/dist/services/tool-registry.d.ts.map +1 -1
  146. package/dist/services/tool-registry.js +5 -3
  147. package/dist/services/tool-registry.js.map +1 -1
  148. package/dist/services/vcs/azure-devops.d.ts +66 -1
  149. package/dist/services/vcs/azure-devops.d.ts.map +1 -1
  150. package/dist/services/vcs/azure-devops.js +192 -21
  151. package/dist/services/vcs/azure-devops.js.map +1 -1
  152. package/dist/services/vcs/types.d.ts +1 -1
  153. package/dist/skills/fleet-sprint-cli/SKILL.md +18 -0
  154. package/dist/skills/pm/SKILL.md +1 -1
  155. package/dist/skills/pm/cost.md +0 -3
  156. package/dist/skills/pm/fleet-addendum.md +2 -2
  157. package/dist/tools/check-status.d.ts +7 -4
  158. package/dist/tools/check-status.d.ts.map +1 -1
  159. package/dist/tools/check-status.js +2 -0
  160. package/dist/tools/check-status.js.map +1 -1
  161. package/dist/tools/compose-permissions.d.ts +6 -0
  162. package/dist/tools/compose-permissions.d.ts.map +1 -1
  163. package/dist/tools/compose-permissions.js +182 -34
  164. package/dist/tools/compose-permissions.js.map +1 -1
  165. package/dist/tools/credential-store-set.js +1 -1
  166. package/dist/tools/execute-command.d.ts.map +1 -1
  167. package/dist/tools/execute-command.js +31 -20
  168. package/dist/tools/execute-command.js.map +1 -1
  169. package/dist/tools/execute-prompt.d.ts +15 -2
  170. package/dist/tools/execute-prompt.d.ts.map +1 -1
  171. package/dist/tools/execute-prompt.js +1196 -892
  172. package/dist/tools/execute-prompt.js.map +1 -1
  173. package/dist/tools/kb-capture.d.ts +2 -2
  174. package/dist/tools/kb-capture.d.ts.map +1 -1
  175. package/dist/tools/kb-capture.js +29 -5
  176. package/dist/tools/kb-capture.js.map +1 -1
  177. package/dist/tools/kb-export.d.ts +2 -2
  178. package/dist/tools/kb-export.d.ts.map +1 -1
  179. package/dist/tools/kb-export.js +3 -28
  180. package/dist/tools/kb-export.js.map +1 -1
  181. package/dist/tools/kb-feedback.d.ts.map +1 -1
  182. package/dist/tools/kb-feedback.js +3 -1
  183. package/dist/tools/kb-feedback.js.map +1 -1
  184. package/dist/tools/kb-freshness-sweep.d.ts.map +1 -1
  185. package/dist/tools/kb-freshness-sweep.js +3 -1
  186. package/dist/tools/kb-freshness-sweep.js.map +1 -1
  187. package/dist/tools/kb-import.d.ts.map +1 -1
  188. package/dist/tools/kb-import.js +2 -1
  189. package/dist/tools/kb-import.js.map +1 -1
  190. package/dist/tools/kb-list.d.ts.map +1 -1
  191. package/dist/tools/kb-list.js +3 -1
  192. package/dist/tools/kb-list.js.map +1 -1
  193. package/dist/tools/kb-query.d.ts +2 -2
  194. package/dist/tools/kb-reconcile-prefilter.d.ts.map +1 -1
  195. package/dist/tools/kb-reconcile-prefilter.js +3 -1
  196. package/dist/tools/kb-reconcile-prefilter.js.map +1 -1
  197. package/dist/tools/kb-resolve-contradiction.d.ts.map +1 -1
  198. package/dist/tools/kb-resolve-contradiction.js +3 -1
  199. package/dist/tools/kb-resolve-contradiction.js.map +1 -1
  200. package/dist/tools/kb-setup.d.ts.map +1 -1
  201. package/dist/tools/kb-setup.js +125 -20
  202. package/dist/tools/kb-setup.js.map +1 -1
  203. package/dist/tools/kb-stats.d.ts.map +1 -1
  204. package/dist/tools/kb-stats.js +64 -43
  205. package/dist/tools/kb-stats.js.map +1 -1
  206. package/dist/tools/list-members.d.ts +2 -2
  207. package/dist/tools/list-members.d.ts.map +1 -1
  208. package/dist/tools/list-members.js +1 -0
  209. package/dist/tools/list-members.js.map +1 -1
  210. package/dist/tools/member-detail.d.ts +2 -2
  211. package/dist/tools/member-detail.d.ts.map +1 -1
  212. package/dist/tools/member-detail.js +17 -0
  213. package/dist/tools/member-detail.js.map +1 -1
  214. package/dist/tools/member-reservation.d.ts +58 -1
  215. package/dist/tools/member-reservation.d.ts.map +1 -1
  216. package/dist/tools/member-reservation.js +61 -20
  217. package/dist/tools/member-reservation.js.map +1 -1
  218. package/dist/tools/provision-auth.d.ts +80 -1
  219. package/dist/tools/provision-auth.d.ts.map +1 -1
  220. package/dist/tools/provision-auth.js +142 -54
  221. package/dist/tools/provision-auth.js.map +1 -1
  222. package/dist/tools/provision-vcs-auth.d.ts +91 -1
  223. package/dist/tools/provision-vcs-auth.d.ts.map +1 -1
  224. package/dist/tools/provision-vcs-auth.js +209 -49
  225. package/dist/tools/provision-vcs-auth.js.map +1 -1
  226. package/dist/tools/register-member.d.ts +12 -9
  227. package/dist/tools/register-member.d.ts.map +1 -1
  228. package/dist/tools/register-member.js +99 -12
  229. package/dist/tools/register-member.js.map +1 -1
  230. package/dist/tools/remove-member.d.ts.map +1 -1
  231. package/dist/tools/remove-member.js +27 -2
  232. package/dist/tools/remove-member.js.map +1 -1
  233. package/dist/tools/send-email.d.ts +2 -2
  234. package/dist/tools/setup-git-app.d.ts.map +1 -1
  235. package/dist/tools/setup-git-app.js +11 -7
  236. package/dist/tools/setup-git-app.js.map +1 -1
  237. package/dist/tools/shutdown-server.d.ts +2 -0
  238. package/dist/tools/shutdown-server.d.ts.map +1 -1
  239. package/dist/tools/shutdown-server.js +23 -1
  240. package/dist/tools/shutdown-server.js.map +1 -1
  241. package/dist/tools/update-member.d.ts +12 -9
  242. package/dist/tools/update-member.d.ts.map +1 -1
  243. package/dist/tools/update-member.js +43 -11
  244. package/dist/tools/update-member.js.map +1 -1
  245. package/dist/tools/vcs-credential-exec.d.ts +127 -0
  246. package/dist/tools/vcs-credential-exec.d.ts.map +1 -0
  247. package/dist/tools/vcs-credential-exec.js +197 -0
  248. package/dist/tools/vcs-credential-exec.js.map +1 -0
  249. package/dist/types.d.ts +13 -0
  250. package/dist/types.d.ts.map +1 -1
  251. package/dist/utils/log-helpers.d.ts.map +1 -1
  252. package/dist/utils/log-helpers.js +2 -2
  253. package/dist/utils/log-helpers.js.map +1 -1
  254. package/dist/utils/prompt-errors.d.ts.map +1 -1
  255. package/dist/utils/prompt-errors.js +7 -1
  256. package/dist/utils/prompt-errors.js.map +1 -1
  257. package/dist/utils/shell-escape.d.ts +16 -0
  258. package/dist/utils/shell-escape.d.ts.map +1 -1
  259. package/dist/utils/shell-escape.js +22 -2
  260. package/dist/utils/shell-escape.js.map +1 -1
  261. package/dist/utils/vcs-provider-detect.d.ts +65 -0
  262. package/dist/utils/vcs-provider-detect.d.ts.map +1 -0
  263. package/dist/utils/vcs-provider-detect.js +109 -0
  264. package/dist/utils/vcs-provider-detect.js.map +1 -0
  265. package/dist/utils/workspace-trust.d.ts +20 -17
  266. package/dist/utils/workspace-trust.d.ts.map +1 -1
  267. package/dist/utils/workspace-trust.js +87 -1
  268. package/dist/utils/workspace-trust.js.map +1 -1
  269. package/dist/workflows/auto-sprint.js +176 -15
  270. package/package.json +6 -4
  271. package/packages/apra-fleet-client/src/client/api.mjs +319 -17
  272. package/packages/apra-fleet-client/src/client/errors.mjs +6 -2
  273. package/packages/apra-fleet-se/apra-pm/agents/_shared/GRAPH-SEMANTICS.md +10 -2
  274. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +25 -0
  275. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +11 -0
  276. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +37 -2
  277. package/packages/apra-fleet-se/apra-pm/agents/doer.md +36 -12
  278. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +11 -0
  279. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +11 -0
  280. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +9 -0
  281. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +110 -22
  282. package/packages/apra-fleet-se/apra-pm/agents/planner.md +125 -37
  283. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +11 -0
  284. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +13 -2
  285. package/packages/apra-fleet-se/apra-pm/agents/schemas/plan-reviewer-output.json +37 -0
  286. package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +1 -1
  287. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +0 -3
  288. package/packages/apra-fleet-se/apra-pm/skills/pm/fleet-addendum.md +2 -2
  289. package/packages/apra-fleet-se/bin/cli.mjs +149 -1
  290. package/packages/apra-fleet-se/bin/serve.mjs +78 -4
  291. package/packages/apra-fleet-se/fleet-sprint/abort.mjs +481 -0
  292. package/packages/apra-fleet-se/fleet-sprint/beads-children.mjs +491 -0
  293. package/packages/apra-fleet-se/fleet-sprint/beads-identity-check.mjs +282 -0
  294. package/packages/apra-fleet-se/fleet-sprint/beads-identity.mjs +208 -0
  295. package/packages/apra-fleet-se/fleet-sprint/beads-scope.mjs +638 -0
  296. package/packages/apra-fleet-se/fleet-sprint/beads-transitions.mjs +301 -0
  297. package/packages/apra-fleet-se/fleet-sprint/branch-ensure.mjs +96 -0
  298. package/packages/apra-fleet-se/fleet-sprint/conflict-ladder.mjs +8 -0
  299. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +61 -14
  300. package/packages/apra-fleet-se/fleet-sprint/coordination.mjs +516 -0
  301. package/packages/apra-fleet-se/fleet-sprint/dispatch-failure.mjs +184 -0
  302. package/packages/apra-fleet-se/fleet-sprint/dispatch-role.mjs +1121 -0
  303. package/packages/apra-fleet-se/fleet-sprint/dispatch-safety-guard.mjs +216 -4
  304. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +1 -1
  305. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +276 -0
  306. package/packages/apra-fleet-se/fleet-sprint/docs/escalate-to-llm-design.md +1 -1
  307. package/packages/apra-fleet-se/fleet-sprint/docs/run-sprint-cycle-prelude-decision.md +215 -0
  308. package/packages/apra-fleet-se/fleet-sprint/dolt-literal-guard.mjs +56 -1
  309. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +996 -32
  310. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +267 -0
  311. package/packages/apra-fleet-se/fleet-sprint/explicit-id-create-guard.mjs +501 -0
  312. package/packages/apra-fleet-se/fleet-sprint/fatal-diagnostics.mjs +134 -0
  313. package/packages/apra-fleet-se/fleet-sprint/full-db-fetch-guard.mjs +102 -0
  314. package/packages/apra-fleet-se/fleet-sprint/git-sync.mjs +556 -0
  315. package/packages/apra-fleet-se/fleet-sprint/git-topology.mjs +495 -0
  316. package/packages/apra-fleet-se/fleet-sprint/guarded-modules.mjs +564 -0
  317. package/packages/apra-fleet-se/fleet-sprint/inline-ladder-guard.mjs +216 -0
  318. package/packages/apra-fleet-se/fleet-sprint/kb.mjs +728 -0
  319. package/packages/apra-fleet-se/fleet-sprint/mcp-result.mjs +75 -0
  320. package/packages/apra-fleet-se/fleet-sprint/member-provisioning.mjs +252 -0
  321. package/packages/apra-fleet-se/fleet-sprint/member-sync.mjs +581 -0
  322. package/packages/apra-fleet-se/fleet-sprint/member-target.mjs +93 -0
  323. package/packages/apra-fleet-se/fleet-sprint/newtask-text.mjs +266 -0
  324. package/packages/apra-fleet-se/fleet-sprint/parent-notes-staleness.mjs +201 -0
  325. package/packages/apra-fleet-se/fleet-sprint/phases/deploy.mjs +136 -0
  326. package/packages/apra-fleet-se/fleet-sprint/phases/develop.mjs +822 -0
  327. package/packages/apra-fleet-se/fleet-sprint/phases/ensure-sprint-branch.mjs +294 -0
  328. package/packages/apra-fleet-se/fleet-sprint/phases/final-review.mjs +403 -0
  329. package/packages/apra-fleet-se/fleet-sprint/phases/harvest.mjs +180 -0
  330. package/packages/apra-fleet-se/fleet-sprint/phases/integ-test.mjs +358 -0
  331. package/packages/apra-fleet-se/fleet-sprint/phases/plan.mjs +390 -0
  332. package/packages/apra-fleet-se/fleet-sprint/phases/publish-pr.mjs +323 -0
  333. package/packages/apra-fleet-se/fleet-sprint/phases/re-review.mjs +232 -0
  334. package/packages/apra-fleet-se/fleet-sprint/phases/regression-test.mjs +174 -0
  335. package/packages/apra-fleet-se/fleet-sprint/phases/replan.mjs +197 -0
  336. package/packages/apra-fleet-se/fleet-sprint/phases/review.mjs +305 -0
  337. package/packages/apra-fleet-se/fleet-sprint/prompts.mjs +559 -0
  338. package/packages/apra-fleet-se/fleet-sprint/role-policies.mjs +1416 -0
  339. package/packages/apra-fleet-se/fleet-sprint/round-session.mjs +100 -0
  340. package/packages/apra-fleet-se/fleet-sprint/runner.js +1467 -9798
  341. package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +17 -12
  342. package/packages/apra-fleet-se/fleet-sprint/shell-command-guard.mjs +304 -0
  343. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +18 -0
  344. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +21 -2
  345. package/packages/apra-fleet-se/fleet-sprint/sprint-args.mjs +454 -0
  346. package/packages/apra-fleet-se/fleet-sprint/sprint-report.mjs +239 -0
  347. package/packages/apra-fleet-se/fleet-sprint/sprint-state.mjs +163 -0
  348. package/packages/apra-fleet-se/fleet-sprint/unbracketed-push-guard.mjs +234 -0
  349. package/packages/apra-fleet-se/fleet-sprint/usage-limit-controller.mjs +211 -0
  350. package/packages/apra-fleet-se/fleet-sprint/vcs-auth.mjs +1279 -0
  351. package/packages/apra-fleet-se/fleet-sprint/vcs-module.mjs +153 -19
  352. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/azure-devops.mjs +71 -21
  353. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +28 -0
  354. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +131 -0
  355. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +140 -16
  356. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/shell-helpers.mjs +1 -0
  357. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +77 -2
  358. package/packages/apra-fleet-se/fleet-sprint/worklists.mjs +559 -0
  359. package/packages/apra-fleet-se/package.json +1 -1
  360. package/packages/apra-fleet-workflow/src/viewer/index.mjs +17 -6
  361. package/packages/apra-fleet-workflow/src/workflow/index.mjs +49 -7
  362. package/skills/fleet/SKILL.md +8 -8
  363. package/skills/fleet/auth-azdevops.md +14 -3
  364. package/skills/fleet/auth-bitbucket.md +2 -2
  365. package/skills/fleet/auth-github.md +5 -4
  366. package/skills/fleet/onboarding.md +3 -3
  367. package/skills/fleet/permissions.md +5 -1
  368. package/skills/fleet/profiles/node.json +1 -1
  369. package/skills/fleet/troubleshooting.md +3 -3
  370. package/version.json +1 -1
@@ -0,0 +1,1121 @@
1
+ import { policyFor, PRE_DISPATCH_STEPS_IN_BRACKET } from './role-policies.mjs';
2
+ import {
3
+ isNonRetryableDispatchError,
4
+ isAuthDispatchError,
5
+ isPostDispatchSyncFailure,
6
+ isInfraDispatchFailure,
7
+ isUsageLimitDispatchError,
8
+ usageLimitOf,
9
+ } from './errors.mjs';
10
+ import { AgentOutputError, AgentDispatchError, FleetTransportError, WorkflowError } from '@apralabs/apra-fleet-workflow';
11
+
12
+ // =============================================================================
13
+ // apra-fleet-3swo.5.3 -- dispatchRole(ctx, roleName, opts): the ONE dispatch
14
+ // engine that executes a role's ladder from fleet-sprint/role-policies.mjs's
15
+ // data table, replacing the hand-written agent() ladders runner.js used to
16
+ // spell out once per role.
17
+ //
18
+ // WHAT MOVED HERE: for every role role-policies.mjs marks `migrated: true`,
19
+ // this module owns the whole ladder -- the agent() dispatch itself, the
20
+ // withGitSync(...) bracket around it, the withDispatchWatchdog(...) race, the
21
+ // max_turns-exhaustion resume, the bounded retry ladder (backoff, LLM-auth
22
+ // self-heal, non-retryable abort, post-dispatch-sync-failure abort), the
23
+ // bounded semantic-repair re-ask, and the degrade that decides what the
24
+ // caller gets back once the attempts are spent. runner.js keeps only what is
25
+ // genuinely NOT policy: the prompt text, the presentation labels, the runtime
26
+ // bindings a policy names, and what the caller does with the outcome.
27
+ //
28
+ // apra-fleet-3swo.5.4 finished the job on the DEGRADE side: the failure TEXT
29
+ // a degraded value carries used to arrive as a per-call `synthesizedNotes`
30
+ // map of note builders, i.e. six runner.js call sites each spelling out the
31
+ // same two sentences. It is now `degrade.noteTemplates` data in
32
+ // role-policies.mjs, rendered by renderDegradeNote() below -- ONE
33
+ // implementation of verdict/report fallback text for every role.
34
+ //
35
+ // WHY IT IS NOT A PASS-THROUGH: a dispatchRole that merely wrapped the
36
+ // original inline ladders would leave every behavioural axis duplicated per
37
+ // role, which is the condition role-policies.mjs was built to remove. There
38
+ // is exactly ONE agent() call site in this file, ONE withGitSync(...) bracket
39
+ // call and ONE withDispatchWatchdog(...) race; every per-role difference
40
+ // between them is read out of the policy row rather than written out again.
41
+ // fleet-sprint/inline-ladder-guard.mjs enforces the other half of that: a
42
+ // migrated role that still has an inline agent() ladder anywhere in the
43
+ // guarded-module set is a violation.
44
+ //
45
+ // EVERYTHING RUNNER-SIDE IS INJECTED, NEVER IMPORTED (same discipline as
46
+ // git-sync.mjs): agent(), withGitSync(), withDispatchWatchdog(), the member
47
+ // resolver, the session guard, the auth self-heal hook, the model-tier map,
48
+ // the budget map and the sprint's log() all arrive through `ctx`. This module
49
+ // deliberately never imports runner.js back -- runner.js imports it, so
50
+ // importing runner here would be a module cycle.
51
+ //
52
+ // TURN BASES live here rather than in runner.js because the dispatch that
53
+ // consumes them lives here. They keep their original runner.js NAMES
54
+ // (PLANNER_MAX_TURNS, ...) because role-policies.mjs records each policy's
55
+ // turn budget symbolically, by the name of the constant that supplies it --
56
+ // test/role-policies-table.test.mjs re-derives `maxTurns.value` by looking
57
+ // that name up in real source, so renaming one here would break that proof
58
+ // rather than silently drift.
59
+ // =============================================================================
60
+
61
+ // -----------------------------------------------------------------------------
62
+ // Turn bases. One per migrated ladder, named exactly as role-policies.mjs's
63
+ // `maxTurns.base` records them.
64
+ // -----------------------------------------------------------------------------
65
+
66
+ /** Planner turn base: it builds the whole epic DAG, so it gets a doer-sized budget. */
67
+ const PLANNER_MAX_TURNS = 500;
68
+ /** Plan-reviewer turn base: reviewer-sized, like every other review dispatch. */
69
+ const PLAN_REVIEWER_MAX_TURNS = 500;
70
+ /** Scoped replan planner turn base. */
71
+ const SCOPED_REPLAN_PLANNER_MAX_TURNS = 500;
72
+ /** Scoped replan plan-reviewer turn base. */
73
+ const SCOPED_REPLAN_REVIEWER_MAX_TURNS = 500;
74
+ /** Harvester turn base: it writes docs/changelog across the whole epic. */
75
+ const HARVESTER_MAX_TURNS = 500;
76
+ /** Deployer turn base: it runs real deploy commands per a runbook. */
77
+ const DEPLOYER_MAX_TURNS = 500;
78
+ /**
79
+ * Regression turn base: the real functional suite alone spends roughly one
80
+ * turn per liveness poll for the better part of an hour, and this single
81
+ * dispatch carries both it and the sandbox smoke sprint.
82
+ */
83
+ const REGRESSION_TEST_MAX_TURNS = 500;
84
+ /**
85
+ * Integ turn base: a compliant runner spends ~1 turn per liveness poll, but a
86
+ * real per-feature pass also spends fast, sub-poll turns, so the WALL-CLOCK
87
+ * ceiling (max_total_s) is what should bind first on any progressing run.
88
+ */
89
+ const INTEG_TEST_MAX_TURNS = 500;
90
+ /**
91
+ * Final review turn base: it reads the full diff/evidence across an entire
92
+ * epic's worth of closed tasks, and a timeout here flips a whole sprint's
93
+ * outcome to FAIL.
94
+ */
95
+ const FINAL_REVIEW_MAX_TURNS = 500;
96
+ /**
97
+ * Per-round reviewer turn base: a full-cycle review can genuinely exhaust the
98
+ * fleet's default turn budget, and a fresh retry deterministically hits the
99
+ * same wall -- hence the explicit budget plus the same-session resume.
100
+ */
101
+ const BASE_REVIEWER_MAX_TURNS = 500;
102
+ /**
103
+ * Doer streak turn base. A streak runs a full impl+test+commit cycle, which is
104
+ * categorically heavier than a one-shot prompt; the resume ladder escalates
105
+ * from here by doubling, bounded by the row's resumeAttempts.
106
+ */
107
+ const BASE_DOER_MAX_TURNS = 500;
108
+
109
+ /**
110
+ * Every turn-base constant a policy's `maxTurns.base` may name, keyed by that
111
+ * name. A policy naming a base absent from this map is a table/engine
112
+ * mismatch and throws at dispatch time rather than silently dispatching with
113
+ * no turn budget at all.
114
+ */
115
+ export const TURN_BASES = Object.freeze({
116
+ PLANNER_MAX_TURNS,
117
+ PLAN_REVIEWER_MAX_TURNS,
118
+ SCOPED_REPLAN_PLANNER_MAX_TURNS,
119
+ SCOPED_REPLAN_REVIEWER_MAX_TURNS,
120
+ HARVESTER_MAX_TURNS,
121
+ DEPLOYER_MAX_TURNS,
122
+ REGRESSION_TEST_MAX_TURNS,
123
+ INTEG_TEST_MAX_TURNS,
124
+ FINAL_REVIEW_MAX_TURNS,
125
+ BASE_REVIEWER_MAX_TURNS,
126
+ BASE_DOER_MAX_TURNS,
127
+ });
128
+
129
+ /**
130
+ * The ladder's real timed backoff sleeps exist purely for production
131
+ * busy-lock resilience; a hermetic mock run has no busy-lock to wait out, so
132
+ * the harness sets this flag to exercise the full ladder LOGIC with zero
133
+ * wall-clock. The delay values and the "waiting Ns" log line are unchanged
134
+ * either way, so observable behaviour matches. Same env var the planner's
135
+ * inline ladder read before this migration.
136
+ */
137
+ function instantRetryBackoff() {
138
+ return process.env.APRA_FLEET_MOCK_INSTANT_RETRY_BACKOFF === '1';
139
+ }
140
+
141
+ // -----------------------------------------------------------------------------
142
+ // Policy -> runtime resolution. Each function turns ONE policy field into the
143
+ // value the dispatch actually needs, and throws (rather than defaulting) when
144
+ // the table names something the engine cannot resolve.
145
+ // -----------------------------------------------------------------------------
146
+
147
+ /**
148
+ * The member a dispatch routes to, resolved from `policy.member`:
149
+ * 'role' -- ctx.getMemberForRole(member.role)
150
+ * 'pool-head' -- bindings[member.binding], a runner-local pool head
151
+ * 'runtime' -- bindings[member.binding], a runner-local binding
152
+ *
153
+ * @param {object} ctx
154
+ * @param {{kind:string, role?:string, binding?:string}} member
155
+ * @param {Record<string, any>} bindings
156
+ * @returns {string}
157
+ */
158
+ export function resolveMember(ctx, member, bindings = {}) {
159
+ if (member && member.kind === 'role') return ctx.getMemberForRole(member.role);
160
+ if (member && (member.kind === 'pool-head' || member.kind === 'runtime')) {
161
+ const value = bindings[member.binding];
162
+ if (value === undefined) {
163
+ throw new Error(
164
+ `dispatch-role: member binding '${member.binding}' was not supplied in opts.bindings -- a ` +
165
+ `'${member.kind}'-kind member is a runner-local value the engine cannot resolve on its own.`
166
+ );
167
+ }
168
+ return value;
169
+ }
170
+ throw new Error(`dispatch-role: unresolvable member kind ${JSON.stringify(member && member.kind)}.`);
171
+ }
172
+
173
+ /**
174
+ * The model tier a dispatch is priced at, resolved from `policy.model`:
175
+ * 'fixed' -- ctx.fixedRoleTier[model.key]
176
+ * 'per-bead' -- bindings[model.binding] (the doer's declared tier)
177
+ * 'inherited' -- undefined: a resume of an already-priced dispatch passes
178
+ * no tier of its own.
179
+ */
180
+ export function resolveModelTier(ctx, model, bindings = {}) {
181
+ if (!model) return undefined;
182
+ if (model.kind === 'fixed') return ctx.fixedRoleTier[model.key];
183
+ if (model.kind === 'per-bead') return bindings[model.binding];
184
+ if (model.kind === 'inherited') return undefined;
185
+ throw new Error(`dispatch-role: unresolvable model kind ${JSON.stringify(model.kind)}.`);
186
+ }
187
+
188
+ /**
189
+ * A budget (`timeouts.timeoutS` / `timeouts.maxTotalS`) resolved from its
190
+ * SYMBOLIC name against ctx.budgets. null means "pass nothing and take the
191
+ * transport default", which is a policy value in its own right (streak
192
+ * assignment), not a missing one.
193
+ */
194
+ export function resolveBudget(ctx, name) {
195
+ if (name === null || name === undefined) return undefined;
196
+ const value = ctx.budgets ? ctx.budgets[name] : undefined;
197
+ if (value === undefined) {
198
+ throw new Error(`dispatch-role: policy names budget '${name}', which ctx.budgets does not supply.`);
199
+ }
200
+ return value;
201
+ }
202
+
203
+ /**
204
+ * The turn budget a dispatch passes, resolved from `policy.maxTurns`:
205
+ * null -- no max_turns at all (the transport default)
206
+ * 'constant' -- TURN_BASES[base] * multiplier
207
+ * 'runtime' -- bindings[binding], computed per resume attempt
208
+ */
209
+ export function resolveMaxTurns(maxTurns, bindings = {}) {
210
+ if (!maxTurns) return undefined;
211
+ if (maxTurns.kind === 'runtime') return bindings[maxTurns.binding];
212
+ return turnBaseValue(maxTurns.base) * maxTurns.multiplier;
213
+ }
214
+
215
+ function turnBaseValue(name) {
216
+ const base = TURN_BASES[name];
217
+ if (typeof base !== 'number') {
218
+ throw new Error(
219
+ `dispatch-role: policy names turn base '${name}', which is not one of TURN_BASES ` +
220
+ `(${Object.keys(TURN_BASES).join(', ')}).`
221
+ );
222
+ }
223
+ return base;
224
+ }
225
+
226
+ /**
227
+ * The resume argument, resolved from `policy.resumeArg`:
228
+ * 'same-session' -- true (an in-dispatch continuation of the session just run)
229
+ * 'fresh-session' -- false (a self-contained one-off instruction)
230
+ * 'round-session' -- opts.resumeArg, the runner's per-round session lookup
231
+ * 'worklist' -- opts.resumeArg, the doer's per-worklist resume argument
232
+ * null/absent -- false, NOT undefined (see below)
233
+ *
234
+ * NEVER RETURNS `undefined`. The dispatch below strips undefined options, so
235
+ * an undefined here means the `resume` field is omitted from the payload
236
+ * entirely -- and an omitted `resume` is not neutral: execute_prompt's own
237
+ * default is `resume: true`, a best-effort reattachment to whatever session
238
+ * that member last ran. A dispatch that never declared an intent to continue
239
+ * anything would then silently inherit an unrelated, possibly enormous prior
240
+ * context. Falling back to `false` states the safe intent explicitly instead
241
+ * of letting the transport chain decide it. Every row of the policy table
242
+ * also names its own resumeArg, so this fallback is a backstop for a future
243
+ * row that forgets, not the table's working default.
244
+ */
245
+ export function resolveResumeArg(resumeArg, opts) {
246
+ if (!resumeArg) return false;
247
+ if (resumeArg.kind === 'same-session') return true;
248
+ if (resumeArg.kind === 'fresh-session') return false;
249
+ // A runner-supplied argument: already `false` or an explicit session id at
250
+ // every call site today. `?? false` keeps the never-undefined guarantee if
251
+ // a caller ever omits it.
252
+ return opts.resumeArg ?? false;
253
+ }
254
+
255
+ /**
256
+ * A watchdog label, rebuilt from `policy.watchdog.label`'s segment list: a
257
+ * plain string segment is literal text, an `{ expr }` segment is a runner
258
+ * expression. The only expressions the table uses are turn-base arithmetic
259
+ * (`PLANNER_MAX_TURNS * 2`), evaluated against TURN_BASES, so the watchdog's
260
+ * kill-path identity stays owned by the policy table rather than passed in
261
+ * as an opaque caller string.
262
+ */
263
+ export function resolveWatchdogLabel(segments, bindings = {}) {
264
+ return segments
265
+ .map((segment) => {
266
+ if (typeof segment === 'string') return segment;
267
+ return String(evalLabelExpr(segment.expr, bindings));
268
+ })
269
+ .join('');
270
+ }
271
+
272
+ function evalLabelExpr(expr, bindings) {
273
+ if (Object.prototype.hasOwnProperty.call(bindings, expr)) return bindings[expr];
274
+ const m = /^([A-Za-z_$][\w$]*)(?:\s*\*\s*(\d+))?$/.exec(String(expr).trim());
275
+ if (m && Object.prototype.hasOwnProperty.call(TURN_BASES, m[1])) {
276
+ return m[2] ? TURN_BASES[m[1]] * Number(m[2]) : TURN_BASES[m[1]];
277
+ }
278
+ throw new Error(
279
+ `dispatch-role: watchdog label expression ${JSON.stringify(expr)} is neither a supplied binding nor ` +
280
+ 'turn-base arithmetic over TURN_BASES.'
281
+ );
282
+ }
283
+
284
+ /**
285
+ * The schema object a dispatch validates its output against. Policies record
286
+ * a schema by NAME ('planReviewerVerdict'); ctx.schemas maps that name to the
287
+ * real contracts.mjs schema, so this module never imports the contracts and a
288
+ * policy naming an unknown schema fails loudly instead of dispatching
289
+ * unvalidated.
290
+ */
291
+ function resolveSchema(ctx, schemaName) {
292
+ if (!schemaName) return undefined;
293
+ const schema = ctx.schemas ? ctx.schemas[schemaName] : undefined;
294
+ if (!schema) {
295
+ throw new Error(`dispatch-role: policy names schema '${schemaName}', which ctx.schemas does not supply.`);
296
+ }
297
+ return schema;
298
+ }
299
+
300
+ // -----------------------------------------------------------------------------
301
+ // Degrade: what the caller gets back once a ladder's attempts are spent, per
302
+ // role-policies.mjs's DEGRADE_KINDS.
303
+ // -----------------------------------------------------------------------------
304
+
305
+ /** Every constructor NAME on an error's prototype chain, nearest first. */
306
+ function errorClassNames(err) {
307
+ const names = [];
308
+ for (let proto = err; proto; proto = Object.getPrototypeOf(proto)) {
309
+ const name = proto.constructor && proto.constructor.name;
310
+ if (name) names.push(name);
311
+ if (name === 'Error') break;
312
+ }
313
+ return names;
314
+ }
315
+
316
+ /**
317
+ * Classifies a ladder failure into one of role-policies.mjs's ERROR_CLASSES.
318
+ * The first two are universal:
319
+ * 'schema' -- AgentOutputError: agent()'s own bounded schema-repair loop
320
+ * was exhausted, so no schema-valid output ever arrived;
321
+ * 'dispatch' -- AgentDispatchError/FleetTransportError: the dispatch channel
322
+ * itself failed (a dropped transport is exactly as transient
323
+ * and non-schema as a dispatch error -- neither may abort the
324
+ * whole sprint);
325
+ * null -- anything else, i.e. an unrecognised error class.
326
+ *
327
+ * The remaining three exist only for the roles whose POLICY asks for them,
328
+ * which is what keeps them variances-as-data rather than engine branches:
329
+ * 'infra' -- `degrade.classifiesInfraFailures` (the integ runner): a
330
+ * dispatch that produced no result envelope at all is not a
331
+ * test verdict and must never be recorded as one.
332
+ * 'dispatch' -- also any class named in `degrade.extraDispatchErrors` (the
333
+ * per-round reviewer's own read-side sync-bracket failures).
334
+ * 'sync' -- `degrade.classifiesSyncFailures` (the regression phase):
335
+ * the git/beads sync AROUND the dispatch failed, which for
336
+ * the one phase whose whole job is mutating beads is a
337
+ * routine outcome worth reporting distinctly.
338
+ * 'unknown' -- `degrade.classifiesUnrecognisedErrors` (the regression
339
+ * catch-all): even an unrecognised class gets a degrade path
340
+ * rather than aborting an informational phase.
341
+ *
342
+ * Called with no policy it behaves exactly as the two-class version did.
343
+ *
344
+ * @param {Error} err
345
+ * @param {object} [policy] the ROLE_POLICIES row whose degrade is in force
346
+ */
347
+ export function classifyLadderError(err, policy) {
348
+ const degrade = policy ? policy.degrade : null;
349
+ if (err instanceof AgentOutputError) return 'schema';
350
+ // BEFORE the generic dispatch class: an infra failure IS an
351
+ // AgentDispatchError, and the whole point of the class is telling the two
352
+ // apart for the one role that must not conflate them.
353
+ if (degrade && degrade.classifiesInfraFailures
354
+ && err instanceof AgentDispatchError && isInfraDispatchFailure(err)) {
355
+ return 'infra';
356
+ }
357
+ if (err instanceof AgentDispatchError || err instanceof FleetTransportError) return 'dispatch';
358
+ if (degrade && degrade.extraDispatchErrors.length > 0) {
359
+ const names = errorClassNames(err);
360
+ if (degrade.extraDispatchErrors.some((name) => names.includes(name))) return 'dispatch';
361
+ }
362
+ if (degrade && degrade.classifiesSyncFailures
363
+ && (isPostDispatchSyncFailure(err) || err instanceof WorkflowError)) {
364
+ return 'sync';
365
+ }
366
+ if (degrade && degrade.classifiesUnrecognisedErrors) return 'unknown';
367
+ return null;
368
+ }
369
+
370
+ /**
371
+ * Thrown by the engine itself when a SCHEMA-VALID result is rejected by the
372
+ * caller's own semantic validator under `retry.retryOnInvalidResult`. It is
373
+ * never surfaced to the caller: the ladder either retries the attempt or
374
+ * converts it through `opts.onResultRejected`.
375
+ */
376
+ export class LadderResultRejectedError extends Error {
377
+ constructor(reason) {
378
+ super(`dispatch-role: the ladder's result was rejected by its own validator (${reason}).`);
379
+ this.name = 'LadderResultRejectedError';
380
+ this.reason = reason;
381
+ }
382
+ }
383
+
384
+ /**
385
+ * The value a degrade fabricates for one failed attempt, from
386
+ * `policy.degrade`. Only 'synthesized-verdict' fabricates anything on the
387
+ * planning side: 'fallback-value', 'defer-to-next-cycle' and 'non-approval'
388
+ * all hand the caller `null` and let it apply its own deterministic fallback
389
+ * (selectStreaks' one-bead-per-streak grouping; deferring the flagged beads
390
+ * to the next cycle; treating the scoped round as not approved).
391
+ *
392
+ * `degrade.marker` is stamped on every synthesized value so a degraded result
393
+ * is never mistaken for a genuine one, and `degrade.neverSynthesizes` is what
394
+ * role-policies-table.test.mjs holds this shape to: no degrade path anywhere
395
+ * may fabricate an approval.
396
+ */
397
+ function synthesizeDegradedValue(policy, opts, err, errorClass) {
398
+ const degrade = policy.degrade;
399
+ // `degrade.classes` -- not the degrade KIND -- decides whether this
400
+ // ladder fabricates anything for THIS error class. A ladder that
401
+ // recognises a class but does not list it (streak assignment's
402
+ // 'fallback-value', the scoped replan's 'defer-to-next-cycle') hands the
403
+ // caller null on purpose.
404
+ if (!degrade.synthesized || !degrade.classes.includes(errorClass)) return null;
405
+ const value = { ...degrade.synthesized, [degrade.notesField]: renderDegradeNote(policy, err, errorClass) };
406
+ if (degrade.marker) value[degrade.marker] = true;
407
+ return value;
408
+ }
409
+
410
+ /**
411
+ * apra-fleet-3swo.5.4: the ONE place a degraded value's failure TEXT is
412
+ * built, for every role.
413
+ *
414
+ * Each runner.js dispatch site used to hand the engine its own map of
415
+ * per-class note builders, so six call sites carried six near-identical
416
+ * copies of the same two sentences and any change to the wording had six
417
+ * places to drift. The wording is now `degrade.noteTemplates` DATA in
418
+ * role-policies.mjs and this function is the only thing that reads it.
419
+ *
420
+ * A class the ladder fabricates for but has no template for THROWS rather
421
+ * than falling back to a generic sentence: a silent generic note is exactly
422
+ * how a role's distinct degrade text (the regression phase's "may not have
423
+ * reached the shared remote") would quietly disappear while every test that
424
+ * only checks `typeof notes === 'string'` kept passing.
425
+ *
426
+ * `{message}` falls back to String(err) so a non-Error throw (which only the
427
+ * regression catch-all's 'unknown' class can even reach) still reads as
428
+ * something rather than as an empty note.
429
+ */
430
+ function renderDegradeNote(policy, err, errorClass) {
431
+ const { noteTemplates } = policy.degrade;
432
+ const template = noteTemplates && noteTemplates[errorClass];
433
+ if (typeof template !== 'string') {
434
+ throw new Error(
435
+ `dispatch-role: policy '${policy.role}' fabricates a value for error class '${errorClass}' but records ` +
436
+ 'no degrade.noteTemplates entry for it -- add the template to role-policies.mjs rather than letting the ' +
437
+ 'degrade write an empty note.'
438
+ );
439
+ }
440
+ return template.replace(/\{(message|name)\}/g, (_, field) => {
441
+ if (field === 'name') return String((err && err.name) || 'Error');
442
+ const message = err && err.message;
443
+ return message ? String(message) : String(err);
444
+ });
445
+ }
446
+
447
+ /**
448
+ * The DEGRADE_STEPS a policy runs on each attempt that degrades (as opposed
449
+ * to `postResult`, which runs only after a SUCCESSFUL attempt). The one step
450
+ * today is the per-round reviewer's 'clear-round-session': a failed round's
451
+ * session must not be resumed by the next round, and a successful one must.
452
+ */
453
+ async function runDegradeSteps(ctx, policy, err, errorClass) {
454
+ for (const step of policy.degrade.steps) {
455
+ const hook = ctx.steps && ctx.steps[step];
456
+ if (typeof hook !== 'function') {
457
+ throw new Error(`dispatch-role: policy names degrade step '${step}', which ctx.steps does not supply.`);
458
+ }
459
+ await hook({ policy, error: err, errorClass });
460
+ }
461
+ }
462
+
463
+ // -----------------------------------------------------------------------------
464
+ // The engine.
465
+ // -----------------------------------------------------------------------------
466
+
467
+ /**
468
+ * Runs `roleName`'s dispatch ladder exactly as role-policies.mjs describes it.
469
+ *
470
+ * @param {object} ctx runner-supplied primitives (see this file's header):
471
+ * agent, withGitSync, withDispatchWatchdog, log, getMemberForRole,
472
+ * memberSessionGuard, onLlmAuthFailure, fixedRoleTier, budgets, schemas,
473
+ * isNoMutationDispatchFailure, invalidateAllBeadsCache, steps.
474
+ * @param {string} roleName a key of ROLE_POLICIES.
475
+ * @param {object} opts per-call values the policy deliberately does not carry:
476
+ * prompt -- the built prompt (required)
477
+ * resumePrompt -- the prompt a 'max-turns-resume' secondary sends
478
+ * repairPrompt -- (reason) => prompt, for a 'semantic-repair-re-ask'
479
+ * validate -- (value) => { ok, reason, result }: the semantic
480
+ * validation `postResult: ['select-streaks-validate']`
481
+ * names. Its `result` comes back as `validation`.
482
+ * resumeArg -- runtime value for a 'round-session'/'worklist' resumeArg
483
+ * onSessionId -- session-id recorder
484
+ * bindings -- runner-local values a policy names by binding
485
+ * roleLabel -- human role name used in this engine's log lines
486
+ * label/resumeLabel/repairLabel -- presentation labels (NOT policy: see
487
+ * role-policies.mjs's "deliberately out of scope" note)
488
+ * attemptOptions -- ({ attempt, skipPreDispatchSync }) => extra withGitSync options
489
+ * afterAttempt -- async (value) => void, run INSIDE the attempt's try so
490
+ * a failure in it is classified by the same ladder
491
+ * onResultRejected -- (reason) => Error, the error a `retryOnInvalidResult`
492
+ * ladder throws once its budget is spent on results its
493
+ * own validator keeps rejecting
494
+ * prepare -- async ({dispatch, resumeAttempt}) => {prompt, label,
495
+ * resumeArg, bindings}: per-dispatch values that are only
496
+ * knowable INSIDE the git-sync bracket, after this
497
+ * dispatch's in-bracket pre-dispatch steps have run (the
498
+ * doer's streak narrows when the claim finds beads another
499
+ * sprint already holds, and its prompt/label/tier follow)
500
+ * bindings -- runner-local values a policy names by binding; a
501
+ * FUNCTION ({resumeAttempt}) => bindings when a value
502
+ * differs per resume (the doer's escalating turn budget)
503
+ * @returns {Promise<{ok:boolean, value:any, error:Error|null, degraded:boolean,
504
+ * inconclusive:{reason:string,message:string}|null,
505
+ * attempts:number, resumesIssued:number,
506
+ * stepResults:Record<string,any>, validation:any}>}
507
+ */
508
+ export async function dispatchRole(ctx, roleName, opts = {}) {
509
+ // Destructured so this module's ONE dispatch reads `agent(` -- the literal
510
+ // token dispatch-safety-guard.mjs and inline-ladder-guard.mjs scan for. A
511
+ // `ctx.agent(` call would fall outside both guards' call-site regexes and
512
+ // leave this file's only dispatch silently unguarded.
513
+ const { agent } = ctx;
514
+ // ctx.policies: the table this run reads its row from, defaulting to the
515
+ // real frozen ROLE_POLICIES. It exists so a test can splice ONE field of
516
+ // ONE row and observe the engine behave differently -- which is the only
517
+ // way to prove a per-role variance (the integ INCONCLUSIVE record, the
518
+ // regression catch-all, the final-review heal short-circuit, the
519
+ // deployer's pre-dispatch prompt invariant) is really driven by POLICY
520
+ // DATA rather than by a branch in this file that happens to agree with
521
+ // the table. Production never passes it.
522
+ const policy = ctx.policies ? policyFor(roleName, ctx.policies) : policyFor(roleName);
523
+ /**
524
+ * The runner-local values a policy names by binding. A FUNCTION when a
525
+ * value differs per resume attempt -- the doer's escalating turn budget is
526
+ * computed from the attempt number, so the table records it as a
527
+ * 'runtime' turn budget and the runner supplies the arithmetic.
528
+ */
529
+ const bindingsFor = (resumeAttempt = 0) => (typeof opts.bindings === 'function'
530
+ ? opts.bindings({ resumeAttempt })
531
+ : (opts.bindings || {}));
532
+ const bindings = bindingsFor(0);
533
+ const member = resolveMember(ctx, policy.member, bindings);
534
+ const roleLabel = opts.roleLabel || policy.role;
535
+ const retry = policy.retry;
536
+ const backoffMs = retry.backoffMs;
537
+ const attempts = retry.attempts;
538
+
539
+ // --- ONE dispatch, however the policy shapes it ------------------------
540
+ // Every per-dispatch difference (member, persona, tier, budgets, turn
541
+ // budget, schema, resume argument) is resolved from the policy row rather
542
+ // than written out again per role. member_name is spelled at the call site
543
+ // itself, never folded into `options`, because dispatch-safety-guard.mjs
544
+ // requires every agent() call site to name its member explicitly.
545
+ //
546
+ // EVERYTHING IS RESOLVED INSIDE `invoke`, i.e. INSIDE the git-sync bracket
547
+ // when there is one. That matters for exactly one reason, and it is a real
548
+ // one: an in-bracket pre-dispatch step can CHANGE what the dispatch should
549
+ // say. The doer claims its beads after the bracket's D-pull, which is what
550
+ // reveals that another sprint already holds some of them; the streak
551
+ // narrows, and its prompt, its label and the tier it is priced at all
552
+ // follow. Resolving options before the bracket opened would dispatch the
553
+ // pre-claim scope.
554
+ const runDispatch = (dispatch, defaultPrompt, defaultLabel, attemptOpts, extra = {}) => {
555
+ const invoke = async () => {
556
+ // In-bracket pre-dispatch steps, then the caller's own preparation.
557
+ const inBracket = await runPreDispatchSteps(ctx, dispatch, member, opts, extra, 'in-bracket');
558
+ if (inBracket) return inBracket.value;
559
+ const prepared = opts.prepare ? await opts.prepare({ dispatch, ...extra }) : {};
560
+ const localBindings = { ...bindingsFor(extra.resumeAttempt || 0), ...(prepared.bindings || {}) };
561
+ const localOpts = prepared.resumeArg !== undefined ? { ...opts, resumeArg: prepared.resumeArg } : opts;
562
+ const options = {
563
+ agentType: dispatch.agentType ?? undefined,
564
+ model: resolveModelTier(ctx, dispatch.model, localBindings),
565
+ timeout_s: resolveBudget(ctx, dispatch.timeouts.timeoutS),
566
+ max_total_s: resolveBudget(ctx, dispatch.timeouts.maxTotalS),
567
+ max_turns: resolveMaxTurns(dispatch.maxTurns, localBindings),
568
+ schema: resolveSchema(ctx, dispatch.schema),
569
+ resume: resolveResumeArg(dispatch.resumeArg, localOpts),
570
+ onSessionId: opts.onSessionId,
571
+ label: prepared.label ?? defaultLabel,
572
+ };
573
+ for (const key of Object.keys(options)) {
574
+ if (options[key] === undefined) delete options[key];
575
+ }
576
+ const inFlight = agent(prepared.prompt ?? defaultPrompt, {
577
+ ...options,
578
+ member_name: member,
579
+ });
580
+ if (!dispatch.watchdog.armed) return inFlight;
581
+ // Raced against a client-side watchdog so a frozen-but-alive
582
+ // member session can never leave this await silently hanging past
583
+ // its budget -- needed in ADDITION to, not instead of, the
584
+ // server-side timeout_s/max_total_s above.
585
+ return ctx.withDispatchWatchdog(inFlight, {
586
+ timeoutS: resolveBudget(ctx, dispatch.watchdog.timeoutS),
587
+ member,
588
+ label: resolveWatchdogLabel(dispatch.watchdog.label, localBindings),
589
+ log: ctx.log,
590
+ });
591
+ };
592
+ // `dispatch.bracket`, not `policy.bracket`: a secondary dispatch
593
+ // inherits its main dispatch's bracket by spread today, but reading it
594
+ // off the dispatch actually being run is what keeps that an inherited
595
+ // DEFAULT rather than a hard-wired assumption the table cannot
596
+ // override.
597
+ if (!dispatch.bracket.wrapped) return invoke();
598
+ return ctx.withGitSync(member, dispatch.bracket.pushCode === true, invoke, {
599
+ pushBeads: dispatch.bracket.pushBeads === true,
600
+ ...(attemptOpts || {}),
601
+ });
602
+ };
603
+
604
+ // --- one ATTEMPT: the main dispatch, plus the resume it may need --------
605
+ // TWO conditions reach the SAME secondary dispatch, and the policy says
606
+ // which of them this ladder honours:
607
+ // retry.maxTurnsResume -- the turn budget was spent. Universal.
608
+ // retry.infraResumeAttempts -- the member CLI died mid-turn and lost
609
+ // its result envelope, so the run may have
610
+ // made real progress and merely failed to
611
+ // report it. The integ runner alone, and
612
+ // bounded at one recovery.
613
+ const runAttempt = async (attemptOpts) => {
614
+ const preShortCircuit = await runPreDispatchSteps(ctx, policy, member, opts, {});
615
+ if (preShortCircuit) return preShortCircuit.value;
616
+ try {
617
+ return await runDispatch(policy, opts.prompt, opts.label, attemptOpts);
618
+ } catch (err) {
619
+ const secondary = policy.secondary;
620
+ const isTurnExhaustion = err instanceof AgentDispatchError
621
+ && err.details && err.details.reason === 'max_turns_exhausted';
622
+ const isInfra = err instanceof AgentDispatchError && isInfraDispatchFailure(err);
623
+ const resumesOnExhaustion = retry.maxTurnsResume && isTurnExhaustion;
624
+ const resumesOnInfra = retry.infraResumeAttempts > 0 && isInfra && !isTurnExhaustion;
625
+ if (!secondary || secondary.kind !== 'max-turns-resume' || (!resumesOnExhaustion && !resumesOnInfra)) {
626
+ throw err;
627
+ }
628
+ // A BOUNDED ladder of resumes, not a single one: retry.resumeAttempts
629
+ // says how many, and retry.turnEscalation='double' is performed by
630
+ // the runtime turn budget the policy names (the runner's bindings
631
+ // thunk is handed the attempt number). A resume that fails for any
632
+ // reason OTHER than spending its turns again is not something more
633
+ // turns can fix, so the escalation stops there.
634
+ let resumeAttempt = 0;
635
+ let lastResumeErr = err;
636
+ while (resumeAttempt < Math.max(retry.resumeAttempts, resumesOnInfra ? 1 : 0)) {
637
+ resumeAttempt += 1;
638
+ // A resume follows an agent that DID run (max_turns_exhausted is
639
+ // a resumable partial-work case, not a no-mutation failure), so
640
+ // it always runs the full pre-dispatch sync -- no attemptOpts.
641
+ //
642
+ // Run BEFORE announcing the resume: a pre-dispatch step may find
643
+ // the work already DONE (the doer's 'verify-streak-closed': a
644
+ // streak whose beads all closed before the turn limit hit is a
645
+ // success that merely missed its VERIFY checkpoint), and
646
+ // announcing a resume that never happens reads as a wasted
647
+ // dispatch in the log.
648
+ const shortCircuit = await runPreDispatchSteps(ctx, secondary, member, opts, { resumeAttempt });
649
+ if (shortCircuit) return shortCircuit.value;
650
+ if (resumeAttempt === 1 && resumesOnExhaustion) {
651
+ ctx.log(
652
+ `${roleLabel} exhausted its turn limit ` +
653
+ `(max_turns=${resolveMaxTurns(policy.maxTurns, bindingsFor(0))}) -- resuming the same ` +
654
+ `session with max_turns=${resolveMaxTurns(secondary.maxTurns, bindingsFor(1))}.`
655
+ );
656
+ } else if (resumeAttempt === 1) {
657
+ ctx.log(
658
+ `${roleLabel}: infrastructure dispatch failure ` +
659
+ `(${(err.details && err.details.reason) || 'unknown'}) -- the member produced no result ` +
660
+ 'envelope. This is NOT a failure verdict; resuming the same session once to recover ' +
661
+ 'before recording anything.'
662
+ );
663
+ } else {
664
+ ctx.log(
665
+ `${roleLabel} exhausted its turn limit again -- resuming the same session with ` +
666
+ `max_turns=${resolveMaxTurns(secondary.maxTurns, bindingsFor(resumeAttempt))} ` +
667
+ `(attempt ${resumeAttempt}/${retry.resumeAttempts}).`
668
+ );
669
+ }
670
+ resumesIssued += 1;
671
+ try {
672
+ return await runDispatch(secondary, opts.resumePrompt, opts.resumeLabel, undefined, { resumeAttempt });
673
+ } catch (resumeErr) {
674
+ lastResumeErr = resumeErr;
675
+ const exhaustedAgain = resumeErr instanceof AgentDispatchError
676
+ && resumeErr.details && resumeErr.details.reason === 'max_turns_exhausted';
677
+ if (retry.maxTurnsResume && exhaustedAgain) continue;
678
+ throw resumeErr;
679
+ }
680
+ }
681
+ // The escalating ladder is spent. A ladder that declares
682
+ // abortAfterSpentResumeLadder has thereby PROVED the task is too
683
+ // large for one streak, so another full attempt at the same size
684
+ // would only reproduce it; the caller is told so instead.
685
+ resumeLadderSpent = retry.abortAfterSpentResumeLadder;
686
+ throw lastResumeErr;
687
+ }
688
+ };
689
+
690
+ // A usage-limit re-dispatch after the controller reported the member is
691
+ // usable again (apra-fleet-hzeb.4.2). It mirrors runAttempt's resume path:
692
+ // it runs the resume dispatch's own pre-dispatch steps, then the resume
693
+ // dispatch itself, so a role with a resume ladder continues the SAME member
694
+ // session it hit the limit on (warm context kept) rather than starting a
695
+ // fresh one. Only reached when the failing attempt reported a sessionId and
696
+ // the role actually has a max-turns resume secondary; otherwise the caller
697
+ // re-runs runAttempt fresh.
698
+ const redispatchViaUsageLimitResume = async (attemptOpts) => {
699
+ const secondary = policy.secondary;
700
+ const shortCircuit = await runPreDispatchSteps(ctx, secondary, member, opts, { resumeAttempt: 1 });
701
+ if (shortCircuit) return shortCircuit.value;
702
+ return runDispatch(secondary, opts.resumePrompt ?? opts.prompt, opts.resumeLabel ?? opts.label, attemptOpts, { resumeAttempt: 1 });
703
+ };
704
+
705
+ let lastErr = null;
706
+ let value;
707
+ let ok = false;
708
+ let degradedValue = null;
709
+ let skipPreDispatchSyncNext = false;
710
+ // Set once an auth self-heal succeeded under retry.authSelfHealShortCircuits:
711
+ // the attempt it grants is the ladder's last, whatever it returns.
712
+ let healRetryIsFinal = false;
713
+ // How many attempts the ladder really made, and how many resume dispatches
714
+ // it issued. Surfaced on the outcome because a caller can legitimately
715
+ // need to know (the doer records whether a streak was retried).
716
+ let attemptsMade = 0;
717
+ let resumesIssued = 0;
718
+ let stepResults = {};
719
+ // Set when an attempt's escalating resume ladder ran out under a policy
720
+ // that treats that as terminal. Reset per attempt.
721
+ let resumeLadderSpent = false;
722
+ // apra-fleet-hzeb.4.2: pending usage-limit re-dispatch mode for the NEXT
723
+ // loop pass. null = normal attempt; 'fresh' = re-run runAttempt after a
724
+ // paused-then-resumed member; 'resume' = continue the SAME session via the
725
+ // resume ladder. A usage-limit re-dispatch does NOT consume a ladder
726
+ // attempt (see the hook below), so it also skips the retry backoff.
727
+ let usageLimitRedispatch = null;
728
+
729
+ for (let attempt = 1; attempt <= attempts; attempt++) {
730
+ if (!usageLimitRedispatch && backoffMs && backoffMs[attempt - 1] > 0) {
731
+ ctx.log(
732
+ `${roleLabel} dispatch: waiting ${backoffMs[attempt - 1] / 1000}s before retry attempt ` +
733
+ `${attempt}/${backoffMs.length}...`
734
+ );
735
+ if (!instantRetryBackoff()) {
736
+ await new Promise((resolve) => setTimeout(resolve, backoffMs[attempt - 1]));
737
+ }
738
+ }
739
+ attemptsMade = attempt;
740
+ resumeLadderSpent = false;
741
+ try {
742
+ // A generic retry resumes onto the streak branch's REMOTE TIP so it
743
+ // builds on already-published work instead of re-implementing the
744
+ // task as a divergent, content-identical duplicate commit that can
745
+ // never fast-forward. Only after a failure that may have committed:
746
+ // an auth/trust failure provably ran nothing, so its retry keeps
747
+ // plain ff-only pre-dispatch sync.
748
+ const retryFollowsPossibleMutation = attempt > 1 && lastErr
749
+ && !isNonRetryableDispatchError(lastErr);
750
+ const attemptOpts = {
751
+ ...(retry.skipPreDispatchSyncOnNoMutation ? { skipPreDispatchSync: skipPreDispatchSyncNext } : {}),
752
+ ...(retry.resumeOntoRemoteTipOnRetry && retryFollowsPossibleMutation
753
+ ? { resumeOntoRemoteTip: true }
754
+ : {}),
755
+ ...(opts.attemptOptions ? opts.attemptOptions({ attempt }) : {}),
756
+ };
757
+ // A usage-limit resume re-dispatch continues the same session via
758
+ // the resume ladder; every other pass (including a 'fresh'
759
+ // usage-limit re-dispatch) is a normal full attempt. Read and clear
760
+ // the mode BEFORE the await so a failing re-dispatch never leaves a
761
+ // stale mode armed for a later attempt -- the hook re-sets it if the
762
+ // re-dispatch hits the limit again.
763
+ const redispatchMode = usageLimitRedispatch;
764
+ usageLimitRedispatch = null;
765
+ value = redispatchMode === 'resume'
766
+ ? await redispatchViaUsageLimitResume(attemptOpts)
767
+ : await runAttempt(attemptOpts);
768
+ if (opts.afterAttempt) await opts.afterAttempt(value);
769
+ // A postResult step may REJECT the result (the reviewer's
770
+ // contract guard: a CHANGES_NEEDED verdict with nothing for the
771
+ // orchestrator to act on is self-contradictory). Steps run in
772
+ // order and the rejection throws immediately, so a later step
773
+ // never acts on a result the ladder has already judged unusable.
774
+ stepResults = await runPostResultSteps(ctx, policy, value, opts, member);
775
+ ok = true;
776
+ lastErr = null;
777
+ degradedValue = null;
778
+ break;
779
+ } catch (err) {
780
+ lastErr = err;
781
+
782
+ // A rejected-but-schema-valid result is NOT a degrade: the
783
+ // dispatch worked, its answer was unusable. Retry the whole
784
+ // attempt inside the same budget -- a nudge cannot fix a verdict
785
+ // that contradicts itself, only a fresh review can -- then hand
786
+ // the caller its own error rather than a fabricated value.
787
+ if (err instanceof LadderResultRejectedError) {
788
+ if (retry.retryOnInvalidResult && attempt < attempts) {
789
+ ctx.log(
790
+ `${roleLabel}: result rejected (${err.reason}) -- re-running the dispatch ` +
791
+ `(attempt ${attempt + 1} of ${attempts}) before treating this as a distinct failure.`
792
+ );
793
+ continue;
794
+ }
795
+ throw opts.onResultRejected ? opts.onResultRejected(err.reason) : err;
796
+ }
797
+
798
+ // The turn ALREADY RAN and its output is committed on the member's
799
+ // own clone -- only the post-dispatch sync failed, and withGitSync
800
+ // already retried that step on its own. Re-dispatching would spawn
801
+ // a second session for the same phase on top of completed work.
802
+ //
803
+ // This ENDS the ladder but still runs the degrade below, because
804
+ // "the dispatch ran and its writes are local" is itself something
805
+ // a caller may need reported: the regression phase, whose whole job
806
+ // is filing carry-over beads, has to say in its summary that they
807
+ // may not have reached the shared remote. A ladder that fabricates
808
+ // nothing for this class (the planner, the doer) is unaffected --
809
+ // its degrade.classes simply does not list it.
810
+ const completedButSyncFailed =
811
+ (retry.skipRedispatchOnPostDispatchSyncFailure && isPostDispatchSyncFailure(err))
812
+ || resumeLadderSpent;
813
+ if (retry.skipRedispatchOnPostDispatchSyncFailure && isPostDispatchSyncFailure(err)) {
814
+ ctx.log(
815
+ `${roleLabel} dispatch COMPLETED but its post-dispatch sync failed: ${err.message} Aborting ` +
816
+ 'retries WITHOUT re-dispatching -- the turn already ran and its writes are local; fix the sync ' +
817
+ 'and re-run.'
818
+ );
819
+ }
820
+
821
+ // Only a provably no-mutation dispatch failure leaves the workspace
822
+ // unchanged, so only then may the next attempt skip its
823
+ // pre-dispatch sync. Any other error re-arms it.
824
+ if (!completedButSyncFailed && retry.skipPreDispatchSyncOnNoMutation) {
825
+ skipPreDispatchSyncNext = ctx.isNoMutationDispatchFailure(err);
826
+ }
827
+
828
+ // Usage-limit pause/resume (apra-fleet-hzeb.4.2). A provider
829
+ // rate/usage limit is neither a failure of this role nor something a
830
+ // retry ladder can out-wait on its own budget -- it needs a real
831
+ // wall-clock wait until the quota window resets. When the policy
832
+ // arms usageLimitPause and the runner wired an onUsageLimit
833
+ // controller, hand the signal to it: it pauses the whole run through
834
+ // the engine's cooperative pause primitive (releasing reservations,
835
+ // showing the resume time on the dashboard), waits, re-probes the
836
+ // member on a bounded backoff, and reports whether the member is
837
+ // usable again. A resumed member RE-DISPATCHES this role WITHOUT
838
+ // consuming one of the ladder's real attempts; an exhausted wait
839
+ // gives up with the controller's typed UsageLimitWaitExhaustedError
840
+ // (registered in abort.mjs's isTypedAbortError, so it routes through
841
+ // finalizeAbort()/an [ABORTED] PR like every other terminal abort).
842
+ //
843
+ // This runs OUTSIDE any withGitSync bracket: the failing dispatch's
844
+ // bracket has fully unwound by the time its error reaches this catch
845
+ // (openSyncBracketCount is back to 0), which is what lets the
846
+ // engine's clean-state pause guard actually engage the pause -- a
847
+ // pause requested mid-bracket would be deferred forever.
848
+ if (!completedButSyncFailed && retry.usageLimitPause
849
+ && isUsageLimitDispatchError(err) && typeof ctx.onUsageLimit === 'function') {
850
+ const failedSessionId = (err.details && err.details.sessionId) || null;
851
+ const outcome = await ctx.onUsageLimit({
852
+ member,
853
+ roleLabel,
854
+ signal: usageLimitOf(err),
855
+ sessionId: failedSessionId,
856
+ tier: resolveModelTier(ctx, policy.model, bindings),
857
+ });
858
+ if (outcome && outcome.resumed) {
859
+ // The member is usable again: re-dispatch this role without
860
+ // charging a ladder attempt. Prefer resuming the reported
861
+ // session when the role actually HAS a resume ladder (warm
862
+ // context kept); otherwise re-dispatch fresh.
863
+ const canResumeSession = Boolean(failedSessionId) && retry.resumeAttempts > 0
864
+ && policy.secondary && policy.secondary.kind === 'max-turns-resume';
865
+ usageLimitRedispatch = canResumeSession ? 'resume' : 'fresh';
866
+ attempt -= 1;
867
+ continue;
868
+ }
869
+ // The controller waited/re-probed to its budget and the member
870
+ // is still limited: its typed give-up error is this ladder's
871
+ // last word and propagates straight out (no degrade).
872
+ throw (outcome && outcome.error) || err;
873
+ }
874
+
875
+ // Auth/workspace-trust failures are deterministic -- no retry can
876
+ // succeed -- so a ladder that declares abortOnNonRetryable ends
877
+ // rather than burning its remaining attempts on the same wall.
878
+ // Deliberately WITHOUT a degrade: a ladder that aborts here has a
879
+ // credentials/trust problem to fix, not a result to fabricate.
880
+ if (!completedButSyncFailed && retry.abortOnNonRetryable && isNonRetryableDispatchError(err)) {
881
+ // An LLM-auth failure (unlike workspace trust, which self-heal
882
+ // cannot fix) gets one bounded self-heal attempt first.
883
+ if (retry.authSelfHeal && isAuthDispatchError(err) && typeof ctx.onLlmAuthFailure === 'function') {
884
+ const healed = await ctx.onLlmAuthFailure({
885
+ member, label: `${roleLabel} dispatch`, error: err.message,
886
+ });
887
+ if (healed) {
888
+ ctx.log(`${roleLabel} dispatch: LLM auth self-heal succeeded -- retrying.`);
889
+ // retry.authSelfHealShortCircuits: the healed retry is
890
+ // this ladder's LAST word. A role whose dispatch is
891
+ // the single most expensive in the sprint (final
892
+ // review) must not fall through to the generic retry
893
+ // as well -- that fires a SECOND full review and
894
+ // silently discards the healed verdict, which for a
895
+ // PASS/FAIL gate can invert the sprint's outcome.
896
+ healRetryIsFinal = retry.authSelfHealShortCircuits;
897
+ continue;
898
+ }
899
+ }
900
+ ctx.log(
901
+ `${roleLabel} dispatch threw a non-retryable error (auth/trust): ${err.message}. Aborting ` +
902
+ "retries -- fix the member's credentials/trust and re-run."
903
+ );
904
+ // A ladder whose own failure legitimately fails the whole
905
+ // sprint propagates instead of degrading: with the dispatch
906
+ // channel walled off there is no judgement to fabricate.
907
+ if (retry.rethrowsUnhealedNonRetryable) throw err;
908
+ break;
909
+ }
910
+
911
+ // A ladder that does NOT abort on a non-retryable error still
912
+ // self-heals an unhealed LLM-auth failure, because the SAME member
913
+ // is dispatched again later in the cycle and would otherwise walk
914
+ // into the identical wall.
915
+ if (!completedButSyncFailed && !retry.abortOnNonRetryable && retry.authSelfHeal
916
+ && isAuthDispatchError(err) && typeof ctx.onLlmAuthFailure === 'function') {
917
+ await ctx.onLlmAuthFailure({ member, label: `${roleLabel} dispatch`, error: err.message });
918
+ }
919
+
920
+ // RUN-level control signals are not failures of this role at all,
921
+ // so they keep propagating even through a catch-all that swallows
922
+ // everything else: honouring a cancellation outranks finishing an
923
+ // informational phase, and swallowing a blown spend ceiling would
924
+ // let the run keep spending past a limit the operator set.
925
+ if (policy.degrade.rethrowsRunControlSignals.length > 0) {
926
+ const names = errorClassNames(err);
927
+ if (policy.degrade.rethrowsRunControlSignals.some((name) => names.includes(name))) {
928
+ ctx.log(`${roleLabel}: run-level ${names[0] || 'control signal'} received -- not retrying this dispatch: ${err.message}`);
929
+ throw err;
930
+ }
931
+ }
932
+
933
+ const errorClass = classifyLadderError(err, policy);
934
+ // An unrecognised error class still propagates rather than being
935
+ // degraded silently -- except under a degrade that declares
936
+ // otherwise, and except under 'fatal', whose whole contract is to
937
+ // accumulate and rethrow after the ladder is spent.
938
+ if (errorClass === null && policy.degrade.kind !== 'fatal'
939
+ && policy.degrade.rethrowsUnrecognisedErrors) {
940
+ throw err;
941
+ }
942
+ if (errorClass === 'schema') {
943
+ ctx.log(`${roleLabel}: schema-repair exhausted, degrading (${policy.degrade.kind}): ${err.message}`);
944
+ } else if (errorClass === 'dispatch') {
945
+ ctx.log(`${roleLabel}: agent dispatch failed, degrading (${policy.degrade.kind}): ${err.message}`);
946
+ } else if (errorClass === 'infra') {
947
+ ctx.log(
948
+ `${roleLabel}: infrastructure dispatch failure persisted -- degrading ` +
949
+ `(${policy.degrade.kind}), NOT recording a failure verdict: ${err.message}`
950
+ );
951
+ } else if (errorClass === 'sync') {
952
+ ctx.log(
953
+ `${roleLabel}: the git/beads sync around the dispatch FAILED (${err.name}: ${err.message}) -- ` +
954
+ `degrading (${policy.degrade.kind}). Anything this phase filed may still be local-only.`
955
+ );
956
+ } else if (errorClass === 'unknown') {
957
+ ctx.log(
958
+ `${roleLabel}: unexpected error, degrading (${policy.degrade.kind}) -- this phase never aborts ` +
959
+ `the sprint: ${err && err.stack ? err.stack : err}`
960
+ );
961
+ }
962
+ await runDegradeSteps(ctx, policy, err, errorClass);
963
+ degradedValue = synthesizeDegradedValue(policy, opts, err, errorClass);
964
+ const isLastAttempt = attempt === attempts || healRetryIsFinal || completedButSyncFailed;
965
+ ctx.log(
966
+ `${roleLabel} dispatch threw: ${err.message}.` +
967
+ (isLastAttempt ? ' Retries exhausted.' : ` Retrying (attempt ${attempt + 1} of ${attempts}).`)
968
+ );
969
+ if (healRetryIsFinal || completedButSyncFailed) break;
970
+ }
971
+ }
972
+
973
+ if (!ok) {
974
+ // The one FATAL degrade in the table: there is no sprint without a
975
+ // plan, so an exhausted planner ladder rethrows rather than
976
+ // synthesizing one.
977
+ if (policy.degrade.kind === 'fatal' && lastErr) throw lastErr;
978
+ return {
979
+ ok: false,
980
+ value: degradedValue,
981
+ error: lastErr,
982
+ degraded: true,
983
+ // An 'inconclusive' degrade whose terminal failure really was an
984
+ // envelope-less infra fault reports WHY there is no verdict, so
985
+ // the caller records "no evidence" instead of "the tests failed".
986
+ // Driven by degrade.kind: any other kind reports null here, which
987
+ // is what makes the INCONCLUSIVE variance policy data rather than
988
+ // a branch the integ caller happens to take.
989
+ inconclusive: inconclusiveOf(policy, lastErr),
990
+ attempts: attemptsMade,
991
+ resumesIssued,
992
+ stepResults: {},
993
+ validation: opts.validate ? opts.validate(degradedValue).result : null,
994
+ };
995
+ }
996
+
997
+ // --- semantic-repair re-ask -------------------------------------------
998
+ // ONE bounded attempt layered on top of agent()'s own schema-repair loop:
999
+ // a candidate can be schema-valid yet semantically invalid, and dropping
1000
+ // it straight to the caller's deterministic fallback silently discards
1001
+ // real intent. Re-ask once with the exact validation failure; only then
1002
+ // let the caller fall back. Guarded, never looped.
1003
+ let validation = null;
1004
+ if (opts.validate) {
1005
+ let verdictOfCandidate = opts.validate(value);
1006
+ if (!verdictOfCandidate.ok && retry.semanticRepairReAsks > 0 && value) {
1007
+ ctx.log(
1008
+ `${roleLabel}: candidate rejected (${verdictOfCandidate.reason}) -- re-asking once with the ` +
1009
+ 'validation failure before falling back.'
1010
+ );
1011
+ try {
1012
+ value = await runDispatch(policy.secondary, opts.repairPrompt(verdictOfCandidate.reason), opts.repairLabel);
1013
+ verdictOfCandidate = opts.validate(value);
1014
+ } catch (repairErr) {
1015
+ if (classifyLadderError(repairErr, policy) === null) throw repairErr;
1016
+ ctx.log(`${roleLabel} (semantic repair): dispatch failed (${repairErr.message}) -- falling back.`);
1017
+ }
1018
+ }
1019
+ validation = verdictOfCandidate.result;
1020
+ }
1021
+
1022
+ return {
1023
+ ok: true,
1024
+ value,
1025
+ error: null,
1026
+ degraded: false,
1027
+ inconclusive: null,
1028
+ attempts: attemptsMade,
1029
+ resumesIssued,
1030
+ stepResults,
1031
+ validation,
1032
+ };
1033
+ }
1034
+
1035
+ /**
1036
+ * The "there is no verdict, and here is why" record an 'inconclusive' degrade
1037
+ * returns, or null for every other degrade kind (and for an inconclusive
1038
+ * ladder whose terminal failure was NOT an infra fault -- that one really did
1039
+ * fail, and says so).
1040
+ */
1041
+ function inconclusiveOf(policy, lastErr) {
1042
+ if (policy.degrade.kind !== 'inconclusive' || !lastErr) return null;
1043
+ if (classifyLadderError(lastErr, policy) !== 'infra') return null;
1044
+ return {
1045
+ reason: (lastErr.details && lastErr.details.reason) ?? 'unknown',
1046
+ message: lastErr.message,
1047
+ };
1048
+ }
1049
+
1050
+ /**
1051
+ * The `preDispatch` steps role-policies.mjs records for a dispatch. Only one
1052
+ * lands on the planning side today: 'kill-stale-session', the kill every
1053
+ * max_turns resume performs before resuming a session that may still be
1054
+ * alive. The remaining PRE_DISPATCH_STEPS belong to execution-side ladders
1055
+ * and arrive with their own migration; a step with no engine handler and no
1056
+ * ctx.steps hook throws rather than being silently skipped.
1057
+ */
1058
+ async function runPreDispatchSteps(ctx, dispatch, member, opts = {}, extra = {}, placement = 'before-bracket') {
1059
+ const wantsInBracket = placement === 'in-bracket';
1060
+ for (const step of dispatch.preDispatch) {
1061
+ if (PRE_DISPATCH_STEPS_IN_BRACKET.includes(step) !== wantsInBracket) continue;
1062
+ if (step === 'kill-stale-session') {
1063
+ await ctx.memberSessionGuard.killIfAlive(member);
1064
+ continue;
1065
+ }
1066
+ const hook = ctx.steps && ctx.steps[step];
1067
+ if (typeof hook !== 'function') {
1068
+ throw new Error(`dispatch-role: policy names preDispatch step '${step}', which ctx.steps does not supply.`);
1069
+ }
1070
+ // A step is handed the dispatch's own PROMPT as well as its member,
1071
+ // because some pre-dispatch invariants are properties of the prompt
1072
+ // ('sprint-self-id-in-prompt': the deploy runbook's active-sprints
1073
+ // gate self-blocks unless the prompt states the sprint's OWN
1074
+ // reservation id, so the step verifies that rather than trusting it).
1075
+ const result = await hook({ phase: 'preDispatch', member, dispatch, opts, ...extra });
1076
+ // A step may report the work already DONE, in which case the dispatch
1077
+ // it precedes is skipped entirely and its value stands in.
1078
+ if (result && result.shortCircuit === true) return result;
1079
+ }
1080
+ return null;
1081
+ }
1082
+
1083
+ /**
1084
+ * The `postResult` steps role-policies.mjs records. 'invalidate-beads-cache'
1085
+ * is the one every beads-mutating planning ladder carries: a dispatch that
1086
+ * mutated beads on its OWN clone is invisible to the orchestrator's cache
1087
+ * until it is dropped. 'select-streaks-validate' IS opts.validate, performed
1088
+ * by the semantic-repair path above, so it is a no-op here.
1089
+ */
1090
+ async function runPostResultSteps(ctx, policy, value, opts = {}, member = null) {
1091
+ const results = {};
1092
+ for (const step of policy.postResult) {
1093
+ if (step === 'select-streaks-validate') continue;
1094
+ if (step === 'invalidate-beads-cache') {
1095
+ ctx.invalidateAllBeadsCache();
1096
+ continue;
1097
+ }
1098
+ const hook = ctx.steps && ctx.steps[step];
1099
+ if (typeof hook !== 'function') {
1100
+ throw new Error(`dispatch-role: policy names postResult step '${step}', which ctx.steps does not supply.`);
1101
+ }
1102
+ // The RESULT is handed to the step: every remaining post-result step
1103
+ // is about what the dispatch actually returned ('kb-apply' applies the
1104
+ // report's KB work, 'verify-streak-closed' checks the closes it
1105
+ // claims), so a step that could not see the value could not do its job.
1106
+ const outcome = await hook({ phase: 'postResult', policy, value, opts, member });
1107
+ // A step that REJECTS the result ends the attempt then and there:
1108
+ // later steps must not act on a value the ladder has judged unusable,
1109
+ // and retry.retryOnInvalidResult decides whether the ladder spends
1110
+ // another attempt on it or hands the caller its own error.
1111
+ if (outcome && outcome.rejected === true) {
1112
+ throw new LadderResultRejectedError(outcome.reason);
1113
+ }
1114
+ // A step that COMPUTES something the caller needs (the doer's
1115
+ // 'verify-streak-closed' returns which of the streak's beads are
1116
+ // really still open) hands it back on the outcome's `stepResults`,
1117
+ // rather than the caller re-doing the work the policy just did.
1118
+ results[step] = outcome;
1119
+ }
1120
+ return results;
1121
+ }