@apralabs/apra-fleet 0.4.3 → 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 (951) hide show
  1. package/README.md +66 -30
  2. package/dist/agents/backlog-groomer.md +75 -27
  3. package/dist/agents/ci-watcher.md +37 -22
  4. package/dist/agents/deployer.md +39 -22
  5. package/dist/agents/doer.md +74 -40
  6. package/dist/agents/harvester.md +49 -40
  7. package/dist/agents/integ-test-runner.md +40 -23
  8. package/dist/agents/kb-reconciler.md +28 -7
  9. package/dist/agents/plan-reviewer.md +49 -24
  10. package/dist/agents/planner.md +66 -43
  11. package/dist/agents/regression-test-runner.md +101 -78
  12. package/dist/agents/reviewer.md +117 -56
  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/planner-output.json +1 -1
  17. package/dist/agents/schemas/regression-test-runner-output.json +41 -7
  18. package/dist/agents/schemas/reviewer-output.json +62 -3
  19. package/dist/cli/agent-transform.d.ts +7 -0
  20. package/dist/cli/agent-transform.js +46 -1
  21. package/dist/cli/auth.d.ts +1 -0
  22. package/dist/cli/auth.js +38 -8
  23. package/dist/cli/beads-install.d.ts +35 -0
  24. package/dist/cli/beads-install.js +125 -0
  25. package/dist/cli/beads-pin.d.ts +5 -0
  26. package/dist/cli/beads-pin.js +27 -0
  27. package/dist/cli/call.d.ts +27 -0
  28. package/dist/cli/call.js +177 -0
  29. package/dist/cli/config.d.ts +24 -1
  30. package/dist/cli/config.js +69 -2
  31. package/dist/cli/dolt-install.d.ts +18 -2
  32. package/dist/cli/dolt-install.js +46 -15
  33. package/dist/cli/fleet-se-guard.d.ts +51 -0
  34. package/dist/cli/fleet-se-guard.js +215 -0
  35. package/dist/cli/install-guard.d.ts +54 -0
  36. package/dist/cli/install-guard.js +132 -4
  37. package/dist/cli/install.d.ts +77 -21
  38. package/dist/cli/install.js +610 -152
  39. package/dist/cli/kb-commit.d.ts +2 -1
  40. package/dist/cli/kb-commit.js +1 -1
  41. package/dist/cli/kb-import.d.ts +2 -1
  42. package/dist/cli/kb-import.js +1 -1
  43. package/dist/cli/register-member.js +20 -3
  44. package/dist/cli/remove-member.d.ts +4 -0
  45. package/dist/cli/remove-member.js +63 -0
  46. package/dist/cli/secret.js +9 -0
  47. package/dist/cli/start.js +59 -4
  48. package/dist/cli/status.d.ts +3 -0
  49. package/dist/cli/status.js +45 -12
  50. package/dist/cli/stop.js +64 -9
  51. package/dist/cli/uninstall.js +101 -15
  52. package/dist/cli/update.js +33 -2
  53. package/dist/cli/watch.js +1 -1
  54. package/dist/cli/workflow.js +3 -2
  55. package/dist/commands/kb-server.js +9 -2
  56. package/dist/hub-service/http-server.d.ts +5 -1
  57. package/dist/hub-service/http-server.js +55 -5
  58. package/dist/index.js +155 -8
  59. package/dist/os/child-env-bound.d.ts +77 -0
  60. package/dist/os/child-env-bound.js +171 -0
  61. package/dist/os/linux.d.ts +7 -2
  62. package/dist/os/linux.js +40 -14
  63. package/dist/os/macos.d.ts +1 -1
  64. package/dist/os/macos.js +2 -11
  65. package/dist/os/os-commands.d.ts +17 -2
  66. package/dist/os/windows-gitbash.d.ts +1 -0
  67. package/dist/os/windows-gitbash.js +17 -3
  68. package/dist/os/windows-wrapper.d.ts +0 -4
  69. package/dist/os/windows-wrapper.js +2 -1
  70. package/dist/os/windows.d.ts +5 -2
  71. package/dist/os/windows.js +75 -29
  72. package/dist/paths.d.ts +21 -0
  73. package/dist/paths.js +35 -0
  74. package/dist/providers/agy.d.ts +6 -2
  75. package/dist/providers/agy.js +245 -106
  76. package/dist/providers/claude-permission-denial.d.ts +7 -0
  77. package/dist/providers/claude-permission-denial.js +137 -0
  78. package/dist/providers/claude.d.ts +86 -38
  79. package/dist/providers/claude.js +426 -164
  80. package/dist/providers/codex.js +5 -1
  81. package/dist/providers/copilot.js +5 -1
  82. package/dist/providers/opencode.d.ts +10 -2
  83. package/dist/providers/opencode.js +114 -53
  84. package/dist/providers/provider.d.ts +171 -33
  85. package/dist/providers/provider.js +164 -3
  86. package/dist/services/agent-provisioner.d.ts +29 -0
  87. package/dist/services/agent-provisioner.js +107 -0
  88. package/dist/services/agent-shadow.d.ts +96 -0
  89. package/dist/services/agent-shadow.js +479 -0
  90. package/dist/services/agy-project.d.ts +2 -1
  91. package/dist/services/agy-project.js +15 -17
  92. package/dist/services/auth-socket.d.ts +25 -0
  93. package/dist/services/auth-socket.js +68 -23
  94. package/dist/services/auth-web.js +1 -1
  95. package/dist/services/budget-awareness.d.ts +11 -11
  96. package/dist/services/budget-awareness.js +15 -3
  97. package/dist/services/claude-local-scope-mcp.d.ts +19 -0
  98. package/dist/services/claude-local-scope-mcp.js +91 -0
  99. package/dist/services/cloud/aws.js +2 -1
  100. package/dist/services/cloud/lifecycle.js +19 -2
  101. package/dist/services/cloud/task-wrapper.d.ts +0 -9
  102. package/dist/services/cloud/task-wrapper.js +15 -6
  103. package/dist/services/event-loop-watchdog.d.ts +32 -0
  104. package/dist/services/event-loop-watchdog.js +140 -0
  105. package/dist/services/http-transport.d.ts +49 -1
  106. package/dist/services/http-transport.js +190 -24
  107. package/dist/services/in-flight-agents.d.ts +2 -0
  108. package/dist/services/in-flight-agents.js +4 -0
  109. package/dist/services/knowledge/bible-basis-filter.d.ts +53 -0
  110. package/dist/services/knowledge/bible-basis-filter.js +134 -0
  111. package/dist/services/knowledge/bible-blob-id.d.ts +44 -0
  112. package/dist/services/knowledge/bible-blob-id.js +113 -0
  113. package/dist/services/knowledge/bible-import.d.ts +65 -0
  114. package/dist/services/knowledge/bible-import.js +211 -0
  115. package/dist/services/knowledge/file-hash.d.ts +31 -0
  116. package/dist/services/knowledge/file-hash.js +153 -23
  117. package/dist/services/knowledge/http-provider.d.ts +4 -3
  118. package/dist/services/knowledge/http-provider.js +17 -5
  119. package/dist/services/knowledge/kb-maintainer-grant.d.ts +15 -0
  120. package/dist/services/knowledge/kb-maintainer-grant.js +34 -0
  121. package/dist/services/knowledge/kb-providers.d.ts +4 -0
  122. package/dist/services/knowledge/kb-providers.js +8 -0
  123. package/dist/services/knowledge/kb-removed-scope-keys.d.ts +28 -0
  124. package/dist/services/knowledge/kb-removed-scope-keys.js +59 -0
  125. package/dist/services/knowledge/kb-scopes.d.ts +14 -0
  126. package/dist/services/knowledge/kb-scopes.js +47 -0
  127. package/dist/services/knowledge/kb-self.d.ts +91 -0
  128. package/dist/services/knowledge/kb-self.js +198 -0
  129. package/dist/services/knowledge/member-bible-view.d.ts +21 -0
  130. package/dist/services/knowledge/member-bible-view.js +194 -0
  131. package/dist/services/knowledge/pre-init.js +1 -0
  132. package/dist/services/knowledge/project-slug.js +2 -2
  133. package/dist/services/knowledge/sqlite-provider.d.ts +64 -11
  134. package/dist/services/knowledge/sqlite-provider.js +303 -41
  135. package/dist/services/knowledge/types.d.ts +45 -2
  136. package/dist/services/member-access-secret.d.ts +70 -0
  137. package/dist/services/member-access-secret.js +195 -0
  138. package/dist/services/member-call-counts.d.ts +24 -0
  139. package/dist/services/member-call-counts.js +58 -0
  140. package/dist/services/member-config-io.d.ts +192 -0
  141. package/dist/services/member-config-io.js +443 -0
  142. package/dist/services/member-fleet-install.d.ts +710 -0
  143. package/dist/services/member-fleet-install.js +1895 -0
  144. package/dist/services/member-secret-env.d.ts +42 -0
  145. package/dist/services/member-secret-env.js +68 -0
  146. package/dist/services/member-tool-allowlist.d.ts +49 -0
  147. package/dist/services/member-tool-allowlist.js +111 -0
  148. package/dist/services/model-pricing.d.ts +19 -0
  149. package/dist/services/model-pricing.js +54 -8
  150. package/dist/services/port-holder.d.ts +86 -0
  151. package/dist/services/port-holder.js +351 -0
  152. package/dist/services/preflight-check.js +2 -0
  153. package/dist/services/registry.d.ts +13 -2
  154. package/dist/services/registry.js +27 -1
  155. package/dist/services/relay-strategy.d.ts +2 -0
  156. package/dist/services/relay-strategy.js +8 -0
  157. package/dist/services/server-lifecycle.d.ts +26 -0
  158. package/dist/services/server-lifecycle.js +85 -0
  159. package/dist/services/service-manager/index.d.ts +7 -1
  160. package/dist/services/service-manager/index.js +17 -4
  161. package/dist/services/service-manager/linux.d.ts +1 -1
  162. package/dist/services/service-manager/linux.js +15 -7
  163. package/dist/services/service-manager/macos.d.ts +11 -1
  164. package/dist/services/service-manager/macos.js +45 -7
  165. package/dist/services/service-manager/service-path.d.ts +24 -0
  166. package/dist/services/service-manager/service-path.js +55 -0
  167. package/dist/services/service-manager/types.d.ts +38 -3
  168. package/dist/services/service-manager/types.js +29 -0
  169. package/dist/services/service-manager/windows.d.ts +181 -2
  170. package/dist/services/service-manager/windows.js +666 -49
  171. package/dist/services/service-notice.d.ts +14 -0
  172. package/dist/services/service-notice.js +62 -0
  173. package/dist/services/service-start-guard.d.ts +20 -0
  174. package/dist/services/service-start-guard.js +86 -0
  175. package/dist/services/session-cost.d.ts +24 -0
  176. package/dist/services/session-cost.js +105 -0
  177. package/dist/services/session-mcp-config.d.ts +83 -0
  178. package/dist/services/session-mcp-config.js +211 -0
  179. package/dist/services/sftp.d.ts +34 -0
  180. package/dist/services/sftp.js +304 -76
  181. package/dist/services/shell-probe.d.ts +0 -24
  182. package/dist/services/shell-probe.js +28 -3
  183. package/dist/services/singleton.d.ts +68 -2
  184. package/dist/services/singleton.js +168 -11
  185. package/dist/services/sprint-coordination.js +9 -3
  186. package/dist/services/ssh.d.ts +27 -0
  187. package/dist/services/ssh.js +229 -38
  188. package/dist/services/stall/find-log-file.js +12 -5
  189. package/dist/services/stall/index.d.ts +1 -1
  190. package/dist/services/stall/read-log-tail.d.ts +23 -0
  191. package/dist/services/stall/read-log-tail.js +33 -2
  192. package/dist/services/stall/stall-detector.d.ts +25 -1
  193. package/dist/services/stall/stall-detector.js +85 -6
  194. package/dist/services/stall/stall-poller.d.ts +16 -0
  195. package/dist/services/stall/stall-poller.js +50 -6
  196. package/dist/services/stopped-marker.d.ts +16 -0
  197. package/dist/services/stopped-marker.js +55 -0
  198. package/dist/services/strategy.d.ts +33 -1
  199. package/dist/services/strategy.js +86 -17
  200. package/dist/services/supervisor-service-cleanup.d.ts +52 -0
  201. package/dist/services/supervisor-service-cleanup.js +332 -0
  202. package/dist/services/tool-registry.d.ts +8 -1
  203. package/dist/services/tool-registry.js +160 -59
  204. package/dist/services/tool-scope.d.ts +58 -0
  205. package/dist/services/tool-scope.js +99 -0
  206. package/dist/services/watch/project-resolver.js +1 -0
  207. package/dist/skills/auto-sprint-args/SKILL.md +2 -2
  208. package/dist/skills/fleet-sprint-cli/SKILL.md +39 -15
  209. package/dist/skills/pm/SKILL.md +3 -3
  210. package/dist/skills/pm/index.md +4 -2
  211. package/dist/skills/pm/kb-reconcile.md +29 -14
  212. package/dist/skills/pm/kb-review.md +1 -0
  213. package/dist/skills/pm/sprint.md +5 -5
  214. package/dist/tools/check-status.d.ts +53 -5
  215. package/dist/tools/check-status.js +210 -53
  216. package/dist/tools/child-id-allocator.d.ts +2 -2
  217. package/dist/tools/child-id-allocator.js +1 -1
  218. package/dist/tools/code-index-heal.d.ts +8 -0
  219. package/dist/tools/code-index-heal.js +21 -0
  220. package/dist/tools/code-index-state.d.ts +45 -0
  221. package/dist/tools/code-index-state.js +115 -0
  222. package/dist/tools/code-intelligence-codebase-memory.js +6 -33
  223. package/dist/tools/code-intelligence-freshness.js +1 -1
  224. package/dist/tools/code-intelligence-gitnexus.d.ts +30 -0
  225. package/dist/tools/code-intelligence-gitnexus.js +333 -57
  226. package/dist/tools/code-intelligence-kb-enrich.js +7 -6
  227. package/dist/tools/code-intelligence-readiness.d.ts +99 -0
  228. package/dist/tools/code-intelligence-readiness.js +206 -0
  229. package/dist/tools/code-intelligence-reindex.d.ts +195 -0
  230. package/dist/tools/code-intelligence-reindex.js +530 -50
  231. package/dist/tools/code-intelligence-telemetry.d.ts +6 -1
  232. package/dist/tools/code-intelligence-telemetry.js +12 -3
  233. package/dist/tools/code-intelligence.d.ts +81 -31
  234. package/dist/tools/code-intelligence.js +156 -52
  235. package/dist/tools/compose-permissions.d.ts +57 -2
  236. package/dist/tools/compose-permissions.js +497 -44
  237. package/dist/tools/execute-command.d.ts +11 -0
  238. package/dist/tools/execute-command.js +80 -12
  239. package/dist/tools/execute-prompt.d.ts +59 -15
  240. package/dist/tools/execute-prompt.js +544 -133
  241. package/dist/tools/kb-bible-commit.d.ts +65 -0
  242. package/dist/tools/kb-bible-commit.js +239 -0
  243. package/dist/tools/kb-capture.d.ts +13 -9
  244. package/dist/tools/kb-capture.js +42 -11
  245. package/dist/tools/kb-context.d.ts +27 -7
  246. package/dist/tools/kb-context.js +60 -9
  247. package/dist/tools/kb-export.d.ts +96 -7
  248. package/dist/tools/kb-export.js +228 -65
  249. package/dist/tools/kb-feedback.d.ts +13 -9
  250. package/dist/tools/kb-feedback.js +13 -7
  251. package/dist/tools/kb-freshness-sweep.d.ts +11 -7
  252. package/dist/tools/kb-freshness-sweep.js +7 -7
  253. package/dist/tools/kb-harvest.d.ts +11 -7
  254. package/dist/tools/kb-harvest.js +7 -7
  255. package/dist/tools/kb-import.d.ts +26 -10
  256. package/dist/tools/kb-import.js +169 -159
  257. package/dist/tools/kb-invalidate.d.ts +17 -10
  258. package/dist/tools/kb-invalidate.js +41 -8
  259. package/dist/tools/kb-list.d.ts +14 -10
  260. package/dist/tools/kb-list.js +30 -10
  261. package/dist/tools/kb-promote.d.ts +11 -7
  262. package/dist/tools/kb-promote.js +14 -8
  263. package/dist/tools/kb-query.d.ts +21 -11
  264. package/dist/tools/kb-query.js +76 -13
  265. package/dist/tools/kb-reconcile-prefilter.d.ts +11 -7
  266. package/dist/tools/kb-reconcile-prefilter.js +10 -8
  267. package/dist/tools/kb-resolve-contradiction.d.ts +11 -7
  268. package/dist/tools/kb-resolve-contradiction.js +7 -7
  269. package/dist/tools/kb-session-prime.d.ts +14 -7
  270. package/dist/tools/kb-session-prime.js +44 -44
  271. package/dist/tools/kb-setup.d.ts +11 -4
  272. package/dist/tools/kb-setup.js +25 -11
  273. package/dist/tools/kb-stats.d.ts +11 -10
  274. package/dist/tools/kb-stats.js +22 -41
  275. package/dist/tools/list-members.js +5 -2
  276. package/dist/tools/member-detail.d.ts +3 -0
  277. package/dist/tools/member-detail.js +88 -17
  278. package/dist/tools/member-reservation.d.ts +2 -2
  279. package/dist/tools/provision-auth.d.ts +39 -1
  280. package/dist/tools/provision-auth.js +269 -47
  281. package/dist/tools/provision-vcs-auth.d.ts +2 -2
  282. package/dist/tools/receive-files.js +3 -1
  283. package/dist/tools/register-member.d.ts +34 -8
  284. package/dist/tools/register-member.js +76 -58
  285. package/dist/tools/remove-member.js +110 -32
  286. package/dist/tools/send-email.d.ts +2 -2
  287. package/dist/tools/send-files.js +6 -4
  288. package/dist/tools/session-stats.d.ts +17 -0
  289. package/dist/tools/session-stats.js +27 -0
  290. package/dist/tools/shutdown-server.js +5 -0
  291. package/dist/tools/update-agent-cli.d.ts +19 -0
  292. package/dist/tools/update-agent-cli.js +59 -2
  293. package/dist/tools/update-member.d.ts +13 -10
  294. package/dist/tools/update-member.js +138 -7
  295. package/dist/tools/vcs-credential-exec.js +8 -2
  296. package/dist/types.d.ts +98 -1
  297. package/dist/utils/agent-helpers.js +2 -0
  298. package/dist/utils/auth-env.d.ts +15 -4
  299. package/dist/utils/auth-env.js +52 -23
  300. package/dist/utils/find-on-path.d.ts +37 -0
  301. package/dist/utils/find-on-path.js +85 -0
  302. package/dist/utils/log-helpers.d.ts +37 -0
  303. package/dist/utils/log-helpers.js +106 -20
  304. package/dist/utils/owner-only-fs.d.ts +56 -0
  305. package/dist/utils/owner-only-fs.js +98 -0
  306. package/dist/utils/process-utils.d.ts +28 -0
  307. package/dist/utils/process-utils.js +68 -0
  308. package/dist/utils/prompt-errors.js +4 -1
  309. package/dist/utils/session-caller.d.ts +4 -2
  310. package/dist/utils/session-caller.js +3 -2
  311. package/dist/utils/shell-escape.d.ts +42 -3
  312. package/dist/utils/shell-escape.js +70 -4
  313. package/dist/utils/ssh-error-messages.js +3 -0
  314. package/dist/utils/workspace-trust.d.ts +24 -1
  315. package/dist/utils/workspace-trust.js +21 -17
  316. package/dist/workflows/auto-sprint.js +223 -43
  317. package/package.json +11 -8
  318. package/packages/apra-fleet-client/package.json +2 -2
  319. package/packages/apra-fleet-client/src/client/api.mjs +558 -27
  320. package/packages/apra-fleet-client/src/client/auto-start.mjs +434 -0
  321. package/packages/apra-fleet-client/src/client/client.mjs +9 -0
  322. package/packages/apra-fleet-client/src/client/factory.mjs +23 -4
  323. package/packages/apra-fleet-client/src/client/reconnecting-transport.mjs +137 -0
  324. package/packages/apra-fleet-client/src/client/server-resolution.mjs +267 -30
  325. package/packages/apra-fleet-client/src/client/transport.mjs +37 -3
  326. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +75 -27
  327. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +37 -22
  328. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +39 -22
  329. package/packages/apra-fleet-se/apra-pm/agents/doer.md +74 -40
  330. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +49 -40
  331. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +40 -23
  332. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +28 -7
  333. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +49 -24
  334. package/packages/apra-fleet-se/apra-pm/agents/planner.md +66 -43
  335. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +101 -78
  336. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +117 -56
  337. package/packages/apra-fleet-se/apra-pm/agents/schemas/backlog-groomer-output.json +1 -1
  338. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +32 -0
  339. package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-input.json +1 -5
  340. package/packages/apra-fleet-se/apra-pm/agents/schemas/planner-output.json +1 -1
  341. package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-output.json +41 -7
  342. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +62 -3
  343. package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +3 -3
  344. package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +4 -2
  345. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-reconcile.md +29 -14
  346. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-review.md +1 -0
  347. package/packages/apra-fleet-se/apra-pm/skills/pm/sprint.md +5 -5
  348. package/packages/apra-fleet-se/bin/cli.mjs +184 -54
  349. package/packages/apra-fleet-se/bin/serve.mjs +143 -10
  350. package/packages/apra-fleet-se/fleet-sprint/abort.mjs +56 -20
  351. package/packages/apra-fleet-se/fleet-sprint/backlog-role.mjs +93 -0
  352. package/packages/apra-fleet-se/fleet-sprint/beads-children.mjs +208 -53
  353. package/packages/apra-fleet-se/fleet-sprint/beads-identity-check.mjs +576 -33
  354. package/packages/apra-fleet-se/fleet-sprint/beads-identity.mjs +9 -0
  355. package/packages/apra-fleet-se/fleet-sprint/beads-memory-hygiene.mjs +201 -0
  356. package/packages/apra-fleet-se/fleet-sprint/beads-scope.mjs +114 -7
  357. package/packages/apra-fleet-se/fleet-sprint/beads-transitions.mjs +154 -8
  358. package/packages/apra-fleet-se/fleet-sprint/ci-gate.mjs +353 -0
  359. package/packages/apra-fleet-se/fleet-sprint/conflict-ladder.mjs +12 -0
  360. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +60 -1
  361. package/packages/apra-fleet-se/fleet-sprint/coordination.mjs +25 -2
  362. package/packages/apra-fleet-se/fleet-sprint/dispatch-accounting.mjs +270 -0
  363. package/packages/apra-fleet-se/fleet-sprint/dispatch-failure.mjs +22 -2
  364. package/packages/apra-fleet-se/fleet-sprint/dispatch-role.mjs +205 -16
  365. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +52 -14
  366. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +6 -1
  367. package/packages/apra-fleet-se/fleet-sprint/docs/fleet-sprint-diagram.md +3 -3
  368. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +339 -20
  369. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +210 -11
  370. package/packages/apra-fleet-se/fleet-sprint/explicit-id-create-guard.mjs +4 -4
  371. package/packages/apra-fleet-se/fleet-sprint/git-sync.mjs +200 -9
  372. package/packages/apra-fleet-se/fleet-sprint/git-topology.mjs +57 -9
  373. package/packages/apra-fleet-se/fleet-sprint/guarded-modules.mjs +53 -4
  374. package/packages/apra-fleet-se/fleet-sprint/kb-hints.mjs +181 -0
  375. package/packages/apra-fleet-se/fleet-sprint/kb-injection.mjs +64 -0
  376. package/packages/apra-fleet-se/fleet-sprint/kb-maintainer.mjs +298 -0
  377. package/packages/apra-fleet-se/fleet-sprint/kb.mjs +1257 -301
  378. package/packages/apra-fleet-se/fleet-sprint/lower-quality.mjs +39 -0
  379. package/packages/apra-fleet-se/fleet-sprint/member-align.mjs +391 -0
  380. package/packages/apra-fleet-se/fleet-sprint/member-call.mjs +374 -0
  381. package/packages/apra-fleet-se/fleet-sprint/member-init-probe.mjs +644 -0
  382. package/packages/apra-fleet-se/fleet-sprint/member-provisioning.mjs +447 -0
  383. package/packages/apra-fleet-se/fleet-sprint/member-sync.mjs +250 -29
  384. package/packages/apra-fleet-se/fleet-sprint/orphan-reclaim.mjs +153 -0
  385. package/packages/apra-fleet-se/fleet-sprint/phases/deploy.mjs +82 -0
  386. package/packages/apra-fleet-se/fleet-sprint/phases/develop.mjs +97 -50
  387. package/packages/apra-fleet-se/fleet-sprint/phases/ensure-sprint-branch.mjs +1 -0
  388. package/packages/apra-fleet-se/fleet-sprint/phases/final-review.mjs +81 -18
  389. package/packages/apra-fleet-se/fleet-sprint/phases/harvest.mjs +43 -11
  390. package/packages/apra-fleet-se/fleet-sprint/phases/integ-test.mjs +6 -6
  391. package/packages/apra-fleet-se/fleet-sprint/phases/plan.mjs +20 -15
  392. package/packages/apra-fleet-se/fleet-sprint/phases/publish-pr.mjs +60 -38
  393. package/packages/apra-fleet-se/fleet-sprint/phases/re-review.mjs +42 -10
  394. package/packages/apra-fleet-se/fleet-sprint/phases/regression-test.mjs +16 -11
  395. package/packages/apra-fleet-se/fleet-sprint/phases/replan.mjs +36 -3
  396. package/packages/apra-fleet-se/fleet-sprint/phases/review.mjs +72 -12
  397. package/packages/apra-fleet-se/fleet-sprint/pr-body.mjs +259 -0
  398. package/packages/apra-fleet-se/fleet-sprint/prompts.mjs +83 -25
  399. package/packages/apra-fleet-se/fleet-sprint/role-policies.mjs +19 -1
  400. package/packages/apra-fleet-se/fleet-sprint/runner.js +834 -142
  401. package/packages/apra-fleet-se/fleet-sprint/se-os-commands.mjs +24 -0
  402. package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +130 -0
  403. package/packages/apra-fleet-se/fleet-sprint/se-windows.mjs +111 -0
  404. package/packages/apra-fleet-se/fleet-sprint/shell-command-guard.mjs +44 -1
  405. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +39 -15
  406. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +84 -30
  407. package/packages/apra-fleet-se/fleet-sprint/sprint-args.mjs +138 -2
  408. package/packages/apra-fleet-se/fleet-sprint/sprint-report.mjs +111 -11
  409. package/packages/apra-fleet-se/fleet-sprint/sprint-state.mjs +22 -0
  410. package/packages/apra-fleet-se/fleet-sprint/usage-limit-controller.mjs +7 -0
  411. package/packages/apra-fleet-se/fleet-sprint/vcs-auth.mjs +180 -14
  412. package/packages/apra-fleet-se/fleet-sprint/vcs-module.mjs +134 -7
  413. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/azure-devops.mjs +99 -0
  414. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +223 -0
  415. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +49 -0
  416. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/shell-helpers.mjs +8 -4
  417. package/packages/apra-fleet-se/fleet-sprint/verify-block.mjs +152 -0
  418. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +235 -21
  419. package/packages/apra-fleet-se/package.json +2 -2
  420. package/packages/apra-fleet-se/src/supervisor/api.mjs +919 -0
  421. package/packages/apra-fleet-se/src/supervisor/backlog-member.mjs +332 -0
  422. package/packages/apra-fleet-se/src/supervisor/backlog.mjs +982 -0
  423. package/packages/apra-fleet-se/src/supervisor/beads-identity.mjs +246 -0
  424. package/packages/apra-fleet-se/src/supervisor/beads-view.mjs +438 -0
  425. package/packages/apra-fleet-se/src/supervisor/child-port.mjs +36 -0
  426. package/packages/apra-fleet-se/src/supervisor/dashboard.mjs +1659 -0
  427. package/packages/apra-fleet-se/src/supervisor/dolt-mutex.mjs +350 -0
  428. package/packages/apra-fleet-se/src/supervisor/dolt-orphan-sweep.mjs +338 -0
  429. package/packages/apra-fleet-se/src/supervisor/fleet-members.mjs +279 -0
  430. package/packages/apra-fleet-se/src/supervisor/history-view.mjs +276 -0
  431. package/packages/apra-fleet-se/src/supervisor/history.mjs +328 -0
  432. package/packages/apra-fleet-se/src/supervisor/id-allocator.mjs +521 -0
  433. package/packages/apra-fleet-se/src/supervisor/launch-form.mjs +444 -0
  434. package/packages/apra-fleet-se/src/supervisor/ledger.mjs +629 -0
  435. package/packages/apra-fleet-se/src/supervisor/lib/exec-bd.mjs +303 -0
  436. package/packages/apra-fleet-se/src/supervisor/log-timestamp.mjs +51 -0
  437. package/packages/apra-fleet-se/src/supervisor/log-view.mjs +159 -0
  438. package/packages/apra-fleet-se/src/supervisor/proxy.mjs +474 -0
  439. package/packages/apra-fleet-se/src/supervisor/readopt.mjs +136 -0
  440. package/packages/apra-fleet-se/src/supervisor/reconcile.mjs +263 -0
  441. package/packages/apra-fleet-se/src/supervisor/rename-with-retry.mjs +87 -0
  442. package/packages/apra-fleet-se/src/supervisor/scope-overlap.mjs +327 -0
  443. package/packages/apra-fleet-se/src/supervisor/self-log.mjs +133 -0
  444. package/packages/apra-fleet-se/src/supervisor/server.mjs +399 -0
  445. package/packages/apra-fleet-se/src/supervisor/spawner.mjs +542 -0
  446. package/packages/apra-fleet-se/src/supervisor/sprint-identity.mjs +96 -0
  447. package/packages/apra-fleet-se/src/supervisor/watchdog.mjs +987 -0
  448. package/packages/apra-fleet-workflow/package.json +1 -1
  449. package/packages/apra-fleet-workflow/src/viewer/index.mjs +64 -9
  450. package/packages/apra-fleet-workflow/src/viewer/run-summary.mjs +127 -0
  451. package/packages/apra-fleet-workflow/src/workflow/index.mjs +71 -5
  452. package/packages/apra-fleet-workflow/src/workflow/pricing.mjs +75 -25
  453. package/skills/fleet/permissions.md +9 -0
  454. package/skills/fleet/profiles/tag-kb-reconciler.json +2 -6
  455. package/version.json +1 -1
  456. package/dist/cli/agent-transform.d.ts.map +0 -1
  457. package/dist/cli/agent-transform.js.map +0 -1
  458. package/dist/cli/auth.d.ts.map +0 -1
  459. package/dist/cli/auth.js.map +0 -1
  460. package/dist/cli/config.d.ts.map +0 -1
  461. package/dist/cli/config.js.map +0 -1
  462. package/dist/cli/dolt-install.d.ts.map +0 -1
  463. package/dist/cli/dolt-install.js.map +0 -1
  464. package/dist/cli/install-guard.d.ts.map +0 -1
  465. package/dist/cli/install-guard.js.map +0 -1
  466. package/dist/cli/install.d.ts.map +0 -1
  467. package/dist/cli/install.js.map +0 -1
  468. package/dist/cli/join.d.ts.map +0 -1
  469. package/dist/cli/join.js.map +0 -1
  470. package/dist/cli/kb-commit.d.ts.map +0 -1
  471. package/dist/cli/kb-commit.js.map +0 -1
  472. package/dist/cli/kb-directives.d.ts.map +0 -1
  473. package/dist/cli/kb-directives.js.map +0 -1
  474. package/dist/cli/kb-import.d.ts.map +0 -1
  475. package/dist/cli/kb-import.js.map +0 -1
  476. package/dist/cli/register-member.d.ts.map +0 -1
  477. package/dist/cli/register-member.js.map +0 -1
  478. package/dist/cli/restart.d.ts.map +0 -1
  479. package/dist/cli/restart.js.map +0 -1
  480. package/dist/cli/secret.d.ts.map +0 -1
  481. package/dist/cli/secret.js.map +0 -1
  482. package/dist/cli/spoke.d.ts.map +0 -1
  483. package/dist/cli/spoke.js.map +0 -1
  484. package/dist/cli/start.d.ts.map +0 -1
  485. package/dist/cli/start.js.map +0 -1
  486. package/dist/cli/status.d.ts.map +0 -1
  487. package/dist/cli/status.js.map +0 -1
  488. package/dist/cli/stop.d.ts.map +0 -1
  489. package/dist/cli/stop.js.map +0 -1
  490. package/dist/cli/uninstall.d.ts.map +0 -1
  491. package/dist/cli/uninstall.js.map +0 -1
  492. package/dist/cli/update.d.ts.map +0 -1
  493. package/dist/cli/update.js.map +0 -1
  494. package/dist/cli/watch.d.ts.map +0 -1
  495. package/dist/cli/watch.js.map +0 -1
  496. package/dist/cli/workflow-assets.d.ts.map +0 -1
  497. package/dist/cli/workflow-assets.js.map +0 -1
  498. package/dist/cli/workflow.d.ts.map +0 -1
  499. package/dist/cli/workflow.js.map +0 -1
  500. package/dist/commands/kb-server.d.ts.map +0 -1
  501. package/dist/commands/kb-server.js.map +0 -1
  502. package/dist/delivery-mode.d.ts.map +0 -1
  503. package/dist/delivery-mode.js.map +0 -1
  504. package/dist/hub-service/activity.d.ts.map +0 -1
  505. package/dist/hub-service/activity.js.map +0 -1
  506. package/dist/hub-service/audit-log.d.ts.map +0 -1
  507. package/dist/hub-service/audit-log.js.map +0 -1
  508. package/dist/hub-service/db/pool.d.ts.map +0 -1
  509. package/dist/hub-service/db/pool.js.map +0 -1
  510. package/dist/hub-service/enrollment.d.ts.map +0 -1
  511. package/dist/hub-service/enrollment.js.map +0 -1
  512. package/dist/hub-service/envelope-routes.d.ts.map +0 -1
  513. package/dist/hub-service/envelope-routes.js.map +0 -1
  514. package/dist/hub-service/handlers/installers.d.ts.map +0 -1
  515. package/dist/hub-service/handlers/installers.js.map +0 -1
  516. package/dist/hub-service/http-server.d.ts.map +0 -1
  517. package/dist/hub-service/http-server.js.map +0 -1
  518. package/dist/hub-service/hub-jwt.d.ts.map +0 -1
  519. package/dist/hub-service/hub-jwt.js.map +0 -1
  520. package/dist/hub-service/jwt-revocation.d.ts.map +0 -1
  521. package/dist/hub-service/jwt-revocation.js.map +0 -1
  522. package/dist/hub-service/machines.d.ts.map +0 -1
  523. package/dist/hub-service/machines.js.map +0 -1
  524. package/dist/hub-service/main.d.ts.map +0 -1
  525. package/dist/hub-service/main.js.map +0 -1
  526. package/dist/hub-service/member-tokens.d.ts.map +0 -1
  527. package/dist/hub-service/member-tokens.js.map +0 -1
  528. package/dist/hub-service/member-view.d.ts.map +0 -1
  529. package/dist/hub-service/member-view.js.map +0 -1
  530. package/dist/hub-service/members.d.ts.map +0 -1
  531. package/dist/hub-service/members.js.map +0 -1
  532. package/dist/hub-service/presence.d.ts.map +0 -1
  533. package/dist/hub-service/presence.js.map +0 -1
  534. package/dist/hub-service/project-view.d.ts.map +0 -1
  535. package/dist/hub-service/project-view.js.map +0 -1
  536. package/dist/hub-service/projects.d.ts.map +0 -1
  537. package/dist/hub-service/projects.js.map +0 -1
  538. package/dist/hub-service/relay-queue.d.ts.map +0 -1
  539. package/dist/hub-service/relay-queue.js.map +0 -1
  540. package/dist/hub-service/session-jwt.d.ts.map +0 -1
  541. package/dist/hub-service/session-jwt.js.map +0 -1
  542. package/dist/hub-service/usage.d.ts.map +0 -1
  543. package/dist/hub-service/usage.js.map +0 -1
  544. package/dist/hub-service/users.d.ts.map +0 -1
  545. package/dist/hub-service/users.js.map +0 -1
  546. package/dist/hub-service/workspaces.d.ts.map +0 -1
  547. package/dist/hub-service/workspaces.js.map +0 -1
  548. package/dist/index.d.ts.map +0 -1
  549. package/dist/index.js.map +0 -1
  550. package/dist/onboarding/text.d.ts.map +0 -1
  551. package/dist/onboarding/text.js.map +0 -1
  552. package/dist/os/git-bash-candidates.d.ts.map +0 -1
  553. package/dist/os/git-bash-candidates.js.map +0 -1
  554. package/dist/os/index.d.ts.map +0 -1
  555. package/dist/os/index.js.map +0 -1
  556. package/dist/os/linux.d.ts.map +0 -1
  557. package/dist/os/linux.js.map +0 -1
  558. package/dist/os/macos.d.ts.map +0 -1
  559. package/dist/os/macos.js.map +0 -1
  560. package/dist/os/os-commands.d.ts.map +0 -1
  561. package/dist/os/os-commands.js.map +0 -1
  562. package/dist/os/windows-gitbash.d.ts.map +0 -1
  563. package/dist/os/windows-gitbash.js.map +0 -1
  564. package/dist/os/windows-wrapper.d.ts.map +0 -1
  565. package/dist/os/windows-wrapper.js.map +0 -1
  566. package/dist/os/windows.d.ts.map +0 -1
  567. package/dist/os/windows.js.map +0 -1
  568. package/dist/paths.d.ts.map +0 -1
  569. package/dist/paths.js.map +0 -1
  570. package/dist/providers/agy.d.ts.map +0 -1
  571. package/dist/providers/agy.js.map +0 -1
  572. package/dist/providers/claude.d.ts.map +0 -1
  573. package/dist/providers/claude.js.map +0 -1
  574. package/dist/providers/codex.d.ts.map +0 -1
  575. package/dist/providers/codex.js.map +0 -1
  576. package/dist/providers/copilot.d.ts.map +0 -1
  577. package/dist/providers/copilot.js.map +0 -1
  578. package/dist/providers/email/headers.d.ts.map +0 -1
  579. package/dist/providers/email/headers.js.map +0 -1
  580. package/dist/providers/email/index.d.ts.map +0 -1
  581. package/dist/providers/email/index.js.map +0 -1
  582. package/dist/providers/email/provider.d.ts.map +0 -1
  583. package/dist/providers/email/provider.js.map +0 -1
  584. package/dist/providers/email/sendgrid.d.ts.map +0 -1
  585. package/dist/providers/email/sendgrid.js.map +0 -1
  586. package/dist/providers/email/smtp.d.ts.map +0 -1
  587. package/dist/providers/email/smtp.js.map +0 -1
  588. package/dist/providers/index.d.ts.map +0 -1
  589. package/dist/providers/index.js.map +0 -1
  590. package/dist/providers/none.d.ts.map +0 -1
  591. package/dist/providers/none.js.map +0 -1
  592. package/dist/providers/opencode.d.ts.map +0 -1
  593. package/dist/providers/opencode.js.map +0 -1
  594. package/dist/providers/provider.d.ts.map +0 -1
  595. package/dist/providers/provider.js.map +0 -1
  596. package/dist/services/agent-provisioner.d.ts.map +0 -1
  597. package/dist/services/agent-provisioner.js.map +0 -1
  598. package/dist/services/agy-project.d.ts.map +0 -1
  599. package/dist/services/agy-project.js.map +0 -1
  600. package/dist/services/auth-socket.d.ts.map +0 -1
  601. package/dist/services/auth-socket.js.map +0 -1
  602. package/dist/services/auth-web.d.ts.map +0 -1
  603. package/dist/services/auth-web.js.map +0 -1
  604. package/dist/services/budget-awareness.d.ts.map +0 -1
  605. package/dist/services/budget-awareness.js.map +0 -1
  606. package/dist/services/cloud/activity.d.ts.map +0 -1
  607. package/dist/services/cloud/activity.js.map +0 -1
  608. package/dist/services/cloud/aws.d.ts.map +0 -1
  609. package/dist/services/cloud/aws.js.map +0 -1
  610. package/dist/services/cloud/cost.d.ts.map +0 -1
  611. package/dist/services/cloud/cost.js.map +0 -1
  612. package/dist/services/cloud/idle-manager.d.ts.map +0 -1
  613. package/dist/services/cloud/idle-manager.js.map +0 -1
  614. package/dist/services/cloud/lifecycle.d.ts.map +0 -1
  615. package/dist/services/cloud/lifecycle.js.map +0 -1
  616. package/dist/services/cloud/task-wrapper.d.ts.map +0 -1
  617. package/dist/services/cloud/task-wrapper.js.map +0 -1
  618. package/dist/services/cloud/types.d.ts.map +0 -1
  619. package/dist/services/cloud/types.js.map +0 -1
  620. package/dist/services/cloud-sync.d.ts.map +0 -1
  621. package/dist/services/cloud-sync.js.map +0 -1
  622. package/dist/services/context-admission.d.ts.map +0 -1
  623. package/dist/services/context-admission.js.map +0 -1
  624. package/dist/services/credential-cleanup.d.ts.map +0 -1
  625. package/dist/services/credential-cleanup.js.map +0 -1
  626. package/dist/services/credential-store.d.ts.map +0 -1
  627. package/dist/services/credential-store.js.map +0 -1
  628. package/dist/services/event-bus.d.ts.map +0 -1
  629. package/dist/services/event-bus.js.map +0 -1
  630. package/dist/services/exit-drain.d.ts.map +0 -1
  631. package/dist/services/exit-drain.js.map +0 -1
  632. package/dist/services/file-chunker.d.ts.map +0 -1
  633. package/dist/services/file-chunker.js.map +0 -1
  634. package/dist/services/file-transfer-relay.d.ts.map +0 -1
  635. package/dist/services/file-transfer-relay.js.map +0 -1
  636. package/dist/services/file-transfer.d.ts.map +0 -1
  637. package/dist/services/file-transfer.js.map +0 -1
  638. package/dist/services/git-config.d.ts.map +0 -1
  639. package/dist/services/git-config.js.map +0 -1
  640. package/dist/services/github-app.d.ts.map +0 -1
  641. package/dist/services/github-app.js.map +0 -1
  642. package/dist/services/http-transport.d.ts.map +0 -1
  643. package/dist/services/http-transport.js.map +0 -1
  644. package/dist/services/hub-client.d.ts.map +0 -1
  645. package/dist/services/hub-client.js.map +0 -1
  646. package/dist/services/icons.d.ts.map +0 -1
  647. package/dist/services/icons.js.map +0 -1
  648. package/dist/services/jwt.d.ts.map +0 -1
  649. package/dist/services/jwt.js.map +0 -1
  650. package/dist/services/knowledge/audn.d.ts.map +0 -1
  651. package/dist/services/knowledge/audn.js.map +0 -1
  652. package/dist/services/knowledge/file-hash.d.ts.map +0 -1
  653. package/dist/services/knowledge/file-hash.js.map +0 -1
  654. package/dist/services/knowledge/http-provider.d.ts.map +0 -1
  655. package/dist/services/knowledge/http-provider.js.map +0 -1
  656. package/dist/services/knowledge/kb-config.d.ts.map +0 -1
  657. package/dist/services/knowledge/kb-config.js.map +0 -1
  658. package/dist/services/knowledge/kb-providers.d.ts.map +0 -1
  659. package/dist/services/knowledge/kb-providers.js.map +0 -1
  660. package/dist/services/knowledge/kb-scope-input.d.ts +0 -5
  661. package/dist/services/knowledge/kb-scope-input.d.ts.map +0 -1
  662. package/dist/services/knowledge/kb-scope-input.js +0 -11
  663. package/dist/services/knowledge/kb-scope-input.js.map +0 -1
  664. package/dist/services/knowledge/kb-service.d.ts.map +0 -1
  665. package/dist/services/knowledge/kb-service.js.map +0 -1
  666. package/dist/services/knowledge/path-validation.d.ts.map +0 -1
  667. package/dist/services/knowledge/path-validation.js.map +0 -1
  668. package/dist/services/knowledge/pre-init.d.ts.map +0 -1
  669. package/dist/services/knowledge/pre-init.js.map +0 -1
  670. package/dist/services/knowledge/project-slug.d.ts.map +0 -1
  671. package/dist/services/knowledge/project-slug.js.map +0 -1
  672. package/dist/services/knowledge/require-sqlite-project.d.ts.map +0 -1
  673. package/dist/services/knowledge/require-sqlite-project.js.map +0 -1
  674. package/dist/services/knowledge/sqlite-provider.d.ts.map +0 -1
  675. package/dist/services/knowledge/sqlite-provider.js.map +0 -1
  676. package/dist/services/knowledge/types.d.ts.map +0 -1
  677. package/dist/services/knowledge/types.js.map +0 -1
  678. package/dist/services/known-hosts.d.ts.map +0 -1
  679. package/dist/services/known-hosts.js.map +0 -1
  680. package/dist/services/known-sessions.d.ts.map +0 -1
  681. package/dist/services/known-sessions.js.map +0 -1
  682. package/dist/services/member-home.d.ts.map +0 -1
  683. package/dist/services/member-home.js.map +0 -1
  684. package/dist/services/member-remote-url.d.ts.map +0 -1
  685. package/dist/services/member-remote-url.js.map +0 -1
  686. package/dist/services/model-pricing.d.ts.map +0 -1
  687. package/dist/services/model-pricing.js.map +0 -1
  688. package/dist/services/onboarding.d.ts.map +0 -1
  689. package/dist/services/onboarding.js.map +0 -1
  690. package/dist/services/orphan-recovery.d.ts.map +0 -1
  691. package/dist/services/orphan-recovery.js.map +0 -1
  692. package/dist/services/pending-responses.d.ts.map +0 -1
  693. package/dist/services/pending-responses.js.map +0 -1
  694. package/dist/services/preflight-check.d.ts.map +0 -1
  695. package/dist/services/preflight-check.js.map +0 -1
  696. package/dist/services/registry.d.ts.map +0 -1
  697. package/dist/services/registry.js.map +0 -1
  698. package/dist/services/relay-context.d.ts.map +0 -1
  699. package/dist/services/relay-context.js.map +0 -1
  700. package/dist/services/relay-executor.d.ts.map +0 -1
  701. package/dist/services/relay-executor.js.map +0 -1
  702. package/dist/services/relay-request.d.ts.map +0 -1
  703. package/dist/services/relay-request.js.map +0 -1
  704. package/dist/services/relay-strategy.d.ts.map +0 -1
  705. package/dist/services/relay-strategy.js.map +0 -1
  706. package/dist/services/secret-token.d.ts.map +0 -1
  707. package/dist/services/secret-token.js.map +0 -1
  708. package/dist/services/service-manager/index.d.ts.map +0 -1
  709. package/dist/services/service-manager/index.js.map +0 -1
  710. package/dist/services/service-manager/linux.d.ts.map +0 -1
  711. package/dist/services/service-manager/linux.js.map +0 -1
  712. package/dist/services/service-manager/macos.d.ts.map +0 -1
  713. package/dist/services/service-manager/macos.js.map +0 -1
  714. package/dist/services/service-manager/types.d.ts.map +0 -1
  715. package/dist/services/service-manager/types.js.map +0 -1
  716. package/dist/services/service-manager/windows.d.ts.map +0 -1
  717. package/dist/services/service-manager/windows.js.map +0 -1
  718. package/dist/services/session-registry.d.ts.map +0 -1
  719. package/dist/services/session-registry.js.map +0 -1
  720. package/dist/services/sftp.d.ts.map +0 -1
  721. package/dist/services/sftp.js.map +0 -1
  722. package/dist/services/shell-probe.d.ts.map +0 -1
  723. package/dist/services/shell-probe.js.map +0 -1
  724. package/dist/services/singleton.d.ts.map +0 -1
  725. package/dist/services/singleton.js.map +0 -1
  726. package/dist/services/sprint-coordination.d.ts.map +0 -1
  727. package/dist/services/sprint-coordination.js.map +0 -1
  728. package/dist/services/ssh.d.ts.map +0 -1
  729. package/dist/services/ssh.js.map +0 -1
  730. package/dist/services/stall/find-log-file.d.ts.map +0 -1
  731. package/dist/services/stall/find-log-file.js.map +0 -1
  732. package/dist/services/stall/index.d.ts.map +0 -1
  733. package/dist/services/stall/index.js.map +0 -1
  734. package/dist/services/stall/log-path-resolver.d.ts.map +0 -1
  735. package/dist/services/stall/log-path-resolver.js.map +0 -1
  736. package/dist/services/stall/read-log-tail.d.ts.map +0 -1
  737. package/dist/services/stall/read-log-tail.js.map +0 -1
  738. package/dist/services/stall/stall-detector.d.ts.map +0 -1
  739. package/dist/services/stall/stall-detector.js.map +0 -1
  740. package/dist/services/stall/stall-poller.d.ts.map +0 -1
  741. package/dist/services/stall/stall-poller.js.map +0 -1
  742. package/dist/services/stall/time-utils.d.ts.map +0 -1
  743. package/dist/services/stall/time-utils.js.map +0 -1
  744. package/dist/services/statusline.d.ts.map +0 -1
  745. package/dist/services/statusline.js.map +0 -1
  746. package/dist/services/strategy.d.ts.map +0 -1
  747. package/dist/services/strategy.js.map +0 -1
  748. package/dist/services/substitution-engine.d.ts.map +0 -1
  749. package/dist/services/substitution-engine.js.map +0 -1
  750. package/dist/services/task-cleanup.d.ts.map +0 -1
  751. package/dist/services/task-cleanup.js.map +0 -1
  752. package/dist/services/token-issuer.d.ts.map +0 -1
  753. package/dist/services/token-issuer.js.map +0 -1
  754. package/dist/services/tool-registry.d.ts.map +0 -1
  755. package/dist/services/tool-registry.js.map +0 -1
  756. package/dist/services/update-check.d.ts.map +0 -1
  757. package/dist/services/update-check.js.map +0 -1
  758. package/dist/services/user-config.d.ts.map +0 -1
  759. package/dist/services/user-config.js.map +0 -1
  760. package/dist/services/vcs/azure-devops.d.ts.map +0 -1
  761. package/dist/services/vcs/azure-devops.js.map +0 -1
  762. package/dist/services/vcs/bitbucket.d.ts.map +0 -1
  763. package/dist/services/vcs/bitbucket.js.map +0 -1
  764. package/dist/services/vcs/constants.d.ts.map +0 -1
  765. package/dist/services/vcs/constants.js.map +0 -1
  766. package/dist/services/vcs/github.d.ts.map +0 -1
  767. package/dist/services/vcs/github.js.map +0 -1
  768. package/dist/services/vcs/types.d.ts.map +0 -1
  769. package/dist/services/vcs/types.js.map +0 -1
  770. package/dist/services/version-check.d.ts.map +0 -1
  771. package/dist/services/version-check.js.map +0 -1
  772. package/dist/services/watch/fleet-log.d.ts.map +0 -1
  773. package/dist/services/watch/fleet-log.js.map +0 -1
  774. package/dist/services/watch/project-resolver.d.ts.map +0 -1
  775. package/dist/services/watch/project-resolver.js.map +0 -1
  776. package/dist/services/watch/transcript-formatter.d.ts.map +0 -1
  777. package/dist/services/watch/transcript-formatter.js.map +0 -1
  778. package/dist/smoke-test.d.ts.map +0 -1
  779. package/dist/smoke-test.js.map +0 -1
  780. package/dist/tools/check-status.d.ts.map +0 -1
  781. package/dist/tools/check-status.js.map +0 -1
  782. package/dist/tools/child-id-allocator.d.ts.map +0 -1
  783. package/dist/tools/child-id-allocator.js.map +0 -1
  784. package/dist/tools/cloud-control.d.ts.map +0 -1
  785. package/dist/tools/cloud-control.js.map +0 -1
  786. package/dist/tools/code-intelligence-codebase-memory.d.ts.map +0 -1
  787. package/dist/tools/code-intelligence-codebase-memory.js.map +0 -1
  788. package/dist/tools/code-intelligence-freshness.d.ts.map +0 -1
  789. package/dist/tools/code-intelligence-freshness.js.map +0 -1
  790. package/dist/tools/code-intelligence-gitnexus.d.ts.map +0 -1
  791. package/dist/tools/code-intelligence-gitnexus.js.map +0 -1
  792. package/dist/tools/code-intelligence-kb-enrich.d.ts.map +0 -1
  793. package/dist/tools/code-intelligence-kb-enrich.js.map +0 -1
  794. package/dist/tools/code-intelligence-reindex.d.ts.map +0 -1
  795. package/dist/tools/code-intelligence-reindex.js.map +0 -1
  796. package/dist/tools/code-intelligence-telemetry.d.ts.map +0 -1
  797. package/dist/tools/code-intelligence-telemetry.js.map +0 -1
  798. package/dist/tools/code-intelligence-tests.d.ts.map +0 -1
  799. package/dist/tools/code-intelligence-tests.js.map +0 -1
  800. package/dist/tools/code-intelligence.d.ts.map +0 -1
  801. package/dist/tools/code-intelligence.js.map +0 -1
  802. package/dist/tools/compose-permissions.d.ts.map +0 -1
  803. package/dist/tools/compose-permissions.js.map +0 -1
  804. package/dist/tools/credential-store-delete.d.ts.map +0 -1
  805. package/dist/tools/credential-store-delete.js.map +0 -1
  806. package/dist/tools/credential-store-list.d.ts.map +0 -1
  807. package/dist/tools/credential-store-list.js.map +0 -1
  808. package/dist/tools/credential-store-set.d.ts.map +0 -1
  809. package/dist/tools/credential-store-set.js.map +0 -1
  810. package/dist/tools/credential-store-update.d.ts.map +0 -1
  811. package/dist/tools/credential-store-update.js.map +0 -1
  812. package/dist/tools/dolt-push-mutex.d.ts.map +0 -1
  813. package/dist/tools/dolt-push-mutex.js.map +0 -1
  814. package/dist/tools/execute-command.d.ts.map +0 -1
  815. package/dist/tools/execute-command.js.map +0 -1
  816. package/dist/tools/execute-prompt.d.ts.map +0 -1
  817. package/dist/tools/execute-prompt.js.map +0 -1
  818. package/dist/tools/get-member-model-pricing.d.ts.map +0 -1
  819. package/dist/tools/get-member-model-pricing.js.map +0 -1
  820. package/dist/tools/kb-capture.d.ts.map +0 -1
  821. package/dist/tools/kb-capture.js.map +0 -1
  822. package/dist/tools/kb-context.d.ts.map +0 -1
  823. package/dist/tools/kb-context.js.map +0 -1
  824. package/dist/tools/kb-export.d.ts.map +0 -1
  825. package/dist/tools/kb-export.js.map +0 -1
  826. package/dist/tools/kb-feedback.d.ts.map +0 -1
  827. package/dist/tools/kb-feedback.js.map +0 -1
  828. package/dist/tools/kb-freshness-sweep.d.ts.map +0 -1
  829. package/dist/tools/kb-freshness-sweep.js.map +0 -1
  830. package/dist/tools/kb-harvest.d.ts.map +0 -1
  831. package/dist/tools/kb-harvest.js.map +0 -1
  832. package/dist/tools/kb-import.d.ts.map +0 -1
  833. package/dist/tools/kb-import.js.map +0 -1
  834. package/dist/tools/kb-invalidate.d.ts.map +0 -1
  835. package/dist/tools/kb-invalidate.js.map +0 -1
  836. package/dist/tools/kb-list.d.ts.map +0 -1
  837. package/dist/tools/kb-list.js.map +0 -1
  838. package/dist/tools/kb-promote.d.ts.map +0 -1
  839. package/dist/tools/kb-promote.js.map +0 -1
  840. package/dist/tools/kb-query.d.ts.map +0 -1
  841. package/dist/tools/kb-query.js.map +0 -1
  842. package/dist/tools/kb-reconcile-prefilter.d.ts.map +0 -1
  843. package/dist/tools/kb-reconcile-prefilter.js.map +0 -1
  844. package/dist/tools/kb-resolve-contradiction.d.ts.map +0 -1
  845. package/dist/tools/kb-resolve-contradiction.js.map +0 -1
  846. package/dist/tools/kb-session-prime.d.ts.map +0 -1
  847. package/dist/tools/kb-session-prime.js.map +0 -1
  848. package/dist/tools/kb-setup.d.ts.map +0 -1
  849. package/dist/tools/kb-setup.js.map +0 -1
  850. package/dist/tools/kb-stats.d.ts.map +0 -1
  851. package/dist/tools/kb-stats.js.map +0 -1
  852. package/dist/tools/list-members.d.ts.map +0 -1
  853. package/dist/tools/list-members.js.map +0 -1
  854. package/dist/tools/member-detail.d.ts.map +0 -1
  855. package/dist/tools/member-detail.js.map +0 -1
  856. package/dist/tools/member-reservation.d.ts.map +0 -1
  857. package/dist/tools/member-reservation.js.map +0 -1
  858. package/dist/tools/monitor-task.d.ts.map +0 -1
  859. package/dist/tools/monitor-task.js.map +0 -1
  860. package/dist/tools/provision-auth.d.ts.map +0 -1
  861. package/dist/tools/provision-auth.js.map +0 -1
  862. package/dist/tools/provision-vcs-auth.d.ts.map +0 -1
  863. package/dist/tools/provision-vcs-auth.js.map +0 -1
  864. package/dist/tools/receive-files.d.ts.map +0 -1
  865. package/dist/tools/receive-files.js.map +0 -1
  866. package/dist/tools/register-member.d.ts.map +0 -1
  867. package/dist/tools/register-member.js.map +0 -1
  868. package/dist/tools/remove-member.d.ts.map +0 -1
  869. package/dist/tools/remove-member.js.map +0 -1
  870. package/dist/tools/report-status.d.ts.map +0 -1
  871. package/dist/tools/report-status.js.map +0 -1
  872. package/dist/tools/respond-to-message.d.ts.map +0 -1
  873. package/dist/tools/respond-to-message.js.map +0 -1
  874. package/dist/tools/revoke-vcs-auth.d.ts.map +0 -1
  875. package/dist/tools/revoke-vcs-auth.js.map +0 -1
  876. package/dist/tools/send-email.d.ts.map +0 -1
  877. package/dist/tools/send-email.js.map +0 -1
  878. package/dist/tools/send-files.d.ts.map +0 -1
  879. package/dist/tools/send-files.js.map +0 -1
  880. package/dist/tools/send-message.d.ts.map +0 -1
  881. package/dist/tools/send-message.js.map +0 -1
  882. package/dist/tools/setup-git-app.d.ts.map +0 -1
  883. package/dist/tools/setup-git-app.js.map +0 -1
  884. package/dist/tools/setup-ssh-key.d.ts.map +0 -1
  885. package/dist/tools/setup-ssh-key.js.map +0 -1
  886. package/dist/tools/shutdown-server.d.ts.map +0 -1
  887. package/dist/tools/shutdown-server.js.map +0 -1
  888. package/dist/tools/stop-prompt.d.ts.map +0 -1
  889. package/dist/tools/stop-prompt.js.map +0 -1
  890. package/dist/tools/update-agent-cli.d.ts.map +0 -1
  891. package/dist/tools/update-agent-cli.js.map +0 -1
  892. package/dist/tools/update-member.d.ts.map +0 -1
  893. package/dist/tools/update-member.js.map +0 -1
  894. package/dist/tools/vcs-credential-exec.d.ts.map +0 -1
  895. package/dist/tools/vcs-credential-exec.js.map +0 -1
  896. package/dist/tools/version.d.ts.map +0 -1
  897. package/dist/tools/version.js.map +0 -1
  898. package/dist/types.d.ts.map +0 -1
  899. package/dist/types.js.map +0 -1
  900. package/dist/utils/agent-helpers.d.ts.map +0 -1
  901. package/dist/utils/agent-helpers.js.map +0 -1
  902. package/dist/utils/ansi.d.ts.map +0 -1
  903. package/dist/utils/ansi.js.map +0 -1
  904. package/dist/utils/auth-env.d.ts.map +0 -1
  905. package/dist/utils/auth-env.js.map +0 -1
  906. package/dist/utils/collect-secret.d.ts.map +0 -1
  907. package/dist/utils/collect-secret.js.map +0 -1
  908. package/dist/utils/credential-validation.d.ts.map +0 -1
  909. package/dist/utils/credential-validation.js.map +0 -1
  910. package/dist/utils/crypto.d.ts.map +0 -1
  911. package/dist/utils/crypto.js.map +0 -1
  912. package/dist/utils/deep-merge.d.ts.map +0 -1
  913. package/dist/utils/deep-merge.js.map +0 -1
  914. package/dist/utils/file-permissions.d.ts.map +0 -1
  915. package/dist/utils/file-permissions.js.map +0 -1
  916. package/dist/utils/gpu-parser.d.ts.map +0 -1
  917. package/dist/utils/gpu-parser.js.map +0 -1
  918. package/dist/utils/log-helpers.d.ts.map +0 -1
  919. package/dist/utils/log-helpers.js.map +0 -1
  920. package/dist/utils/oob-timeout.d.ts.map +0 -1
  921. package/dist/utils/oob-timeout.js.map +0 -1
  922. package/dist/utils/opencode-model-validation.d.ts.map +0 -1
  923. package/dist/utils/opencode-model-validation.js.map +0 -1
  924. package/dist/utils/pid-helpers.d.ts.map +0 -1
  925. package/dist/utils/pid-helpers.js.map +0 -1
  926. package/dist/utils/platform.d.ts.map +0 -1
  927. package/dist/utils/platform.js.map +0 -1
  928. package/dist/utils/process-utils.d.ts.map +0 -1
  929. package/dist/utils/process-utils.js.map +0 -1
  930. package/dist/utils/prompt-errors.d.ts.map +0 -1
  931. package/dist/utils/prompt-errors.js.map +0 -1
  932. package/dist/utils/resolve-member.d.ts.map +0 -1
  933. package/dist/utils/resolve-member.js.map +0 -1
  934. package/dist/utils/secure-input.d.ts.map +0 -1
  935. package/dist/utils/secure-input.js.map +0 -1
  936. package/dist/utils/session-caller.d.ts.map +0 -1
  937. package/dist/utils/session-caller.js.map +0 -1
  938. package/dist/utils/shell-escape.d.ts.map +0 -1
  939. package/dist/utils/shell-escape.js.map +0 -1
  940. package/dist/utils/skill-matrix.d.ts.map +0 -1
  941. package/dist/utils/skill-matrix.js.map +0 -1
  942. package/dist/utils/ssh-error-messages.d.ts.map +0 -1
  943. package/dist/utils/ssh-error-messages.js.map +0 -1
  944. package/dist/utils/vcs-provider-detect.d.ts.map +0 -1
  945. package/dist/utils/vcs-provider-detect.js.map +0 -1
  946. package/dist/utils/work-folder-validation.d.ts.map +0 -1
  947. package/dist/utils/work-folder-validation.js.map +0 -1
  948. package/dist/utils/workspace-trust.d.ts.map +0 -1
  949. package/dist/utils/workspace-trust.js.map +0 -1
  950. package/dist/version.d.ts.map +0 -1
  951. package/dist/version.js.map +0 -1
