@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,1416 @@
1
+ // =============================================================================
2
+ // ROLE DISPATCH POLICY TABLE -- the per-role dispatch policy of every sprint
3
+ // role, expressed as DATA instead of as thirteen hand-written ladders inside
4
+ // runner.js.
5
+ //
6
+ // WHAT THIS IS FOR: runner.js currently spells out one bespoke dispatch ladder
7
+ // per role (planner, plan-reviewer, doer, reviewer, ...), and every ladder
8
+ // re-implements the same axes -- how the dispatch is wrapped in a git-sync
9
+ // bracket, its turn budget and timeouts, whether a client-side watchdog is
10
+ // armed, how retries and degrades work, where its knowledge block comes from,
11
+ // and what runs before/after it. This module records those axes, per role, as
12
+ // plain frozen data so a single engine can execute them.
13
+ //
14
+ // WHO CONSUMES IT (apra-fleet-3swo.5.3): fleet-sprint/dispatch-role.mjs's
15
+ // dispatchRole(ctx, roleName, opts) EXECUTES a row -- the agent() dispatch, its
16
+ // git-sync bracket, its watchdog, its resume, its retry ladder and its degrade
17
+ // are all read out of the row rather than written out per role. A row is only
18
+ // live once `migrated: true` says so; until then runner.js still runs that
19
+ // role's hand-written ladder and the row is a description of it. The table and
20
+ // the engine landed as separate changes, and each role's migration is its own
21
+ // commit, so every step stays independently revertible.
22
+ //
23
+ // HOW IT IS KEPT HONEST: test/role-policies-table.test.mjs re-derives every
24
+ // value below from REAL SOURCE, on whichever side of the migration the role
25
+ // currently sits.
26
+ // - NOT migrated: scanned out of runner.js's real dispatch sites with the
27
+ // same structural scanner the two behaviour-pin files use
28
+ // (test/planning-role-dispatch-pins.test.mjs and
29
+ // test/execution-role-dispatch-pins.test.mjs).
30
+ // - MIGRATED: re-derived by RUNNING dispatch-role.mjs against a recording
31
+ // ctx and observing what it actually does, because once a ladder is
32
+ // data-driven its behaviour stops being a property of any source region
33
+ // (a regex over the engine's generic loop would answer identically for
34
+ // every role). See that file's section (7) for the full reasoning.
35
+ // Either way the table describes REAL behaviour -- a row that drifts fails
36
+ // that test, and a row that disagrees with a pin fails the pin too.
37
+ //
38
+ // SYMBOLIC VALUES: budgets and turn bases are recorded by the NAME of the
39
+ // runner constant that supplies them ('DISPATCH_TIMEOUT_S',
40
+ // 'BASE_DOER_MAX_TURNS', ...), not by a hard number, because those constants
41
+ // are derived per run (DISPATCH_TIMEOUT_S comes from the validated CLI args).
42
+ // Members and model tiers are recorded as a resolution KIND plus its argument
43
+ // ('role'/'pool-head'/'runtime', 'fixed'/'per-bead'/'inherited') rather than
44
+ // as the runner's expression text, so the engine can resolve them itself.
45
+ //
46
+ // DELIBERATELY OUT OF SCOPE: per-dispatch `label` strings and prompt building.
47
+ // A label is presentation, not policy, and the prompts each role sends are
48
+ // already owned by prompts.mjs; the pin files pin neither. Watchdog labels ARE
49
+ // here, because arming a watchdog is a policy decision and the label is part
50
+ // of its kill-path identity.
51
+ // =============================================================================
52
+
53
+ /** Recursively freezes plain objects and arrays. */
54
+ function freezeDeep(value) {
55
+ if (Array.isArray(value)) {
56
+ value.forEach(freezeDeep);
57
+ return Object.freeze(value);
58
+ }
59
+ if (value && typeof value === 'object') {
60
+ for (const key of Object.keys(value)) freezeDeep(value[key]);
61
+ return Object.freeze(value);
62
+ }
63
+ return value;
64
+ }
65
+
66
+ // -----------------------------------------------------------------------------
67
+ // Field vocabularies. Each is a closed set: a policy value outside these lists
68
+ // is a variance that could not be expressed as data, and must be added here
69
+ // (with its meaning) rather than special-cased at the call site.
70
+ // -----------------------------------------------------------------------------
71
+
72
+ /** The nine policy axes every role entry must carry. */
73
+ export const POLICY_FIELDS = Object.freeze([
74
+ 'bracket',
75
+ 'timeouts',
76
+ 'maxTurns',
77
+ 'watchdog',
78
+ 'retry',
79
+ 'degrade',
80
+ 'kbInjection',
81
+ 'preDispatch',
82
+ 'postResult',
83
+ ]);
84
+
85
+ /** How a dispatch's member is resolved. */
86
+ export const MEMBER_KINDS = Object.freeze(['role', 'pool-head', 'runtime']);
87
+
88
+ /** How a dispatch's model tier is resolved. */
89
+ export const MODEL_KINDS = Object.freeze(['fixed', 'per-bead', 'inherited']);
90
+
91
+ /**
92
+ * Where a dispatch's KNOWLEDGE BANK block comes from.
93
+ * 'wrapper' -- injected by the shared dispatch wrapper for any role
94
+ * outside KB_SELF_INJECTING_ROLES;
95
+ * 'prompt-builder' -- the role's own prompt builder places it (doer,
96
+ * reviewer, and the reviewer-persona final review);
97
+ * 'none' -- the dispatch carries no role persona at all, so it
98
+ * receives no block (streak assignment).
99
+ */
100
+ export const KB_INJECTION_KINDS = Object.freeze(['wrapper', 'prompt-builder', 'none']);
101
+
102
+ /**
103
+ * The error CLASSES a ladder can tell apart when it degrades. The engine
104
+ * (fleet-sprint/dispatch-role.mjs classifyLadderError) resolves a thrown
105
+ * error to exactly one of these, and `degrade.classes` records which of them
106
+ * a given role actually fabricates a value for.
107
+ *
108
+ * 'schema' -- AgentOutputError: agent()'s own bounded schema-repair loop
109
+ * was exhausted, so no schema-valid output ever arrived.
110
+ * 'dispatch' -- AgentDispatchError/FleetTransportError (plus any class a
111
+ * policy names in `extraDispatchErrors`): the dispatch
112
+ * channel itself failed.
113
+ * 'infra' -- an AgentDispatchError with no result envelope at all
114
+ * (empty_response / inactivity / orphan-recovery timeout).
115
+ * Recognised ONLY by a policy that sets
116
+ * `classifiesInfraFailures`, because for every other role an
117
+ * infra failure is just a dispatch failure; for the integ
118
+ * runner it is the difference between "no evidence" and "the
119
+ * tests failed".
120
+ * 'sync' -- the git/beads sync AROUND the dispatch failed. Recognised
121
+ * ONLY by a policy that sets `classifiesSyncFailures`.
122
+ * 'unknown' -- anything else, recognised ONLY by a policy that sets
123
+ * `classifiesUnrecognisedErrors` (the regression catch-all).
124
+ */
125
+ export const ERROR_CLASSES = Object.freeze(['schema', 'dispatch', 'infra', 'sync', 'unknown']);
126
+
127
+ /**
128
+ * Steps the engine runs on the DEGRADE path -- i.e. once per attempt that
129
+ * failed and fabricated (or declined to fabricate) a value, never after a
130
+ * successful one. Kept separate from POST_RESULT_STEPS precisely because the
131
+ * distinction is load-bearing: the per-round reviewer must drop its round
132
+ * session when a round FAILS, and must NOT drop it when the round succeeds.
133
+ *
134
+ * 'clear-round-session' -- do not let a failed round's session be resumed
135
+ */
136
+ export const DEGRADE_STEPS = Object.freeze(['clear-round-session']);
137
+
138
+ /** How a failed ladder degrades once its attempts are spent. */
139
+ export const DEGRADE_KINDS = Object.freeze([
140
+ 'fatal', // rethrow; the sprint cannot continue (planner)
141
+ 'synthesized-verdict', // fabricate a non-approving verdict
142
+ 'synthesized-report', // fabricate a non-success report (deployer)
143
+ 'inconclusive', // record "no verdict", never a false failure (integ)
144
+ 'fallback-value', // substitute a deterministic value (streak assignment)
145
+ 'defer-to-next-cycle', // leave the work for the next cycle (scoped replan)
146
+ 'non-approval', // treat as "not approved" and continue
147
+ 'per-bead-attribution', // attribute per bead, then isolate the streak (doer)
148
+ 'catch-all', // swallow everything; the phase is informational
149
+ 'proceed-without-report', // continue with no validated report (harvester)
150
+ ]);
151
+
152
+ /**
153
+ * Steps the engine runs BEFORE a dispatch. Region-anchored evidence for each
154
+ * lives in test/role-policies-table.test.mjs.
155
+ * 'claim-beads-batched' -- claim the streak's beads once per turn
156
+ * 'kill-stale-session' -- kill a still-alive session before resuming it
157
+ * 'sprint-self-id-in-prompt' -- state the sprint's OWN reservation id so the
158
+ * deploy gate cannot self-block
159
+ * 'verify-streak-closed' -- check whether the work is already done, which
160
+ * can short-circuit the dispatch entirely
161
+ */
162
+ export const PRE_DISPATCH_STEPS = Object.freeze([
163
+ 'claim-beads-batched',
164
+ 'kill-stale-session',
165
+ 'sprint-self-id-in-prompt',
166
+ 'verify-streak-closed',
167
+ ]);
168
+
169
+ /**
170
+ * The subset of PRE_DISPATCH_STEPS that must run INSIDE the dispatch's
171
+ * git-sync bracket rather than before it. This is a property of the STEP, not
172
+ * of the role that records it, which is why it lives here rather than as a
173
+ * per-row field: claiming beads is only meaningful once the bracket's D-pull
174
+ * has brought in which beads other sprints already hold, so a claim made
175
+ * before the bracket opens is a claim made against stale remote state. Every
176
+ * other step is cheaper and safer outside.
177
+ */
178
+ export const PRE_DISPATCH_STEPS_IN_BRACKET = Object.freeze(['claim-beads-batched']);
179
+
180
+ /**
181
+ * Steps the engine runs AFTER the dispatch's result (or its failure) is in
182
+ * hand.
183
+ * 'invalidate-beads-cache' -- the dispatch mutated beads on its own clone
184
+ * 'verify-streak-closed' -- confirm which beads really closed
185
+ * 'kb-apply' -- apply the report's KB work
186
+ * 'reviewer-contract-guard' -- reject a self-contradictory reviewer verdict
187
+ * 'clear-round-session' -- do not let a failed round's session be resumed
188
+ * 'select-streaks-validate' -- validate the returned grouping before trusting it
189
+ */
190
+ export const POST_RESULT_STEPS = Object.freeze([
191
+ 'invalidate-beads-cache',
192
+ 'verify-streak-closed',
193
+ 'kb-apply',
194
+ 'reviewer-contract-guard',
195
+ 'clear-round-session',
196
+ 'select-streaks-validate',
197
+ ]);
198
+
199
+ /** Kinds of secondary dispatch a ladder can make. */
200
+ export const SECONDARY_KINDS = Object.freeze(['max-turns-resume', 'semantic-repair-re-ask']);
201
+
202
+ // -----------------------------------------------------------------------------
203
+ // Small constructors. They exist so every row is written the same way and so a
204
+ // defaulted field is defaulted in ONE place -- not to hide data: every value
205
+ // they produce is a plain frozen object.
206
+ // -----------------------------------------------------------------------------
207
+
208
+ const roleMember = (role) => ({ kind: 'role', role });
209
+ const poolHeadMember = (role, binding) => ({ kind: 'pool-head', role, binding });
210
+ const runtimeMember = (binding) => ({ kind: 'runtime', binding });
211
+
212
+ const fixedTier = (key) => ({ kind: 'fixed', key });
213
+ const perBeadTier = (binding) => ({ kind: 'per-bead', binding });
214
+ /** The resume of an already-priced dispatch passes no tier of its own. */
215
+ const INHERITED_TIER = { kind: 'inherited' };
216
+
217
+ /** A turn budget of `base` (a runner constant), optionally doubled. */
218
+ const turns = (base, multiplier, value) => ({
219
+ kind: 'constant', base, multiplier, value: value * multiplier,
220
+ });
221
+ /** A turn budget only known at run time (the doer's escalating resume ladder). */
222
+ const runtimeTurns = (binding) => ({ kind: 'runtime', binding, base: null, multiplier: null, value: null });
223
+
224
+ /** A dispatch wrapped in the git-sync bracket, with its two push flags. */
225
+ const bracketed = (pushCode, pushBeads) => ({ wrapped: true, pushCode, pushBeads });
226
+ /** Streak assignment is pure compute: no repo access, so no bracket at all. */
227
+ const NO_BRACKET = { wrapped: false, pushCode: null, pushBeads: null };
228
+
229
+ const budgets = (timeoutS, maxTotalS) => ({ timeoutS, maxTotalS });
230
+
231
+ /**
232
+ * Requires a non-empty rationale string. Both watchdog constructors below
233
+ * route through this so a row can never carry an armed/disarmed value with no
234
+ * recorded WHY (apra-fleet-3swo.7.12): the justification lives INSIDE the
235
+ * watchdog object itself (the SHAPE CONSTRAINT that keeps POLICY_FIELDS at
236
+ * nine axes), and role-policies-table.test.mjs enumerates ROLE_NAMES to prove
237
+ * every one of them carries one.
238
+ */
239
+ function requireReason(reason, ctorName) {
240
+ if (typeof reason !== 'string' || reason.trim().length === 0) {
241
+ throw new TypeError(`role-policies: ${ctorName}(...) requires a non-empty string 'reason' argument.`);
242
+ }
243
+ return reason;
244
+ }
245
+
246
+ /**
247
+ * A disarmed client-side watchdog, with the reason THIS dispatch runs without
248
+ * one. There is no silent default any more (the normalizer's old
249
+ * `spec.watchdog ?? NO_WATCHDOG` fallback is gone) -- every one of the 13
250
+ * ROLE_POLICIES entries calls this or `watchdog(...)` explicitly.
251
+ */
252
+ const noWatchdog = (reason) => ({
253
+ armed: false, timeoutS: null, member: null, label: null,
254
+ reason: requireReason(reason, 'noWatchdog'),
255
+ });
256
+ /**
257
+ * An armed client-side watchdog. `member: 'dispatch'` records the pinned
258
+ * invariant that a watchdog always names the same member its dispatch routes
259
+ * to, so its kill path targets the right session. `label` is a segment list:
260
+ * a plain string is literal text, an object is a runner expression
261
+ * interpolated into it. `reason` is the recorded WHY this dispatch is judged
262
+ * to need the extra client-side kill-path.
263
+ *
264
+ * `timeoutS: null` here is a SENTINEL, not a real budget name -- deliberately
265
+ * NOT a hard-coded 'DISPATCH_TIMEOUT_S' literal (apra-fleet-3swo.7.12 Final
266
+ * Review reopen). withDispatchWatchdog is a pure wall-clock race with no
267
+ * activity signal, so racing it against the INACTIVITY budget
268
+ * (timeouts.timeoutS) kills an actively-progressing dispatch early on any row
269
+ * whose HARD elapsed ceiling (timeouts.maxTotalS) is deliberately longer --
270
+ * exactly integ-test-runner and regression-test-runner. `null` here means
271
+ * "resolve from this same row's own timeouts", and resolveWatchdogTimeout()
272
+ * below does that resolution in BOTH policy() and secondary() before this
273
+ * object is ever read by dispatch-role.mjs.
274
+ */
275
+ const watchdog = (label, reason) => ({
276
+ armed: true, timeoutS: null, member: 'dispatch', label,
277
+ reason: requireReason(reason, 'watchdog'),
278
+ });
279
+
280
+ /**
281
+ * Resolves an armed watchdog's `timeoutS` sentinel against that SAME row's
282
+ * own `timeouts`, so the client-side kill-path uses the row's HARD elapsed
283
+ * ceiling (`timeouts.maxTotalS`) rather than its inactivity budget
284
+ * (`timeouts.timeoutS`) whenever the two differ (apra-fleet-3swo.7.12 Final
285
+ * Review reopen). When `maxTotalS` is null (NO_BUDGETS) or equal to
286
+ * `timeoutS`, falling back to `timeoutS` yields the identical value either
287
+ * way. A disarmed watchdog's `timeoutS` is already null and is returned
288
+ * unchanged -- there is nothing to resolve.
289
+ *
290
+ * Called from BOTH `policy()` and `secondary()`, not just one: four of the
291
+ * armed secondaries (planner, deployer, integ-test-runner,
292
+ * regression-test-runner) build their OWN `watchdog(...)` directly inside
293
+ * `over` rather than inheriting the main row's already-resolved one, so a
294
+ * fix applied only inside `policy()` would leave all four secondaries
295
+ * hard-coded to the wrong budget.
296
+ */
297
+ function resolveWatchdogTimeout(watchdogSpec, timeoutsSpec) {
298
+ if (!watchdogSpec.armed) return watchdogSpec;
299
+ return { ...watchdogSpec, timeoutS: timeoutsSpec.maxTotalS ?? timeoutsSpec.timeoutS };
300
+ }
301
+
302
+ const SAME_SESSION_RESUME = { kind: 'same-session' };
303
+ const WORKLIST_RESUME = { kind: 'worklist' };
304
+ const roundSessionResume = (role) => ({ kind: 'round-session', role });
305
+ /**
306
+ * A dispatch that must ALWAYS start a clean session: a single, self-contained
307
+ * instruction that assumes no prior conversation with the member.
308
+ *
309
+ * Spelled explicitly rather than left as the table's `null` default because
310
+ * `resume` is a field whose ABSENCE is not neutral: execute_prompt's own
311
+ * server-side default is `resume: true` (best-effort resume of the member's
312
+ * stored last session). Any transport that forwards an omitted `resume`
313
+ * straight through therefore silently reattaches a one-off dispatch to
314
+ * whatever unrelated session that member last ran -- cross-contaminating a
315
+ * fresh instruction with a stale, possibly huge prior context. A row that
316
+ * says nothing about resume is the row most likely to be wrong about it, so
317
+ * every dispatch here states its intent and `resolveResumeArg` never emits
318
+ * `undefined`.
319
+ */
320
+ const FRESH_SESSION_RESUME = { kind: 'fresh-session' };
321
+
322
+ const retry = (over) => ({
323
+ /**
324
+ * apra-fleet-hzeb.4.1: whether this ladder pauses (via the engine's
325
+ * usage-limit pause/resume primitive, hzeb.4.2 follow-up) on a
326
+ * usage-limit dispatch failure rather than treating it as an ordinary
327
+ * dispatch/infra failure. Defaults false and is set true EXPLICITLY on
328
+ * every one of the 13 roles below -- deliberately not hard-defaulted to
329
+ * true here, the same "no silent default" discipline `watchdog`/
330
+ * `noWatchdog` already apply (see requireReason above): a role that never
331
+ * declares it should fail this axis' shape check loudly rather than
332
+ * inherit a value nobody chose for it.
333
+ */
334
+ usageLimitPause: false,
335
+ /** Dispatch attempts in the ladder, excluding any resume. */
336
+ attempts: 1,
337
+ /** Explicit backoff ladder in ms, when the role has one. */
338
+ backoffMs: null,
339
+ /** One bounded LLM-auth self-heal inside the ladder. */
340
+ authSelfHeal: false,
341
+ /** A healed attempt short-circuits the generic retry (final review only). */
342
+ authSelfHealShortCircuits: false,
343
+ /** Auth/workspace-trust failures end the ladder instead of burning attempts. */
344
+ abortOnNonRetryable: false,
345
+ /**
346
+ * An auth/trust failure the self-heal could NOT fix PROPAGATES rather than
347
+ * degrading. For a ladder whose own failure legitimately fails the whole
348
+ * sprint (the final review), fabricating a verdict when the dispatch
349
+ * channel itself is walled off would report a judgement nobody made.
350
+ */
351
+ rethrowsUnhealedNonRetryable: false,
352
+ /** A dispatch that already ran is never re-dispatched for a sync failure. */
353
+ skipRedispatchOnPostDispatchSyncFailure: false,
354
+ /** A provably no-mutation failure lets the next attempt skip its pre-sync. */
355
+ skipPreDispatchSyncOnNoMutation: false,
356
+ /** A generic retry resumes onto the branch's remote tip (doer). */
357
+ resumeOntoRemoteTipOnRetry: false,
358
+ /** Turn exhaustion resumes the SAME session rather than restarting. */
359
+ maxTurnsResume: false,
360
+ /** How many such resumes are allowed. */
361
+ resumeAttempts: 0,
362
+ /** How the turn budget grows per resume. */
363
+ turnEscalation: null,
364
+ /**
365
+ * A spent escalating resume ladder ENDS the ladder rather than falling
366
+ * through to another full attempt. A streak that could not finish at
367
+ * four times its base turn budget has proved it is too large for one
368
+ * streak; re-dispatching it at the base budget only reproduces that.
369
+ */
370
+ abortAfterSpentResumeLadder: false,
371
+ /** Extra resumes granted for an infrastructure (no-envelope) failure. */
372
+ infraResumeAttempts: 0,
373
+ /** Bounded re-asks that feed the validation failure back to the model. */
374
+ semanticRepairReAsks: 0,
375
+ /**
376
+ * A SCHEMA-VALID result the caller's own validator rejects is spent as a
377
+ * failed attempt (retried inside the same budget) rather than returned.
378
+ * Distinct from `semanticRepairReAsks`, which re-ASKS the same session
379
+ * once with the validation failure instead of re-running the attempt:
380
+ * the reviewer's self-contradictory-verdict guard needs a whole fresh
381
+ * review, not a nudge, and it throws rather than degrading once the
382
+ * budget is spent.
383
+ */
384
+ retryOnInvalidResult: false,
385
+ ...over,
386
+ });
387
+
388
+ /**
389
+ * The two failure notes EVERY fabricating ladder carries, phrased from the
390
+ * role's own display `subject` and the shape of what it failed to return
391
+ * (`artifact`: a review role returns a 'verdict', a test-runner/deploy role
392
+ * returns a 'report'). `over` supplies the classes only one role recognises
393
+ * (the regression catch-all's 'sync' and 'unknown') and the rare deliberate
394
+ * rewording -- the final review's dispatch note says "after repair attempts"
395
+ * because its ladder really does exhaust a bounded self-heal first.
396
+ *
397
+ * This is where the six copies of these sentences collapsed to one
398
+ * (apra-fleet-3swo.5.4): every remaining difference between two roles' notes
399
+ * is now visibly an ARGUMENT, so a reader can see at a glance that only the
400
+ * regression phase says anything the others do not.
401
+ */
402
+ const degradeNotes = (subject, artifact, over = {}) => ({
403
+ schema: `${subject} failed to return a schema-valid ${artifact} after repair attempts: {message}`,
404
+ dispatch: `${subject} dispatch failed: {message}`,
405
+ ...over,
406
+ });
407
+
408
+ const degrade = (over) => ({
409
+ kind: 'fatal',
410
+ /** The value fabricated by the degrade path, if any. */
411
+ synthesized: null,
412
+ /**
413
+ * The ERROR_CLASSES this ladder fabricates `synthesized` for. A class the
414
+ * ladder recognises but does not list here degrades to `null` and lets
415
+ * the caller apply its own deterministic fallback. Empty means the
416
+ * ladder fabricates nothing at all.
417
+ */
418
+ classes: [],
419
+ /**
420
+ * The field of `synthesized` that carries the ladder's answer, and which
421
+ * `neverSynthesizes` therefore constrains ('verdict' for every review
422
+ * role, 'deployed' for the deployer). null when the ladder fabricates
423
+ * nothing.
424
+ */
425
+ verdictField: null,
426
+ /**
427
+ * The field of `synthesized` the human-readable failure text goes in.
428
+ * 'notes' for the verdict-shaped roles, 'summary' for the report-shaped
429
+ * test-runner roles.
430
+ */
431
+ notesField: 'notes',
432
+ /**
433
+ * apra-fleet-3swo.5.4: the failure TEXT a degrade writes into
434
+ * `notesField`, as one template per ERROR_CLASS in `classes`.
435
+ *
436
+ * WHY IT IS DATA AND NOT A CALLER CALLBACK: before this, every runner.js
437
+ * dispatch site handed the engine its own `synthesizedNotes` map of
438
+ * per-class note builders -- six near-identical copies of the same two
439
+ * sentences, which is the per-role fallback duplication the policy table
440
+ * exists to remove. Rendering is now ONE implementation in
441
+ * dispatch-role.mjs (renderDegradeNote) driven by these templates, so
442
+ * changing what a degraded verdict says is a table edit, and a class a
443
+ * ladder fabricates for but has no template for is a loud table/engine
444
+ * mismatch rather than a silently empty note.
445
+ *
446
+ * PLACEHOLDERS: `{message}` (the terminal error's message, falling back
447
+ * to String(err) when a non-Error was thrown) and `{name}` (its
448
+ * constructor name -- the regression phase's sync note names the class
449
+ * because "which sync layer failed" is what the operator acts on).
450
+ * Nothing else is interpolated: a note that needed runner state would be
451
+ * a variance the table could not express, and belongs in this comment as
452
+ * a reason to widen the vocabulary rather than as an escape hatch.
453
+ */
454
+ noteTemplates: {},
455
+ /** A field stamped on every synthesized value so it is recognisable. */
456
+ marker: null,
457
+ /** How many distinct degrade paths produce that value. */
458
+ paths: 0,
459
+ /** Values no degrade path may ever fabricate, in `verdictField`. */
460
+ neverSynthesizes: [],
461
+ /**
462
+ * Error CLASS NAMES (any name on the thrown error's prototype chain) that
463
+ * this ladder treats as a plain 'dispatch' failure on top of
464
+ * AgentDispatchError/FleetTransportError. The per-round reviewer lists
465
+ * its own read-side sync-bracket failures here; a real DIVERGENCE class
466
+ * is deliberately absent, so it still propagates.
467
+ */
468
+ extraDispatchErrors: [],
469
+ /** Tell an envelope-less INFRA dispatch failure apart from a real verdict. */
470
+ classifiesInfraFailures: false,
471
+ /** Tell a sync failure AROUND the dispatch apart from the dispatch failing. */
472
+ classifiesSyncFailures: false,
473
+ /** Give even an unrecognised error class a degrade path of its own. */
474
+ classifiesUnrecognisedErrors: false,
475
+ /** DEGRADE_STEPS the engine runs on each attempt that degrades. */
476
+ steps: [],
477
+ /** An unrecognised error class still propagates. */
478
+ rethrowsUnrecognisedErrors: true,
479
+ /**
480
+ * Error classes that are RUN-level control signals rather than a failure
481
+ * of this role, and so keep propagating even through a degrade that
482
+ * swallows everything else.
483
+ */
484
+ rethrowsRunControlSignals: [],
485
+ /** The degrade ends the sprint. */
486
+ abortsSprint: false,
487
+ ...over,
488
+ });
489
+
490
+ /**
491
+ * Builds a role entry. Every entry carries all nine POLICY_FIELDS plus the
492
+ * identity fields the dispatch needs (member, agentType, model, schema,
493
+ * resumeArg) and an optional `secondary` dispatch.
494
+ */
495
+ function policy(role, spec) {
496
+ if (typeof spec.ladderAnchor !== 'string' || spec.ladderAnchor.length === 0) {
497
+ throw new TypeError(`role-policies: policy('${role}', ...) requires a non-empty string spec.ladderAnchor.`);
498
+ }
499
+ return {
500
+ role,
501
+ /** 'main' for a role's primary dispatch. */
502
+ kind: 'main',
503
+ /** The ladder this dispatch belongs to; a role's own name by default. */
504
+ ladder: role,
505
+ /**
506
+ * True once this role's dispatch has moved off its inline runner.js
507
+ * agent() ladder onto the dispatchRole(ctx, roleName, opts) engine
508
+ * (apra-fleet-3swo.5.3/.5.6). NOT one of the nine POLICY_FIELDS axes
509
+ * (deliberately -- it is migration bookkeeping, not a dispatch
510
+ * policy), so it is not asserted by the "every role carries all nine
511
+ * policy fields" shape test. fleet-sprint/inline-ladder-guard.mjs
512
+ * reads this field to know which roles must no longer have a
513
+ * surviving inline ladder; false for every role until its migration
514
+ * bead lands.
515
+ */
516
+ migrated: spec.migrated ?? false,
517
+ /**
518
+ * apra-fleet-3swo.24: a literal source substring, UNIQUE ACROSS EVERY
519
+ * DISPATCH this table describes, that occurs inside this dispatch's
520
+ * own real `agent(...)` call text in runner.js. NOT one of the nine
521
+ * POLICY_FIELDS axes (same reasoning as `migrated` above -- it is
522
+ * call-site identity, not dispatch policy).
523
+ *
524
+ * UNIQUENESS ACROSS THE TABLE, NOT EXCLUSIVITY TO ONE CALL SITE: a
525
+ * dispatch's own anchor can legitimately appear at MORE than one real
526
+ * agent() call site of its OWN ladder. integ-test-runner's and
527
+ * regression-test-runner's main anchors ('featurePrompt,' /
528
+ * 'regressionPrompt,') each match two sites, because each role's own
529
+ * resume prompt re-embeds its main prompt variable verbatim
530
+ * (inline-ladder-guard.test.mjs's apra-fleet-3swo.35 block records and
531
+ * pins this). What matters is that no anchor is ever shared BETWEEN
532
+ * two different dispatches (see this file's (d) anchor-uniqueness
533
+ * test block).
534
+ *
535
+ * WHY THIS EXISTS: a role's `member` resolution expression
536
+ * (memberExprFor()) is NOT role-unique -- roleMember('planner') is
537
+ * shared by planner, scoped-replan-planner and streak-assignment, and
538
+ * roleMember('plan-reviewer') by plan-reviewer and
539
+ * scoped-replan-plan-reviewer. agentType and schema do not
540
+ * disambiguate either (see inline-ladder-guard.mjs's header).
541
+ * fleet-sprint/inline-ladder-guard.mjs therefore requires a call
542
+ * site's text to include BOTH this role's member expression AND its
543
+ * ladderAnchor before reporting a surviving inline ladder -- the
544
+ * member expression alone would flag every sibling ladder that
545
+ * happens to route through the same member.
546
+ */
547
+ ladderAnchor: spec.ladderAnchor,
548
+ member: spec.member,
549
+ agentType: spec.agentType ?? null,
550
+ model: spec.model,
551
+ schema: spec.schema ?? null,
552
+ resumeArg: spec.resumeArg ?? null,
553
+ bracket: spec.bracket,
554
+ timeouts: spec.timeouts,
555
+ maxTurns: spec.maxTurns ?? null,
556
+ // REQUIRED, not defaulted (apra-fleet-3swo.7.12): watchdog moved out of
557
+ // the optional-with-default group below (maxTurns, resumeArg, ...) and
558
+ // into this required group, alongside bracket/timeouts/retry/degrade/
559
+ // kbInjection/member/model. An entry that omits it gets `undefined`
560
+ // here rather than a silently-supplied NO_WATCHDOG, so every read of
561
+ // `.armed` on a row that forgot to declare one throws immediately
562
+ // (resolveWatchdogTimeout's own `.armed` read below throws first).
563
+ // When armed, resolves the sentinel `timeoutS: null` against THIS
564
+ // row's own `timeouts` (Final Review reopen, apra-fleet-3swo.7.12).
565
+ watchdog: resolveWatchdogTimeout(spec.watchdog, spec.timeouts),
566
+ retry: spec.retry,
567
+ degrade: spec.degrade,
568
+ kbInjection: spec.kbInjection,
569
+ preDispatch: spec.preDispatch ?? [],
570
+ postResult: spec.postResult ?? [],
571
+ secondary: null,
572
+ };
573
+ }
574
+
575
+ /**
576
+ * Builds a ladder's SECONDARY dispatch from its main one: the shape mirrors
577
+ * the runner's own "spread the shared options, then override inline", so a
578
+ * field not named in `over` is inherited verbatim.
579
+ *
580
+ * `over.ladderAnchor` is REQUIRED (not merely inherited): a secondary
581
+ * dispatch is always a DIFFERENT real `agent(...)` call site in runner.js
582
+ * than its main dispatch, so silently inheriting the main dispatch's anchor
583
+ * would make the two indistinguishable -- exactly the collision this bead
584
+ * (apra-fleet-3swo.24) exists to remove.
585
+ */
586
+ function secondary(main, role, kind, over) {
587
+ if (typeof over.ladderAnchor !== 'string' || over.ladderAnchor.length === 0) {
588
+ throw new TypeError(
589
+ `role-policies: secondary(..., '${role}', '${kind}', over) must override ladderAnchor with a ` +
590
+ 'non-empty string -- inheriting the main dispatch\'s anchor would make the two indistinguishable.'
591
+ );
592
+ }
593
+ const merged = {
594
+ ...main,
595
+ role,
596
+ kind,
597
+ ladder: main.ladder,
598
+ secondary: null,
599
+ ...over,
600
+ };
601
+ // Re-resolve here too (apra-fleet-3swo.7.12 Final Review reopen): `over`
602
+ // never overrides `timeouts` (every secondary inherits its main row's
603
+ // budgets unchanged), but FOUR secondaries (planner, deployer,
604
+ // integ-test-runner, regression-test-runner) DO override `watchdog` with
605
+ // a fresh `watchdog(...)` call carrying the unresolved `timeoutS: null`
606
+ // sentinel -- `main.watchdog` being already-resolved does not help those,
607
+ // since the spread replaces it outright. Idempotent when `over` carried
608
+ // no watchdog of its own: `merged.watchdog` is then `main.watchdog`,
609
+ // already resolved against the identical `merged.timeouts`.
610
+ merged.watchdog = resolveWatchdogTimeout(merged.watchdog, merged.timeouts);
611
+ return merged;
612
+ }
613
+
614
+ // -----------------------------------------------------------------------------
615
+ // The table.
616
+ // -----------------------------------------------------------------------------
617
+
618
+ const planner = policy('planner', {
619
+ // apra-fleet-3swo.5.3: migrated -- the planner ladder no longer exists
620
+ // inline in runner.js; dispatchRole executes this row.
621
+ migrated: true,
622
+ ladderAnchor: 'plannerPrompt,',
623
+ member: roleMember('planner'),
624
+ agentType: 'planner',
625
+ model: fixedTier('planner'),
626
+ schema: null,
627
+ resumeArg: roundSessionResume('planner'),
628
+ bracket: bracketed(false, true),
629
+ timeouts: budgets('DISPATCH_INACTIVITY_TIMEOUT_S', 'DISPATCH_TIMEOUT_S'),
630
+ maxTurns: turns('PLANNER_MAX_TURNS', 1, 500),
631
+ watchdog: watchdog(
632
+ ['Plan (interactive)'],
633
+ 'The interactive planner is the single dispatch every sprint cycle blocks on before any other role can run; '
634
+ + 'a member that goes alive-but-silent mid-session leaves no other client-side signal (execute_prompt\'s '
635
+ + 'server-side timeout_s is not the only guard against that), so a watchdog backstops it here.'
636
+ ),
637
+ kbInjection: 'wrapper',
638
+ retry: retry({
639
+ usageLimitPause: true,
640
+ attempts: 5,
641
+ backoffMs: [0, 5000, 15000, 30000, 60000],
642
+ authSelfHeal: true,
643
+ abortOnNonRetryable: true,
644
+ skipRedispatchOnPostDispatchSyncFailure: true,
645
+ skipPreDispatchSyncOnNoMutation: true,
646
+ maxTurnsResume: true,
647
+ resumeAttempts: 1,
648
+ turnEscalation: 'double',
649
+ }),
650
+ // The planner is the ONLY role whose exhausted ladder is fatal: there is
651
+ // no sprint without a plan, so it rethrows rather than synthesizing one.
652
+ // A 'fatal' degrade ACCUMULATES every attempt's error and rethrows after
653
+ // the ladder is spent -- which used to include a run cancellation: once
654
+ // the run's AbortSignal fires, the client rejects every later tools/call
655
+ // synchronously ("aborted before a response was received"), so the five
656
+ // attempts and ~110s of backoff could never succeed. Name the run-level
657
+ // signals so they escape on the first attempt, as they do on every
658
+ // non-fatal row.
659
+ degrade: degrade({ kind: 'fatal', abortsSprint: true, rethrowsRunControlSignals: ['CancelledError', 'BudgetExceededError'] }),
660
+ preDispatch: [],
661
+ postResult: ['invalidate-beads-cache'],
662
+ });
663
+ planner.secondary = secondary(planner, 'planner', 'max-turns-resume', {
664
+ ladderAnchor: 'Continue your planning pass exactly where you left off',
665
+ maxTurns: turns('PLANNER_MAX_TURNS', 2, 500),
666
+ watchdog: watchdog(
667
+ ['Plan (resume, max_turns=', { expr: 'PLANNER_MAX_TURNS * 2' }, ')'],
668
+ 'Same interactive session, continued: the resumed dispatch carries the identical single-point-of-failure '
669
+ + 'risk as the main planner dispatch, so it is armed identically.'
670
+ ),
671
+ resumeArg: SAME_SESSION_RESUME,
672
+ preDispatch: ['kill-stale-session'],
673
+ });
674
+
675
+ const planReviewer = policy('plan-reviewer', {
676
+ // apra-fleet-3swo.5.3: migrated -- dispatchRole executes this row.
677
+ migrated: true,
678
+ ladderAnchor: 'priorRoundVerdicts: priorPlanRoundVerdicts',
679
+ member: roleMember('plan-reviewer'),
680
+ agentType: 'plan-reviewer',
681
+ model: fixedTier('plan-reviewer'),
682
+ schema: 'planReviewerVerdict',
683
+ // One bounded review pass over an already-produced plan, self-contained in
684
+ // its prompt: never a continuation of anything this member ran before.
685
+ resumeArg: FRESH_SESSION_RESUME,
686
+ bracket: bracketed(false, null),
687
+ timeouts: budgets('DISPATCH_INACTIVITY_TIMEOUT_S', 'DISPATCH_TIMEOUT_S'),
688
+ maxTurns: turns('PLAN_REVIEWER_MAX_TURNS', 1, 500),
689
+ watchdog: noWatchdog(
690
+ 'A single bounded review pass over an already-produced plan; left disarmed as inherited from the '
691
+ + 'pre-engine ladder (never independently chosen), not one of the roles this pass singled out as an '
692
+ + 'obvious arming candidate. A hang here blocks one plan-review round, not the whole sprint the way an '
693
+ + 'idle planner does; revisit if plan-reviewer hangs are ever observed in practice.'
694
+ ),
695
+ kbInjection: 'wrapper',
696
+ retry: retry({
697
+ attempts: 2,
698
+ usageLimitPause: true,
699
+ authSelfHeal: true,
700
+ maxTurnsResume: true,
701
+ resumeAttempts: 1,
702
+ turnEscalation: 'double',
703
+ }),
704
+ degrade: degrade({
705
+ kind: 'synthesized-verdict',
706
+ // `taskAssignments: []` is part of the SHAPE this ladder fabricates
707
+ // (the runner reads it back off the verdict), so it belongs in the
708
+ // policy's own template rather than being hard-wired into the engine
709
+ // -- the reviewer and deployer degrades fabricate different shapes.
710
+ synthesized: { verdict: 'CHANGES_NEEDED', taskAssignments: [] },
711
+ classes: ['schema', 'dispatch'],
712
+ noteTemplates: degradeNotes('Plan reviewer', 'verdict'),
713
+ verdictField: 'verdict',
714
+ marker: 'dispatchFailed',
715
+ paths: 2,
716
+ neverSynthesizes: ['APPROVED'],
717
+ }),
718
+ });
719
+ planReviewer.secondary = secondary(planReviewer, 'plan-reviewer', 'max-turns-resume', {
720
+ ladderAnchor: 'Continue your plan review exactly where you left off',
721
+ maxTurns: turns('PLAN_REVIEWER_MAX_TURNS', 2, 500),
722
+ resumeArg: SAME_SESSION_RESUME,
723
+ preDispatch: ['kill-stale-session'],
724
+ });
725
+
726
+ const scopedReplanPlanner = policy('scoped-replan-planner', {
727
+ // apra-fleet-3swo.5.3: migrated -- dispatchRole executes this row.
728
+ migrated: true,
729
+ ladderAnchor: "label: 'Scoped Replan Plan (interactive)'",
730
+ member: roleMember('planner'),
731
+ agentType: 'planner',
732
+ model: fixedTier('planner'),
733
+ schema: null,
734
+ // A scoped re-plan is a fresh, single-purpose instruction: it carries the
735
+ // reviewer's scope in its own prompt and must not inherit the interactive
736
+ // planner's (or anyone else's) stored session on this member.
737
+ resumeArg: FRESH_SESSION_RESUME,
738
+ bracket: bracketed(false, true),
739
+ timeouts: budgets('DISPATCH_INACTIVITY_TIMEOUT_S', 'DISPATCH_TIMEOUT_S'),
740
+ maxTurns: turns('SCOPED_REPLAN_PLANNER_MAX_TURNS', 1, 500),
741
+ watchdog: watchdog(
742
+ ['Scoped Replan Plan (interactive)'],
743
+ 'Same interactive-planner risk profile as the main planner dispatch (single dispatch the scoped-replan '
744
+ + 'cycle blocks on, alive-but-silent has no other client-side signal), so it is armed identically.'
745
+ ),
746
+ kbInjection: 'wrapper',
747
+ // A single bounded attempt: no retry ladder and no resume of its own.
748
+ retry: retry({ usageLimitPause: true, attempts: 1, authSelfHeal: true }),
749
+ degrade: degrade({ kind: 'defer-to-next-cycle', rethrowsUnrecognisedErrors: false }),
750
+ postResult: ['invalidate-beads-cache'],
751
+ });
752
+
753
+ const scopedReplanPlanReviewer = policy('scoped-replan-plan-reviewer', {
754
+ // apra-fleet-3swo.5.3: migrated -- dispatchRole executes this row.
755
+ migrated: true,
756
+ ladderAnchor: "label: 'Scoped Replan Review'",
757
+ member: roleMember('plan-reviewer'),
758
+ agentType: 'plan-reviewer',
759
+ model: fixedTier('plan-reviewer'),
760
+ schema: 'planReviewerVerdict',
761
+ // Reviews ONE scoped re-plan on its own terms; same reasoning as
762
+ // plan-reviewer above -- a self-contained pass, never a continuation.
763
+ resumeArg: FRESH_SESSION_RESUME,
764
+ bracket: bracketed(false, null),
765
+ timeouts: budgets('DISPATCH_INACTIVITY_TIMEOUT_S', 'DISPATCH_TIMEOUT_S'),
766
+ maxTurns: turns('SCOPED_REPLAN_REVIEWER_MAX_TURNS', 1, 500),
767
+ watchdog: noWatchdog(
768
+ 'Same reasoning as plan-reviewer: a single bounded review pass with no code/bead mutation of its own, '
769
+ + 'left disarmed as inherited from the pre-engine ladder. Its own single-attempt ladder degrades to a '
770
+ + 'safe non-approval rather than needing a second, independent kill-path.'
771
+ ),
772
+ kbInjection: 'wrapper',
773
+ retry: retry({ usageLimitPause: true, attempts: 1, authSelfHeal: true }),
774
+ degrade: degrade({ kind: 'non-approval', rethrowsUnrecognisedErrors: false }),
775
+ });
776
+
777
+ const streakAssignment = policy('streak-assignment', {
778
+ // apra-fleet-3swo.5.3: migrated -- dispatchRole executes this row.
779
+ migrated: true,
780
+ ladderAnchor: "label: 'Streak Assignment',",
781
+ // Borrows the planner MEMBER for model-tier routing only, and carries no
782
+ // agentType: it has no persona of its own, and activating the planner
783
+ // persona on this narrow grouping task makes the model go exploring.
784
+ member: roleMember('planner'),
785
+ agentType: null,
786
+ model: fixedTier('streakAssignment'),
787
+ schema: 'streakAssignment',
788
+ // Pure compute over a bead list handed to it in the prompt -- there is no
789
+ // prior conversation to continue, and inheriting one would only pollute
790
+ // the assignment with unrelated context. Its 'semantic-repair-re-ask'
791
+ // secondary inherits this: that re-ask is deliberately self-contained
792
+ // (it restates the whole question), not a resume of the failed attempt.
793
+ resumeArg: FRESH_SESSION_RESUME,
794
+ // The one dispatch outside any git-sync bracket: pure compute, no repo access.
795
+ bracket: NO_BRACKET,
796
+ // Explicit budgets(null, null) rather than the transport just inheriting
797
+ // NO_BUDGETS from nothing being named: this row and its secondary
798
+ // (below) are the only two that pass no budget name at all, so stating
799
+ // both fields explicitly here keeps that a visible, deliberate choice
800
+ // rather than an implicit default (apra-fleet-25yl.1.5).
801
+ timeouts: budgets(null, null),
802
+ maxTurns: null,
803
+ watchdog: noWatchdog(
804
+ 'The one dispatch with no bracket and no repo state (bracket: NO_BRACKET) -- a stuck session holds no '
805
+ + 'in-flight code/beads mutation open -- and its own semantic-repair re-ask plus fallback-value degrade '
806
+ + '(one-bead-per-streak) already give a deterministic, safe answer if the dispatch never returns. '
807
+ + 'Left disarmed: inherited, and lower-risk than the bracketed roles for that reason.'
808
+ ),
809
+ kbInjection: 'none',
810
+ retry: retry({ usageLimitPause: true, attempts: 1, authSelfHeal: true, semanticRepairReAsks: 1 }),
811
+ degrade: degrade({
812
+ kind: 'fallback-value',
813
+ synthesized: { grouping: 'one-bead-per-streak' },
814
+ }),
815
+ postResult: ['select-streaks-validate'],
816
+ });
817
+ streakAssignment.secondary = secondary(streakAssignment, 'streak-assignment', 'semantic-repair-re-ask', {
818
+ ladderAnchor: "label: 'Streak Assignment (semantic repair)'",
819
+ // Explicit rather than relying on secondary()'s inherited-from-main
820
+ // default: this is the sibling to the main row's explicit
821
+ // budgets(null, null) above (apra-fleet-25yl.1.5).
822
+ timeouts: budgets(null, null),
823
+ });
824
+
825
+ const doer = policy('doer', {
826
+ // apra-fleet-3swo.5.7: migrated -- dispatchRole executes this row.
827
+ migrated: true,
828
+ ladderAnchor: 'doerPrompt,',
829
+ member: runtimeMember('doerMember'),
830
+ agentType: 'doer',
831
+ // The ONE role dispatched at a per-bead declared tier rather than a fixed one.
832
+ model: perBeadTier('doerModel'),
833
+ schema: 'doerReport',
834
+ resumeArg: WORKLIST_RESUME,
835
+ bracket: bracketed(true, true),
836
+ timeouts: budgets('DISPATCH_INACTIVITY_TIMEOUT_S', 'DISPATCH_TIMEOUT_S'),
837
+ maxTurns: turns('BASE_DOER_MAX_TURNS', 1, 500),
838
+ watchdog: noWatchdog(
839
+ 'Doer streaks dispatch and run in PARALLEL across streaks -- the parallel runner isolates each one, and '
840
+ + 'the per-bead-attribution degrade already reads back which of the streak\'s beads actually closed rather '
841
+ + 'than trusting the ladder\'s own outcome -- so a frozen-but-alive doer session blocks only its own '
842
+ + 'streak, not the sprint, and a later cycle\'s reclaimStaleInProgress recovers any bead the hang left '
843
+ + 'stuck. This is a reasoned choice, not merely historical: arming would race a client-side kill against a '
844
+ + 'session that may still be committing real code/beads mid-turn, which is exactly the risk '
845
+ + 'resumeOntoRemoteTipOnRetry and abortAfterSpentResumeLadder already handle conservatively.'
846
+ ),
847
+ kbInjection: 'prompt-builder',
848
+ retry: retry({
849
+ attempts: 2,
850
+ usageLimitPause: true,
851
+ authSelfHeal: true,
852
+ abortOnNonRetryable: true,
853
+ skipRedispatchOnPostDispatchSyncFailure: true,
854
+ resumeOntoRemoteTipOnRetry: true,
855
+ maxTurnsResume: true,
856
+ resumeAttempts: 2,
857
+ turnEscalation: 'double',
858
+ abortAfterSpentResumeLadder: true,
859
+ }),
860
+ degrade: degrade({
861
+ kind: 'per-bead-attribution',
862
+ // Fabricates NOTHING (degrade.classes is empty): a failed streak's
863
+ // real outcome is decided by reading which of its beads actually
864
+ // closed, which is the caller's per-bead attribution pass. The streak
865
+ // error is re-thrown AFTER that attribution so the parallel runner
866
+ // isolates this streak; it never ends the sprint.
867
+ rethrowsUnrecognisedErrors: false,
868
+ }),
869
+ preDispatch: ['claim-beads-batched'],
870
+ postResult: ['verify-streak-closed', 'kb-apply'],
871
+ });
872
+ const doerResume = secondary(doer, 'doer-resume', 'max-turns-resume', {
873
+ ladderAnchor: 'Continue exactly where you left off from this same session',
874
+ // No tier: the streak was already priced on the dispatch this continues.
875
+ model: INHERITED_TIER,
876
+ // The escalating ladder computes the budget per resume attempt.
877
+ maxTurns: runtimeTurns('maxTurns'),
878
+ resumeArg: SAME_SESSION_RESUME,
879
+ // A turn-exhausted streak whose beads are ALL closed already is a success
880
+ // and gets no resume dispatch at all, so the check runs BEFORE the kill.
881
+ preDispatch: ['verify-streak-closed', 'kill-stale-session'],
882
+ });
883
+ doer.secondary = doerResume;
884
+
885
+ const reviewer = policy('reviewer', {
886
+ // apra-fleet-3swo.5.7: migrated -- dispatchRole executes this row.
887
+ migrated: true,
888
+ ladderAnchor: 'acceptanceCriteriaJson,',
889
+ member: poolHeadMember('reviewer', 'reviewerPool[0]'),
890
+ agentType: 'reviewer',
891
+ model: fixedTier('reviewer'),
892
+ schema: 'reviewerVerdict',
893
+ resumeArg: roundSessionResume('reviewer'),
894
+ bracket: bracketed(false, null),
895
+ timeouts: budgets('DISPATCH_INACTIVITY_TIMEOUT_S', 'DISPATCH_TIMEOUT_S'),
896
+ maxTurns: turns('BASE_REVIEWER_MAX_TURNS', 1, 500),
897
+ watchdog: noWatchdog(
898
+ 'One review round at a time, gated behind the same server-side timeout_s as every dispatch, and its own '
899
+ + 'degrade path already treats an unresponsive or self-contradictory round conservatively as '
900
+ + 'CHANGES_NEEDED. Left disarmed as inherited from the pre-engine ladder; unlike the planner it is not a '
901
+ + 'single point of failure the whole sprint idles on before anything else can even start. Historical '
902
+ + 'rather than freshly re-derived against an observed incident -- revisit if reviewer hangs recur.'
903
+ ),
904
+ kbInjection: 'prompt-builder',
905
+ retry: retry({
906
+ attempts: 2,
907
+ usageLimitPause: true,
908
+ authSelfHeal: true,
909
+ maxTurnsResume: true,
910
+ resumeAttempts: 1,
911
+ turnEscalation: 'double',
912
+ // The SAME two-attempt budget covers both ways a round can fail: an
913
+ // infrastructure failure, and a schema-valid verdict the contract
914
+ // guard rejects. A self-contradictory verdict cannot be nudged into
915
+ // shape -- only a fresh review can fix it -- so the whole attempt is
916
+ // spent again rather than re-asked (contrast streak assignment's
917
+ // semanticRepairReAsks). Once the budget is gone the caller gets a
918
+ // ReviewerContractViolationError, never a fabricated verdict.
919
+ retryOnInvalidResult: true,
920
+ }),
921
+ degrade: degrade({
922
+ kind: 'synthesized-verdict',
923
+ // The verdicts fabricated here stand for INFRASTRUCTURE failures, not
924
+ // the reviewer contradicting itself, so they are marked dispatchFailed
925
+ // -- which is also what stops the contract guard above from mistaking
926
+ // one for a self-contradictory verdict.
927
+ synthesized: { verdict: 'CHANGES_NEEDED', reopenIds: [], newTasks: [] },
928
+ classes: ['schema', 'dispatch'],
929
+ noteTemplates: degradeNotes('Reviewer', 'verdict'),
930
+ verdictField: 'verdict',
931
+ marker: 'dispatchFailed',
932
+ paths: 2,
933
+ neverSynthesizes: ['APPROVED'],
934
+ // The review's own read-side sync bracket can fail for the same
935
+ // transient infrastructure reasons as the dispatch, so it degrades
936
+ // identically. A REAL divergence (GitDivergedError / DoltDivergedError
937
+ // -- deliberately NOT listed) still propagates: that is a branch
938
+ // integrity problem, not a blip.
939
+ extraDispatchErrors: ['GitSyncError', 'DoltSyncError'],
940
+ // On FAILURE only. A failed round's session must not be resumed by the
941
+ // next round; a SUCCESSFUL round's must, which is exactly why this is
942
+ // a degrade step rather than a postResult one.
943
+ steps: ['clear-round-session'],
944
+ }),
945
+ postResult: ['reviewer-contract-guard', 'kb-apply'],
946
+ });
947
+ reviewer.secondary = secondary(reviewer, 'reviewer', 'max-turns-resume', {
948
+ ladderAnchor: 'Continue your review exactly where you left off',
949
+ maxTurns: turns('BASE_REVIEWER_MAX_TURNS', 2, 500),
950
+ resumeArg: SAME_SESSION_RESUME,
951
+ preDispatch: ['kill-stale-session'],
952
+ });
953
+
954
+ const finalReview = policy('final-review', {
955
+ // apra-fleet-3swo.5.7: migrated -- dispatchRole executes this row.
956
+ migrated: true,
957
+ ladderAnchor: 'buildFinalVerdictPrompt({',
958
+ // Final Review has no role member of its own: it is the reviewer role,
959
+ // dispatching the reviewer persona over the whole sprint.
960
+ member: roleMember('reviewer'),
961
+ agentType: 'reviewer',
962
+ model: fixedTier('reviewer'),
963
+ schema: 'finalVerdict',
964
+ // Runs ONCE, over the whole sprint, from a prompt that carries its entire
965
+ // scope. Deliberately NOT a continuation of the per-round reviewer
966
+ // sessions on the same member: final review is meant to be fresh eyes.
967
+ resumeArg: FRESH_SESSION_RESUME,
968
+ bracket: bracketed(false, null),
969
+ timeouts: budgets('DISPATCH_INACTIVITY_TIMEOUT_S', 'DISPATCH_TIMEOUT_S'),
970
+ maxTurns: turns('FINAL_REVIEW_MAX_TURNS', 1, 500),
971
+ watchdog: noWatchdog(
972
+ 'Runs exactly once, after every other role finished, with its own bounded auth self-heal and a 4-path '
973
+ + 'degrade that already synthesizes a FAIL verdict on repair/dispatch exhaustion -- the conservative '
974
+ + 'answer for a final gate. Left disarmed as inherited; not re-derived against a specific observed hang.'
975
+ ),
976
+ kbInjection: 'prompt-builder',
977
+ retry: retry({
978
+ attempts: 2,
979
+ usageLimitPause: true,
980
+ authSelfHeal: true,
981
+ // A healed attempt already produced a verdict; running the generic
982
+ // retry as well would fire a second full review and discard it.
983
+ authSelfHealShortCircuits: true,
984
+ // An auth/trust failure that could NOT be healed ends the ladder
985
+ // instead of burning the retry on the identical wall -- and
986
+ // PROPAGATES, because a sprint whose final verdict could not be
987
+ // obtained at all must not be handed a fabricated one.
988
+ abortOnNonRetryable: true,
989
+ rethrowsUnhealedNonRetryable: true,
990
+ maxTurnsResume: true,
991
+ resumeAttempts: 1,
992
+ turnEscalation: 'double',
993
+ }),
994
+ degrade: degrade({
995
+ kind: 'synthesized-verdict',
996
+ synthesized: { verdict: 'FAIL' },
997
+ // The one deliberate rewording in the table: this ladder's dispatch
998
+ // note says "after repair attempts" because its retry really does
999
+ // spend a bounded LLM-auth self-heal before giving up.
1000
+ noteTemplates: degradeNotes('Final reviewer', 'verdict', {
1001
+ dispatch: 'Final reviewer dispatch failed after repair attempts: {message}',
1002
+ }),
1003
+ // TWO error classes reached from TWO ladder positions -- the healed
1004
+ // retry and the generic retry -- which is what makes four paths over
1005
+ // two classes. A dead dispatch channel never passes a sprint.
1006
+ classes: ['schema', 'dispatch'],
1007
+ verdictField: 'verdict',
1008
+ paths: 4,
1009
+ neverSynthesizes: ['PASS'],
1010
+ }),
1011
+ postResult: ['kb-apply'],
1012
+ });
1013
+ finalReview.secondary = secondary(finalReview, 'final-review', 'max-turns-resume', {
1014
+ ladderAnchor: 'Continue your final review exactly where you left off',
1015
+ maxTurns: turns('FINAL_REVIEW_MAX_TURNS', 2, 500),
1016
+ resumeArg: SAME_SESSION_RESUME,
1017
+ preDispatch: ['kill-stale-session'],
1018
+ });
1019
+
1020
+ const deployer = policy('deployer', {
1021
+ // apra-fleet-3swo.5.7: migrated -- dispatchRole executes this row.
1022
+ migrated: true,
1023
+ ladderAnchor: 'deployerPrompt,',
1024
+ member: roleMember('deployer'),
1025
+ agentType: 'deployer',
1026
+ model: fixedTier('deployer'),
1027
+ schema: 'deployerReport',
1028
+ // A single deploy pass driven entirely by the target's deploy runbook in
1029
+ // its own prompt; no prior session on this member is relevant to it.
1030
+ resumeArg: FRESH_SESSION_RESUME,
1031
+ bracket: bracketed(false, null),
1032
+ timeouts: budgets('DISPATCH_INACTIVITY_TIMEOUT_S', 'DISPATCH_TIMEOUT_S'),
1033
+ maxTurns: turns('DEPLOYER_MAX_TURNS', 1, 500),
1034
+ // ARMED (apra-fleet-3swo.7.12, a behaviour change from previously-inherited
1035
+ // NO_WATCHDOG): named explicitly as an obvious arming candidate. One long,
1036
+ // unattended deploy dispatch gates the whole sprint's Integration Test /
1037
+ // Regression Test / Final Review phases behind it with no other in-flight
1038
+ // work to fall back on; a frozen-but-alive deploy session would otherwise
1039
+ // hang the sprint indefinitely with no client-side ceiling. Armed
1040
+ // identically in shape to the planner (same DISPATCH_TIMEOUT_S budget,
1041
+ // same member:'dispatch' kill target).
1042
+ watchdog: watchdog(
1043
+ ['Deploy'],
1044
+ 'Long, unattended, single dispatch gating every later phase with no parallel counterpart; a '
1045
+ + 'frozen-but-alive session here would otherwise hang the sprint with no client-side ceiling.'
1046
+ ),
1047
+ kbInjection: 'wrapper',
1048
+ retry: retry({
1049
+ attempts: 1,
1050
+ usageLimitPause: true,
1051
+ authSelfHeal: true,
1052
+ maxTurnsResume: true,
1053
+ resumeAttempts: 1,
1054
+ turnEscalation: 'double',
1055
+ }),
1056
+ degrade: degrade({
1057
+ kind: 'synthesized-report',
1058
+ // A REPORT, not a verdict: the answer field is `deployed` and the
1059
+ // failure text goes in `notes`. Both are recorded here rather than
1060
+ // assumed by the engine, which is what lets one engine fabricate the
1061
+ // reviewer's verdict shape and the deployer's report shape alike.
1062
+ synthesized: { deployed: false },
1063
+ classes: ['schema', 'dispatch'],
1064
+ noteTemplates: degradeNotes('Deployer', 'report'),
1065
+ verdictField: 'deployed',
1066
+ paths: 2,
1067
+ neverSynthesizes: [true],
1068
+ }),
1069
+ // The deploy runbook gates on foreign reservations, so the prompt must
1070
+ // carry the sprint's OWN reservation id or the gate self-blocks.
1071
+ preDispatch: ['sprint-self-id-in-prompt'],
1072
+ });
1073
+ deployer.secondary = secondary(deployer, 'deployer', 'max-turns-resume', {
1074
+ ladderAnchor: 'Continue the deploy exactly where you left off',
1075
+ maxTurns: turns('DEPLOYER_MAX_TURNS', 2, 500),
1076
+ watchdog: watchdog(
1077
+ ['Deploy (resume, max_turns=', { expr: 'DEPLOYER_MAX_TURNS * 2' }, ')'],
1078
+ 'Same unattended-single-dispatch risk as the main deploy dispatch, so the resume is armed identically.'
1079
+ ),
1080
+ resumeArg: SAME_SESSION_RESUME,
1081
+ preDispatch: ['kill-stale-session'],
1082
+ });
1083
+
1084
+ const integTestRunner = policy('integ-test-runner', {
1085
+ // apra-fleet-3swo.5.7: migrated -- dispatchRole executes this row.
1086
+ migrated: true,
1087
+ ladderAnchor: 'featurePrompt,',
1088
+ member: roleMember('integ-test-runner'),
1089
+ agentType: 'integ-test-runner',
1090
+ model: fixedTier('integ-test-runner'),
1091
+ schema: 'integReport',
1092
+ // One self-contained playbook run per cycle. Resuming a prior cycle's (or
1093
+ // any other role's) session would let stale context stand in for the live
1094
+ // evidence this role exists to collect.
1095
+ resumeArg: FRESH_SESSION_RESUME,
1096
+ bracket: bracketed(false, true),
1097
+ // Shorter INACTIVITY timer, longer HARD elapsed ceiling: a hung runner
1098
+ // still dies on silence, while an active long pass is never killed.
1099
+ timeouts: budgets('DISPATCH_INACTIVITY_TIMEOUT_S', 'INTEG_MAX_TOTAL_S'),
1100
+ maxTurns: turns('INTEG_TEST_MAX_TURNS', 1, 500),
1101
+ // ARMED (apra-fleet-3swo.7.12, a behaviour change from previously-inherited
1102
+ // NO_WATCHDOG): named explicitly as an obvious arming candidate. Dispatched
1103
+ // alone with a deliberately long maxTotalS (INTEG_MAX_TOTAL_S) so a real
1104
+ // test pass can run to completion, and with no parallel work alongside it
1105
+ // the way doer streaks have; an alive-but-silent session has no other
1106
+ // client-side signal and would otherwise hang the cycle for the whole long
1107
+ // budget. The existing 'inconclusive' degrade (classifiesInfraFailures)
1108
+ // already has a safe fabricated report ready for the watchdog's
1109
+ // AgentDispatchError to land in.
1110
+ watchdog: watchdog(
1111
+ ['Integration Test'],
1112
+ 'Long, unattended, single dispatch with no parallel counterpart; a frozen-but-alive session would '
1113
+ + 'otherwise hang the whole integ-test cycle for the full long maxTotalS budget with no way to abort early.'
1114
+ ),
1115
+ kbInjection: 'wrapper',
1116
+ retry: retry({
1117
+ attempts: 1,
1118
+ usageLimitPause: true,
1119
+ authSelfHeal: true,
1120
+ maxTurnsResume: true,
1121
+ resumeAttempts: 1,
1122
+ turnEscalation: 'double',
1123
+ infraResumeAttempts: 1,
1124
+ }),
1125
+ // An infrastructure failure produced no test evidence, so it must never be
1126
+ // recorded as a test FAILURE.
1127
+ //
1128
+ // THE ASYMMETRY IS THE VARIANCE. A schema-repair exhaustion or an ordinary
1129
+ // dispatch failure DID reach a running test pass and legitimately record
1130
+ // passed:false -- those two classes are in `classes` and fabricate the
1131
+ // report below. An 'infra'-class failure did not: the member CLI died
1132
+ // mid-turn and lost its result envelope without ever reporting pass or
1133
+ // fail. That class is deliberately NOT in `classes`, so the engine
1134
+ // fabricates nothing for it and instead returns an `inconclusive` record
1135
+ // (reason + message) that the caller turns into an INCONCLUSIVE cycle
1136
+ // entry. classifiesInfraFailures is what makes the class reachable at all;
1137
+ // without it an envelope-less failure would fall into 'dispatch' and be
1138
+ // recorded as a test failure that never happened.
1139
+ degrade: degrade({
1140
+ kind: 'inconclusive',
1141
+ marker: 'integInfraInconclusive',
1142
+ classifiesInfraFailures: true,
1143
+ classes: ['schema', 'dispatch'],
1144
+ noteTemplates: degradeNotes('Integ test runner', 'report'),
1145
+ synthesized: { featuresClosed: 0, issuesCreated: 0, passed: false, bugsFiled: [] },
1146
+ verdictField: 'passed',
1147
+ notesField: 'summary',
1148
+ paths: 2,
1149
+ neverSynthesizes: [true],
1150
+ }),
1151
+ });
1152
+ integTestRunner.secondary = secondary(integTestRunner, 'integ-test-runner', 'max-turns-resume', {
1153
+ ladderAnchor: 'Continue the integration test run exactly where you left off',
1154
+ maxTurns: turns('INTEG_TEST_MAX_TURNS', 2, 500),
1155
+ watchdog: watchdog(
1156
+ ['Integration Test (resume, max_turns=', { expr: 'INTEG_TEST_MAX_TURNS * 2' }, ')'],
1157
+ 'Same unattended-single-dispatch risk as the main integ-test dispatch, so the resume is armed identically.'
1158
+ ),
1159
+ resumeArg: SAME_SESSION_RESUME,
1160
+ preDispatch: ['kill-stale-session'],
1161
+ });
1162
+
1163
+ const regressionTestRunner = policy('regression-test-runner', {
1164
+ // apra-fleet-3swo.5.7: migrated -- dispatchRole executes this row.
1165
+ migrated: true,
1166
+ ladderAnchor: 'regressionPrompt,',
1167
+ member: roleMember('regression-test-runner'),
1168
+ agentType: 'regression-test-runner',
1169
+ model: fixedTier('regression-test-runner'),
1170
+ schema: 'regressionReport',
1171
+ // Same reasoning as integ-test-runner: one self-contained playbook run
1172
+ // per sprint, whose evidence must come from THIS run, not a warm session.
1173
+ resumeArg: FRESH_SESSION_RESUME,
1174
+ bracket: bracketed(false, true),
1175
+ timeouts: budgets('DISPATCH_INACTIVITY_TIMEOUT_S', 'REGRESSION_TEST_MAX_TOTAL_S'),
1176
+ maxTurns: turns('REGRESSION_TEST_MAX_TURNS', 1, 500),
1177
+ // ARMED (apra-fleet-3swo.7.12, a behaviour change from previously-inherited
1178
+ // NO_WATCHDOG): named explicitly as an obvious arming candidate, for the
1179
+ // same reason as integ-test-runner -- one long, unattended dispatch with no
1180
+ // parallel counterpart and a catch-all degrade already built to absorb a
1181
+ // fabricated failing report. A frozen-but-alive session here would
1182
+ // otherwise hang the whole regression phase.
1183
+ watchdog: watchdog(
1184
+ ['Regression Test'],
1185
+ 'Long, unattended, single dispatch with no parallel counterpart; a frozen-but-alive session would '
1186
+ + 'otherwise hang the whole regression phase for the full long maxTotalS budget with no way to abort early.'
1187
+ ),
1188
+ kbInjection: 'wrapper',
1189
+ retry: retry({
1190
+ attempts: 1,
1191
+ usageLimitPause: true,
1192
+ // The phase never re-dispatches, and it says so explicitly: a
1193
+ // post-dispatch sync failure is classified into its own degrade
1194
+ // summary (the carry-over beads it filed may be local-only) rather
1195
+ // than re-running the pass.
1196
+ skipRedispatchOnPostDispatchSyncFailure: true,
1197
+ maxTurnsResume: true,
1198
+ resumeAttempts: 1,
1199
+ turnEscalation: 'double',
1200
+ }),
1201
+ // The only load-bearing catch-all in the table: this phase is
1202
+ // informational, and a failure here must never turn a green sprint into a
1203
+ // terminal ABORTED record that skips Harvest and Publish. Cancellation and
1204
+ // budget exhaustion are RUN-level signals, not failures of this phase, so
1205
+ // they still propagate.
1206
+ degrade: degrade({
1207
+ kind: 'catch-all',
1208
+ // FOUR degrade classes, which is what "catch-all" means expressed as
1209
+ // data: on top of the two every ladder distinguishes, this one also
1210
+ // tells apart a SYNC failure around the dispatch (the phase files
1211
+ // carry-over beads, so a D-push failure is a routine outcome worth
1212
+ // reporting honestly rather than as "the pass failed") and an
1213
+ // otherwise UNRECOGNISED error (a divergence class is a typed sprint
1214
+ // abort, and letting one through here would turn a green sprint into
1215
+ // a terminal ABORTED record that skips Harvest and Publish).
1216
+ classes: ['schema', 'dispatch', 'sync', 'unknown'],
1217
+ noteTemplates: degradeNotes('Regression test runner', 'report', {
1218
+ // Said honestly rather than as a clean "the pass failed": the
1219
+ // carry-over beads may or may not have reached the shared remote,
1220
+ // and the operator needs to know which -- hence {name} as well as
1221
+ // {message}, so the summary says WHICH sync layer failed.
1222
+ sync: 'Regression pass could not be completed: git/beads sync around the dispatch failed '
1223
+ + '({name}: {message}). Any carry-over beads filed may not have reached the shared remote.',
1224
+ unknown: 'Regression test runner failed with an unexpected error: {message}',
1225
+ }),
1226
+ classifiesSyncFailures: true,
1227
+ classifiesUnrecognisedErrors: true,
1228
+ // A REPORT shape, like the deployer's: the answer is `passed` and the
1229
+ // failure text goes in `summary`.
1230
+ synthesized: { passed: false, suitePassed: false, smokePassed: false, bugsFiled: [] },
1231
+ verdictField: 'passed',
1232
+ notesField: 'summary',
1233
+ paths: 4,
1234
+ neverSynthesizes: [true],
1235
+ rethrowsUnrecognisedErrors: false,
1236
+ rethrowsRunControlSignals: ['CancelledError', 'BudgetExceededError'],
1237
+ }),
1238
+ });
1239
+ regressionTestRunner.secondary = secondary(regressionTestRunner, 'regression-test-runner', 'max-turns-resume', {
1240
+ ladderAnchor: 'Continue the regression pass exactly where you left off',
1241
+ maxTurns: turns('REGRESSION_TEST_MAX_TURNS', 2, 500),
1242
+ watchdog: watchdog(
1243
+ ['Regression Test (resume, max_turns=', { expr: 'REGRESSION_TEST_MAX_TURNS * 2' }, ')'],
1244
+ 'Same unattended-single-dispatch risk as the main regression dispatch, so the resume is armed identically.'
1245
+ ),
1246
+ resumeArg: SAME_SESSION_RESUME,
1247
+ preDispatch: ['kill-stale-session'],
1248
+ });
1249
+
1250
+ const harvester = policy('harvester', {
1251
+ // apra-fleet-3swo.5.7: migrated -- dispatchRole executes this row.
1252
+ migrated: true,
1253
+ ladderAnchor: 'harvesterPrompt,',
1254
+ member: roleMember('harvester'),
1255
+ agentType: 'harvester',
1256
+ model: fixedTier('harvester'),
1257
+ schema: 'harvesterReport',
1258
+ // Runs once at the end of the sprint from a fully-specified prompt; no
1259
+ // earlier session on this member is part of its job.
1260
+ resumeArg: FRESH_SESSION_RESUME,
1261
+ // Writes docs AND defers low-priority beads, so it pushes both.
1262
+ bracket: bracketed(true, true),
1263
+ timeouts: budgets('DISPATCH_INACTIVITY_TIMEOUT_S', 'DISPATCH_TIMEOUT_S'),
1264
+ maxTurns: turns('HARVESTER_MAX_TURNS', 1, 500),
1265
+ watchdog: noWatchdog(
1266
+ 'Runs after the sprint\'s pass/fail verdict is already decided; a hang here degrades to '
1267
+ + '\'proceed-without-report\', a genuine no-op on the sprint\'s outcome since nothing downstream reads its '
1268
+ + 'report before the run exits. Left disarmed: historical, and the low stakes of its own degrade path made '
1269
+ + 'a second kill-path a low priority here relative to the three roles this pass armed.'
1270
+ ),
1271
+ kbInjection: 'wrapper',
1272
+ retry: retry({
1273
+ attempts: 1,
1274
+ usageLimitPause: true,
1275
+ authSelfHeal: true,
1276
+ maxTurnsResume: true,
1277
+ resumeAttempts: 1,
1278
+ turnEscalation: 'double',
1279
+ }),
1280
+ // Fabricates NOTHING: by this point the sprint's verdict is already
1281
+ // decided, so a missing harvest report is a gap in the record rather than
1282
+ // a result to invent. degrade.classes is empty, which is what makes that
1283
+ // "produces no value" rather than "produces an empty one".
1284
+ degrade: degrade({ kind: 'proceed-without-report' }),
1285
+ postResult: ['kb-apply'],
1286
+ });
1287
+ harvester.secondary = secondary(harvester, 'harvester', 'max-turns-resume', {
1288
+ ladderAnchor: 'Continue your harvest exactly where you left off',
1289
+ maxTurns: turns('HARVESTER_MAX_TURNS', 2, 500),
1290
+ resumeArg: SAME_SESSION_RESUME,
1291
+ preDispatch: ['kill-stale-session'],
1292
+ });
1293
+
1294
+ // -----------------------------------------------------------------------------
1295
+ // Usage-limit pause/resume engine budgets (apra-fleet-hzeb.4.1)
1296
+ // -----------------------------------------------------------------------------
1297
+ //
1298
+ // The classifier/budget half of fleet-sprint's usage-limit pause/resume
1299
+ // feature: every role above now carries retry.usageLimitPause === true, and
1300
+ // errors.mjs records the matching vocabulary (isUsageLimitDispatchError,
1301
+ // usageLimitOf, UsageLimitWaitExhaustedError -- the latter registered in
1302
+ // abort.mjs's isTypedAbortError so an exhausted wait routes through
1303
+ // finalizeAbort()/an [ABORTED] PR like every other typed sprint abort). The
1304
+ // pause/reprobe CONTROLLER that actually reads these budgets and the
1305
+ // dispatchRole hook that arms it are the follow-up task (apra-fleet-hzeb.4.2)
1306
+ // -- this table only RECORDS the budgets as data, the same way every other
1307
+ // engine budget in this file is recorded rather than hard-coded at a call
1308
+ // site.
1309
+ //
1310
+ // USAGE_LIMIT_MAX_WAIT_S is the one CLI-overridable value here (arg
1311
+ // `usage_limit_max_wait_s`, seconds). Wiring that CLI override -- and these
1312
+ // defaults generally -- into runner.js's dispatchCtx.budgets (alongside
1313
+ // DISPATCH_TIMEOUT_S et al.) is part of the hzeb.4.2 controller bring-up, not
1314
+ // this task: this task's own scope note names runner.js's ONLY change as
1315
+ // registering UsageLimitWaitExhaustedError in isTypedAbortError. Until 4.2
1316
+ // wires it through, this exported default is the value in effect.
1317
+ export const USAGE_LIMIT_BUDGET_DEFAULTS = freezeDeep({
1318
+ /**
1319
+ * Total wall-clock seconds a single dispatch may stay paused across all
1320
+ * reprobes before giving up (UsageLimitWaitExhaustedError). Default 6h.
1321
+ * Arg: usage_limit_max_wait_s.
1322
+ */
1323
+ USAGE_LIMIT_MAX_WAIT_S: 6 * 60 * 60,
1324
+ /** Max reprobe attempts allowed before giving up, independent of elapsed wait. */
1325
+ USAGE_LIMIT_MAX_REPROBES: 6,
1326
+ /**
1327
+ * Floor on any single wait -- never reprobe sooner than this even when a
1328
+ * provider's resumeAt is imminent.
1329
+ */
1330
+ USAGE_LIMIT_MIN_WAIT_S: 60,
1331
+ /**
1332
+ * Reprobe backoff ladder in ms, one entry per reprobe attempt (index 0 is
1333
+ * the first reprobe): 15m, 30m, then 60m for every attempt after that, up
1334
+ * to USAGE_LIMIT_MAX_REPROBES entries.
1335
+ */
1336
+ USAGE_LIMIT_REPROBE_BACKOFF_MS: [15, 30, 60, 60, 60, 60].map((m) => m * 60 * 1000),
1337
+ });
1338
+
1339
+ /**
1340
+ * The policy table, keyed by role name.
1341
+ *
1342
+ * `doer-resume` is registered as a role of its own because it is the one
1343
+ * resume dispatch that shares nothing but its member with the dispatch it
1344
+ * continues: its model tier is inherited rather than declared, and its turn
1345
+ * budget is a run-time value from the escalating resume ladder. It is the SAME
1346
+ * frozen object as ROLE_POLICIES.doer.secondary; every other ladder's resume
1347
+ * is reachable as <role>.secondary.
1348
+ */
1349
+ export const ROLE_POLICIES = freezeDeep({
1350
+ planner,
1351
+ 'plan-reviewer': planReviewer,
1352
+ 'scoped-replan-planner': scopedReplanPlanner,
1353
+ 'scoped-replan-plan-reviewer': scopedReplanPlanReviewer,
1354
+ 'streak-assignment': streakAssignment,
1355
+ doer,
1356
+ 'doer-resume': doerResume,
1357
+ reviewer,
1358
+ 'final-review': finalReview,
1359
+ deployer,
1360
+ 'integ-test-runner': integTestRunner,
1361
+ 'regression-test-runner': regressionTestRunner,
1362
+ harvester,
1363
+ });
1364
+
1365
+ /** Every role name in the table, in table order. */
1366
+ export const ROLE_NAMES = Object.freeze(Object.keys(ROLE_POLICIES));
1367
+
1368
+ /**
1369
+ * The policy for `role`, or throws naming the roles that do exist.
1370
+ *
1371
+ * `table` defaults to the real frozen ROLE_POLICIES. It is a parameter only
1372
+ * so a test can hand the engine a table with ONE field of ONE row changed and
1373
+ * watch the behaviour change with it -- see dispatch-role.mjs's `ctx.policies`.
1374
+ */
1375
+ export function policyFor(role, table = ROLE_POLICIES) {
1376
+ const found = table[role];
1377
+ if (!found) {
1378
+ throw new Error(`role-policies: no policy for role '${role}' (known roles: ${Object.keys(table).join(', ')})`);
1379
+ }
1380
+ return found;
1381
+ }
1382
+
1383
+ /**
1384
+ * Every DISPATCH the table describes: each role's main dispatch plus its
1385
+ * secondary, de-duplicated (doer-resume is reachable both as a role and as
1386
+ * the doer's secondary).
1387
+ */
1388
+ export function allDispatchPolicies() {
1389
+ const seen = new Set();
1390
+ const out = [];
1391
+ for (const name of ROLE_NAMES) {
1392
+ const entry = ROLE_POLICIES[name];
1393
+ for (const dispatch of [entry, entry.secondary]) {
1394
+ if (!dispatch || seen.has(dispatch)) continue;
1395
+ seen.add(dispatch);
1396
+ out.push(dispatch);
1397
+ }
1398
+ }
1399
+ return out;
1400
+ }
1401
+
1402
+ /** True when this role's dispatches push CODE (not just beads). */
1403
+ export function pushesCode(role) {
1404
+ return policyFor(role).bracket.pushCode === true;
1405
+ }
1406
+
1407
+ /**
1408
+ * Role names this table marks `migrated: true` -- i.e. roles whose dispatch
1409
+ * has moved off its inline runner.js agent() ladder onto the dispatchRole
1410
+ * engine. Empty today (apra-fleet-3swo.5.8 lands this field and
1411
+ * fleet-sprint/inline-ladder-guard.mjs, the guard that consumes it, ahead of
1412
+ * either migration bead actually flipping a role to true).
1413
+ */
1414
+ export function migratedRoleNames() {
1415
+ return ROLE_NAMES.filter((name) => ROLE_POLICIES[name].migrated === true);
1416
+ }