@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,1684 @@
1
+ // KB (Knowledge Bank) work for fleet-sprint: the per-dispatch relevance-ranked read (kb_query), the vetting
2
+ // and forwarding of a role's kb_captures/kb_promotions payload (kb_capture/
3
+ // kb_promote), the per-round bible commit (kb_bible_commit), the once-per-sprint
4
+ // priming client (kb_session_prime/kb_import) and the prompt-construction
5
+ // helpers that hand a role's primed knowledge and promotion candidates to
6
+ // its dispatch prompt -- extracted move-only out of runner.js
7
+ // (apra-fleet-3swo.4.4 for the original KB work concern; apra-fleet-3swo.6.11
8
+ // for createKbPrimingClient, KB_SELF_INJECTING_ROLES, kbQueryTerms,
9
+ // kbKnowledgeBlock and kbPromotionBlock). runner.js re-exports every symbol
10
+ // it previously exported from this region, so existing importers of
11
+ // fleet-sprint/runner.js resolve unchanged.
12
+ //
13
+ // Every kb_* call here is BEST-EFFORT and NON-FATAL: a KB outage (cold KB,
14
+ // unreachable server, a rejected or throwing member call) must only be logged,
15
+ // never fail a dispatch.
16
+ //
17
+ // SCOPE IS THE SESSION, NOT AN ARGUMENT. No kb_* tool takes a repo/scope
18
+ // argument: a kb_* call operates on the calling session's own KB, and a
19
+ // MEMBER session resolves that member's registered work folder. So every
20
+ // member-targeted kb_* call here goes through the injected memberCall(member,
21
+ // tool, args) (member-call.mjs) -- a member-scoped session on that member --
22
+ // rather than the orchestrator's own callTool, whose FULL session would
23
+ // resolve the server's folder instead (the apra-fleet-tm7 repo-blindness
24
+ // class). The orchestrator's callTool is used only for member_detail, to
25
+ // learn each member's id and type.
26
+
27
+ import { ROLES, wrapUntrustedBlock } from './contracts.mjs';
28
+ import { toolErrorText } from './mcp-result.mjs';
29
+ import { cleanQueryTerms } from './kb-hints.mjs';
30
+ import { E_MEMBER_FLEET_TOO_OLD } from './member-call.mjs';
31
+
32
+ // Local, validated role constant -- mirrors runner.js's own roleConst()
33
+ // pattern (kb.mjs does not import runner.js's private helper, to avoid a
34
+ // module import cycle) so a rename/typo in contracts.ROLES still throws
35
+ // here at module-load time instead of silently narrowing KB_PROMOTER_ROLES
36
+ // to nothing.
37
+ function kbRoleConst(name) {
38
+ if (!ROLES.includes(name)) {
39
+ throw new Error(`[Role Contract] '${name}' is not a member of contracts.ROLES: ${ROLES.join(', ')}`);
40
+ }
41
+ return name;
42
+ }
43
+ const ROLE_REVIEWER = kbRoleConst('reviewer');
44
+ // Same mirrored-local pattern as ROLE_REVIEWER above, needed by
45
+ // KB_SELF_INJECTING_ROLES below (moved verbatim from runner.js, which still
46
+ // keeps its own module-private ROLE_DOER for its other call sites).
47
+ const ROLE_DOER = kbRoleConst('doer');
48
+
49
+ /**
50
+ * Cap on primed entries carried into a dispatch prompt. kb_session_prime can
51
+ * return up to ~28 (10 direct FTS hits + 3 global + 5 graph-neighbour + 5
52
+ * project-bible + 5 global-bible); a dispatch prompt is not a place to spend
53
+ * that much budget on context the role may not need, and the entries are
54
+ * already returned in relevance order.
55
+ */
56
+ export const KB_MAX_KNOWLEDGE_ENTRIES = 12;
57
+
58
+ /**
59
+ * The injection rule for every engine-built knowledge block: only CONFIRMED
60
+ * entries that sit outside any unresolved contradiction reach a role prompt.
61
+ * INFERRED/UNVERIFIED entries are the sprint's own unreviewed captures, and a
62
+ * flagged or contradiction_of entry is one the KB itself says is disputed --
63
+ * neither is knowledge a role should build on without checking.
64
+ *
65
+ * kb_query is ASKED for exactly this set (confidence + exclude_disputed), but
66
+ * the engine re-applies it on every path regardless: an older fleet server
67
+ * ignores the unknown params, kb_session_prime has no such filter, and a
68
+ * hand-edited bible can carry anything. Defense in depth, not duplication.
69
+ *
70
+ * @param {object} e
71
+ * @returns {boolean}
72
+ */
73
+ export function isInjectableKbEntry(e) {
74
+ return Boolean(e)
75
+ && e.confidence === 'CONFIRMED'
76
+ && !e.flagged_for_review
77
+ && !e.contradiction_of;
78
+ }
79
+
80
+ /**
81
+ * KB trust pipeline Phase 2, execution half for this engine.
82
+ *
83
+ * The role output schemas are SHARED with apra-pm (contracts.mjs loads them from
84
+ * apra-pm/agents/schemas), so every role dispatched here is now asked for
85
+ * kb_captures, and the reviewer for kb_promotions. Without a consumer those
86
+ * fields would be silently dropped -- the knowledge would be gathered and
87
+ * thrown away. This is that consumer.
88
+ *
89
+ * Unlike apra-pm's auto-sprint.js -- a Claude Workflow script with no tool
90
+ * access, which must hand its vetted payload to an executor subagent -- this
91
+ * engine runs in-process with an injected memberCall, so it makes the kb_capture
92
+ * and kb_promote calls DIRECTLY, as the member whose repo learned them. Judgment still belongs to the role; execution
93
+ * belongs here.
94
+ *
95
+ * Validation mirrors lib/vet-kb-work.mjs in apra-pm and the provider invariants
96
+ * it reflects: a capture must cite at least one source file (SqliteProvider
97
+ * rejects an entry the freshness sweep can never stale), a promotion needs a
98
+ * recorded evidence string, and kb_promotions is refused from any role other
99
+ * than reviewer -- widening capture to four roles must not widen promotion.
100
+ *
101
+ * @param {{ memberCall?: (member: object, name: string, args: object) => Promise<any>, log?: Function }} opts
102
+ * @returns {{ apply: (role: string, member: object, result: any) => Promise<{captured: number, promoted: number, refused: number}> }}
103
+ */
104
+ export const KB_PROMOTER_ROLES = Object.freeze(new Set([ROLE_REVIEWER]));
105
+ export const KB_MIN_PROMOTE_REASON = 20;
106
+ export const KB_CAPTURE_TYPES = Object.freeze(['knowledge', 'learning', 'runbook']);
107
+
108
+ /**
109
+ * True when an MCP tool result represents a tool-level failure. The MCP client
110
+ * resolves such results instead of throwing (apra-fleet-23c), so callers that
111
+ * only catch exceptions silently treat failures as successes. (memberCall
112
+ * throws a typed MemberCallError instead; both shapes are handled.)
113
+ */
114
+ function isToolError(res) {
115
+ return !!(res && typeof res === 'object' && res.isError === true);
116
+ }
117
+
118
+ export function vetKbWork(role, result) {
119
+ const captures = [];
120
+ const promotions = [];
121
+ const refused = [];
122
+
123
+ const rawCaptures = (result && Array.isArray(result.kb_captures)) ? result.kb_captures : [];
124
+ for (const c of rawCaptures) {
125
+ if (!c || typeof c.title !== 'string' || typeof c.summary !== 'string') {
126
+ refused.push(`${role}: capture missing title/summary`);
127
+ continue;
128
+ }
129
+ if (!Array.isArray(c.source_files) || c.source_files.length === 0) {
130
+ refused.push(`${role}: capture "${c.title}" cites no source files`);
131
+ continue;
132
+ }
133
+ if (!KB_CAPTURE_TYPES.includes(c.type)) {
134
+ refused.push(`${role}: capture "${c.title}" has unsupported type ${String(c.type)}`);
135
+ continue;
136
+ }
137
+ // apra-fleet-23c: kbCaptureSchema requires content (z.string().min(1)).
138
+ // Omitting it here meant every kb_capture the engine sent failed zod
139
+ // validation at the MCP boundary and persisted nothing.
140
+ if (typeof c.content !== 'string' || c.content.trim().length === 0) {
141
+ refused.push(`${role}: capture "${c.title}" has no content`);
142
+ continue;
143
+ }
144
+ captures.push({
145
+ type: c.type,
146
+ title: c.title,
147
+ summary: c.summary,
148
+ content: c.content,
149
+ source_files: c.source_files,
150
+ symbols: Array.isArray(c.symbols) ? c.symbols : [],
151
+ });
152
+ }
153
+
154
+ const rawPromotions = (result && Array.isArray(result.kb_promotions)) ? result.kb_promotions : [];
155
+ if (rawPromotions.length > 0 && !KB_PROMOTER_ROLES.has(role)) {
156
+ refused.push(`${role}: kb_promotions refused -- promotion is reviewer-only`);
157
+ } else {
158
+ for (const p of rawPromotions) {
159
+ if (!p || typeof p.id !== 'string' || p.id.length === 0) {
160
+ refused.push(`${role}: promotion missing id`);
161
+ continue;
162
+ }
163
+ if (typeof p.reason !== 'string' || p.reason.trim().length < KB_MIN_PROMOTE_REASON) {
164
+ refused.push(`${role}: promotion ${p.id} has no recorded evidence`);
165
+ continue;
166
+ }
167
+ promotions.push({ id: p.id, reason: p.reason.trim() });
168
+ }
169
+ }
170
+
171
+ // kb_discards: the reviewer's DISCARD judgement on a promotion candidate.
172
+ // Same role gate and evidence bar as kb_promotions -- a discard removes an
173
+ // entry from every read, so it is no less consequential than a promotion.
174
+ const discards = [];
175
+ const rawDiscards = (result && Array.isArray(result.kb_discards)) ? result.kb_discards : [];
176
+ if (rawDiscards.length > 0 && !KB_PROMOTER_ROLES.has(role)) {
177
+ refused.push(`${role}: kb_discards refused -- discard is reviewer-only`);
178
+ } else {
179
+ for (const d of rawDiscards) {
180
+ if (!d || typeof d.id !== 'string' || d.id.length === 0) {
181
+ refused.push(`${role}: discard missing id`);
182
+ continue;
183
+ }
184
+ if (typeof d.reason !== 'string' || d.reason.trim().length < KB_MIN_PROMOTE_REASON) {
185
+ refused.push(`${role}: discard ${d.id} has no recorded evidence`);
186
+ continue;
187
+ }
188
+ discards.push({ id: d.id, reason: d.reason.trim() });
189
+ }
190
+ }
191
+
192
+ // One output may not both CONFIRM and DISCARD the same entry: the two
193
+ // judgements contradict each other, so neither is executed and both sides
194
+ // are logged.
195
+ const discardIds = new Set(discards.map((d) => d.id));
196
+ const conflicted = new Set(promotions.filter((p) => discardIds.has(p.id)).map((p) => p.id));
197
+ for (const p of promotions) {
198
+ if (conflicted.has(p.id)) refused.push(`${role}: promotion ${p.id} refused -- the same output also discards it (promote reason: ${p.reason})`);
199
+ }
200
+ for (const d of discards) {
201
+ if (conflicted.has(d.id)) refused.push(`${role}: discard ${d.id} refused -- the same output also promotes it (discard reason: ${d.reason})`);
202
+ }
203
+
204
+ return {
205
+ captures,
206
+ promotions: promotions.filter((p) => !conflicted.has(p.id)),
207
+ discards: discards.filter((d) => !conflicted.has(d.id)),
208
+ refused,
209
+ };
210
+ }
211
+
212
+ /** Max promotion candidates offered to one reviewer, so the prompt stays bounded. */
213
+ export const KB_MAX_PROMOTION_CANDIDATES = 40;
214
+
215
+ /** Display label for a member record in log lines. */
216
+ function memberLabel(member) {
217
+ return (member && (member.name || member.id)) || 'unknown member';
218
+ }
219
+
220
+ /** The committed bible, relative to the maintainer's checkout root. */
221
+ const BIBLE_FILE = '.fleet/kb-canonical.json';
222
+
223
+ /**
224
+ * kb_bible_commit skip reasons the engine keeps queued: the cause can clear on
225
+ * its own (uncommitted edits, entries captured against commits the maintainer
226
+ * has not pulled yet), so the id is offered again at the next round. Every
227
+ * other reason (not_confirmed_or_unknown, no_source_files, or one this engine
228
+ * does not know) cannot change by retrying and drops the id.
229
+ */
230
+ const KB_RETRYABLE_SKIP_REASONS = Object.freeze(new Set(['basis_mismatch']));
231
+
232
+ /**
233
+ * How many bible-commit rounds in a row an id may be skipped with a retryable
234
+ * reason before it is dropped with a WARN, so a permanently drifted entry
235
+ * cannot sit in the queue forever.
236
+ */
237
+ export const KB_BIBLE_SKIP_RETRY_ROUNDS = 3;
238
+
239
+ /**
240
+ * memberCall error codes that mean the TOOL refused the call (the member was
241
+ * reached and answered). Every other coded error -- a connect failure, a
242
+ * send_files failure, an unparseable remote reply -- means the member could
243
+ * not be reached, so the write stays queued for a later attempt.
244
+ */
245
+ const KB_TOOL_REJECTION_CODES = Object.freeze(new Set(['E-TOOL', 'E-USAGE', 'E-ARGS-FILE', 'E-CALL']));
246
+
247
+ /** True when a thrown memberCall error means the member was unreachable. */
248
+ function isUnreachableError(err) {
249
+ return !!(err && typeof err.code === 'string' && err.code.length > 0 && !KB_TOOL_REJECTION_CODES.has(err.code));
250
+ }
251
+
252
+ /** The member name a kb work call names (a member record or a bare name). */
253
+ function memberNameOf(member) {
254
+ if (typeof member === 'string') return member;
255
+ return (member && typeof member.name === 'string') ? member.name : null;
256
+ }
257
+
258
+ /**
259
+ * Every KB write for a repository goes through that repository's
260
+ * kb_maintainer (kb-maintainer.mjs), in the maintainer's MEMBER session --
261
+ * never through the member whose dispatch produced it, and never through the
262
+ * orchestrator's own session.
263
+ *
264
+ * - apply() vets a role's kb_captures / kb_promotions, then QUEUES them per
265
+ * repository and flushes that repository's queue.
266
+ * - A flush runs the existing G-pull (opts.gPull -> git-sync's bracketed
267
+ * syncMemberBefore) on the maintainer BEFORE the batch, so the
268
+ * maintainer's checkout holds the files a capture cites and the KB's
269
+ * basis check passes. A G-pull failure means the maintainer is
270
+ * unreachable: the batch stays queued and a WARN is logged.
271
+ * - A maintainer that is mid-dispatch (it is usually also a doer) is BUSY:
272
+ * its repository's writes stay queued and are applied between its
273
+ * dispatches, never during one. runner.js reports the dispatch lifecycle
274
+ * through dispatchStarted()/dispatchEnded(); the end of a dispatch
275
+ * flushes whatever queued up behind it.
276
+ * - A capture from a member whose work folder is not a repository has no
277
+ * maintainer and is dropped with a WARN.
278
+ * - A write the maintainer cannot be reached for mid-batch is put back at
279
+ * the head of the queue: nothing is lost and nothing is silently dropped.
280
+ *
281
+ * The bible commit (commitRound): every promotion the maintainer applied is
282
+ * remembered per repository as a CONFIRMATION awaiting the bible. After each
283
+ * review round (reviewer, final reviewer, harvester) the engine calls
284
+ * commitRound(), which per repository with confirmations runs, on the
285
+ * maintainer: G-pull, kb_bible_commit {ids, baseBranch, baseCommit}, G-push.
286
+ * baseBranch is the sprint's TARGET BASE branch and baseCommit the base
287
+ * commit the entries were verified against (opts.bibleBase resolves both on
288
+ * the maintainer). A rejected G-push is retried exactly once: abort any
289
+ * in-progress rebase, G-pull onto the new remote tip, kb_bible_commit again
290
+ * with the same ids (it merges at entry level, so the concurrent change's
291
+ * entries survive with no manual merge) and G-push again. A second failure
292
+ * keeps the ids queued for the next round with a WARN. When kb_bible_commit
293
+ * commits nothing (committed:false) the ids leave the queue only once origin
294
+ * is shown to hold the bible (opts.bibleUnpushed): an earlier round's bible
295
+ * commit still unpushed on the maintainer is G-pushed (same retry and reset
296
+ * guards), and an undecidable check keeps the ids queued with a WARN. After
297
+ * seal() (a FAIL verdict or an aborted sprint) nothing further is committed.
298
+ * An id kb_bible_commit skips with basis_mismatch stays queued and is offered
299
+ * again next round (the mismatch can be transient), for at most
300
+ * opts.bibleSkipRetryRounds (default KB_BIBLE_SKIP_RETRY_ROUNDS) skipped
301
+ * rounds in a row, then is dropped with a WARN naming it and the reason; any
302
+ * other skip reason drops the id at once.
303
+ *
304
+ * @param {{
305
+ * memberCall?: (member: object, name: string, args: object, opts?: { kbMaintainer?: boolean }) => Promise<any>,
306
+ * maintainers?: object|(() => object),
307
+ * gPull?: (memberName: string, options?: { resetToRemoteTip?: boolean }) => Promise<any>,
308
+ * gPush?: (memberName: string) => Promise<any>,
309
+ * abortRebase?: (memberName: string) => Promise<any>,
310
+ * bibleBase?: (memberName: string) => Promise<{ baseBranch: string, baseCommit: string }|null>,
311
+ * canResetCheckout?: (memberName: string, bibleFile: string) => Promise<{ safe: boolean, reason?: string }>,
312
+ * checkedOutBranch?: (memberName: string) => Promise<{ branch: string|null, sprintBranch: string|null }>,
313
+ * bibleUnpushed?: (memberName: string, bibleFile: string) => Promise<{ unpushed: boolean|null, reason?: string }>,
314
+ * unpushedOnlyBible?: (memberName: string, bibleFile: string) => Promise<{ onlyBible: boolean, reason?: string }>,
315
+ * sprintStartMs?: number|(() => number),
316
+ * bibleSkipRetryRounds?: number,
317
+ * log?: Function,
318
+ * }} opts
319
+ */
320
+ /**
321
+ * memberCall options for a call made AS a repository's kb_maintainer: the
322
+ * session carries the kb_maintainer grant, so the server also serves it
323
+ * kb_promote, kb_resolve_contradiction and kb_reconcile_prefilter (see
324
+ * member-call.mjs).
325
+ */
326
+ export const KB_MAINTAINER_CALL = Object.freeze({ kbMaintainer: true });
327
+
328
+ export function createKbWorkClient(opts = {}) {
329
+ const { memberCall, gPull, gPush, abortRebase, bibleBase, canResetCheckout, checkedOutBranch, bibleUnpushed, unpushedOnlyBible, log = () => {} } = opts;
330
+ /** The sprint's start time (ms since epoch) from the sprint state, or null when unknown. */
331
+ const sprintStartMs = () => {
332
+ const v = typeof opts.sprintStartMs === 'function' ? opts.sprintStartMs() : opts.sprintStartMs;
333
+ return (typeof v === 'number' && Number.isFinite(v)) ? v : null;
334
+ };
335
+ const active = typeof memberCall === 'function';
336
+
337
+ /** The kb_maintainer selector (createKbMaintainerSelector), or null. */
338
+ function selector() {
339
+ const m = typeof opts.maintainers === 'function' ? opts.maintainers() : opts.maintainers;
340
+ return (m && typeof m.maintainerForMember === 'function') ? m : null;
341
+ }
342
+
343
+ /** repo -> queued writes, oldest first: { kind, role, payload }. */
344
+ const queues = new Map();
345
+ /** repo -> Set of candidate ids the latest promotionCandidates() call offered. */
346
+ const offeredCandidates = new Map();
347
+ /** repo -> tail of the serialized flush chain for that repository. */
348
+ const flushChains = new Map();
349
+ /** member name -> open dispatch count (nested brackets count once each). */
350
+ const busy = new Map();
351
+ /** member name -> the write currently in flight to it, if any. */
352
+ const inFlight = new Map();
353
+ /** repo -> ids the maintainer CONFIRMED that are not yet in a pushed bible commit (insertion order). */
354
+ const confirmations = new Map();
355
+ /** repo -> (id -> rounds in a row kb_bible_commit skipped it with a retryable reason). */
356
+ const skipRounds = new Map();
357
+ const skipRetryRounds = Number.isInteger(opts.bibleSkipRetryRounds) && opts.bibleSkipRetryRounds > 0
358
+ ? opts.bibleSkipRetryRounds
359
+ : KB_BIBLE_SKIP_RETRY_ROUNDS;
360
+ /**
361
+ * Repositories whose maintainer may hold bible retirements not yet in a
362
+ * bible commit: a kb_invalidate discard was applied there since the last
363
+ * successful kb_bible_commit. kb_bible_commit removes superseded and
364
+ * invalidated entries at every call, so such a repository gets a call
365
+ * (with ids [] when nothing is confirmed) even in a round that promoted
366
+ * nothing.
367
+ */
368
+ const retirements = new Set();
369
+ /** Why the bible commit was sealed (a FAIL verdict, an abort), or null while open. */
370
+ let sealedReason = null;
371
+
372
+ const isBusy = (memberName) => (busy.get(memberName) || 0) > 0;
373
+
374
+ /** Best-effort JSON out of an MCP result (string, content-block, or plain object). */
375
+ function parseResult(result) {
376
+ if (typeof result === 'string') { try { return JSON.parse(result); } catch { return null; } }
377
+ if (result && Array.isArray(result.content) && result.content[0] && typeof result.content[0].text === 'string') {
378
+ try { return JSON.parse(result.content[0].text); } catch { return null; }
379
+ }
380
+ return (result && typeof result === 'object') ? result : null;
381
+ }
382
+
383
+ /**
384
+ * The maintainer selection ({repo, member, record}) KB writes produced by
385
+ * `memberName` go to, or null. A member whose own work folder is not a
386
+ * repository has none.
387
+ */
388
+ function maintainerFor(memberName) {
389
+ const sel = selector();
390
+ if (!sel || !memberName) return null;
391
+ const m = sel.maintainerForMember(memberName);
392
+ return (m && m.member && m.record) ? m : null;
393
+ }
394
+
395
+ /**
396
+ * The maintainer a REVIEWER's candidates come from and its CONFIRM/DISCARD
397
+ * judgements go to: the reviewer's own repository's maintainer, or -- for
398
+ * a reviewer whose work folder is not a checkout -- the sprint's only
399
+ * maintainer when exactly one repository has one.
400
+ */
401
+ function reviewMaintainerFor(memberName) {
402
+ if (!memberName) return null;
403
+ const own = maintainerFor(memberName);
404
+ if (own) return own;
405
+ const sel = selector();
406
+ if (!sel || typeof sel.maintainers !== 'function' || typeof sel.getKbMaintainer !== 'function') return null;
407
+ const repos = [...sel.maintainers()].filter(([, m]) => m && m.member).map(([repo]) => repo);
408
+ if (repos.length !== 1) return null;
409
+ const m = sel.getKbMaintainer(repos[0]);
410
+ return (m && m.member && m.record) ? m : null;
411
+ }
412
+
413
+ /**
414
+ * The record knowledge reads run as: the repository kb_maintainer of
415
+ * `member`'s repository (see reviewMaintainerFor). Without a selector at
416
+ * all (unit-test seam) the member itself, when it is a record.
417
+ */
418
+ function readTarget(member) {
419
+ const sel = selector();
420
+ if (!sel) return (member && typeof member === 'object' && member.id) ? member : null;
421
+ const m = reviewMaintainerFor(memberNameOf(member));
422
+ return m ? m.record : null;
423
+ }
424
+
425
+ /** kb_query on the target: CONFIRMED, undisputed entries (direct hits, then graph-related). */
426
+ async function queryEntries(record, query) {
427
+ try {
428
+ const res = await memberCall(record, 'kb_query', {
429
+ query,
430
+ limit: KB_MAX_KNOWLEDGE_ENTRIES,
431
+ expand_related: true,
432
+ confidence: ['CONFIRMED'],
433
+ exclude_disputed: true,
434
+ });
435
+ // apra-fleet-23c: a tool-level failure RESOLVES with {isError:true}
436
+ // rather than throwing; log it instead of reading it as "no hits".
437
+ if (isToolError(res)) {
438
+ log(`[kb-work] kb_query rejected for ${memberLabel(record)} (non-fatal): ${toolErrorText(res)}`);
439
+ return [];
440
+ }
441
+ const parsed = parseResult(res);
442
+ if (!parsed) return [];
443
+ const hits = Array.isArray(parsed.l1_results) ? parsed.l1_results : [];
444
+ const related = Array.isArray(parsed.related_claims) ? parsed.related_claims : [];
445
+ const seen = new Set();
446
+ const out = [];
447
+ for (const e of hits) {
448
+ if (typeof e?.id !== 'string' || !isInjectableKbEntry(e) || seen.has(e.id)) continue;
449
+ seen.add(e.id);
450
+ out.push(e);
451
+ }
452
+ // Related claims sit BELOW every direct hit and carry a marker.
453
+ for (const e of related) {
454
+ if (typeof e?.id !== 'string' || !isInjectableKbEntry(e) || seen.has(e.id)) continue;
455
+ seen.add(e.id);
456
+ out.push({ ...e, via: 'kb-graph' });
457
+ }
458
+ return out.slice(0, KB_MAX_KNOWLEDGE_ENTRIES);
459
+ } catch (err) {
460
+ log(`[kb-work] kb_query failed for ${memberLabel(record)} (non-fatal): ${err.message}`);
461
+ return [];
462
+ }
463
+ }
464
+
465
+ /** kb_session_prime with the role's hints; only injectable entries survive. */
466
+ async function primeEntries(record, hintSymbols, hintModules) {
467
+ try {
468
+ const res = await memberCall(record, 'kb_session_prime', {
469
+ ...(hintSymbols.length > 0 ? { hint_symbols: hintSymbols } : {}),
470
+ ...(hintModules.length > 0 ? { hint_modules: hintModules } : {}),
471
+ confidence: ['CONFIRMED'],
472
+ });
473
+ if (isToolError(res)) {
474
+ log(`[kb-work] kb_session_prime rejected for ${memberLabel(record)} (non-fatal): ${toolErrorText(res)}`);
475
+ return [];
476
+ }
477
+ const parsed = parseResult(res);
478
+ const top = parsed && Array.isArray(parsed.top_entries) ? parsed.top_entries : [];
479
+ return top.filter((e) => typeof e?.id === 'string' && isInjectableKbEntry(e)).slice(0, KB_MAX_KNOWLEDGE_ENTRIES);
480
+ } catch (err) {
481
+ log(`[kb-work] kb_session_prime failed for ${memberLabel(record)} (non-fatal): ${err.message}`);
482
+ return [];
483
+ }
484
+ }
485
+
486
+ const zeroCounts = () => ({ captured: 0, promoted: 0, discarded: 0 });
487
+
488
+ const OPS = {
489
+ capture: {
490
+ tool: 'kb_capture',
491
+ args: (p) => ({ ...p }),
492
+ subject: (p) => `"${p.title}"`,
493
+ counter: 'captured',
494
+ },
495
+ promote: {
496
+ tool: 'kb_promote',
497
+ args: (p) => ({ id: p.id, reason: p.reason }),
498
+ subject: (p) => p.id,
499
+ counter: 'promoted',
500
+ },
501
+ discard: {
502
+ tool: 'kb_invalidate',
503
+ args: (p) => ({ ids: [p.id] }),
504
+ subject: (p) => p.id,
505
+ counter: 'discarded',
506
+ // kb_invalidate {ids} answers {discarded, not_found,
507
+ // already_discarded}. Every candidate is maintainer-tagged by
508
+ // construction, so a not-found means the entry is gone: logged,
509
+ // non-fatal, and not counted as a discard.
510
+ accept: (p, res) => {
511
+ const parsed = parseResult(res);
512
+ if (parsed && Array.isArray(parsed.not_found) && parsed.not_found.includes(p.id)) {
513
+ log(`[kb-work] kb_invalidate: entry ${p.id} not found on the maintainer -- already gone (non-fatal)`);
514
+ return false;
515
+ }
516
+ if (parsed && Array.isArray(parsed.already_discarded) && parsed.already_discarded.includes(p.id)) {
517
+ log(`[kb-work] kb_invalidate: entry ${p.id} was already discarded (non-fatal)`);
518
+ return false;
519
+ }
520
+ return true;
521
+ },
522
+ },
523
+ };
524
+
525
+ /**
526
+ * Apply one repository's queue in the maintainer's session. Never throws.
527
+ * @returns {Promise<{captured: number, promoted: number, discarded: number}>}
528
+ */
529
+ async function flushRepo(repo) {
530
+ const counts = zeroCounts();
531
+ const queue = queues.get(repo);
532
+ if (!queue || queue.length === 0) return counts;
533
+ const sel = selector();
534
+ const target = sel && typeof sel.getKbMaintainer === 'function' ? sel.getKbMaintainer(repo) : null;
535
+ if (!target || !target.record) {
536
+ log(`[kb-work] WARN: repository ${repo} has no kb_maintainer -- ${queue.length} KB write(s) stay queued`);
537
+ return counts;
538
+ }
539
+ const maintainer = target.member;
540
+ if (isBusy(maintainer)) {
541
+ log(`[kb-work] maintainer '${maintainer}' is mid-dispatch -- ${queue.length} KB write(s) for ${repo} stay queued until its dispatch ends`);
542
+ return counts;
543
+ }
544
+ // G-pull BEFORE every batch: the maintainer's checkout must hold the
545
+ // files the queued captures cite before kb_capture's basis check runs.
546
+ if (typeof gPull === 'function') {
547
+ // Same sprint-branch guard as the bible commit path: a pull on any
548
+ // other branch would move that branch, so nothing runs there.
549
+ if (!(await onSprintBranch(maintainer, repo, queue.length, 'KB write'))) return counts;
550
+ // Register the pull in inFlight so dispatchStarted() waits it out
551
+ // instead of running its own G-pull concurrently on the same checkout.
552
+ const pull = Promise.resolve().then(() => gPull(maintainer));
553
+ inFlight.set(maintainer, pull.then(() => {}, () => {}));
554
+ try {
555
+ await pull;
556
+ } catch (err) {
557
+ log(`[kb-work] WARN: G-pull on maintainer '${maintainer}' failed (${err && err.message ? err.message : String(err)}) -- maintainer unreachable; ${queue.length} KB write(s) for ${repo} stay queued`);
558
+ return counts;
559
+ } finally {
560
+ inFlight.delete(maintainer);
561
+ }
562
+ }
563
+ const batch = queue.splice(0, queue.length);
564
+ for (let i = 0; i < batch.length; i++) {
565
+ const op = batch[i];
566
+ if (isBusy(maintainer)) {
567
+ // A dispatch started on the maintainer while this batch ran:
568
+ // no write may land during it.
569
+ queue.unshift(...batch.slice(i));
570
+ log(`[kb-work] maintainer '${maintainer}' started a dispatch -- ${batch.length - i} KB write(s) for ${repo} stay queued until it ends`);
571
+ break;
572
+ }
573
+ const spec = OPS[op.kind];
574
+ // AS the kb_maintainer: the grant is what lets the session see
575
+ // kb_promote (no other member session is served it).
576
+ const call = memberCall(target.record, spec.tool, spec.args(op.payload), KB_MAINTAINER_CALL);
577
+ inFlight.set(maintainer, call.then(() => {}, () => {}));
578
+ let res;
579
+ try {
580
+ res = await call;
581
+ } catch (err) {
582
+ if (err && err.code === E_MEMBER_FLEET_TOO_OLD) {
583
+ // The maintainer's install cannot open the kb_maintainer
584
+ // grant: nothing in this batch can land until it is
585
+ // upgraded, so all of it stays queued.
586
+ queue.unshift(...batch.slice(i));
587
+ log(`[kb-work] WARNING: maintainer '${maintainer}' cannot run ${spec.tool}: ${err.message} -- ${batch.length - i} KB write(s) for ${repo} stay queued`);
588
+ break;
589
+ }
590
+ if (isUnreachableError(err)) {
591
+ queue.unshift(...batch.slice(i));
592
+ log(`[kb-work] WARN: maintainer '${maintainer}' unreachable during ${spec.tool} for ${spec.subject(op.payload)} (${err.message}) -- ${batch.length - i} KB write(s) for ${repo} stay queued`);
593
+ break;
594
+ }
595
+ log(`[kb-work] ${spec.tool} failed for ${spec.subject(op.payload)} (non-fatal): ${err && err.message ? err.message : String(err)}`);
596
+ continue;
597
+ } finally {
598
+ inFlight.delete(maintainer);
599
+ }
600
+ // apra-fleet-23c: an MCP client RESOLVES with {isError:true} on a
601
+ // tool-level failure rather than throwing, so a non-throwing call
602
+ // is not by itself a success.
603
+ if (isToolError(res)) {
604
+ log(`[kb-work] ${spec.tool} rejected for ${spec.subject(op.payload)} (non-fatal): ${toolErrorText(res)}`);
605
+ continue;
606
+ }
607
+ if (typeof spec.accept === 'function' && !spec.accept(op.payload, res)) continue;
608
+ counts[spec.counter]++;
609
+ if (op.kind === 'discard') retirements.add(repo);
610
+ if (op.kind === 'promote') {
611
+ if (!confirmations.has(repo)) confirmations.set(repo, new Set());
612
+ confirmations.get(repo).add(op.payload.id);
613
+ }
614
+ }
615
+ if (counts.captured || counts.promoted || counts.discarded) {
616
+ log(`[kb-work] maintainer '${maintainer}' (${repo}): captured ${counts.captured}, promoted ${counts.promoted}, discarded ${counts.discarded}`);
617
+ }
618
+ return counts;
619
+ }
620
+
621
+ /**
622
+ * Serialize every maintainer operation per repository (queue flushes and
623
+ * bible commits) so two never interleave on one checkout.
624
+ */
625
+ function serialize(repo, fn) {
626
+ const prev = flushChains.get(repo) || Promise.resolve();
627
+ const next = prev.then(fn, fn);
628
+ flushChains.set(repo, next.then(() => {}, () => {}));
629
+ return next;
630
+ }
631
+
632
+ function flush(repo) {
633
+ return serialize(repo, () => flushRepo(repo));
634
+ }
635
+
636
+ const errText = (err) => (err && err.message ? err.message : String(err));
637
+
638
+ /**
639
+ * What a bible commit carries, for its log lines: the confirmations, or
640
+ * -- for a removal-only call (ids []) -- the pending bible removals.
641
+ */
642
+ const bibleLoad = (ids) => (ids.length > 0 ? `${ids.length} confirmation(s)` : 'the pending bible removal(s)');
643
+ /** onSprintBranch for a bible commit carrying `ids` (see bibleLoad). */
644
+ const bibleOnSprintBranch = (maintainer, repo, ids) => (ids.length > 0
645
+ ? onSprintBranch(maintainer, repo, ids.length)
646
+ : onSprintBranch(maintainer, repo, 'the', 'pending bible removal'));
647
+
648
+ /**
649
+ * One kb_bible_commit attempt on the maintainer: G-pull, resolve the
650
+ * base, kb_bible_commit, then G-push when a commit was made. Returns
651
+ * { ok: true, result } or { ok: false, stage, error } -- never throws.
652
+ * `resetToRemoteTip` is the retry's G-pull: after a rejected push the
653
+ * maintainer holds a local bible commit the remote tip does not, so a
654
+ * fast-forward pull would fail by construction; kb_bible_commit re-merges
655
+ * the same ids at entry level on top of the new tip instead.
656
+ */
657
+ async function bibleAttempt(target, repo, ids, { resetToRemoteTip = false } = {}) {
658
+ const maintainer = target.member;
659
+ if (!(await bibleOnSprintBranch(maintainer, repo, ids))) return { ok: false, stage: 'branch check', error: 'the maintainer is not on the sprint branch', branchBlocked: true };
660
+ try {
661
+ await gPull(maintainer, resetToRemoteTip ? { resetToRemoteTip: true } : {});
662
+ } catch (err) {
663
+ return { ok: false, stage: 'G-pull', error: errText(err) };
664
+ }
665
+ let base;
666
+ try {
667
+ base = await bibleBase(maintainer);
668
+ } catch (err) {
669
+ return { ok: false, stage: 'base resolution', error: errText(err) };
670
+ }
671
+ if (!base || typeof base.baseBranch !== 'string' || !base.baseBranch || typeof base.baseCommit !== 'string' || !base.baseCommit) {
672
+ return { ok: false, stage: 'base resolution', error: 'the base branch or base commit could not be resolved on the maintainer' };
673
+ }
674
+ if (!(await bibleOnSprintBranch(maintainer, repo, ids))) return { ok: false, stage: 'branch check', error: 'the maintainer is not on the sprint branch', branchBlocked: true };
675
+ let res;
676
+ try {
677
+ res = await memberCall(target.record, 'kb_bible_commit', { ids, baseBranch: base.baseBranch, baseCommit: base.baseCommit }, KB_MAINTAINER_CALL);
678
+ } catch (err) {
679
+ return { ok: false, stage: 'kb_bible_commit', error: errText(err), fleetTooOld: !!(err && err.code === E_MEMBER_FLEET_TOO_OLD) };
680
+ }
681
+ if (isToolError(res)) return { ok: false, stage: 'kb_bible_commit', error: toolErrorText(res) };
682
+ const result = parseResult(res) || {};
683
+ // Nothing committed (every id skipped, or the entry set unchanged).
684
+ // That alone does not mean the entries are published: an earlier
685
+ // round's bible commit may still sit unpushed on the maintainer (its
686
+ // G-push was rejected and the reset onto the remote tip was refused to
687
+ // protect unrelated local work). Only origin decides: when it already
688
+ // holds the checkout's bible there is nothing to push; when a local
689
+ // commit holds it, push that commit; otherwise (or when it cannot be
690
+ // established) the ids stay queued.
691
+ if (result.committed === false) {
692
+ const where = await bibleOnOrigin(maintainer);
693
+ if (where.unpushed === false) return { ok: true, result, pushed: false };
694
+ if (where.unpushed !== true) return { ok: false, stage: 'publication check', error: where.reason || 'whether origin holds the bible could not be established' };
695
+ log(`[kb-work] kb_bible_commit made no new commit on maintainer '${maintainer}', but an earlier bible commit is not on origin yet -- pushing it`);
696
+ }
697
+ if (!(await bibleOnSprintBranch(maintainer, repo, ids))) return { ok: false, stage: 'branch check', error: 'the maintainer is not on the sprint branch', branchBlocked: true };
698
+ // A bible push must publish the bible commit(s) only: never a doer
699
+ // commit that sits unpushed underneath them. Without an injected
700
+ // probe the push is allowed.
701
+ if (typeof unpushedOnlyBible === 'function') {
702
+ let verdict;
703
+ try { verdict = await unpushedOnlyBible(maintainer, BIBLE_FILE); } catch (err) { verdict = { onlyBible: false, reason: errText(err) }; }
704
+ if (!verdict || verdict.onlyBible !== true) {
705
+ log(`[kb-work] WARN: not pushing the bible commit from maintainer '${maintainer}' (${repo}): ${(verdict && verdict.reason) || 'unknown'} -- a bible push must not publish other commits; ${bibleLoad(ids)} stay queued for the next round`);
706
+ return { ok: false, stage: 'push guard', error: (verdict && verdict.reason) || 'unpushed non-bible commits', branchBlocked: true };
707
+ }
708
+ }
709
+ try {
710
+ await gPush(maintainer);
711
+ } catch (err) {
712
+ return { ok: false, stage: 'G-push', error: errText(err) };
713
+ }
714
+ return { ok: true, result, pushed: true };
715
+ }
716
+
717
+ /**
718
+ * Whether origin's sprint branch already holds the maintainer checkout's
719
+ * bible, through the injected bibleUnpushed probe. Resolves
720
+ * { unpushed: false } when it does, { unpushed: true } when a local-only
721
+ * commit holds the bible, or { unpushed: null, reason } when that cannot
722
+ * be established (no probe wired, a git failure, a bible change that is
723
+ * not committed) -- never assumes published. Never throws.
724
+ */
725
+ async function bibleOnOrigin(maintainer) {
726
+ if (typeof bibleUnpushed !== 'function') return { unpushed: null, reason: 'no publication check is wired for the bible commit' };
727
+ let r;
728
+ try { r = await bibleUnpushed(maintainer, BIBLE_FILE); } catch (err) { return { unpushed: null, reason: errText(err) }; }
729
+ if (r && (r.unpushed === true || r.unpushed === false)) return { unpushed: r.unpushed };
730
+ return { unpushed: null, reason: (r && r.reason) || 'the publication check returned no answer' };
731
+ }
732
+
733
+ /**
734
+ * True when a hard reset onto the remote tip would drop nothing but the
735
+ * bible commit. When it would drop anything else (or that cannot be
736
+ * established), logs a WARN and returns false -- the caller keeps the ids
737
+ * queued and does not reset. Without an injected guard the reset is allowed.
738
+ */
739
+ async function resetIsSafe(maintainer, repo) {
740
+ if (typeof canResetCheckout !== 'function') return true;
741
+ let verdict;
742
+ try { verdict = await canResetCheckout(maintainer, BIBLE_FILE); } catch (err) { verdict = { safe: false, reason: errText(err) }; }
743
+ if (verdict && verdict.safe) return true;
744
+ log(`[kb-work] WARN: not resetting maintainer '${maintainer}' (${repo}) onto the remote tip: ${(verdict && verdict.reason) || 'unknown'} -- unrelated local work was preserved; the bible confirmations stay queued for the next round`);
745
+ return false;
746
+ }
747
+
748
+ /**
749
+ * True when the maintainer's checked-out branch is the sprint branch.
750
+ * Checked before the first G-pull of a bible commit and before every
751
+ * reset onto the remote tip, so no pull, reset --hard, commit or push
752
+ * ever runs on any other branch. When the branch differs (or cannot be
753
+ * read), logs a WARN naming the maintainer and both branches and returns
754
+ * false -- the caller keeps the ids queued. Without an injected guard
755
+ * the check passes.
756
+ */
757
+ async function onSprintBranch(maintainer, repo, count, what = 'confirmation') {
758
+ if (typeof checkedOutBranch !== 'function') return true;
759
+ let found = null;
760
+ let sprintBranch = null;
761
+ let readError = null;
762
+ try {
763
+ const r = await checkedOutBranch(maintainer);
764
+ found = r && typeof r.branch === 'string' && r.branch ? r.branch : null;
765
+ sprintBranch = r && typeof r.sprintBranch === 'string' && r.sprintBranch ? r.sprintBranch : null;
766
+ } catch (err) {
767
+ readError = errText(err);
768
+ }
769
+ if (found && sprintBranch && found === sprintBranch) return true;
770
+ const foundText = found ? `'${found}'` : `an unreadable branch${readError ? ` (${readError})` : ''}`;
771
+ log(`[kb-work] WARN: maintainer '${maintainer}' (${repo}) has ${foundText} checked out, not the sprint branch '${sprintBranch || 'unknown'}' -- no pull, bible commit, push or reset is made there; ${count} ${what}(s) stay queued for the next round`);
772
+ return false;
773
+ }
774
+
775
+ /**
776
+ * Commit one repository's pending confirmations to the bible on its
777
+ * maintainer. Never throws; ids that do not reach a pushed commit stay
778
+ * pending for the next round.
779
+ * @returns {Promise<{ committed: number, pending: number }>}
780
+ */
781
+ async function commitRepo(repo) {
782
+ const pending = confirmations.get(repo) || new Set();
783
+ // No confirmations and no retirements: no call at all (no member
784
+ // traffic). Retirements alone make a removal-only call with ids [].
785
+ if (pending.size === 0 && !retirements.has(repo)) return { committed: 0, pending: 0 };
786
+ const ids = [...pending];
787
+ const load = bibleLoad(ids);
788
+ if (sealedReason) return { committed: 0, pending: ids.length };
789
+ const sel = selector();
790
+ const target = sel && typeof sel.getKbMaintainer === 'function' ? sel.getKbMaintainer(repo) : null;
791
+ if (!target || !target.record) {
792
+ log(`[kb-work] WARN: repository ${repo} has no kb_maintainer -- ${load} stay queued for the bible`);
793
+ return { committed: 0, pending: ids.length };
794
+ }
795
+ const maintainer = target.member;
796
+ if (typeof gPull !== 'function' || typeof gPush !== 'function' || typeof bibleBase !== 'function') {
797
+ log(`[kb-work] WARN: no git sync wired for the bible commit -- ${load} for ${repo} stay queued`);
798
+ return { committed: 0, pending: ids.length };
799
+ }
800
+ if (isBusy(maintainer)) {
801
+ log(`[kb-work] WARN: maintainer '${maintainer}' is mid-dispatch -- ${load} for ${repo} stay queued for the next round's bible commit`);
802
+ return { committed: 0, pending: ids.length };
803
+ }
804
+ let release;
805
+ inFlight.set(maintainer, new Promise((r) => { release = r; }));
806
+ try {
807
+ let outcome = await bibleAttempt(target, repo, ids);
808
+ if (!outcome.ok && outcome.stage === 'G-push') {
809
+ log(`[kb-work] G-push of the bible commit on maintainer '${maintainer}' (${repo}) was rejected (${outcome.error}) -- retrying once: rebase --abort, G-pull, kb_bible_commit, G-push`);
810
+ if (typeof abortRebase === 'function' && (await bibleOnSprintBranch(maintainer, repo, ids))) {
811
+ try { await abortRebase(maintainer); } catch (err) { log(`[kb-work] rebase --abort on maintainer '${maintainer}' failed (non-fatal): ${errText(err)}`); }
812
+ }
813
+ // The reset throws away the maintainer's local-only commits and
814
+ // uncommitted changes; it is usually also a doer, so only reset
815
+ // when that is the bible commit alone.
816
+ if (!(await bibleOnSprintBranch(maintainer, repo, ids))) return { committed: 0, pending: ids.length };
817
+ if (!(await resetIsSafe(maintainer, repo))) return { committed: 0, pending: ids.length };
818
+ outcome = await bibleAttempt(target, repo, ids, { resetToRemoteTip: true });
819
+ if (!outcome.ok && (outcome.stage === 'G-push' || outcome.stage === 'kb_bible_commit')) {
820
+ // Leave the checkout on the remote tip: an unpushed bible
821
+ // commit would make the maintainer's next fast-forward
822
+ // G-pull fail. The ids stay queued and are re-merged by
823
+ // the next round's kb_bible_commit.
824
+ if (typeof abortRebase === 'function' && !outcome.branchBlocked && (await bibleOnSprintBranch(maintainer, repo, ids))) {
825
+ try { await abortRebase(maintainer); } catch { /* best-effort */ }
826
+ }
827
+ try { if ((await bibleOnSprintBranch(maintainer, repo, ids)) && (await resetIsSafe(maintainer, repo))) await gPull(maintainer, { resetToRemoteTip: true }); } catch (err) {
828
+ log(`[kb-work] WARN: could not reset maintainer '${maintainer}' onto the remote tip after the failed bible commit: ${errText(err)}`);
829
+ }
830
+ }
831
+ }
832
+ if (!outcome.ok && outcome.branchBlocked) return { committed: 0, pending: ids.length };
833
+ if (!outcome.ok && outcome.fleetTooOld) {
834
+ log(`[kb-work] WARNING: bible commit for ${repo} cannot run on maintainer '${maintainer}': ${outcome.error} -- ${load} stay queued for the next round`);
835
+ return { committed: 0, pending: ids.length };
836
+ }
837
+ if (!outcome.ok) {
838
+ log(`[kb-work] WARN: bible commit for ${repo} on maintainer '${maintainer}' failed at ${outcome.stage} (${outcome.error}) -- ${load} stay queued for the next round`);
839
+ return { committed: 0, pending: ids.length };
840
+ }
841
+ // The call succeeded: whatever retirements the maintainer held were
842
+ // removed by it (kb_bible_commit drops them at every call).
843
+ retirements.delete(repo);
844
+ const skipped = Array.isArray(outcome.result.skipped) ? outcome.result.skipped : [];
845
+ // A skip whose cause can clear on its own (basis_mismatch: the cited
846
+ // files at the maintainer's HEAD differ from the recorded basis, e.g.
847
+ // the entry was captured against commits not pulled yet) stays queued
848
+ // and is offered again next round, for a bounded number of rounds.
849
+ // Any other skip (not CONFIRMED or unknown, no source files) cannot
850
+ // change by retrying and leaves the queue. Merged ids leave it too.
851
+ if (!skipRounds.has(repo)) skipRounds.set(repo, new Map());
852
+ const rounds = skipRounds.get(repo);
853
+ const retained = [];
854
+ const dropped = [];
855
+ const exhausted = [];
856
+ for (const x of skipped) {
857
+ if (!x || typeof x.id !== 'string') continue;
858
+ if (!KB_RETRYABLE_SKIP_REASONS.has(x.reason)) { dropped.push(x); continue; }
859
+ const n = (rounds.get(x.id) || 0) + 1;
860
+ if (n >= skipRetryRounds) { exhausted.push({ ...x, rounds: n }); continue; }
861
+ rounds.set(x.id, n);
862
+ retained.push(x);
863
+ }
864
+ const keep = new Set(retained.map((x) => x.id));
865
+ for (const id of ids) {
866
+ if (keep.has(id)) continue;
867
+ pending.delete(id);
868
+ rounds.delete(id);
869
+ }
870
+ if (pending.size === 0) confirmations.delete(repo);
871
+ if (rounds.size === 0) skipRounds.delete(repo);
872
+ const merged = Array.isArray(outcome.result.merged) ? outcome.result.merged.length : ids.length - skipped.length;
873
+ const describe = (list) => list.map((x) => (x.reason ? `${x.id} (${x.reason})` : x.id)).join(', ');
874
+ if (dropped.length > 0) {
875
+ log(`[kb-work] kb_bible_commit skipped ${dropped.length} id(s) for ${repo} that cannot succeed on a retry (dropped from the queue, with the reason the tool returned): ${describe(dropped)}`);
876
+ }
877
+ if (retained.length > 0) {
878
+ log(`[kb-work] kb_bible_commit skipped ${retained.length} id(s) for ${repo} for a reason that can clear (kept queued for the next round, at most ${skipRetryRounds} skipped rounds in a row): ${describe(retained)}`);
879
+ }
880
+ for (const x of exhausted) {
881
+ log(`[kb-work] WARN: dropping ${x.id} from the bible queue for ${repo}: kb_bible_commit skipped it with reason ${x.reason || 'unknown'} for ${x.rounds} round(s) in a row`);
882
+ }
883
+ // Bible entries the maintainer KB holds as superseded or invalidated
884
+ // are removed by the tool at every call; name each one here so the
885
+ // removal is visible in the run log, not only in the commit message.
886
+ const removed = Array.isArray(outcome.result.removed) ? outcome.result.removed.filter((x) => x && typeof x.id === 'string') : [];
887
+ if (removed.length > 0) {
888
+ log(`[kb-work] kb_bible_commit removed ${removed.length} superseded/invalidated entry(ies) from the bible for ${repo}: ${describe(removed)}`);
889
+ }
890
+ if (ids.length === 0) {
891
+ log(`[kb-work] removal-only bible commit for ${repo} on maintainer '${maintainer}': ${outcome.pushed ? `${removed.length} removal(s) committed and pushed` : 'nothing to remove -- nothing to push'}`);
892
+ } else {
893
+ log(`[kb-work] bible commit for ${repo} on maintainer '${maintainer}': ${merged} confirmation(s) ${outcome.pushed ? 'committed and pushed' : 'already in the bible -- nothing to push'}`);
894
+ }
895
+ return { committed: outcome.pushed ? merged : 0, pending: pending.size };
896
+ } finally {
897
+ inFlight.delete(maintainer);
898
+ release();
899
+ }
900
+ }
901
+
902
+ function enqueue(repo, kind, role, payload) {
903
+ if (!queues.has(repo)) queues.set(repo, []);
904
+ queues.get(repo).push({ kind, role, payload });
905
+ }
906
+
907
+ /** Repositories whose maintainer is `memberName`. */
908
+ function reposMaintainedBy(memberName) {
909
+ const sel = selector();
910
+ if (!sel || typeof sel.maintainers !== 'function') return [];
911
+ const out = [];
912
+ for (const [repo, m] of sel.maintainers()) if (m && m.member === memberName) out.push(repo);
913
+ return out;
914
+ }
915
+
916
+ return {
917
+ /**
918
+ * Dispatch lifecycle: a dispatch is starting on `memberName`. Marks it
919
+ * busy (no queued KB write starts on it from here on) and waits out a
920
+ * write already in flight to it. Never throws.
921
+ */
922
+ async dispatchStarted(memberName) {
923
+ if (!memberName) return;
924
+ busy.set(memberName, (busy.get(memberName) || 0) + 1);
925
+ const pending = inFlight.get(memberName);
926
+ if (pending) await pending;
927
+ },
928
+ /**
929
+ * Dispatch lifecycle: a dispatch on `memberName` ended. When it was the
930
+ * last open one, apply the writes that queued up behind it for every
931
+ * repository it maintains. Never throws.
932
+ */
933
+ async dispatchEnded(memberName) {
934
+ if (!memberName) return;
935
+ const n = (busy.get(memberName) || 0) - 1;
936
+ if (n > 0) { busy.set(memberName, n); return; }
937
+ busy.delete(memberName);
938
+ for (const repo of reposMaintainedBy(memberName)) {
939
+ try { await flush(repo); } catch (err) { log(`[kb-work] flush for ${repo} failed (non-fatal): ${err.message}`); }
940
+ }
941
+ },
942
+ /** Try every repository's queue (e.g. before the final review's bible commit). Never throws. */
943
+ async flushAll() {
944
+ const counts = zeroCounts();
945
+ for (const repo of [...queues.keys()]) {
946
+ const c = await flush(repo);
947
+ for (const k of Object.keys(counts)) counts[k] += c[k];
948
+ }
949
+ return counts;
950
+ },
951
+ /** Number of KB writes still queued (all repositories, or one). */
952
+ pendingCount(repo) {
953
+ if (repo) return (queues.get(repo) || []).length;
954
+ let n = 0;
955
+ for (const q of queues.values()) n += q.length;
956
+ return n;
957
+ },
958
+ /** Log a WARN for every repository that still has queued writes or confirmations. */
959
+ warnPending() {
960
+ for (const [repo, q] of queues) {
961
+ if (q.length > 0) log(`[kb-work] WARN: ${q.length} KB write(s) for ${repo} are still queued (maintainer busy or unreachable) -- not applied`);
962
+ }
963
+ for (const [repo, ids] of confirmations) {
964
+ if (ids.size > 0) log(`[kb-work] WARN: ${ids.size} confirmation(s) for ${repo} are not in a pushed bible commit${sealedReason ? ` (bible commits sealed: ${sealedReason})` : ''}`);
965
+ }
966
+ for (const repo of retirements) {
967
+ if (!confirmations.has(repo)) log(`[kb-work] WARN: the pending bible removal(s) for ${repo} are not in a pushed bible commit${sealedReason ? ` (bible commits sealed: ${sealedReason})` : ''}`);
968
+ }
969
+ },
970
+ /**
971
+ * The review-round bible commit: apply whatever is still queued, then
972
+ * for every repository with confirmations, on its maintainer: G-pull,
973
+ * kb_bible_commit, G-push (see the client header for the retry). A
974
+ * repository with no confirmations but a discard applied since its
975
+ * last bible commit gets a removal-only call (ids []). A round with
976
+ * neither makes no call at all. A no-op once
977
+ * sealed. Never throws.
978
+ * @param {string} [label] the round, for the log
979
+ * @returns {Promise<{ committed: number, pending: number }>}
980
+ */
981
+ async commitRound(label = 'review round') {
982
+ const out = { committed: 0, pending: 0 };
983
+ if (!active) return out;
984
+ if (sealedReason) {
985
+ let n = 0;
986
+ for (const ids of confirmations.values()) n += ids.size;
987
+ if (n > 0) log(`[kb-work] ${label}: bible commits are sealed (${sealedReason}) -- ${n} confirmation(s) not committed`);
988
+ return { committed: 0, pending: n };
989
+ }
990
+ for (const repo of [...queues.keys()]) {
991
+ if (queues.get(repo).length > 0) await flush(repo);
992
+ }
993
+ for (const repo of new Set([...confirmations.keys(), ...retirements])) {
994
+ const r = await serialize(repo, () => commitRepo(repo));
995
+ out.committed += r.committed;
996
+ out.pending += r.pending;
997
+ }
998
+ return out;
999
+ },
1000
+ /**
1001
+ * Stop every further bible commit: a FAIL verdict or an aborted
1002
+ * sprint commits nothing more, and the confirmation queue is not
1003
+ * flushed. Idempotent; the first reason wins.
1004
+ */
1005
+ seal(reason) {
1006
+ if (sealedReason) return;
1007
+ sealedReason = String(reason || 'sealed');
1008
+ let n = 0;
1009
+ for (const ids of confirmations.values()) n += ids.size;
1010
+ log(`[kb-work] bible commits sealed (${sealedReason})${n > 0 ? ` -- ${n} confirmation(s) will not be committed` : ''}`);
1011
+ },
1012
+ /** Confirmations not yet in a pushed bible commit (all repositories, or one). */
1013
+ pendingConfirmations(repo) {
1014
+ if (repo) return [...(confirmations.get(repo) || [])];
1015
+ const out = [];
1016
+ for (const ids of confirmations.values()) out.push(...ids);
1017
+ return out;
1018
+ },
1019
+ /**
1020
+ * Per repository, the confirmations not yet in a pushed bible commit,
1021
+ * for the persisted sprint analysis: [{ repo, count }] (repositories
1022
+ * with none are left out), plus why bible commits were sealed, if
1023
+ * they were.
1024
+ * @returns {{ repos: Array<{ repo: string, count: number }>, sealedReason: string|null }}
1025
+ */
1026
+ unpublishedBible() {
1027
+ const repos = [];
1028
+ for (const [repo, ids] of confirmations) if (ids.size > 0) repos.push({ repo, count: ids.size });
1029
+ return { repos, sealedReason };
1030
+ },
1031
+ /**
1032
+ * The maintainer member record a reviewer's KB reads and judgements
1033
+ * go to (its repository's maintainer, or the sprint's only one), or null.
1034
+ */
1035
+ maintainerRecordFor(member) {
1036
+ const m = reviewMaintainerFor(memberNameOf(member));
1037
+ return m ? m.record : null;
1038
+ },
1039
+ /**
1040
+ * apra-fleet-0ef: the INFERRED entries this reviewer may promote.
1041
+ *
1042
+ * The engine's contract is "judgment belongs to the role, execution
1043
+ * belongs here" -- the reviewer returns `kb_promotions:[{id, reason}]`
1044
+ * and `apply()` calls kb_promote. But an entry id exists only inside
1045
+ * the KB, and the reviewer subagent has no apra-fleet MCP tools to
1046
+ * look one up, so it could never name an id: `kb_promotions` was
1047
+ * structurally always empty and nothing was ever promoted. (kb_captures
1048
+ * worked only because a capture needs no pre-existing id.) This is the
1049
+ * missing input: the engine reads the candidates and hands them to the
1050
+ * reviewer in its prompt.
1051
+ *
1052
+ * Best-effort by design -- a cold or unreachable KB must degrade to
1053
+ * "nothing to promote", never fail the review dispatch.
1054
+ */
1055
+ async promotionCandidates(member) {
1056
+ // The candidates live in the reviewer's repository MAINTAINER's KB
1057
+ // (every KB write is routed there), tagged member:<maintainer uuid>
1058
+ // by its MEMBER session. Without a maintainer there is no session
1059
+ // to read them from; refuse rather than read some other KB (the
1060
+ // apra-fleet-tm7 repo-blindness class).
1061
+ const target = active ? reviewMaintainerFor(memberNameOf(member)) : null;
1062
+ if (!target) return [];
1063
+ // Replace (never accumulate) this review scope's offered set up
1064
+ // front, so a failed read leaves nothing offered from a prior round.
1065
+ offeredCandidates.set(target.repo, new Set());
1066
+ // Writes still queued for this repository (a capture from this
1067
+ // very round) get their chance to land before the read.
1068
+ if (queues.has(target.repo)) await flush(target.repo);
1069
+ try {
1070
+ const res = await memberCall(target.record, 'kb_query', {
1071
+ tag: `member:${target.record.id}`,
1072
+ confidence: ['INFERRED'],
1073
+ limit: KB_MAX_PROMOTION_CANDIDATES,
1074
+ });
1075
+ if (isToolError(res)) {
1076
+ log(`[kb-work] kb_query for promotion candidates rejected on maintainer '${target.member}' (non-fatal): ${toolErrorText(res)}`);
1077
+ return [];
1078
+ }
1079
+ const parsed = parseResult(res);
1080
+ const results = parsed && Array.isArray(parsed.l1_results) ? parsed.l1_results
1081
+ : (parsed && Array.isArray(parsed.results) ? parsed.results : []);
1082
+ // The sprint window: only entries captured during THIS sprint
1083
+ // are this sprint's to judge. An entry whose created_at cannot
1084
+ // be read cannot be shown to be in the window.
1085
+ const since = sprintStartMs();
1086
+ const inWindow = (e) => {
1087
+ if (since === null) return true;
1088
+ const t = typeof e.created_at === 'string' ? Date.parse(e.created_at) : NaN;
1089
+ return Number.isFinite(t) && t >= since;
1090
+ };
1091
+ const offered = results
1092
+ // promote() refuses type='user-directive' outright (activation
1093
+ // is human-terminal, CLI-only), so offering one as a candidate
1094
+ // can only produce a guaranteed refusal.
1095
+ .filter((e) => e && typeof e.id === 'string' && e.type !== 'user-directive' && inWindow(e))
1096
+ .slice(0, KB_MAX_PROMOTION_CANDIDATES);
1097
+ offeredCandidates.set(target.repo, new Set(offered.map((e) => e.id)));
1098
+ return offered;
1099
+ } catch (err) {
1100
+ log(`[kb-work] could not read promotion candidates from maintainer '${target.member}' (non-fatal): ${err.message}`);
1101
+ return [];
1102
+ }
1103
+ },
1104
+ /**
1105
+ * KB audit follow-up: the per-dispatch, relevance-ranked read.
1106
+ *
1107
+ * primeAll() runs ONCE per member at sprint start with no hints, so
1108
+ * every role received the same handful of entries no matter what it was
1109
+ * about to work on -- and kb_query went unused by this engine entirely.
1110
+ * This asks the KB what it knows about THIS dispatch, using the terms
1111
+ * the engine already holds (bead ids and their titles).
1112
+ *
1113
+ * `expand_related` is what finally reads the KB's own graph. The KB has
1114
+ * been writing `refines` and `contradiction_of` edges since AUDN
1115
+ * shipped and traversing none of them: 554 edges, 0 reads. A role about
1116
+ * to act on an entry is precisely who needs to know that entry has a
1117
+ * newer framing -- a CONFIRMED refinement arrives as a related claim.
1118
+ *
1119
+ * Only CONFIRMED, undisputed entries are requested and kept (see
1120
+ * isInjectableKbEntry). A contradiction pair is excluded on BOTH sides
1121
+ * rather than shown as a dispute: confidence tier does NOT track
1122
+ * correctness across a contradiction chain (the warehouse chain-A
1123
+ * shape, where the incorrect entry outranks both of its corrections),
1124
+ * so neither side is safe to hand a role as knowledge until the pair is
1125
+ * resolved.
1126
+ *
1127
+ * Best-effort, like every other KB read here: no member, no terms, a
1128
+ * cold KB or an unreachable one all degrade to "no knowledge", never to
1129
+ * a failed dispatch.
1130
+ */
1131
+ async relevantKnowledge(member, hints) {
1132
+ return (await this.knowledgeFor(member, hints)).entries;
1133
+ },
1134
+ /**
1135
+ * The per-dispatch read behind the KNOWLEDGE BANK block: the entries
1136
+ * AND the source they really came from.
1137
+ *
1138
+ * Read from the repository's kb_maintainer through memberCall -- never
1139
+ * from the dispatched member (whose own KB may be cold, absent or on
1140
+ * a different checkout) and never from the orchestrator session. A
1141
+ * client built without a maintainer selector (unit-test seam) reads as
1142
+ * the member it is given.
1143
+ *
1144
+ * `hints` is either a bare term list or {terms, hintSymbols,
1145
+ * hintModules} (kb-hints.mjs roleHints). Order: kb_query on the
1146
+ * terms; when that finds nothing, kb_session_prime ranked by
1147
+ * hint_symbols/hint_modules; when that finds nothing too, NOTHING --
1148
+ * there is deliberately no fall-back to an arbitrary set.
1149
+ *
1150
+ * @returns {Promise<{ entries: object[], source: 'query'|'prime' }>}
1151
+ */
1152
+ async knowledgeFor(member, hints) {
1153
+ const h = Array.isArray(hints)
1154
+ ? { terms: hints, hintSymbols: [], hintModules: [] }
1155
+ : { terms: [], hintSymbols: [], hintModules: [], ...(hints || {}) };
1156
+ const strs = (v) => (Array.isArray(v) ? v.filter((t) => typeof t === 'string' && t.trim()) : []);
1157
+ const terms = strs(h.terms);
1158
+ const hintSymbols = strs(h.hintSymbols);
1159
+ const hintModules = strs(h.hintModules);
1160
+ const nothing = { entries: [], source: terms.length > 0 || hintSymbols.length + hintModules.length === 0 ? 'query' : 'prime' };
1161
+ if (!active || !member) return nothing;
1162
+ if (terms.length === 0 && hintSymbols.length === 0 && hintModules.length === 0) return nothing;
1163
+ const target = readTarget(member);
1164
+ if (!target) {
1165
+ log(`[kb-work] no kb_maintainer to read knowledge from for ${memberLabel(member)} -- no knowledge this dispatch`);
1166
+ return nothing;
1167
+ }
1168
+ if (terms.length > 0) {
1169
+ const queried = await queryEntries(target, terms.join(' '));
1170
+ if (queried.length > 0) return { entries: queried, source: 'query' };
1171
+ }
1172
+ if (hintSymbols.length > 0 || hintModules.length > 0) {
1173
+ const primed = await primeEntries(target, hintSymbols, hintModules);
1174
+ if (primed.length > 0) return { entries: primed, source: 'prime' };
1175
+ }
1176
+ return nothing;
1177
+ },
1178
+ /**
1179
+ * Vet a role's KB work and route it to the producing member's
1180
+ * repository maintainer: queued per repository, then applied in the
1181
+ * maintainer's MEMBER session after a G-pull (see the client header).
1182
+ * `member` names the member whose dispatch produced `result` (a member
1183
+ * record or a bare name); it decides WHICH repository, never which
1184
+ * session -- no write is ever sent to it unless it is the maintainer.
1185
+ *
1186
+ * @returns {Promise<{captured: number, promoted: number, discarded: number, refused: number}>}
1187
+ * counts of the writes applied by this call's flush (writes left
1188
+ * queued for a busy or unreachable maintainer are not counted).
1189
+ */
1190
+ async apply(role, member, result) {
1191
+ const { captures, promotions, discards, refused } = vetKbWork(role, result);
1192
+
1193
+ for (const r of refused) log(`[kb-work] refused -- ${r}`);
1194
+ // Log every promotion with its stated evidence BEFORE attempting it.
1195
+ // This log is the audit trail the bible never had.
1196
+ for (const p of promotions) log(`[kb-work] promote ${p.id} (${role}): ${p.reason}`);
1197
+ for (const d of discards) log(`[kb-work] discard ${d.id} (${role}): ${d.reason}`);
1198
+
1199
+ let extraRefused = 0;
1200
+ const done = (counts) => ({ ...counts, refused: refused.length + extraRefused });
1201
+ if (captures.length === 0 && promotions.length === 0 && discards.length === 0) return done(zeroCounts());
1202
+ const dropped = `${captures.length} capture(s), ${promotions.length} promotion(s) and ${discards.length} discard(s) dropped`;
1203
+
1204
+ const producer = memberNameOf(member);
1205
+ // Without a resolved member there is no repository the writes
1206
+ // belong to -- the tm7 defect. Refuse rather than guess.
1207
+ if (!active || !producer) {
1208
+ log(`[kb-work] WARN: no member resolved for ${role} -- ${dropped}`);
1209
+ return done(zeroCounts());
1210
+ }
1211
+ const sel = selector();
1212
+ const nonRepo = !!(sel && typeof sel.isNonRepoMember === 'function' && sel.isNonRepoMember(producer));
1213
+ // A capture belongs to the PRODUCER's repository: a member whose
1214
+ // work folder is not a repository has none, so its captures are
1215
+ // dropped. Review judgements (CONFIRM/DISCARD) act on candidates
1216
+ // read from the reviewer's maintainer (reviewMaintainerFor), so
1217
+ // they follow the same resolution as the candidate read.
1218
+ let target = null;
1219
+ if (captures.length > 0) {
1220
+ if (nonRepo) {
1221
+ log(`[kb-work] WARN: member '${producer}' (${role}): work folder is not a repository -- ${captures.length} capture(s) dropped`);
1222
+ } else {
1223
+ target = maintainerFor(producer);
1224
+ if (target) {
1225
+ for (const c of captures) enqueue(target.repo, 'capture', role, c);
1226
+ } else {
1227
+ log(`[kb-work] WARN: no kb_maintainer for member '${producer}' (${role}) -- ${captures.length} capture(s) dropped`);
1228
+ }
1229
+ }
1230
+ }
1231
+ const repos = new Set(target ? [target.repo] : []);
1232
+ if (promotions.length > 0 || discards.length > 0) {
1233
+ const review = reviewMaintainerFor(producer);
1234
+ if (review) {
1235
+ // Only ids offered in this dispatch's candidate block may be
1236
+ // judged; anything else is refused before any kb_* call.
1237
+ const offered = offeredCandidates.get(review.repo) || new Set();
1238
+ const inBlock = (kind, x) => {
1239
+ if (offered.has(x.id)) return true;
1240
+ log(`[kb-work] refused -- ${role}: ${kind} ${x.id} not in this dispatch's candidate block`);
1241
+ extraRefused += 1;
1242
+ return false;
1243
+ };
1244
+ for (const p of promotions) if (inBlock('promotion', p)) enqueue(review.repo, 'promote', role, p);
1245
+ for (const d of discards) if (inBlock('discard', d)) enqueue(review.repo, 'discard', role, d);
1246
+ repos.add(review.repo);
1247
+ } else {
1248
+ log(`[kb-work] WARN: no kb_maintainer for member '${producer}' (${role}) -- ${promotions.length} promotion(s) and ${discards.length} discard(s) dropped`);
1249
+ }
1250
+ }
1251
+ const counts = zeroCounts();
1252
+ for (const repo of repos) {
1253
+ const c = await flush(repo);
1254
+ for (const k of Object.keys(counts)) counts[k] += c[k];
1255
+ }
1256
+ return done(counts);
1257
+ },
1258
+ };
1259
+ }
1260
+
1261
+ /**
1262
+ * apra-fleet-e28 / KB trust pipeline Phase 2: KB priming for the fleet-sprint
1263
+ * engine, which had none -- it lived only in the Claude workflow copy.
1264
+ *
1265
+ * `callTool` (the orchestrator's own session, used only for member_detail) and
1266
+ * `memberCall` (member-call.mjs: a MEMBER-scoped session on that member) are
1267
+ * injected, so this stays transport-agnostic and unit-testable without a live
1268
+ * fleet server.
1269
+ *
1270
+ * WHY PER MEMBER, NOT PER SPRINT: this engine has no repo of its own. It
1271
+ * coordinates members by name and branch; the repo lives on each member's side,
1272
+ * possibly on a different host at a different path. A kb_* call operates on
1273
+ * the CALLING SESSION's own KB -- a member session resolves that member's
1274
+ * registered work folder -- so each member is primed through its own member
1275
+ * session. Priming through the orchestrator's session would read whichever
1276
+ * repo the fleet server sits in (the apra-fleet-tm7 / apra-fleet-3zl
1277
+ * repo-blindness defect). member_detail supplies the member's id and type
1278
+ * (what memberCall needs) and its work folder.
1279
+ *
1280
+ * Best-effort throughout, matching the reservation client's precedent: a member
1281
+ * that cannot be resolved, or whose prime call fails, is logged and skipped. A
1282
+ * sprint must not fail because the KB is cold -- priming is an optimisation,
1283
+ * and every role contract's Step 0 already degrades gracefully when the KB
1284
+ * tools are unavailable.
1285
+ *
1286
+ * @param {{ callTool?: (name: string, args: object) => Promise<any>, memberCall?: (member: object, name: string, args: object) => Promise<any>, members?: string[], maintainers?: object|Function, baseBranch?: string, log?: Function }} opts
1287
+ * @returns {{ primeAll: () => Promise<{primed: number, skipped: number}> }}
1288
+ */
1289
+
1290
+ export function createKbPrimingClient(opts = {}) {
1291
+ const { callTool, memberCall, members = [], log = () => {} } = opts;
1292
+ // A plain branch name only (it becomes refs/remotes/origin/<base>).
1293
+ const baseBranch = (typeof opts.baseBranch === 'string' && /^[A-Za-z0-9_][A-Za-z0-9._/-]*$/.test(opts.baseBranch) && !opts.baseBranch.includes('..'))
1294
+ ? opts.baseBranch : null;
1295
+ const maintainerSel = () => {
1296
+ const m = typeof opts.maintainers === 'function' ? opts.maintainers() : opts.maintainers;
1297
+ return (m && typeof m.maintainerForMember === 'function') ? m : null;
1298
+ };
1299
+ /**
1300
+ * True when `target`'s kb_import accepts `ref`: always for a local member
1301
+ * (served by this process); for a remote member only when its tools/list
1302
+ * advertises the property. Any doubt (no listTools, an unreadable answer)
1303
+ * is false.
1304
+ */
1305
+ async function supportsImportRef(target) {
1306
+ if (String(target && (target.type || target.agentType) || '').toLowerCase() === 'local') return true;
1307
+ if (typeof opts.listTools !== 'function') return false;
1308
+ try {
1309
+ const list = parseResult(await opts.listTools(target));
1310
+ const tools = Array.isArray(list) ? list : (list && Array.isArray(list.tools) ? list.tools : []);
1311
+ const imp = tools.find((t) => t && t.name === 'kb_import');
1312
+ const props = imp && imp.inputSchema && imp.inputSchema.properties;
1313
+ return !!(props && typeof props === 'object' && Object.prototype.hasOwnProperty.call(props, 'ref'));
1314
+ } catch {
1315
+ return false;
1316
+ }
1317
+ }
1318
+ /** maintainer record id -> entries primed there (a repository is imported and primed once). */
1319
+ const primedByTarget = new Map();
1320
+ const active = typeof callTool === 'function' && typeof memberCall === 'function' && members.length > 0;
1321
+
1322
+ function parseResult(result) {
1323
+ if (result && typeof result === 'string') { try { return JSON.parse(result); } catch { return null; } }
1324
+ if (result && Array.isArray(result.content) && result.content[0] && typeof result.content[0].text === 'string') {
1325
+ try { return JSON.parse(result.content[0].text); } catch { return null; }
1326
+ }
1327
+ return (result && typeof result === 'object') ? result : null;
1328
+ }
1329
+
1330
+ async function resolveMember(member) {
1331
+ // apra-fleet-n78: format:'json' is REQUIRED. member_detail defaults to
1332
+ // 'compact', whose renderer emits no folder at all -- `folder` is set only
1333
+ // on the json path (src/tools/member-detail.ts). Omitting it made this
1334
+ // return null for every member, so the KB was never primed for anyone.
1335
+ const detail = parseResult(await callTool('member_detail', { member_name: member, format: 'json' }));
1336
+ const d = detail && (detail.member && typeof detail.member === 'object' ? { ...detail.member, ...detail } : detail);
1337
+ const folder = d && d.folder;
1338
+ const id = d && d.id;
1339
+ return {
1340
+ folder: (typeof folder === 'string' && folder.length > 0) ? folder : null,
1341
+ // The record memberCall needs: the member's id (session identity)
1342
+ // and type (local -> in-process session, remote/relay -> the member's
1343
+ // own `apra-fleet call`).
1344
+ record: (typeof id === 'string' && id.length > 0)
1345
+ ? { id, name: member, type: typeof d.type === 'string' ? d.type : undefined }
1346
+ : null,
1347
+ };
1348
+ }
1349
+
1350
+ // member -> work folder, populated by primeAll(). Informational: no kb_*
1351
+ // call takes it any more (the member session resolves it server-side).
1352
+ const folders = new Map();
1353
+
1354
+ // member name -> the member record memberCall needs ({id, name, type}).
1355
+ // createKbWorkClient's calls take this record, so a capture lands in the
1356
+ // KB of the member that actually did the work.
1357
+ const records = new Map();
1358
+
1359
+ // member -> the entries kb_session_prime returned for that member.
1360
+ //
1361
+ // KB audit 2026-08-11: primeAll() used to `await callTool(...)` and throw
1362
+ // the result away, on the assumption that priming "warms" something the
1363
+ // role's own Step 0 would later read. It does not: prime is a pure read,
1364
+ // and the role CANNOT repeat it -- a member-dispatched subagent has the
1365
+ // fleet MCP server disabled (src/providers/claude.ts
1366
+ // composePermissionConfig), so every contract's Step 0 kb_session_prime is
1367
+ // unreachable there. Nothing consumed the knowledge and nothing could, which
1368
+ // is why six sprints retrieved zero entries. Retaining the result is what
1369
+ // lets kbKnowledgeBlock() hand it to the role in its dispatch prompt --
1370
+ // the same shape of fix that made kb_promotions reachable.
1371
+ const knowledge = new Map();
1372
+
1373
+ return {
1374
+ folderOf(member) {
1375
+ return folders.get(member) || null;
1376
+ },
1377
+ /** The member record ({id, name, type}) kb work for `member` runs as, or null. */
1378
+ memberOf(member) {
1379
+ return records.get(member) || null;
1380
+ },
1381
+ knowledgeOf(member) {
1382
+ return knowledge.get(member) || [];
1383
+ },
1384
+ async primeAll() {
1385
+ if (!active) return { primed: 0, skipped: members.length };
1386
+ let primed = 0;
1387
+ let skipped = 0;
1388
+ for (const member of members) {
1389
+ try {
1390
+ const { folder, record } = await resolveMember(member);
1391
+ if (folder) folders.set(member, folder);
1392
+ if (!record) {
1393
+ // No member id means no member session to scope the KB to.
1394
+ // Priming any other way would read the fleet server's own
1395
+ // KB, so skip instead.
1396
+ log(`[kb-prime] could not resolve member '${member}' -- skipping (KB stays cold)`);
1397
+ skipped++;
1398
+ continue;
1399
+ }
1400
+ records.set(member, record);
1401
+ // Knowledge is read from the repository's kb_maintainer, not
1402
+ // the member itself. A sprint without a selector primes the
1403
+ // member's own session (unit-test seam).
1404
+ const sel = maintainerSel();
1405
+ const m = sel ? sel.maintainerForMember(member) : null;
1406
+ const target = sel ? (m && m.record ? m.record : null) : record;
1407
+ if (!target) {
1408
+ log(`[kb-prime] no kb_maintainer for member '${member}' -- no knowledge primed`);
1409
+ primed++;
1410
+ continue;
1411
+ }
1412
+ if (primedByTarget.has(target.id)) {
1413
+ const shared = primedByTarget.get(target.id);
1414
+ if (shared.length > 0) knowledge.set(member, shared);
1415
+ primed++;
1416
+ continue;
1417
+ }
1418
+ // Land the committed bible in the WARM KB before priming.
1419
+ //
1420
+ // Without this the bible is reachable only through
1421
+ // kb_session_prime's cold-seed, which reads it as a FILE
1422
+ // and caps at 5 entries -- apra-fleet's own bible holds 17,
1423
+ // so a sprint could see at most 5 arbitrary ones and FTS
1424
+ // could rank none of them, because they were never rows.
1425
+ // Importing first is what gives the per-dispatch kb_query
1426
+ // (see relevantKnowledge) anything to match against.
1427
+ // Idempotent by id, and best-effort: a repo with no bible,
1428
+ // or an import that rejects every entry, must not stop the
1429
+ // prime it was meant to feed.
1430
+ //
1431
+ // skip_sweep IS LOAD-BEARING (audit 2026-08-12, caught by a
1432
+ // live sprint). kb_import's post-import freshnessSweep
1433
+ // re-judges the ENTIRE KB against this member's worktree. At
1434
+ // sprint start that staled 16 of 17 CONFIRMED entries purely
1435
+ // because the repo had moved on since capture, and the
1436
+ // damage cascaded: retrieval fell to one matchable entry,
1437
+ // the whole-bible publish attempted a 17 -> 9 truncation, and
1438
+ // kb_list (stale=0) returned an EMPTY promotion candidate
1439
+ // list -- reinstating apra-fleet-0ef, "kb_promote can never
1440
+ // fire". This import exists to WARM the KB, never to audit
1441
+ // it; prime()'s own bounded checkFreshness still guards each
1442
+ // entry it actually returns.
1443
+ //
1444
+ // The import on a repository's kb_maintainer runs WITH the
1445
+ // kb_maintainer grant. A session without the grant imports
1446
+ // a committed bible only when the maintainer side already
1447
+ // recorded it as trusted in the hub-side KB, so a bible
1448
+ // this hub never saw (a fresh hub, or a bible merged in
1449
+ // from elsewhere) would never land. The grant import is
1450
+ // the trusted seeding path, and the bible it imports is
1451
+ // marked trusted for every member of the repository -- so
1452
+ // it must not come from the maintainer's work tree or
1453
+ // HEAD. Nothing has cleaned that checkout yet: launch
1454
+ // alignment runs only for some launch modes, branch-ensure
1455
+ // runs after priming, and a reused local branch keeps
1456
+ // local-only commits. The grant import therefore reads the
1457
+ // bible committed on the base branch's remote-tracking ref
1458
+ // (full ref name, so a local branch named origin/<base>
1459
+ // cannot shadow it), which the server verifies against its
1460
+ // blob id. No base branch: no grant import. A sprint
1461
+ // without a maintainer selector (unit-test seam) imports
1462
+ // without the grant, which never records trust.
1463
+ try {
1464
+ // No `path`: the session imports its OWN folder's
1465
+ // bible (.fleet/kb-canonical.json), here at `ref`.
1466
+ let imported = null;
1467
+ if (!sel) {
1468
+ imported = parseResult(await memberCall(target, 'kb_import', { skip_sweep: true }));
1469
+ } else if (baseBranch) {
1470
+ const ref = 'refs/remotes/origin/' + baseBranch;
1471
+ // A REMOTE maintainer runs its own apra-fleet: an
1472
+ // older one drops the unknown `ref` key and would
1473
+ // grant-import (and trust) its WORK-TREE bible. Fail
1474
+ // closed: import only when its kb_import advertises
1475
+ // `ref`. A local member runs in this server.
1476
+ if (await supportsImportRef(target)) {
1477
+ imported = parseResult(await memberCall(target, 'kb_import', { skip_sweep: true, ref }, KB_MAINTAINER_CALL));
1478
+ if (imported && imported.bible_source !== ref) {
1479
+ log(`[kb-prime] WARN kb_import on '${target.name || member}' did not report reading ${ref} (bible_source ${JSON.stringify(imported.bible_source)}) -- upgrade apra-fleet on that member`);
1480
+ }
1481
+ } else {
1482
+ log(`[kb-prime] WARN the apra-fleet on '${target.name || member}' has no kb_import 'ref' (older version) -- bible import skipped; upgrade apra-fleet on that member`);
1483
+ }
1484
+ } else {
1485
+ log(`[kb-prime] no base branch -- bible import skipped for '${member}' (the kb_maintainer imports only the base branch's committed bible)`);
1486
+ }
1487
+ if (imported && typeof imported.imported === 'number' && imported.imported > 0) {
1488
+ log(`[kb-prime] imported ${imported.imported} bible entr(ies) into the warm KB for '${member}'`);
1489
+ }
1490
+ } catch (err) {
1491
+ log(`[kb-prime] kb_import skipped for '${member}' (non-fatal): ${err.message}`);
1492
+ }
1493
+
1494
+ const primeResult = parseResult(await memberCall(target, 'kb_session_prime', {}));
1495
+ // Same injection rule as relevantKnowledge, applied BEFORE the
1496
+ // cap so a prime dominated by INFERRED captures does not
1497
+ // crowd out the CONFIRMED entries behind them.
1498
+ const entries = (primeResult && Array.isArray(primeResult.top_entries))
1499
+ ? primeResult.top_entries.filter((e) => typeof e?.id === 'string' && isInjectableKbEntry(e))
1500
+ : [];
1501
+ const capped = entries.slice(0, KB_MAX_KNOWLEDGE_ENTRIES);
1502
+ primedByTarget.set(target.id, capped);
1503
+ if (capped.length > 0) knowledge.set(member, capped);
1504
+ primed++;
1505
+ } catch (err) {
1506
+ log(`[kb-prime] failed for member '${member}' (non-fatal): ${err.message}`);
1507
+ skipped++;
1508
+ }
1509
+ }
1510
+ if (primed > 0) log(`[kb-prime] primed ${primed} member repo(s)`);
1511
+ return { primed, skipped };
1512
+ },
1513
+ };
1514
+ }
1515
+
1516
+ /**
1517
+ * apra-fleet-0ef / apra-fleet-nx7: the "KNOWLEDGE BANK -- promotion candidates"
1518
+ * block, shared verbatim by the per-round reviewer prompt and the Final Review
1519
+ * prompt.
1520
+ *
1521
+ * It lives in one function because the two prompts must state the SAME evidence
1522
+ * bar. Duplicating the text invites them to drift, and a drifted bar is
1523
+ * invisible: both sides would still "work", just to different standards, and the
1524
+ * only symptom would be inconsistent CONFIRMED quality months later.
1525
+ *
1526
+ * Returns a single-element array (or an empty one) so callers can spread it into
1527
+ * their prompt-section list.
1528
+ *
1529
+ * @param {object[]|undefined} kbCandidates
1530
+ * @returns {string[]}
1531
+ */
1532
+ /**
1533
+ * KB audit 2026-08-11: the "KNOWLEDGE BANK -- what this repo already knows"
1534
+ * block, shared by the doer and reviewer dispatch prompts.
1535
+ *
1536
+ * WHY THIS EXISTS AT ALL. Every role contract's Step 0 tells the role to call
1537
+ * kb_session_prime itself. On a fleet-member dispatch it cannot: the member's
1538
+ * composed permission config disables the apra-fleet MCP server outright
1539
+ * (src/providers/claude.ts composePermissionConfig), so the tool is not merely
1540
+ * unlisted, it is unreachable. That is the same wall kb_promotions hit, and
1541
+ * this is the same fix -- the engine performs the read and hands the result
1542
+ * over as prompt content. Step 0 stays correct for the OTHER execution path
1543
+ * (an apra-pm orchestrator session running these contracts as local subagents,
1544
+ * where the MCP server is present), so both paths now get knowledge.
1545
+ *
1546
+ * Only CONFIRMED, undisputed entries are rendered (isInjectableKbEntry) --
1547
+ * every caller's source is already filtered, and this is the last chokepoint
1548
+ * before the prompt. CONFIRMED means a reviewer verified the claim when it was
1549
+ * captured, not that it is currently true of this branch's tree, which is why
1550
+ * the header still tells the role the code wins.
1551
+ *
1552
+ * Returns a single-element array (or an empty one) so callers can spread it
1553
+ * into their prompt-section list, matching kbPromotionBlock.
1554
+ *
1555
+ * @param {object[]|undefined} entries
1556
+ * @returns {string[]}
1557
+ */
1558
+ /**
1559
+ * Roles whose prompt BUILDER places the knowledge block itself, at a position
1560
+ * that carries meaning. Everything else receives it from the agent() wrapper.
1561
+ * Listing them here (rather than inside the wrapper) keeps the two halves of
1562
+ * that split visible from the block's own definition -- a role added to one
1563
+ * side and forgotten on the other either gets the block twice or never.
1564
+ */
1565
+ export const KB_SELF_INJECTING_ROLES = Object.freeze(new Set([ROLE_DOER, ROLE_REVIEWER]));
1566
+
1567
+ /**
1568
+ * FTS terms for a dispatch's kb_query, drawn from what the engine already
1569
+ * holds: the beads being worked and their ids.
1570
+ *
1571
+ * Bead TITLES are the useful half -- they are prose about the change ("stop
1572
+ * collapsing unknown_zone into unbound_roi"), which is what matches an entry's
1573
+ * title/summary/content. Ids are included because a bead id occasionally
1574
+ * appears verbatim in a captured entry, and query() OR-joins its terms, so a
1575
+ * term that matches nothing costs a little ranking noise rather than filtering
1576
+ * the result to empty. Non-string and blank values are dropped so a partially
1577
+ * populated bead cannot produce a malformed query.
1578
+ *
1579
+ * @param {Array<{id?: string, title?: string}>} beads
1580
+ * @param {string[]} beadIds
1581
+ * @returns {string[]}
1582
+ */
1583
+ export function kbQueryTerms(beads, beadIds) {
1584
+ // Bead TITLES only: tracker ids and stopwords are stripped (they match
1585
+ // nothing useful and only add ranking noise), so a bead id in `beadIds`
1586
+ // never reaches the query -- it is passed solely so a stray id inside a
1587
+ // title is recognised and dropped too.
1588
+ const titles = [];
1589
+ for (const b of Array.isArray(beads) ? beads : []) {
1590
+ if (b && typeof b.title === 'string' && b.title.trim()) titles.push(b.title.trim());
1591
+ }
1592
+ const knownIds = (Array.isArray(beadIds) ? beadIds : []).filter((id) => typeof id === 'string' && id.trim());
1593
+ return cleanQueryTerms(titles, { knownIds });
1594
+ }
1595
+
1596
+ // `captureChannel` (default true, the doer/reviewer/final-review prompt
1597
+ // builders' case) says whether the recipient's returned `kb_captures` field is
1598
+ // actually applied by the engine (a 'kb-apply' postResult step -- see
1599
+ // role-policies.mjs agentTypeAppliesKbCaptures). When it is not, the block
1600
+ // must not promise that the orchestrator records a capture: those roles'
1601
+ // prompts tell them to note the finding in their own report instead.
1602
+ export function kbKnowledgeBlock(entries, { captureChannel = true, source = 'prime', reportEmpty = false } = {}) {
1603
+ if (!Array.isArray(entries)) return [];
1604
+ // CONFIRMED-first, capped at KB_MAX_KNOWLEDGE_ENTRIES. The sources
1605
+ // (relevantKnowledge, primeAll) hand entries over in relevance order, so a
1606
+ // stable CONFIRMED filter + slice keeps the most relevant ones.
1607
+ const injectable = entries.filter(isInjectableKbEntry).slice(0, KB_MAX_KNOWLEDGE_ENTRIES);
1608
+ // The label names where the entries really came from: a per-dispatch
1609
+ // kb_query or the hint-driven kb_session_prime.
1610
+ const label = source === 'query' ? 'kb_query --top_entries' : 'kb_session_prime --top_entries';
1611
+ const captureLine = captureChannel
1612
+ ? 'If you discover something non-obvious and durable while working, report it in the '
1613
+ + '`kb_captures` field of your structured output and the orchestrator will record it.\n'
1614
+ : 'If you discover something non-obvious and durable while working, note it in your '
1615
+ + 'own report.\n';
1616
+ if (injectable.length === 0) {
1617
+ if (!reportEmpty) return [];
1618
+ // Nothing relevant matched: say so explicitly rather than falling back
1619
+ // to an arbitrary set of entries.
1620
+ return [
1621
+ 'KNOWLEDGE BANK -- what this repo already knows. No relevant CONFIRMED knowledge-bank '
1622
+ + 'entries were found for this task (source: ' + (source === 'query' ? 'kb_query' : 'kb_session_prime') + '). '
1623
+ + 'Nothing relevant was found, so no entries are provided; proceed from the code itself.\n'
1624
+ + captureLine,
1625
+ ];
1626
+ }
1627
+ return [
1628
+ 'KNOWLEDGE BANK -- what this repo already knows. These entries were captured during '
1629
+ + 'earlier work on this repository and are provided so you do not rediscover them the '
1630
+ + 'hard way. Read them BEFORE you start.\n'
1631
+ + 'Only CONFIRMED entries are included: a reviewer promoted each claim on evidence when '
1632
+ + 'it was captured. An entry describes the tree it was captured against, so if one '
1633
+ + 'contradicts what you actually observe in the code right now, the code wins -- say so '
1634
+ + 'in your notes rather than bending your work to fit the entry.\n'
1635
+ + 'You do not need a kb_* tool to read these entries; they do not replace any kb_* lookup '
1636
+ + 'your role instructions call for. '
1637
+ + captureLine
1638
+ + wrapUntrustedBlock(label, JSON.stringify(
1639
+ injectable.map((e) => ({
1640
+ confidence: e.confidence,
1641
+ title: e.title,
1642
+ summary: e.summary,
1643
+ source_files: e.source_files,
1644
+ })),
1645
+ null,
1646
+ 2
1647
+ )),
1648
+ ];
1649
+ }
1650
+
1651
+ export function kbPromotionBlock(kbCandidates) {
1652
+ if (!Array.isArray(kbCandidates) || kbCandidates.length === 0) return [];
1653
+ return [
1654
+ 'KNOWLEDGE BANK -- promotion candidates. These entries were captured during this '
1655
+ + 'sprint and sit at INFERRED. You are the only role that can promote them to '
1656
+ + 'CONFIRMED, or discard them. Do NOT call any kb_* tool yourself: return your '
1657
+ + 'decisions in your structured output and the orchestrator executes them -- '
1658
+ + '`kb_promotions` as [{id, reason}] for entries to CONFIRM, `kb_discards` as '
1659
+ + '[{id, reason}] for entries to DISCARD.\n'
1660
+ + 'Promote ONLY entries whose claim you independently verified during THIS review '
1661
+ + '-- by reading the diff, running the tests, or checking the cited files yourself. '
1662
+ + 'The `reason` must state that evidence (at least 20 characters, e.g. "verified '
1663
+ + 'against server/transit.js:88 and the reopen test"). Evidence, not plausibility: '
1664
+ + 'if an entry merely looks correct, leave it INFERRED -- that is a perfectly good '
1665
+ + 'resting state, and a wrong CONFIRMED entry is worse than no entry. Never '
1666
+ + 'blanket-promote, and never promote by module, tag or timestamp. Promoting '
1667
+ + 'nothing is a valid outcome; return [] in that case.\n'
1668
+ + 'Discard ONLY entries you showed to be WRONG during this review, with the same '
1669
+ + 'evidence bar: the `reason` states what you checked that contradicts the claim. '
1670
+ + 'A discarded entry drops out of every later read. An entry you cannot confirm '
1671
+ + 'is not thereby wrong -- leave it INFERRED. Never list the same id in both '
1672
+ + 'fields; the orchestrator refuses both.\n'
1673
+ + wrapUntrustedBlock('kb_query --tag member:<maintainer> --confidence INFERRED', JSON.stringify(
1674
+ kbCandidates.map((e) => ({
1675
+ id: e.id,
1676
+ title: e.title,
1677
+ summary: e.summary,
1678
+ source_files: e.source_files,
1679
+ })),
1680
+ null,
1681
+ 2
1682
+ )),
1683
+ ];
1684
+ }