@@ -1,7 +1,6 @@
1
- // KB (Knowledge Bank) work for fleet-sprint: the URL-based repo scope
2
- // selector, the per-dispatch relevance-ranked read (kb_query), the vetting
1
+ // KB (Knowledge Bank) work for fleet-sprint: the per-dispatch relevance-ranked read (kb_query), the vetting
3
2
  // and forwarding of a role's kb_captures/kb_promotions payload (kb_capture/
4
- // kb_promote), the canonical-bible publish (kb_export), the once-per-sprint
3
+ // kb_promote), the per-round bible commit (kb_bible_commit), the once-per-sprint
5
4
  // priming client (kb_session_prime/kb_import) and the prompt-construction
6
5
  // helpers that hand a role's primed knowledge and promotion candidates to
7
6
  // its dispatch prompt -- extracted move-only out of runner.js
@@ -12,15 +11,23 @@
12
11
  // fleet-sprint/runner.js resolve unchanged.
13
12
  //
14
13
  // Every kb_* call here is BEST-EFFORT and NON-FATAL: a KB outage (cold KB,
15
- // unreachable server, a rejected or throwing callTool) must only be logged,
16
- // never fail a dispatch. Every call also spreads repo_path AND the scopeOf()
17
- // URL-scope fields -- omitting either was a real defect (apra-fleet-23c
18
- // zod-validation failures without repo_path/content, apra-fleet-tm7's
19
- // repo-blindness without the URL scope) and both must keep flowing on every
20
- // site this module owns.
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.
21
26
 
