@apralabs/apra-fleet 0.4.2 → 0.4.4

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