22
27
  import { ROLES, wrapUntrustedBlock } from './contracts.mjs';
23
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';
24
31
 
25
32
  // Local, validated role constant -- mirrors runner.js's own roleConst()
26
33
  // pattern (kb.mjs does not import runner.js's private helper, to avoid a
@@ -49,23 +56,25 @@ const ROLE_DOER = kbRoleConst('doer');
49
56
  export const KB_MAX_KNOWLEDGE_ENTRIES = 12;
50
57
 
51
58
  /**
52
- * The URL-based KB scope selector, spread into a kb_* call's arguments.
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.
53
64
  *
54
- * repo_path alone is only sufficient for a LOCAL member: resolveProjectSlug
55
- * (src/services/knowledge/project-slug.ts) runs git in that directory to derive
56
- * the project slug. A remote member's work folder is a path on another host, so
57
- * both git probes fail and the slug degrades to 'default' -- collapsing every
58
- * remote member's knowledge into one shared KB. repo_remote_url selects the DB
59
- * directly (apra-fleet-b4g.1) and is what makes a sprint's kb_* calls land in
60
- * the member's own project KB.
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.
61
69
  *
62
- * Absent when no URL is known: an omitted scope is the honest pre-existing
63
- * degradation, while a fabricated one routes writes into a slug that does not
64
- * match the repo's real local-clone slug. The engine never derives a URL -- it
65
- * forwards only what member_detail reports (knownRepoRemoteUrl's rule).
70
+ * @param {object} e
71
+ * @returns {boolean}
66
72
  */
67
- export function kbScope(remoteUrl) {
68
- return (typeof remoteUrl === 'string' && remoteUrl.length > 0) ? { repo_remote_url: remoteUrl } : {};
73
+ export function isInjectableKbEntry(e) {
74
+ return Boolean(e)
75
+ && e.confidence === 'CONFIRMED'
76
+ && !e.flagged_for_review
77
+ && !e.contradiction_of;
69
78
  }
70
79
 
71
80
  /**
@@ -79,8 +88,8 @@ export function kbScope(remoteUrl) {
79
88
  *
80
89
  * Unlike apra-pm's auto-sprint.js -- a Claude Workflow script with no tool
81
90
  * access, which must hand its vetted payload to an executor subagent -- this
82
- * engine runs in-process with an injected callTool, so it makes the kb_capture
83
- * and kb_promote calls DIRECTLY. Judgment still belongs to the role; execution
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
84
93
  * belongs here.
85
94
  *
86
95
  * Validation mirrors lib/vet-kb-work.mjs in apra-pm and the provider invariants
@@ -89,8 +98,8 @@ export function kbScope(remoteUrl) {
89
98
  * recorded evidence string, and kb_promotions is refused from any role other
90
99
  * than reviewer -- widening capture to four roles must not widen promotion.
91
100
  *
92
- * @param {{ callTool?: (name: string, args: object) => Promise<any>, log?: Function }} opts
93
- * @returns {{ apply: (role: string, repoPath: string, result: any) => Promise<{captured: number, promoted: number, refused: number}> }}
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}> }}
94
103
  */
95
104
  export const KB_PROMOTER_ROLES = Object.freeze(new Set([ROLE_REVIEWER]));
96
105
  export const KB_MIN_PROMOTE_REASON = 20;
@@ -99,7 +108,8 @@ export const KB_CAPTURE_TYPES = Object.freeze(['knowledge', 'learning', 'runbook
99
108
  /**
100
109
  * True when an MCP tool result represents a tool-level failure. The MCP client
101
110
  * resolves such results instead of throwing (apra-fleet-23c), so callers that
102
- * only catch exceptions silently treat failures as successes.
111
+ * only catch exceptions silently treat failures as successes. (memberCall
112
+ * throws a typed MemberCallError instead; both shapes are handled.)
103
113
  */
104
114
  function isToolError(res) {
105
115
  return !!(res && typeof res === 'object' && res.isError === true);
@@ -158,29 +168,208 @@ export function vetKbWork(role, result) {
158
168
  }
159
169
  }
160
170
 
161
- return { captures, promotions, refused };
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
+ };
162
210
  }
163
211
 
164
212
  /** Max promotion candidates offered to one reviewer, so the prompt stays bounded. */
165
213
  export const KB_MAX_PROMOTION_CANDIDATES = 40;
166
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
+
167
328
  export function createKbWorkClient(opts = {}) {
168
- const { callTool, log = () => {}, remoteUrlFor } = opts;
169
- const active = typeof callTool === 'function';
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
+ }
170
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;
171
360
  /**
172
- * The URL-based KB scope for a repo path, resolved through the injected
173
- * lookup (createKbPrimingClient's remoteUrlForPath). Deliberately NOT an
174
- * extra parameter on the methods below: they are called from nine places
175
- * across runSprintCycle/finalReview/harvest, and an omitted argument is
176
- * indistinguishable from "no URL known" -- it would silently reinstate the
177
- * repo-blindness this exists to fix. With no lookup injected (every
178
- * construction site predating this, and direct unit calls) the scope is
179
- * absent and behaviour is exactly as before.
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.
180
367
  */
181
- function scopeOf(repoPath) {
182
- return kbScope(typeof remoteUrlFor === 'function' ? remoteUrlFor(repoPath) : null);
183
- }
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;
184
373
 
185
374
  /** Best-effort JSON out of an MCP result (string, content-block, or plain object). */
186
375
  function parseResult(result) {
@@ -191,7 +380,662 @@ export function createKbWorkClient(opts = {}) {
191
380
  return (result && typeof result === 'object') ? result : null;
192
381
  }
193
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
+
194
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
+ },
195
1039
  /**
196
1040
  * apra-fleet-0ef: the INFERRED entries this reviewer may promote.
197
1041
  *
@@ -208,27 +1052,52 @@ export function createKbWorkClient(opts = {}) {
208
1052
  * Best-effort by design -- a cold or unreachable KB must degrade to
209
1053
  * "nothing to promote", never fail the review dispatch.
210
1054
  */
211
- async promotionCandidates(repoPath) {
212
- // Without a repo path kb_list would resolve against the fleet
213
- // server's cwd and offer entries from an unrelated project's KB
214
- // (the apra-fleet-tm7 repo-blindness class). Refuse rather than guess.
215
- if (!active || !repoPath) return [];
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);
216
1069
  try {
217
- const parsed = parseResult(await callTool('kb_list', {
218
- repo_path: repoPath,
219
- ...scopeOf(repoPath),
220
- confidence: 'INFERRED',
1070
+ const res = await memberCall(target.record, 'kb_query', {
1071
+ tag: `member:${target.record.id}`,
1072
+ confidence: ['INFERRED'],
221
1073
  limit: KB_MAX_PROMOTION_CANDIDATES,
222
- }));
223
- const results = parsed && Array.isArray(parsed.results) ? parsed.results : [];
224
- return results
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
225
1092
  // promote() refuses type='user-directive' outright (activation
226
1093
  // is human-terminal, CLI-only), so offering one as a candidate
227
1094
  // can only produce a guaranteed refusal.
228
- .filter((e) => e && typeof e.id === 'string' && e.type !== 'user-directive')
1095
+ .filter((e) => e && typeof e.id === 'string' && e.type !== 'user-directive' && inWindow(e))
229
1096
  .slice(0, KB_MAX_PROMOTION_CANDIDATES);
1097
+ offeredCandidates.set(target.repo, new Set(offered.map((e) => e.id)));
1098
+ return offered;
230
1099
  } catch (err) {
231
- log(`[kb-work] could not list promotion candidates for ${repoPath} (non-fatal): ${err.message}`);
1100
+ log(`[kb-work] could not read promotion candidates from maintainer '${target.member}' (non-fatal): ${err.message}`);
232
1101
  return [];
233
1102
  }
234
1103
  },
@@ -245,160 +1114,146 @@ export function createKbWorkClient(opts = {}) {
245
1114
  * been writing `refines` and `contradiction_of` edges since AUDN
246
1115
  * shipped and traversing none of them: 554 edges, 0 reads. A role about
247
1116
  * to act on an entry is precisely who needs to know that entry has a
248
- * newer framing or a standing dispute -- especially since confidence
249
- * tier does NOT track correctness across a contradiction chain (the
250
- * warehouse chain-A shape, where the incorrect entry outranks both of
251
- * its corrections).
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.
252
1126
  *
253
- * Best-effort, like every other KB read here: no repo path, no terms, a
1127
+ * Best-effort, like every other KB read here: no member, no terms, a
254
1128
  * cold KB or an unreachable one all degrade to "no knowledge", never to
255
1129
  * a failed dispatch.
256
1130
  */
257
- async relevantKnowledge(repoPath, terms) {
258
- if (!active || !repoPath || !Array.isArray(terms) || terms.length === 0) return [];
259
- const query = terms.filter((t) => typeof t === 'string' && t.trim()).join(' ');
260
- if (!query) return [];
261
- try {
262
- const res = await callTool('kb_query', {
263
- repo_path: repoPath,
264
- ...scopeOf(repoPath),
265
- query,
266
- limit: KB_MAX_KNOWLEDGE_ENTRIES,
267
- expand_related: true,
268
- });
269
- // apra-fleet-23c: an MCP callTool RESOLVES with {isError:true}
270
- // for a tool-level failure rather than throwing, so this was
271
- // the one kb_* failure path in this module that stayed
272
- // silent -- parseResult() returns null for that envelope,
273
- // taking the `if (!parsed) return [];` branch below and never
274
- // reaching the catch. Detect it explicitly so a cold or
275
- // misconfigured KB degrades visibly, like every other kb_*
276
- // call here.
277
- if (isToolError(res)) {
278
- log(`[kb-work] kb_query rejected for ${repoPath} (non-fatal): ${toolErrorText(res)}`);
279
- return [];
280
- }
281
- const parsed = parseResult(res);
282
- if (!parsed) return [];
283
- const hits = Array.isArray(parsed.l1_results) ? parsed.l1_results : [];
284
- const related = Array.isArray(parsed.related_claims) ? parsed.related_claims : [];
285
- const seen = new Set();
286
- const out = [];
287
- for (const e of hits) {
288
- if (!e || typeof e.id !== 'string' || seen.has(e.id)) continue;
289
- seen.add(e.id);
290
- out.push(e);
291
- }
292
- // Related claims sit BELOW every direct hit and carry a marker,
293
- // so a role can tell "the KB matched this" from "the KB says
294
- // something about what it matched".
295
- for (const e of related) {
296
- if (!e || typeof e.id !== 'string' || seen.has(e.id)) continue;
297
- seen.add(e.id);
298
- out.push({ ...e, via: 'kb-graph' });
299
- }
300
- return out.slice(0, KB_MAX_KNOWLEDGE_ENTRIES);
301
- } catch (err) {
302
- log(`[kb-work] kb_query failed for ${repoPath} (non-fatal): ${err.message}`);
303
- return [];
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' };
304
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;
305
1177
  },
306
- async apply(role, repoPath, result) {
307
- const { captures, promotions, refused } = vetKbWork(role, result);
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);
308
1192
 
309
1193
  for (const r of refused) log(`[kb-work] refused -- ${r}`);
310
1194
  // Log every promotion with its stated evidence BEFORE attempting it.
311
1195
  // This log is the audit trail the bible never had.
312
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}`);
313
1198
 
314
- // Without a repo path a capture would land in whichever KB the fleet
315
- // server's cwd resolves to -- the tm7 defect. Refuse rather than guess.
316
- if (!active || !repoPath) {
317
- if ((captures.length || promotions.length) && !repoPath) {
318
- log(`[kb-work] no repo path for ${role} -- ${captures.length} capture(s) and ${promotions.length} promotion(s) dropped`);
319
- }
320
- return { captured: 0, promoted: 0, refused: refused.length };
321
- }
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`;
322
1203
 
323
- let captured = 0;
324
- let promoted = 0;
325
- for (const c of captures) {
326
- try {
327
- const res = await callTool('kb_capture', { ...c, repo_path: repoPath, ...scopeOf(repoPath) });
328
- // apra-fleet-23c: an MCP client RESOLVES with {isError:true} on a
329
- // tool-level failure rather than throwing, so counting every
330
- // non-throwing call as a success reported captures that never
331
- // persisted ("captured 3" against a KB that stayed empty).
332
- if (isToolError(res)) {
333
- log(`[kb-work] kb_capture rejected for "${c.title}" (non-fatal): ${toolErrorText(res)}`);
334
- continue;
335
- }
336
- captured++;
337
- } catch (err) {
338
- log(`[kb-work] kb_capture failed for "${c.title}" (non-fatal): ${err.message}`);
339
- }
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());
340
1210
  }
341
- for (const p of promotions) {
342
- try {
343
- // apra-fleet-0ef: repo_path is REQUIRED here, exactly as on
344
- // the kb_capture call above. Omitting it resolved the
345
- // promotion against the fleet server's cwd -- a different
346
- // project's KB, where the id does not exist -- so every
347
- // promotion would have failed "Entry not found" (the
348
- // apra-fleet-tm7 repo-blindness class, fixed for capture
349
- // but missed here).
350
- const res = await callTool('kb_promote', { id: p.id, reason: p.reason, repo_path: repoPath, ...scopeOf(repoPath) });
351
- if (isToolError(res)) {
352
- log(`[kb-work] kb_promote rejected for ${p.id} (non-fatal): ${toolErrorText(res)}`);
353
- continue;
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`);
354
1228
  }
355
- promoted++;
356
- } catch (err) {
357
- log(`[kb-work] kb_promote failed for ${p.id} (non-fatal): ${err.message}`);
358
1229
  }
359
1230
  }
360
- if (captured || promoted) log(`[kb-work] ${role}: captured ${captured}, promoted ${promoted}`);
361
- return { captured, promoted, refused: refused.length };
362
- },
363
-
364
- /**
365
- * KB audit 2026-08-11: publish this repo's CONFIRMED set to its
366
- * canonical bible (<repo>/.fleet/kb-canonical.json).
367
- *
368
- * Nothing in the pipeline had ever called kb_export, so a bible existed
369
- * only where an operator had run the tool by hand -- 1 of 17 repos on
370
- * the audited machine. Promotion therefore ended at the local sqlite
371
- * store: a teammate, a fresh clone, or a member on another host saw
372
- * none of it, and kb_session_prime's cold-seed (which reads exactly
373
- * this file) had nothing to fall back on. Promotion is the sprint's
374
- * work; publishing it is the step that makes the work leave the
375
- * machine.
376
- *
377
- * Called once, AFTER the final review's promotions have been applied,
378
- * so the bible reflects everything this sprint confirmed. Best-effort
379
- * like every other KB call here: a sprint must never fail over an
380
- * export, and the tool itself is a no-op when the entry set is
381
- * unchanged. Committing/pushing the file stays a separate, opt-in
382
- * decision (kb_export's own autoCommit config) -- this does not widen
383
- * the engine's git authority.
384
- */
385
- async exportBible(repoPath) {
386
- // Same repo-blindness guard as every other call here: without a
387
- // path kb_export would resolve against the fleet server's cwd and
388
- // write an unrelated project's bible.
389
- if (!active || !repoPath) return false;
390
- try {
391
- const res = await callTool('kb_export', { repo_path: repoPath, ...scopeOf(repoPath) });
392
- if (isToolError(res)) {
393
- log(`[kb-work] kb_export rejected for ${repoPath} (non-fatal): ${toolErrorText(res)}`);
394
- return false;
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`);
395
1249
  }
396
- log(`[kb-work] exported the canonical bible for ${repoPath}`);
397
- return true;
398
- } catch (err) {
399
- log(`[kb-work] kb_export failed for ${repoPath} (non-fatal): ${err.message}`);
400
- return false;
401
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);
402
1257
  },
403
1258
  };
404
1259
  }
@@ -407,32 +1262,62 @@ export function createKbWorkClient(opts = {}) {
407
1262
  * apra-fleet-e28 / KB trust pipeline Phase 2: KB priming for the fleet-sprint
408
1263
  * engine, which had none -- it lived only in the Claude workflow copy.
409
1264
  *
410
- * `callTool` is injected exactly like `createMemberReservationClient`'s, so this
411
- * stays transport-agnostic and unit-testable without a live fleet server.
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.
412
1269
  *
413
- * WHY PER MEMBER, NOT PER SPRINT: this engine has no repo path of its own. It
1270
+ * WHY PER MEMBER, NOT PER SPRINT: this engine has no repo of its own. It
414
1271
  * coordinates members by name and branch; the repo lives on each member's side,
415
- * possibly on a different host at a different path. `kb_session_prime` selects
416
- * WHICH project KB is read from its `repo_path`, and omitting that argument
417
- * falls back to the fleet server's own cwd -- collapsing every member's
418
- * knowledge into whichever repo the server happens to sit in, which is exactly
419
- * the apra-fleet-tm7 / apra-fleet-3zl repo-blindness defect. So the work folder
420
- * is resolved per member via `member_detail` (which reports it as `folder`) and
421
- * each member is primed against its own repo.
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.
422
1279
  *
423
1280
  * Best-effort throughout, matching the reservation client's precedent: a member
424
- * whose folder cannot be resolved, or whose prime call fails, is logged and
425
- * skipped. A sprint must not fail because the KB is cold -- priming is an
426
- * optimisation, and every role contract's Step 0 already degrades gracefully
427
- * when the KB tools are unavailable.
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.
428
1285
  *
429
- * @param {{ callTool?: (name: string, args: object) => Promise<any>, members?: string[], log?: Function }} opts
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
430
1287
  * @returns {{ primeAll: () => Promise<{primed: number, skipped: number}> }}
431
1288
  */
432
1289
 
433
1290
  export function createKbPrimingClient(opts = {}) {
434
- const { callTool, members = [], log = () => {} } = opts;
435
- const active = typeof callTool === 'function' && members.length > 0;
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;
436
1321
 
437
1322
  function parseResult(result) {
438
1323
  if (result && typeof result === 'string') { try { return JSON.parse(result); } catch { return null; } }
@@ -442,42 +1327,34 @@ export function createKbPrimingClient(opts = {}) {
442
1327
  return (result && typeof result === 'object') ? result : null;
443
1328
  }
444
1329
 
445
- async function scopeFor(member) {
1330
+ async function resolveMember(member) {
446
1331
  // apra-fleet-n78: format:'json' is REQUIRED. member_detail defaults to
447
1332
  // 'compact', whose renderer emits no folder at all -- `folder` is set only
448
1333
  // on the json path (src/tools/member-detail.ts). Omitting it made this
449
1334
  // return null for every member, so the KB was never primed for anyone.
450
1335
  const detail = parseResult(await callTool('member_detail', { member_name: member, format: 'json' }));
451
- // member_detail reports the work folder as `folder` and the repo origin
452
- // URL as `repo_remote_url` (src/tools/member-detail.ts). The URL is
453
- // reported only when the member's registration record proves it, so an
454
- // absent one is normal and must stay absent rather than be derived here.
455
- const folder = detail && (detail.folder || (detail.member && detail.member.folder));
456
- const url = detail && (detail.repo_remote_url || (detail.member && detail.member.repo_remote_url));
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;
457
1339
  return {
458
1340
  folder: (typeof folder === 'string' && folder.length > 0) ? folder : null,
459
- remoteUrl: (typeof url === 'string' && url.length > 0) ? url : 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,
460
1347
  };
461
1348
  }
462
1349
 
463
- // member -> work folder, populated by primeAll(). createKbWorkClient reads
464
- // it so a capture lands in the repo the member actually worked in, rather
465
- // than being resolved against the fleet server's cwd.
1350
+ // member -> work folder, populated by primeAll(). Informational: no kb_*
1351
+ // call takes it any more (the member session resolves it server-side).
466
1352
  const folders = new Map();
467
1353
 
468
- // member -> the repo origin URL member_detail reported for it, when it
469
- // reported one. This is what scopes a REMOTE member's kb_* calls to its own
470
- // project KB instead of the shared 'default' one (see kbScope).
471
- const remoteUrls = new Map();
472
-
473
- // work folder -> that folder's origin URL, or CONFLICTING_URL when two
474
- // members claim the same path string for DIFFERENT repos. The work client
475
- // resolves its scope through this map rather than taking the URL as an
476
- // extra argument at each of its nine call sites: threading the repo path is
477
- // then the same act as threading the scope, so a site cannot forget one
478
- // while remembering the other.
479
- const urlByFolder = new Map();
480
- const CONFLICTING_URL = Symbol('conflicting-remote-url');
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();
481
1358
 
482
1359
  // member -> the entries kb_session_prime returned for that member.
483
1360
  //
@@ -497,24 +1374,9 @@ export function createKbPrimingClient(opts = {}) {
497
1374
  folderOf(member) {
498
1375
  return folders.get(member) || null;
499
1376
  },
500
- remoteUrlOf(member) {
501
- return remoteUrls.get(member) || null;
502
- },
503
- /**
504
- * The URL scoping kb_* calls made against `repoPath`, or null.
505
- *
506
- * Null for an unknown path, for a local member (no URL was reported),
507
- * and for a path two members claim with different URLs. Members on
508
- * different hosts can share a work-folder path string while being
509
- * clones of different repos; picking either URL there would route one
510
- * member's captures into the other's KB, which is strictly worse than
511
- * the 'default' degradation this scoping exists to remove. Refusing
512
- * leaves that case exactly as it was before.
513
- */
514
- remoteUrlForPath(repoPath) {
515
- if (typeof repoPath !== 'string' || repoPath.length === 0) return null;
516
- const url = urlByFolder.get(repoPath);
517
- return (typeof url === 'string') ? url : null;
1377
+ /** The member record ({id, name, type}) kb work for `member` runs as, or null. */
1378
+ memberOf(member) {
1379
+ return records.get(member) || null;
518
1380
  },
519
1381
  knowledgeOf(member) {
520
1382
  return knowledge.get(member) || [];
@@ -525,25 +1387,34 @@ export function createKbPrimingClient(opts = {}) {
525
1387
  let skipped = 0;
526
1388
  for (const member of members) {
527
1389
  try {
528
- const { folder: repoPath, remoteUrl } = await scopeFor(member);
529
- if (repoPath) folders.set(member, repoPath);
530
- if (remoteUrl) remoteUrls.set(member, remoteUrl);
531
- if (repoPath && remoteUrl) {
532
- const known = urlByFolder.get(repoPath);
533
- if (known !== undefined && known !== remoteUrl) {
534
- urlByFolder.set(repoPath, CONFLICTING_URL);
535
- log(`[kb-prime] work folder ${repoPath} is claimed by two different repos -- KB calls for it stay unscoped`);
536
- } else {
537
- urlByFolder.set(repoPath, remoteUrl);
538
- }
539
- }
540
- if (!repoPath) {
541
- // No folder means no repo to scope the KB to. Priming without
542
- // one would read the fleet server's own KB, so skip instead.
543
- log(`[kb-prime] no work folder for member '${member}' -- skipping (KB stays cold)`);
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)`);
544
1397
  skipped++;
545
1398
  continue;
546
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
+ }
547
1418
  // Land the committed bible in the WARM KB before priming.
548
1419
  //
549
1420
  // Without this the bible is reachable only through
@@ -563,26 +1434,73 @@ export function createKbPrimingClient(opts = {}) {
563
1434
  // sprint start that staled 16 of 17 CONFIRMED entries purely
564
1435
  // because the repo had moved on since capture, and the
565
1436
  // damage cascaded: retrieval fell to one matchable entry,
566
- // kb_export attempted a 17 -> 9 bible truncation, and
1437
+ // the whole-bible publish attempted a 17 -> 9 truncation, and
567
1438
  // kb_list (stale=0) returned an EMPTY promotion candidate
568
1439
  // list -- reinstating apra-fleet-0ef, "kb_promote can never
569
1440
  // fire". This import exists to WARM the KB, never to audit
570
1441
  // it; prime()'s own bounded checkFreshness still guards each
571
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.
572
1463
  try {
573
- const imported = parseResult(await callTool('kb_import', { repo_path: repoPath, ...kbScope(remoteUrl), skip_sweep: true }));
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
+ }
574
1487
  if (imported && typeof imported.imported === 'number' && imported.imported > 0) {
575
- log(`[kb-prime] imported ${imported.imported} bible entr(ies) into the warm KB for ${repoPath}`);
1488
+ log(`[kb-prime] imported ${imported.imported} bible entr(ies) into the warm KB for '${member}'`);
576
1489
  }
577
1490
  } catch (err) {
578
- log(`[kb-prime] kb_import skipped for ${repoPath} (non-fatal): ${err.message}`);
1491
+ log(`[kb-prime] kb_import skipped for '${member}' (non-fatal): ${err.message}`);
579
1492
  }
580
1493
 
581
- const primeResult = parseResult(await callTool('kb_session_prime', { repo_path: repoPath, ...kbScope(remoteUrl) }));
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.
582
1498
  const entries = (primeResult && Array.isArray(primeResult.top_entries))
583
- ? primeResult.top_entries.filter((e) => e && typeof e.id === 'string')
1499
+ ? primeResult.top_entries.filter((e) => typeof e?.id === 'string' && isInjectableKbEntry(e))
584
1500
  : [];
585
- if (entries.length > 0) knowledge.set(member, entries.slice(0, KB_MAX_KNOWLEDGE_ENTRIES));
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);
586
1504
  primed++;
587
1505
  } catch (err) {
588
1506
  log(`[kb-prime] failed for member '${member}' (non-fatal): ${err.message}`);
@@ -625,9 +1543,11 @@ export function createKbPrimingClient(opts = {}) {
625
1543
  * (an apra-pm orchestrator session running these contracts as local subagents,
626
1544
  * where the MCP server is present), so both paths now get knowledge.
627
1545
  *
628
- * The trust ladder is restated here rather than assumed: these entries are
629
- * agent-authored claims from earlier sprints, and CONFIRMED means a reviewer
630
- * verified the claim, not that it is currently true of this branch's tree.
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.
631
1551
  *
632
1552
  * Returns a single-element array (or an empty one) so callers can spread it
633
1553
  * into their prompt-section list, matching kbPromotionBlock.
@@ -661,32 +1581,62 @@ export const KB_SELF_INJECTING_ROLES = Object.freeze(new Set([ROLE_DOER, ROLE_RE
661
1581
  * @returns {string[]}
662
1582
  */
663
1583
  export function kbQueryTerms(beads, beadIds) {
664
- const terms = [];
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 = [];
665
1589
  for (const b of Array.isArray(beads) ? beads : []) {
666
- if (b && typeof b.title === 'string' && b.title.trim()) terms.push(b.title.trim());
1590
+ if (b && typeof b.title === 'string' && b.title.trim()) titles.push(b.title.trim());
667
1591
  }
668
- for (const id of Array.isArray(beadIds) ? beadIds : []) {
669
- if (typeof id === 'string' && id.trim()) terms.push(id.trim());
670
- }
671
- return terms;
1592
+ const knownIds = (Array.isArray(beadIds) ? beadIds : []).filter((id) => typeof id === 'string' && id.trim());
1593
+ return cleanQueryTerms(titles, { knownIds });
672
1594
  }
673
1595
 
674
- export function kbKnowledgeBlock(entries) {
675
- if (!Array.isArray(entries) || entries.length === 0) return [];
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
+ }
676
1627
  return [
677
- 'KNOWLEDGE BANK -- what this repo already knows. These entries were captured and '
678
- + 'verified during earlier work on this repository, and are provided so you do not '
679
- + 'rediscover them the hard way. Read them BEFORE you start.\n'
680
- + 'CONFIRMED entries were independently verified by a reviewer: trust them. INFERRED '
681
- + 'entries are unverified hints: treat them as leads to check, not as facts. An entry '
682
- + 'describes the tree it was captured against, so if one contradicts what you actually '
683
- + 'observe in the code right now, the code wins -- say so in your notes rather than '
684
- + 'bending your work to fit the entry.\n'
685
- + 'You do not need to call any kb_* tool to read these. If you discover something '
686
- + 'non-obvious and durable while working, report it in the `kb_captures` field of your '
687
- + 'structured output and the orchestrator will record it.\n'
688
- + wrapUntrustedBlock('kb_session_prime --top_entries', JSON.stringify(
689
- entries.map((e) => ({
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) => ({
690
1640
  confidence: e.confidence,
691
1641
  title: e.title,
692
1642
  summary: e.summary,
@@ -703,9 +1653,10 @@ export function kbPromotionBlock(kbCandidates) {
703
1653
  return [
704
1654
  'KNOWLEDGE BANK -- promotion candidates. These entries were captured during this '
705
1655
  + 'sprint and sit at INFERRED. You are the only role that can promote them to '
706
- + 'CONFIRMED. Do NOT call any kb_* tool yourself: return your decisions in the '
707
- + '`kb_promotions` field of your structured output as [{id, reason}] and the '
708
- + 'orchestrator executes them.\n'
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'
709
1660
  + 'Promote ONLY entries whose claim you independently verified during THIS review '
710
1661
  + '-- by reading the diff, running the tests, or checking the cited files yourself. '
711
1662
  + 'The `reason` must state that evidence (at least 20 characters, e.g. "verified '
@@ -714,7 +1665,12 @@ export function kbPromotionBlock(kbCandidates) {
714
1665
  + 'resting state, and a wrong CONFIRMED entry is worse than no entry. Never '
715
1666
  + 'blanket-promote, and never promote by module, tag or timestamp. Promoting '
716
1667
  + 'nothing is a valid outcome; return [] in that case.\n'
717
- + wrapUntrustedBlock('kb_list --confidence INFERRED', JSON.stringify(
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(
718
1674
  kbCandidates.map((e) => ({
719
1675
  id: e.id,
720
1676
  title: e.title,