@apralabs/apra-fleet 0.4.3 → 0.4.5

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 (1027) hide show
  1. package/README.md +114 -33
  2. package/dist/agents/backlog-groomer.md +80 -27
  3. package/dist/agents/ci-watcher.md +42 -22
  4. package/dist/agents/deployer.md +59 -24
  5. package/dist/agents/doer.md +111 -41
  6. package/dist/agents/harvester.md +60 -48
  7. package/dist/agents/integ-test-runner.md +45 -23
  8. package/dist/agents/kb-reconciler.md +34 -7
  9. package/dist/agents/plan-reviewer.md +54 -24
  10. package/dist/agents/planner.md +71 -43
  11. package/dist/agents/regression-test-runner.md +106 -78
  12. package/dist/agents/reviewer.md +170 -57
  13. package/dist/agents/schemas/backlog-groomer-output.json +1 -1
  14. package/dist/agents/schemas/deployer-output.json +5 -0
  15. package/dist/agents/schemas/doer-output.json +110 -2
  16. package/dist/agents/schemas/harvester-input.json +1 -5
  17. package/dist/agents/schemas/planner-output.json +1 -1
  18. package/dist/agents/schemas/regression-test-runner-output.json +41 -7
  19. package/dist/agents/schemas/reviewer-output.json +166 -5
  20. package/dist/cli/agent-transform.d.ts +7 -0
  21. package/dist/cli/agent-transform.js +46 -1
  22. package/dist/cli/auth.d.ts +1 -0
  23. package/dist/cli/auth.js +42 -8
  24. package/dist/cli/beads-install.d.ts +35 -0
  25. package/dist/cli/beads-install.js +125 -0
  26. package/dist/cli/beads-pin.d.ts +5 -0
  27. package/dist/cli/beads-pin.js +26 -0
  28. package/dist/cli/call.d.ts +27 -0
  29. package/dist/cli/call.js +177 -0
  30. package/dist/cli/claude-mod.d.ts +75 -0
  31. package/dist/cli/claude-mod.js +288 -0
  32. package/dist/cli/config.d.ts +24 -1
  33. package/dist/cli/config.js +69 -2
  34. package/dist/cli/dolt-install.d.ts +19 -3
  35. package/dist/cli/dolt-install.js +51 -16
  36. package/dist/cli/fleet-se-guard.d.ts +59 -0
  37. package/dist/cli/fleet-se-guard.js +231 -0
  38. package/dist/cli/install-guard.d.ts +63 -0
  39. package/dist/cli/install-guard.js +156 -4
  40. package/dist/cli/install.d.ts +89 -21
  41. package/dist/cli/install.js +778 -160
  42. package/dist/cli/kb-commit.d.ts +2 -1
  43. package/dist/cli/kb-commit.js +1 -1
  44. package/dist/cli/kb-import.d.ts +2 -1
  45. package/dist/cli/kb-import.js +1 -1
  46. package/dist/cli/kb-profile.d.ts +16 -0
  47. package/dist/cli/kb-profile.js +81 -0
  48. package/dist/cli/register-member.js +20 -3
  49. package/dist/cli/remove-member.d.ts +4 -0
  50. package/dist/cli/remove-member.js +63 -0
  51. package/dist/cli/secret.js +9 -0
  52. package/dist/cli/start.js +62 -4
  53. package/dist/cli/status.d.ts +3 -0
  54. package/dist/cli/status.js +45 -12
  55. package/dist/cli/stop.js +64 -9
  56. package/dist/cli/uninstall.js +112 -16
  57. package/dist/cli/update.d.ts +4 -0
  58. package/dist/cli/update.js +52 -5
  59. package/dist/cli/watch.js +1 -1
  60. package/dist/cli/workflow.js +3 -2
  61. package/dist/commands/kb-server.d.ts +10 -1
  62. package/dist/commands/kb-server.js +292 -11
  63. package/dist/hub-service/http-server.d.ts +5 -1
  64. package/dist/hub-service/http-server.js +55 -5
  65. package/dist/index.js +177 -9
  66. package/dist/os/child-env-bound.d.ts +77 -0
  67. package/dist/os/child-env-bound.js +171 -0
  68. package/dist/os/git-executable.d.ts +57 -0
  69. package/dist/os/git-executable.js +85 -0
  70. package/dist/os/go-concurrency.d.ts +44 -0
  71. package/dist/os/go-concurrency.js +53 -0
  72. package/dist/os/index.d.ts +1 -0
  73. package/dist/os/index.js +1 -0
  74. package/dist/os/linux.d.ts +9 -2
  75. package/dist/os/linux.js +50 -15
  76. package/dist/os/macos.d.ts +1 -1
  77. package/dist/os/macos.js +2 -11
  78. package/dist/os/os-commands.d.ts +42 -2
  79. package/dist/os/os-commands.js +2 -0
  80. package/dist/os/windows-executable.d.ts +53 -0
  81. package/dist/os/windows-executable.js +185 -0
  82. package/dist/os/windows-gitbash.d.ts +24 -14
  83. package/dist/os/windows-gitbash.js +56 -18
  84. package/dist/os/windows-wrapper.d.ts +0 -4
  85. package/dist/os/windows-wrapper.js +2 -1
  86. package/dist/os/windows.d.ts +7 -2
  87. package/dist/os/windows.js +109 -32
  88. package/dist/paths.d.ts +30 -0
  89. package/dist/paths.js +52 -0
  90. package/dist/providers/agy.d.ts +6 -2
  91. package/dist/providers/agy.js +245 -106
  92. package/dist/providers/claude-permission-denial.d.ts +7 -0
  93. package/dist/providers/claude-permission-denial.js +137 -0
  94. package/dist/providers/claude.d.ts +86 -38
  95. package/dist/providers/claude.js +426 -164
  96. package/dist/providers/codex.js +5 -1
  97. package/dist/providers/copilot.js +5 -1
  98. package/dist/providers/opencode.d.ts +10 -2
  99. package/dist/providers/opencode.js +114 -53
  100. package/dist/providers/provider.d.ts +171 -33
  101. package/dist/providers/provider.js +164 -3
  102. package/dist/services/agent-provisioner.d.ts +29 -0
  103. package/dist/services/agent-provisioner.js +107 -0
  104. package/dist/services/agent-shadow.d.ts +96 -0
  105. package/dist/services/agent-shadow.js +479 -0
  106. package/dist/services/agy-project.d.ts +9 -2
  107. package/dist/services/agy-project.js +22 -19
  108. package/dist/services/auth-socket.d.ts +43 -0
  109. package/dist/services/auth-socket.js +97 -26
  110. package/dist/services/auth-web.js +1 -1
  111. package/dist/services/budget-awareness.d.ts +11 -11
  112. package/dist/services/budget-awareness.js +15 -3
  113. package/dist/services/claude-local-scope-mcp.d.ts +19 -0
  114. package/dist/services/claude-local-scope-mcp.js +91 -0
  115. package/dist/services/cloud/aws.js +2 -1
  116. package/dist/services/cloud/lifecycle.js +19 -2
  117. package/dist/services/cloud/task-wrapper.d.ts +0 -9
  118. package/dist/services/cloud/task-wrapper.js +15 -6
  119. package/dist/services/credential-store.d.ts +33 -0
  120. package/dist/services/credential-store.js +79 -2
  121. package/dist/services/event-loop-watchdog.d.ts +32 -0
  122. package/dist/services/event-loop-watchdog.js +140 -0
  123. package/dist/services/http-transport.d.ts +78 -1
  124. package/dist/services/http-transport.js +347 -52
  125. package/dist/services/in-flight-agents.d.ts +2 -0
  126. package/dist/services/in-flight-agents.js +4 -0
  127. package/dist/services/kb-tool-profile.d.ts +36 -0
  128. package/dist/services/kb-tool-profile.js +88 -0
  129. package/dist/services/knowledge/bible-basis-filter.d.ts +53 -0
  130. package/dist/services/knowledge/bible-basis-filter.js +134 -0
  131. package/dist/services/knowledge/bible-blob-id.d.ts +44 -0
  132. package/dist/services/knowledge/bible-blob-id.js +122 -0
  133. package/dist/services/knowledge/bible-import.d.ts +173 -0
  134. package/dist/services/knowledge/bible-import.js +344 -0
  135. package/dist/services/knowledge/file-hash.d.ts +31 -0
  136. package/dist/services/knowledge/file-hash.js +155 -24
  137. package/dist/services/knowledge/http-provider.d.ts +305 -21
  138. package/dist/services/knowledge/http-provider.js +801 -119
  139. package/dist/services/knowledge/kb-config.d.ts +65 -1
  140. package/dist/services/knowledge/kb-config.js +143 -3
  141. package/dist/services/knowledge/kb-http-auth-state.d.ts +26 -0
  142. package/dist/services/knowledge/kb-http-auth-state.js +40 -0
  143. package/dist/services/knowledge/kb-maintainer-grant.d.ts +15 -0
  144. package/dist/services/knowledge/kb-maintainer-grant.js +34 -0
  145. package/dist/services/knowledge/kb-providers.d.ts +13 -2
  146. package/dist/services/knowledge/kb-providers.js +75 -37
  147. package/dist/services/knowledge/kb-removed-scope-keys.d.ts +28 -0
  148. package/dist/services/knowledge/kb-removed-scope-keys.js +59 -0
  149. package/dist/services/knowledge/kb-scopes.d.ts +14 -0
  150. package/dist/services/knowledge/kb-scopes.js +47 -0
  151. package/dist/services/knowledge/kb-self.d.ts +204 -0
  152. package/dist/services/knowledge/kb-self.js +358 -0
  153. package/dist/services/knowledge/member-bible-view.d.ts +21 -0
  154. package/dist/services/knowledge/member-bible-view.js +207 -0
  155. package/dist/services/knowledge/path-validation.d.ts +7 -0
  156. package/dist/services/knowledge/path-validation.js +11 -0
  157. package/dist/services/knowledge/pre-init.js +1 -0
  158. package/dist/services/knowledge/project-slug.js +5 -4
  159. package/dist/services/knowledge/repository-header.d.ts +77 -0
  160. package/dist/services/knowledge/repository-header.js +233 -0
  161. package/dist/services/knowledge/require-sqlite-project.d.ts +1 -1
  162. package/dist/services/knowledge/require-sqlite-project.js +1 -1
  163. package/dist/services/knowledge/sqlite-provider.d.ts +233 -11
  164. package/dist/services/knowledge/sqlite-provider.js +719 -45
  165. package/dist/services/knowledge/types.d.ts +59 -3
  166. package/dist/services/member-access-secret.d.ts +70 -0
  167. package/dist/services/member-access-secret.js +195 -0
  168. package/dist/services/member-busy.d.ts +12 -0
  169. package/dist/services/member-busy.js +20 -0
  170. package/dist/services/member-call-counts.d.ts +24 -0
  171. package/dist/services/member-call-counts.js +58 -0
  172. package/dist/services/member-config-io.d.ts +193 -0
  173. package/dist/services/member-config-io.js +446 -0
  174. package/dist/services/member-fleet-install.d.ts +710 -0
  175. package/dist/services/member-fleet-install.js +1896 -0
  176. package/dist/services/member-secret-env.d.ts +42 -0
  177. package/dist/services/member-secret-env.js +68 -0
  178. package/dist/services/member-tool-allowlist.d.ts +49 -0
  179. package/dist/services/member-tool-allowlist.js +115 -0
  180. package/dist/services/model-pricing.d.ts +19 -0
  181. package/dist/services/model-pricing.js +54 -8
  182. package/dist/services/port-holder.d.ts +86 -0
  183. package/dist/services/port-holder.js +352 -0
  184. package/dist/services/preflight-check.js +2 -0
  185. package/dist/services/registry.d.ts +13 -2
  186. package/dist/services/registry.js +27 -1
  187. package/dist/services/relay-strategy.d.ts +2 -0
  188. package/dist/services/relay-strategy.js +8 -0
  189. package/dist/services/server-lifecycle.d.ts +26 -0
  190. package/dist/services/server-lifecycle.js +85 -0
  191. package/dist/services/service-manager/index.d.ts +7 -1
  192. package/dist/services/service-manager/index.js +17 -4
  193. package/dist/services/service-manager/linux.d.ts +1 -1
  194. package/dist/services/service-manager/linux.js +15 -7
  195. package/dist/services/service-manager/macos.d.ts +11 -1
  196. package/dist/services/service-manager/macos.js +45 -7
  197. package/dist/services/service-manager/service-path.d.ts +24 -0
  198. package/dist/services/service-manager/service-path.js +55 -0
  199. package/dist/services/service-manager/types.d.ts +54 -3
  200. package/dist/services/service-manager/types.js +29 -0
  201. package/dist/services/service-manager/windows.d.ts +187 -3
  202. package/dist/services/service-manager/windows.js +684 -50
  203. package/dist/services/service-notice.d.ts +21 -0
  204. package/dist/services/service-notice.js +81 -0
  205. package/dist/services/service-start-guard.d.ts +20 -0
  206. package/dist/services/service-start-guard.js +86 -0
  207. package/dist/services/session-cost.d.ts +24 -0
  208. package/dist/services/session-cost.js +105 -0
  209. package/dist/services/session-mcp-config.d.ts +83 -0
  210. package/dist/services/session-mcp-config.js +211 -0
  211. package/dist/services/session-registry.d.ts +13 -0
  212. package/dist/services/session-registry.js +13 -0
  213. package/dist/services/session-roots.d.ts +67 -0
  214. package/dist/services/session-roots.js +126 -0
  215. package/dist/services/sftp.d.ts +34 -0
  216. package/dist/services/sftp.js +304 -76
  217. package/dist/services/shell-probe.d.ts +0 -24
  218. package/dist/services/shell-probe.js +28 -3
  219. package/dist/services/singleton.d.ts +68 -2
  220. package/dist/services/singleton.js +168 -11
  221. package/dist/services/sprint-coordination.js +9 -3
  222. package/dist/services/ssh.d.ts +27 -0
  223. package/dist/services/ssh.js +229 -38
  224. package/dist/services/stall/find-log-file.js +12 -5
  225. package/dist/services/stall/index.d.ts +1 -1
  226. package/dist/services/stall/read-log-tail.d.ts +23 -0
  227. package/dist/services/stall/read-log-tail.js +33 -2
  228. package/dist/services/stall/stall-detector.d.ts +25 -1
  229. package/dist/services/stall/stall-detector.js +85 -6
  230. package/dist/services/stall/stall-poller.d.ts +16 -0
  231. package/dist/services/stall/stall-poller.js +50 -6
  232. package/dist/services/statusline.d.ts +21 -0
  233. package/dist/services/statusline.js +97 -1
  234. package/dist/services/stopped-marker.d.ts +16 -0
  235. package/dist/services/stopped-marker.js +55 -0
  236. package/dist/services/strategy.d.ts +33 -1
  237. package/dist/services/strategy.js +86 -17
  238. package/dist/services/supervisor-service-cleanup.d.ts +52 -0
  239. package/dist/services/supervisor-service-cleanup.js +333 -0
  240. package/dist/services/tool-registry.d.ts +8 -1
  241. package/dist/services/tool-registry.js +251 -62
  242. package/dist/services/tool-scope.d.ts +91 -0
  243. package/dist/services/tool-scope.js +124 -0
  244. package/dist/services/vcs/azure-devops.js +10 -0
  245. package/dist/services/vcs/bitbucket.d.ts +22 -1
  246. package/dist/services/vcs/bitbucket.js +163 -17
  247. package/dist/services/vcs/types.d.ts +25 -2
  248. package/dist/services/watch/project-resolver.js +3 -1
  249. package/dist/skills/auto-sprint-args/SKILL.md +2 -2
  250. package/dist/skills/fleet-sprint-cli/SKILL.md +39 -15
  251. package/dist/skills/pm/SKILL.md +3 -3
  252. package/dist/skills/pm/cost.md +5 -1
  253. package/dist/skills/pm/index.md +11 -9
  254. package/dist/skills/pm/kb-reconcile.md +29 -14
  255. package/dist/skills/pm/kb-review.md +1 -0
  256. package/dist/skills/pm/sprint.md +7 -6
  257. package/dist/tools/check-status.d.ts +104 -5
  258. package/dist/tools/check-status.js +326 -57
  259. package/dist/tools/child-id-allocator.d.ts +2 -2
  260. package/dist/tools/child-id-allocator.js +1 -1
  261. package/dist/tools/code-index-heal.d.ts +8 -0
  262. package/dist/tools/code-index-heal.js +21 -0
  263. package/dist/tools/code-index-state.d.ts +45 -0
  264. package/dist/tools/code-index-state.js +115 -0
  265. package/dist/tools/code-intelligence-codebase-memory.js +6 -33
  266. package/dist/tools/code-intelligence-freshness.js +1 -1
  267. package/dist/tools/code-intelligence-gitnexus.d.ts +49 -0
  268. package/dist/tools/code-intelligence-gitnexus.js +488 -55
  269. package/dist/tools/code-intelligence-kb-enrich.js +7 -6
  270. package/dist/tools/code-intelligence-readiness.d.ts +156 -0
  271. package/dist/tools/code-intelligence-readiness.js +291 -0
  272. package/dist/tools/code-intelligence-reindex.d.ts +219 -0
  273. package/dist/tools/code-intelligence-reindex.js +602 -50
  274. package/dist/tools/code-intelligence-telemetry.d.ts +6 -1
  275. package/dist/tools/code-intelligence-telemetry.js +12 -3
  276. package/dist/tools/code-intelligence.d.ts +81 -31
  277. package/dist/tools/code-intelligence.js +156 -52
  278. package/dist/tools/compose-permissions.d.ts +57 -2
  279. package/dist/tools/compose-permissions.js +497 -44
  280. package/dist/tools/execute-command.d.ts +11 -0
  281. package/dist/tools/execute-command.js +92 -18
  282. package/dist/tools/execute-prompt.d.ts +59 -15
  283. package/dist/tools/execute-prompt.js +550 -135
  284. package/dist/tools/fleet-snapshot.d.ts +21 -0
  285. package/dist/tools/fleet-snapshot.js +78 -0
  286. package/dist/tools/kb-bible-commit.d.ts +79 -0
  287. package/dist/tools/kb-bible-commit.js +348 -0
  288. package/dist/tools/kb-capture.d.ts +15 -11
  289. package/dist/tools/kb-capture.js +42 -11
  290. package/dist/tools/kb-context.d.ts +27 -7
  291. package/dist/tools/kb-context.js +85 -14
  292. package/dist/tools/kb-demote.d.ts +27 -0
  293. package/dist/tools/kb-demote.js +37 -0
  294. package/dist/tools/kb-export.d.ts +128 -7
  295. package/dist/tools/kb-export.js +273 -67
  296. package/dist/tools/kb-feedback.d.ts +15 -9
  297. package/dist/tools/kb-feedback.js +27 -11
  298. package/dist/tools/kb-freshness-sweep.d.ts +11 -7
  299. package/dist/tools/kb-freshness-sweep.js +7 -7
  300. package/dist/tools/kb-harvest.d.ts +11 -7
  301. package/dist/tools/kb-harvest.js +35 -16
  302. package/dist/tools/kb-import.d.ts +42 -10
  303. package/dist/tools/kb-import.js +185 -160
  304. package/dist/tools/kb-invalidate.d.ts +26 -11
  305. package/dist/tools/kb-invalidate.js +118 -12
  306. package/dist/tools/kb-list.d.ts +14 -10
  307. package/dist/tools/kb-list.js +61 -13
  308. package/dist/tools/kb-promote.d.ts +11 -7
  309. package/dist/tools/kb-promote.js +16 -8
  310. package/dist/tools/kb-query.d.ts +24 -11
  311. package/dist/tools/kb-query.js +230 -23
  312. package/dist/tools/kb-reconcile-prefilter.d.ts +11 -7
  313. package/dist/tools/kb-reconcile-prefilter.js +10 -8
  314. package/dist/tools/kb-resolve-contradiction.d.ts +11 -7
  315. package/dist/tools/kb-resolve-contradiction.js +7 -7
  316. package/dist/tools/kb-session-prime.d.ts +14 -7
  317. package/dist/tools/kb-session-prime.js +127 -47
  318. package/dist/tools/kb-setup.d.ts +31 -4
  319. package/dist/tools/kb-setup.js +172 -20
  320. package/dist/tools/kb-stats.d.ts +11 -10
  321. package/dist/tools/kb-stats.js +22 -41
  322. package/dist/tools/list-members.js +6 -3
  323. package/dist/tools/member-detail.d.ts +3 -0
  324. package/dist/tools/member-detail.js +95 -20
  325. package/dist/tools/member-reservation.d.ts +2 -2
  326. package/dist/tools/provision-auth.d.ts +39 -1
  327. package/dist/tools/provision-auth.js +269 -47
  328. package/dist/tools/provision-vcs-auth.d.ts +30 -5
  329. package/dist/tools/provision-vcs-auth.js +53 -7
  330. package/dist/tools/receive-files.js +8 -3
  331. package/dist/tools/register-member.d.ts +34 -8
  332. package/dist/tools/register-member.js +76 -58
  333. package/dist/tools/remove-member.js +110 -32
  334. package/dist/tools/send-email.d.ts +2 -2
  335. package/dist/tools/send-files.js +9 -6
  336. package/dist/tools/send-message.d.ts +3 -0
  337. package/dist/tools/send-message.js +15 -2
  338. package/dist/tools/session-stats.d.ts +17 -0
  339. package/dist/tools/session-stats.js +27 -0
  340. package/dist/tools/shutdown-server.js +5 -0
  341. package/dist/tools/stop-prompt.js +3 -1
  342. package/dist/tools/update-agent-cli.d.ts +19 -0
  343. package/dist/tools/update-agent-cli.js +59 -2
  344. package/dist/tools/update-member.d.ts +13 -10
  345. package/dist/tools/update-member.js +138 -7
  346. package/dist/tools/vcs-credential-exec.d.ts +45 -3
  347. package/dist/tools/vcs-credential-exec.js +98 -13
  348. package/dist/types.d.ts +98 -1
  349. package/dist/utils/agent-helpers.js +2 -0
  350. package/dist/utils/auth-env.d.ts +15 -4
  351. package/dist/utils/auth-env.js +52 -23
  352. package/dist/utils/find-on-path.d.ts +37 -0
  353. package/dist/utils/find-on-path.js +85 -0
  354. package/dist/utils/log-helpers.d.ts +37 -0
  355. package/dist/utils/log-helpers.js +106 -20
  356. package/dist/utils/owner-only-fs.d.ts +56 -0
  357. package/dist/utils/owner-only-fs.js +98 -0
  358. package/dist/utils/process-utils.d.ts +28 -0
  359. package/dist/utils/process-utils.js +72 -0
  360. package/dist/utils/prompt-errors.js +4 -1
  361. package/dist/utils/redact-known-secrets.d.ts +17 -0
  362. package/dist/utils/redact-known-secrets.js +70 -0
  363. package/dist/utils/session-caller.d.ts +4 -2
  364. package/dist/utils/session-caller.js +3 -2
  365. package/dist/utils/shell-escape.d.ts +42 -3
  366. package/dist/utils/shell-escape.js +70 -4
  367. package/dist/utils/skill-matrix.js +1 -1
  368. package/dist/utils/ssh-error-messages.js +3 -0
  369. package/dist/utils/vcs-provider-detect.js +2 -2
  370. package/dist/utils/workspace-trust.d.ts +24 -1
  371. package/dist/utils/workspace-trust.js +21 -17
  372. package/dist/workflows/auto-sprint.js +468 -52
  373. package/package.json +15 -9
  374. package/packages/apra-fleet-client/package.json +2 -2
  375. package/packages/apra-fleet-client/src/client/api.mjs +722 -38
  376. package/packages/apra-fleet-client/src/client/auto-start.mjs +434 -0
  377. package/packages/apra-fleet-client/src/client/client.mjs +9 -0
  378. package/packages/apra-fleet-client/src/client/factory.mjs +23 -4
  379. package/packages/apra-fleet-client/src/client/reconnecting-transport.mjs +170 -0
  380. package/packages/apra-fleet-client/src/client/server-resolution.mjs +267 -30
  381. package/packages/apra-fleet-client/src/client/transport.mjs +43 -3
  382. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +80 -27
  383. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +42 -22
  384. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +59 -24
  385. package/packages/apra-fleet-se/apra-pm/agents/doer.md +111 -41
  386. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +60 -48
  387. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +45 -23
  388. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +34 -7
  389. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +54 -24
  390. package/packages/apra-fleet-se/apra-pm/agents/planner.md +71 -43
  391. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +106 -78
  392. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +170 -57
  393. package/packages/apra-fleet-se/apra-pm/agents/schemas/backlog-groomer-output.json +1 -1
  394. package/packages/apra-fleet-se/apra-pm/agents/schemas/deployer-output.json +5 -0
  395. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +110 -2
  396. package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-input.json +1 -5
  397. package/packages/apra-fleet-se/apra-pm/agents/schemas/planner-output.json +1 -1
  398. package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-output.json +41 -7
  399. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +166 -5
  400. package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +3 -3
  401. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +5 -1
  402. package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +11 -9
  403. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-reconcile.md +29 -14
  404. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-review.md +1 -0
  405. package/packages/apra-fleet-se/apra-pm/skills/pm/sprint.md +7 -6
  406. package/packages/apra-fleet-se/bin/cli.mjs +282 -79
  407. package/packages/apra-fleet-se/bin/serve.mjs +186 -15
  408. package/packages/apra-fleet-se/fleet-sprint/abort.mjs +234 -46
  409. package/packages/apra-fleet-se/fleet-sprint/backlog-role.mjs +93 -0
  410. package/packages/apra-fleet-se/fleet-sprint/bd-sync-command.mjs +69 -0
  411. package/packages/apra-fleet-se/fleet-sprint/beads-children.mjs +229 -53
  412. package/packages/apra-fleet-se/fleet-sprint/beads-identity-check.mjs +576 -33
  413. package/packages/apra-fleet-se/fleet-sprint/beads-identity.mjs +9 -0
  414. package/packages/apra-fleet-se/fleet-sprint/beads-lock-probe.mjs +176 -0
  415. package/packages/apra-fleet-se/fleet-sprint/beads-memory-hygiene.mjs +201 -0
  416. package/packages/apra-fleet-se/fleet-sprint/beads-reachability.mjs +126 -0
  417. package/packages/apra-fleet-se/fleet-sprint/beads-scope.mjs +271 -7
  418. package/packages/apra-fleet-se/fleet-sprint/beads-transitions.mjs +154 -8
  419. package/packages/apra-fleet-se/fleet-sprint/ci-gate.mjs +353 -0
  420. package/packages/apra-fleet-se/fleet-sprint/conflict-ladder.mjs +12 -0
  421. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +142 -3
  422. package/packages/apra-fleet-se/fleet-sprint/coordination.mjs +48 -8
  423. package/packages/apra-fleet-se/fleet-sprint/decision-notify.mjs +338 -0
  424. package/packages/apra-fleet-se/fleet-sprint/decision-wait.mjs +731 -0
  425. package/packages/apra-fleet-se/fleet-sprint/decisions.mjs +372 -0
  426. package/packages/apra-fleet-se/fleet-sprint/dispatch-accounting.mjs +270 -0
  427. package/packages/apra-fleet-se/fleet-sprint/dispatch-failure.mjs +22 -2
  428. package/packages/apra-fleet-se/fleet-sprint/dispatch-role.mjs +244 -22
  429. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +56 -15
  430. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +6 -1
  431. package/packages/apra-fleet-se/fleet-sprint/docs/fleet-sprint-diagram.md +3 -3
  432. package/packages/apra-fleet-se/fleet-sprint/dolt-settle.mjs +9 -3
  433. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +651 -37
  434. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +282 -15
  435. package/packages/apra-fleet-se/fleet-sprint/explicit-id-create-guard.mjs +4 -4
  436. package/packages/apra-fleet-se/fleet-sprint/git-sync.mjs +207 -10
  437. package/packages/apra-fleet-se/fleet-sprint/git-topology.mjs +169 -10
  438. package/packages/apra-fleet-se/fleet-sprint/guarded-modules.mjs +88 -5
  439. package/packages/apra-fleet-se/fleet-sprint/kb-hints.mjs +181 -0
  440. package/packages/apra-fleet-se/fleet-sprint/kb-injection.mjs +64 -0
  441. package/packages/apra-fleet-se/fleet-sprint/kb-maintainer.mjs +298 -0
  442. package/packages/apra-fleet-se/fleet-sprint/kb.mjs +1896 -305
  443. package/packages/apra-fleet-se/fleet-sprint/lower-quality.mjs +39 -0
  444. package/packages/apra-fleet-se/fleet-sprint/member-align.mjs +391 -0
  445. package/packages/apra-fleet-se/fleet-sprint/member-call.mjs +374 -0
  446. package/packages/apra-fleet-se/fleet-sprint/member-init-probe.mjs +644 -0
  447. package/packages/apra-fleet-se/fleet-sprint/member-provisioning.mjs +454 -1
  448. package/packages/apra-fleet-se/fleet-sprint/member-sync.mjs +250 -29
  449. package/packages/apra-fleet-se/fleet-sprint/orphan-reclaim.mjs +153 -0
  450. package/packages/apra-fleet-se/fleet-sprint/phases/deploy.mjs +129 -0
  451. package/packages/apra-fleet-se/fleet-sprint/phases/develop.mjs +302 -52
  452. package/packages/apra-fleet-se/fleet-sprint/phases/ensure-sprint-branch.mjs +1 -0
  453. package/packages/apra-fleet-se/fleet-sprint/phases/final-review.mjs +142 -21
  454. package/packages/apra-fleet-se/fleet-sprint/phases/harvest.mjs +118 -36
  455. package/packages/apra-fleet-se/fleet-sprint/phases/integ-test.mjs +6 -6
  456. package/packages/apra-fleet-se/fleet-sprint/phases/plan.mjs +27 -18
  457. package/packages/apra-fleet-se/fleet-sprint/phases/publish-pr.mjs +99 -52
  458. package/packages/apra-fleet-se/fleet-sprint/phases/re-review.mjs +58 -10
  459. package/packages/apra-fleet-se/fleet-sprint/phases/regression-test.mjs +16 -11
  460. package/packages/apra-fleet-se/fleet-sprint/phases/replan.mjs +36 -3
  461. package/packages/apra-fleet-se/fleet-sprint/phases/review.mjs +90 -15
  462. package/packages/apra-fleet-se/fleet-sprint/pr-body.mjs +272 -0
  463. package/packages/apra-fleet-se/fleet-sprint/prompts.mjs +113 -28
  464. package/packages/apra-fleet-se/fleet-sprint/role-policies.mjs +19 -1
  465. package/packages/apra-fleet-se/fleet-sprint/runner.js +1631 -213
  466. package/packages/apra-fleet-se/fleet-sprint/se-os-commands.mjs +26 -0
  467. package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +183 -0
  468. package/packages/apra-fleet-se/fleet-sprint/se-windows.mjs +138 -0
  469. package/packages/apra-fleet-se/fleet-sprint/set-aside.mjs +288 -0
  470. package/packages/apra-fleet-se/fleet-sprint/shell-command-guard.mjs +44 -1
  471. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +39 -15
  472. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +87 -32
  473. package/packages/apra-fleet-se/fleet-sprint/sprint-args.mjs +158 -2
  474. package/packages/apra-fleet-se/fleet-sprint/sprint-report.mjs +132 -11
  475. package/packages/apra-fleet-se/fleet-sprint/sprint-state.mjs +31 -0
  476. package/packages/apra-fleet-se/fleet-sprint/usage-limit-controller.mjs +7 -0
  477. package/packages/apra-fleet-se/fleet-sprint/vcs-auth.mjs +774 -35
  478. package/packages/apra-fleet-se/fleet-sprint/vcs-module.mjs +134 -7
  479. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/azure-devops.mjs +99 -0
  480. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +811 -17
  481. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +223 -0
  482. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +138 -1
  483. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/shell-helpers.mjs +8 -4
  484. package/packages/apra-fleet-se/fleet-sprint/verify-block.mjs +152 -0
  485. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +460 -23
  486. package/packages/apra-fleet-se/fleet-sprint/worklists.mjs +59 -3
  487. package/packages/apra-fleet-se/package.json +2 -2
  488. package/packages/apra-fleet-se/src/supervisor/api.mjs +1059 -0
  489. package/packages/apra-fleet-se/src/supervisor/backlog-member.mjs +332 -0
  490. package/packages/apra-fleet-se/src/supervisor/backlog.mjs +982 -0
  491. package/packages/apra-fleet-se/src/supervisor/beads-identity.mjs +246 -0
  492. package/packages/apra-fleet-se/src/supervisor/beads-view.mjs +438 -0
  493. package/packages/apra-fleet-se/src/supervisor/child-port.mjs +36 -0
  494. package/packages/apra-fleet-se/src/supervisor/dashboard.mjs +1662 -0
  495. package/packages/apra-fleet-se/src/supervisor/dolt-mutex.mjs +370 -0
  496. package/packages/apra-fleet-se/src/supervisor/dolt-orphan-sweep.mjs +338 -0
  497. package/packages/apra-fleet-se/src/supervisor/fleet-members.mjs +292 -0
  498. package/packages/apra-fleet-se/src/supervisor/history-view.mjs +276 -0
  499. package/packages/apra-fleet-se/src/supervisor/history.mjs +335 -0
  500. package/packages/apra-fleet-se/src/supervisor/id-allocator.mjs +611 -0
  501. package/packages/apra-fleet-se/src/supervisor/launch-form.mjs +444 -0
  502. package/packages/apra-fleet-se/src/supervisor/ledger.mjs +629 -0
  503. package/packages/apra-fleet-se/src/supervisor/lib/exec-bd.mjs +303 -0
  504. package/packages/apra-fleet-se/src/supervisor/log-timestamp.mjs +51 -0
  505. package/packages/apra-fleet-se/src/supervisor/log-view.mjs +159 -0
  506. package/packages/apra-fleet-se/src/supervisor/proxy.mjs +499 -0
  507. package/packages/apra-fleet-se/src/supervisor/readopt.mjs +136 -0
  508. package/packages/apra-fleet-se/src/supervisor/reconcile.mjs +263 -0
  509. package/packages/apra-fleet-se/src/supervisor/rename-with-retry.mjs +87 -0
  510. package/packages/apra-fleet-se/src/supervisor/scope-overlap.mjs +327 -0
  511. package/packages/apra-fleet-se/src/supervisor/self-log.mjs +133 -0
  512. package/packages/apra-fleet-se/src/supervisor/server.mjs +542 -0
  513. package/packages/apra-fleet-se/src/supervisor/spawner.mjs +544 -0
  514. package/packages/apra-fleet-se/src/supervisor/sprint-identity.mjs +96 -0
  515. package/packages/apra-fleet-se/src/supervisor/watchdog.mjs +993 -0
  516. package/packages/apra-fleet-workflow/package.json +3 -2
  517. package/packages/apra-fleet-workflow/src/viewer/index.mjs +150 -14
  518. package/packages/apra-fleet-workflow/src/viewer/request-guard.mjs +222 -0
  519. package/packages/apra-fleet-workflow/src/viewer/run-summary.mjs +127 -0
  520. package/packages/apra-fleet-workflow/src/workflow/index.mjs +105 -7
  521. package/packages/apra-fleet-workflow/src/workflow/pricing.mjs +75 -25
  522. package/plugins/claude-code/fleet-status/.claude-plugin/plugin.json +7 -0
  523. package/plugins/claude-code/fleet-status/hooks/hooks.json +1 -0
  524. package/plugins/claude-code/fleet-status/hooks/register.tsx +906 -0
  525. package/plugins/claude-code/fleet-status/types/index.d.ts +88 -0
  526. package/skills/fleet/auth-bitbucket.md +47 -20
  527. package/skills/fleet/onboarding.md +1 -1
  528. package/skills/fleet/permissions.md +9 -0
  529. package/skills/fleet/profiles/tag-kb-reconciler.json +2 -6
  530. package/skills/fleet/skill-matrix.md +3 -3
  531. package/version.json +1 -1
  532. package/dist/cli/agent-transform.d.ts.map +0 -1
  533. package/dist/cli/agent-transform.js.map +0 -1
  534. package/dist/cli/auth.d.ts.map +0 -1
  535. package/dist/cli/auth.js.map +0 -1
  536. package/dist/cli/config.d.ts.map +0 -1
  537. package/dist/cli/config.js.map +0 -1
  538. package/dist/cli/dolt-install.d.ts.map +0 -1
  539. package/dist/cli/dolt-install.js.map +0 -1
  540. package/dist/cli/install-guard.d.ts.map +0 -1
  541. package/dist/cli/install-guard.js.map +0 -1
  542. package/dist/cli/install.d.ts.map +0 -1
  543. package/dist/cli/install.js.map +0 -1
  544. package/dist/cli/join.d.ts.map +0 -1
  545. package/dist/cli/join.js.map +0 -1
  546. package/dist/cli/kb-commit.d.ts.map +0 -1
  547. package/dist/cli/kb-commit.js.map +0 -1
  548. package/dist/cli/kb-directives.d.ts.map +0 -1
  549. package/dist/cli/kb-directives.js.map +0 -1
  550. package/dist/cli/kb-import.d.ts.map +0 -1
  551. package/dist/cli/kb-import.js.map +0 -1
  552. package/dist/cli/register-member.d.ts.map +0 -1
  553. package/dist/cli/register-member.js.map +0 -1
  554. package/dist/cli/restart.d.ts.map +0 -1
  555. package/dist/cli/restart.js.map +0 -1
  556. package/dist/cli/secret.d.ts.map +0 -1
  557. package/dist/cli/secret.js.map +0 -1
  558. package/dist/cli/spoke.d.ts.map +0 -1
  559. package/dist/cli/spoke.js.map +0 -1
  560. package/dist/cli/start.d.ts.map +0 -1
  561. package/dist/cli/start.js.map +0 -1
  562. package/dist/cli/status.d.ts.map +0 -1
  563. package/dist/cli/status.js.map +0 -1
  564. package/dist/cli/stop.d.ts.map +0 -1
  565. package/dist/cli/stop.js.map +0 -1
  566. package/dist/cli/uninstall.d.ts.map +0 -1
  567. package/dist/cli/uninstall.js.map +0 -1
  568. package/dist/cli/update.d.ts.map +0 -1
  569. package/dist/cli/update.js.map +0 -1
  570. package/dist/cli/watch.d.ts.map +0 -1
  571. package/dist/cli/watch.js.map +0 -1
  572. package/dist/cli/workflow-assets.d.ts.map +0 -1
  573. package/dist/cli/workflow-assets.js.map +0 -1
  574. package/dist/cli/workflow.d.ts.map +0 -1
  575. package/dist/cli/workflow.js.map +0 -1
  576. package/dist/commands/kb-server.d.ts.map +0 -1
  577. package/dist/commands/kb-server.js.map +0 -1
  578. package/dist/delivery-mode.d.ts.map +0 -1
  579. package/dist/delivery-mode.js.map +0 -1
  580. package/dist/hub-service/activity.d.ts.map +0 -1
  581. package/dist/hub-service/activity.js.map +0 -1
  582. package/dist/hub-service/audit-log.d.ts.map +0 -1
  583. package/dist/hub-service/audit-log.js.map +0 -1
  584. package/dist/hub-service/db/pool.d.ts.map +0 -1
  585. package/dist/hub-service/db/pool.js.map +0 -1
  586. package/dist/hub-service/enrollment.d.ts.map +0 -1
  587. package/dist/hub-service/enrollment.js.map +0 -1
  588. package/dist/hub-service/envelope-routes.d.ts.map +0 -1
  589. package/dist/hub-service/envelope-routes.js.map +0 -1
  590. package/dist/hub-service/handlers/installers.d.ts.map +0 -1
  591. package/dist/hub-service/handlers/installers.js.map +0 -1
  592. package/dist/hub-service/http-server.d.ts.map +0 -1
  593. package/dist/hub-service/http-server.js.map +0 -1
  594. package/dist/hub-service/hub-jwt.d.ts.map +0 -1
  595. package/dist/hub-service/hub-jwt.js.map +0 -1
  596. package/dist/hub-service/jwt-revocation.d.ts.map +0 -1
  597. package/dist/hub-service/jwt-revocation.js.map +0 -1
  598. package/dist/hub-service/machines.d.ts.map +0 -1
  599. package/dist/hub-service/machines.js.map +0 -1
  600. package/dist/hub-service/main.d.ts.map +0 -1
  601. package/dist/hub-service/main.js.map +0 -1
  602. package/dist/hub-service/member-tokens.d.ts.map +0 -1
  603. package/dist/hub-service/member-tokens.js.map +0 -1
  604. package/dist/hub-service/member-view.d.ts.map +0 -1
  605. package/dist/hub-service/member-view.js.map +0 -1
  606. package/dist/hub-service/members.d.ts.map +0 -1
  607. package/dist/hub-service/members.js.map +0 -1
  608. package/dist/hub-service/presence.d.ts.map +0 -1
  609. package/dist/hub-service/presence.js.map +0 -1
  610. package/dist/hub-service/project-view.d.ts.map +0 -1
  611. package/dist/hub-service/project-view.js.map +0 -1
  612. package/dist/hub-service/projects.d.ts.map +0 -1
  613. package/dist/hub-service/projects.js.map +0 -1
  614. package/dist/hub-service/relay-queue.d.ts.map +0 -1
  615. package/dist/hub-service/relay-queue.js.map +0 -1
  616. package/dist/hub-service/session-jwt.d.ts.map +0 -1
  617. package/dist/hub-service/session-jwt.js.map +0 -1
  618. package/dist/hub-service/usage.d.ts.map +0 -1
  619. package/dist/hub-service/usage.js.map +0 -1
  620. package/dist/hub-service/users.d.ts.map +0 -1
  621. package/dist/hub-service/users.js.map +0 -1
  622. package/dist/hub-service/workspaces.d.ts.map +0 -1
  623. package/dist/hub-service/workspaces.js.map +0 -1
  624. package/dist/index.d.ts.map +0 -1
  625. package/dist/index.js.map +0 -1
  626. package/dist/onboarding/text.d.ts.map +0 -1
  627. package/dist/onboarding/text.js.map +0 -1
  628. package/dist/os/git-bash-candidates.d.ts.map +0 -1
  629. package/dist/os/git-bash-candidates.js.map +0 -1
  630. package/dist/os/index.d.ts.map +0 -1
  631. package/dist/os/index.js.map +0 -1
  632. package/dist/os/linux.d.ts.map +0 -1
  633. package/dist/os/linux.js.map +0 -1
  634. package/dist/os/macos.d.ts.map +0 -1
  635. package/dist/os/macos.js.map +0 -1
  636. package/dist/os/os-commands.d.ts.map +0 -1
  637. package/dist/os/os-commands.js.map +0 -1
  638. package/dist/os/windows-gitbash.d.ts.map +0 -1
  639. package/dist/os/windows-gitbash.js.map +0 -1
  640. package/dist/os/windows-wrapper.d.ts.map +0 -1
  641. package/dist/os/windows-wrapper.js.map +0 -1
  642. package/dist/os/windows.d.ts.map +0 -1
  643. package/dist/os/windows.js.map +0 -1
  644. package/dist/paths.d.ts.map +0 -1
  645. package/dist/paths.js.map +0 -1
  646. package/dist/providers/agy.d.ts.map +0 -1
  647. package/dist/providers/agy.js.map +0 -1
  648. package/dist/providers/claude.d.ts.map +0 -1
  649. package/dist/providers/claude.js.map +0 -1
  650. package/dist/providers/codex.d.ts.map +0 -1
  651. package/dist/providers/codex.js.map +0 -1
  652. package/dist/providers/copilot.d.ts.map +0 -1
  653. package/dist/providers/copilot.js.map +0 -1
  654. package/dist/providers/email/headers.d.ts.map +0 -1
  655. package/dist/providers/email/headers.js.map +0 -1
  656. package/dist/providers/email/index.d.ts.map +0 -1
  657. package/dist/providers/email/index.js.map +0 -1
  658. package/dist/providers/email/provider.d.ts.map +0 -1
  659. package/dist/providers/email/provider.js.map +0 -1
  660. package/dist/providers/email/sendgrid.d.ts.map +0 -1
  661. package/dist/providers/email/sendgrid.js.map +0 -1
  662. package/dist/providers/email/smtp.d.ts.map +0 -1
  663. package/dist/providers/email/smtp.js.map +0 -1
  664. package/dist/providers/index.d.ts.map +0 -1
  665. package/dist/providers/index.js.map +0 -1
  666. package/dist/providers/none.d.ts.map +0 -1
  667. package/dist/providers/none.js.map +0 -1
  668. package/dist/providers/opencode.d.ts.map +0 -1
  669. package/dist/providers/opencode.js.map +0 -1
  670. package/dist/providers/provider.d.ts.map +0 -1
  671. package/dist/providers/provider.js.map +0 -1
  672. package/dist/services/agent-provisioner.d.ts.map +0 -1
  673. package/dist/services/agent-provisioner.js.map +0 -1
  674. package/dist/services/agy-project.d.ts.map +0 -1
  675. package/dist/services/agy-project.js.map +0 -1
  676. package/dist/services/auth-socket.d.ts.map +0 -1
  677. package/dist/services/auth-socket.js.map +0 -1
  678. package/dist/services/auth-web.d.ts.map +0 -1
  679. package/dist/services/auth-web.js.map +0 -1
  680. package/dist/services/budget-awareness.d.ts.map +0 -1
  681. package/dist/services/budget-awareness.js.map +0 -1
  682. package/dist/services/cloud/activity.d.ts.map +0 -1
  683. package/dist/services/cloud/activity.js.map +0 -1
  684. package/dist/services/cloud/aws.d.ts.map +0 -1
  685. package/dist/services/cloud/aws.js.map +0 -1
  686. package/dist/services/cloud/cost.d.ts.map +0 -1
  687. package/dist/services/cloud/cost.js.map +0 -1
  688. package/dist/services/cloud/idle-manager.d.ts.map +0 -1
  689. package/dist/services/cloud/idle-manager.js.map +0 -1
  690. package/dist/services/cloud/lifecycle.d.ts.map +0 -1
  691. package/dist/services/cloud/lifecycle.js.map +0 -1
  692. package/dist/services/cloud/task-wrapper.d.ts.map +0 -1
  693. package/dist/services/cloud/task-wrapper.js.map +0 -1
  694. package/dist/services/cloud/types.d.ts.map +0 -1
  695. package/dist/services/cloud/types.js.map +0 -1
  696. package/dist/services/cloud-sync.d.ts.map +0 -1
  697. package/dist/services/cloud-sync.js.map +0 -1
  698. package/dist/services/context-admission.d.ts.map +0 -1
  699. package/dist/services/context-admission.js.map +0 -1
  700. package/dist/services/credential-cleanup.d.ts.map +0 -1
  701. package/dist/services/credential-cleanup.js.map +0 -1
  702. package/dist/services/credential-store.d.ts.map +0 -1
  703. package/dist/services/credential-store.js.map +0 -1
  704. package/dist/services/event-bus.d.ts.map +0 -1
  705. package/dist/services/event-bus.js.map +0 -1
  706. package/dist/services/exit-drain.d.ts.map +0 -1
  707. package/dist/services/exit-drain.js.map +0 -1
  708. package/dist/services/file-chunker.d.ts.map +0 -1
  709. package/dist/services/file-chunker.js.map +0 -1
  710. package/dist/services/file-transfer-relay.d.ts.map +0 -1
  711. package/dist/services/file-transfer-relay.js.map +0 -1
  712. package/dist/services/file-transfer.d.ts.map +0 -1
  713. package/dist/services/file-transfer.js.map +0 -1
  714. package/dist/services/git-config.d.ts.map +0 -1
  715. package/dist/services/git-config.js.map +0 -1
  716. package/dist/services/github-app.d.ts.map +0 -1
  717. package/dist/services/github-app.js.map +0 -1
  718. package/dist/services/http-transport.d.ts.map +0 -1
  719. package/dist/services/http-transport.js.map +0 -1
  720. package/dist/services/hub-client.d.ts.map +0 -1
  721. package/dist/services/hub-client.js.map +0 -1
  722. package/dist/services/icons.d.ts.map +0 -1
  723. package/dist/services/icons.js.map +0 -1
  724. package/dist/services/jwt.d.ts.map +0 -1
  725. package/dist/services/jwt.js.map +0 -1
  726. package/dist/services/knowledge/audn.d.ts.map +0 -1
  727. package/dist/services/knowledge/audn.js.map +0 -1
  728. package/dist/services/knowledge/file-hash.d.ts.map +0 -1
  729. package/dist/services/knowledge/file-hash.js.map +0 -1
  730. package/dist/services/knowledge/http-provider.d.ts.map +0 -1
  731. package/dist/services/knowledge/http-provider.js.map +0 -1
  732. package/dist/services/knowledge/kb-config.d.ts.map +0 -1
  733. package/dist/services/knowledge/kb-config.js.map +0 -1
  734. package/dist/services/knowledge/kb-providers.d.ts.map +0 -1
  735. package/dist/services/knowledge/kb-providers.js.map +0 -1
  736. package/dist/services/knowledge/kb-scope-input.d.ts +0 -5
  737. package/dist/services/knowledge/kb-scope-input.d.ts.map +0 -1
  738. package/dist/services/knowledge/kb-scope-input.js +0 -11
  739. package/dist/services/knowledge/kb-scope-input.js.map +0 -1
  740. package/dist/services/knowledge/kb-service.d.ts.map +0 -1
  741. package/dist/services/knowledge/kb-service.js.map +0 -1
  742. package/dist/services/knowledge/path-validation.d.ts.map +0 -1
  743. package/dist/services/knowledge/path-validation.js.map +0 -1
  744. package/dist/services/knowledge/pre-init.d.ts.map +0 -1
  745. package/dist/services/knowledge/pre-init.js.map +0 -1
  746. package/dist/services/knowledge/project-slug.d.ts.map +0 -1
  747. package/dist/services/knowledge/project-slug.js.map +0 -1
  748. package/dist/services/knowledge/require-sqlite-project.d.ts.map +0 -1
  749. package/dist/services/knowledge/require-sqlite-project.js.map +0 -1
  750. package/dist/services/knowledge/sqlite-provider.d.ts.map +0 -1
  751. package/dist/services/knowledge/sqlite-provider.js.map +0 -1
  752. package/dist/services/knowledge/types.d.ts.map +0 -1
  753. package/dist/services/knowledge/types.js.map +0 -1
  754. package/dist/services/known-hosts.d.ts.map +0 -1
  755. package/dist/services/known-hosts.js.map +0 -1
  756. package/dist/services/known-sessions.d.ts.map +0 -1
  757. package/dist/services/known-sessions.js.map +0 -1
  758. package/dist/services/member-home.d.ts.map +0 -1
  759. package/dist/services/member-home.js.map +0 -1
  760. package/dist/services/member-remote-url.d.ts.map +0 -1
  761. package/dist/services/member-remote-url.js.map +0 -1
  762. package/dist/services/model-pricing.d.ts.map +0 -1
  763. package/dist/services/model-pricing.js.map +0 -1
  764. package/dist/services/onboarding.d.ts.map +0 -1
  765. package/dist/services/onboarding.js.map +0 -1
  766. package/dist/services/orphan-recovery.d.ts.map +0 -1
  767. package/dist/services/orphan-recovery.js.map +0 -1
  768. package/dist/services/pending-responses.d.ts.map +0 -1
  769. package/dist/services/pending-responses.js.map +0 -1
  770. package/dist/services/preflight-check.d.ts.map +0 -1
  771. package/dist/services/preflight-check.js.map +0 -1
  772. package/dist/services/registry.d.ts.map +0 -1
  773. package/dist/services/registry.js.map +0 -1
  774. package/dist/services/relay-context.d.ts.map +0 -1
  775. package/dist/services/relay-context.js.map +0 -1
  776. package/dist/services/relay-executor.d.ts.map +0 -1
  777. package/dist/services/relay-executor.js.map +0 -1
  778. package/dist/services/relay-request.d.ts.map +0 -1
  779. package/dist/services/relay-request.js.map +0 -1
  780. package/dist/services/relay-strategy.d.ts.map +0 -1
  781. package/dist/services/relay-strategy.js.map +0 -1
  782. package/dist/services/secret-token.d.ts.map +0 -1
  783. package/dist/services/secret-token.js.map +0 -1
  784. package/dist/services/service-manager/index.d.ts.map +0 -1
  785. package/dist/services/service-manager/index.js.map +0 -1
  786. package/dist/services/service-manager/linux.d.ts.map +0 -1
  787. package/dist/services/service-manager/linux.js.map +0 -1
  788. package/dist/services/service-manager/macos.d.ts.map +0 -1
  789. package/dist/services/service-manager/macos.js.map +0 -1
  790. package/dist/services/service-manager/types.d.ts.map +0 -1
  791. package/dist/services/service-manager/types.js.map +0 -1
  792. package/dist/services/service-manager/windows.d.ts.map +0 -1
  793. package/dist/services/service-manager/windows.js.map +0 -1
  794. package/dist/services/session-registry.d.ts.map +0 -1
  795. package/dist/services/session-registry.js.map +0 -1
  796. package/dist/services/sftp.d.ts.map +0 -1
  797. package/dist/services/sftp.js.map +0 -1
  798. package/dist/services/shell-probe.d.ts.map +0 -1
  799. package/dist/services/shell-probe.js.map +0 -1
  800. package/dist/services/singleton.d.ts.map +0 -1
  801. package/dist/services/singleton.js.map +0 -1
  802. package/dist/services/sprint-coordination.d.ts.map +0 -1
  803. package/dist/services/sprint-coordination.js.map +0 -1
  804. package/dist/services/ssh.d.ts.map +0 -1
  805. package/dist/services/ssh.js.map +0 -1
  806. package/dist/services/stall/find-log-file.d.ts.map +0 -1
  807. package/dist/services/stall/find-log-file.js.map +0 -1
  808. package/dist/services/stall/index.d.ts.map +0 -1
  809. package/dist/services/stall/index.js.map +0 -1
  810. package/dist/services/stall/log-path-resolver.d.ts.map +0 -1
  811. package/dist/services/stall/log-path-resolver.js.map +0 -1
  812. package/dist/services/stall/read-log-tail.d.ts.map +0 -1
  813. package/dist/services/stall/read-log-tail.js.map +0 -1
  814. package/dist/services/stall/stall-detector.d.ts.map +0 -1
  815. package/dist/services/stall/stall-detector.js.map +0 -1
  816. package/dist/services/stall/stall-poller.d.ts.map +0 -1
  817. package/dist/services/stall/stall-poller.js.map +0 -1
  818. package/dist/services/stall/time-utils.d.ts.map +0 -1
  819. package/dist/services/stall/time-utils.js.map +0 -1
  820. package/dist/services/statusline.d.ts.map +0 -1
  821. package/dist/services/statusline.js.map +0 -1
  822. package/dist/services/strategy.d.ts.map +0 -1
  823. package/dist/services/strategy.js.map +0 -1
  824. package/dist/services/substitution-engine.d.ts.map +0 -1
  825. package/dist/services/substitution-engine.js.map +0 -1
  826. package/dist/services/task-cleanup.d.ts.map +0 -1
  827. package/dist/services/task-cleanup.js.map +0 -1
  828. package/dist/services/token-issuer.d.ts.map +0 -1
  829. package/dist/services/token-issuer.js.map +0 -1
  830. package/dist/services/tool-registry.d.ts.map +0 -1
  831. package/dist/services/tool-registry.js.map +0 -1
  832. package/dist/services/update-check.d.ts.map +0 -1
  833. package/dist/services/update-check.js.map +0 -1
  834. package/dist/services/user-config.d.ts.map +0 -1
  835. package/dist/services/user-config.js.map +0 -1
  836. package/dist/services/vcs/azure-devops.d.ts.map +0 -1
  837. package/dist/services/vcs/azure-devops.js.map +0 -1
  838. package/dist/services/vcs/bitbucket.d.ts.map +0 -1
  839. package/dist/services/vcs/bitbucket.js.map +0 -1
  840. package/dist/services/vcs/constants.d.ts.map +0 -1
  841. package/dist/services/vcs/constants.js.map +0 -1
  842. package/dist/services/vcs/github.d.ts.map +0 -1
  843. package/dist/services/vcs/github.js.map +0 -1
  844. package/dist/services/vcs/types.d.ts.map +0 -1
  845. package/dist/services/vcs/types.js.map +0 -1
  846. package/dist/services/version-check.d.ts.map +0 -1
  847. package/dist/services/version-check.js.map +0 -1
  848. package/dist/services/watch/fleet-log.d.ts.map +0 -1
  849. package/dist/services/watch/fleet-log.js.map +0 -1
  850. package/dist/services/watch/project-resolver.d.ts.map +0 -1
  851. package/dist/services/watch/project-resolver.js.map +0 -1
  852. package/dist/services/watch/transcript-formatter.d.ts.map +0 -1
  853. package/dist/services/watch/transcript-formatter.js.map +0 -1
  854. package/dist/smoke-test.d.ts.map +0 -1
  855. package/dist/smoke-test.js.map +0 -1
  856. package/dist/tools/check-status.d.ts.map +0 -1
  857. package/dist/tools/check-status.js.map +0 -1
  858. package/dist/tools/child-id-allocator.d.ts.map +0 -1
  859. package/dist/tools/child-id-allocator.js.map +0 -1
  860. package/dist/tools/cloud-control.d.ts.map +0 -1
  861. package/dist/tools/cloud-control.js.map +0 -1
  862. package/dist/tools/code-intelligence-codebase-memory.d.ts.map +0 -1
  863. package/dist/tools/code-intelligence-codebase-memory.js.map +0 -1
  864. package/dist/tools/code-intelligence-freshness.d.ts.map +0 -1
  865. package/dist/tools/code-intelligence-freshness.js.map +0 -1
  866. package/dist/tools/code-intelligence-gitnexus.d.ts.map +0 -1
  867. package/dist/tools/code-intelligence-gitnexus.js.map +0 -1
  868. package/dist/tools/code-intelligence-kb-enrich.d.ts.map +0 -1
  869. package/dist/tools/code-intelligence-kb-enrich.js.map +0 -1
  870. package/dist/tools/code-intelligence-reindex.d.ts.map +0 -1
  871. package/dist/tools/code-intelligence-reindex.js.map +0 -1
  872. package/dist/tools/code-intelligence-telemetry.d.ts.map +0 -1
  873. package/dist/tools/code-intelligence-telemetry.js.map +0 -1
  874. package/dist/tools/code-intelligence-tests.d.ts.map +0 -1
  875. package/dist/tools/code-intelligence-tests.js.map +0 -1
  876. package/dist/tools/code-intelligence.d.ts.map +0 -1
  877. package/dist/tools/code-intelligence.js.map +0 -1
  878. package/dist/tools/compose-permissions.d.ts.map +0 -1
  879. package/dist/tools/compose-permissions.js.map +0 -1
  880. package/dist/tools/credential-store-delete.d.ts.map +0 -1
  881. package/dist/tools/credential-store-delete.js.map +0 -1
  882. package/dist/tools/credential-store-list.d.ts.map +0 -1
  883. package/dist/tools/credential-store-list.js.map +0 -1
  884. package/dist/tools/credential-store-set.d.ts.map +0 -1
  885. package/dist/tools/credential-store-set.js.map +0 -1
  886. package/dist/tools/credential-store-update.d.ts.map +0 -1
  887. package/dist/tools/credential-store-update.js.map +0 -1
  888. package/dist/tools/dolt-push-mutex.d.ts.map +0 -1
  889. package/dist/tools/dolt-push-mutex.js.map +0 -1
  890. package/dist/tools/execute-command.d.ts.map +0 -1
  891. package/dist/tools/execute-command.js.map +0 -1
  892. package/dist/tools/execute-prompt.d.ts.map +0 -1
  893. package/dist/tools/execute-prompt.js.map +0 -1
  894. package/dist/tools/get-member-model-pricing.d.ts.map +0 -1
  895. package/dist/tools/get-member-model-pricing.js.map +0 -1
  896. package/dist/tools/kb-capture.d.ts.map +0 -1
  897. package/dist/tools/kb-capture.js.map +0 -1
  898. package/dist/tools/kb-context.d.ts.map +0 -1
  899. package/dist/tools/kb-context.js.map +0 -1
  900. package/dist/tools/kb-export.d.ts.map +0 -1
  901. package/dist/tools/kb-export.js.map +0 -1
  902. package/dist/tools/kb-feedback.d.ts.map +0 -1
  903. package/dist/tools/kb-feedback.js.map +0 -1
  904. package/dist/tools/kb-freshness-sweep.d.ts.map +0 -1
  905. package/dist/tools/kb-freshness-sweep.js.map +0 -1
  906. package/dist/tools/kb-harvest.d.ts.map +0 -1
  907. package/dist/tools/kb-harvest.js.map +0 -1
  908. package/dist/tools/kb-import.d.ts.map +0 -1
  909. package/dist/tools/kb-import.js.map +0 -1
  910. package/dist/tools/kb-invalidate.d.ts.map +0 -1
  911. package/dist/tools/kb-invalidate.js.map +0 -1
  912. package/dist/tools/kb-list.d.ts.map +0 -1
  913. package/dist/tools/kb-list.js.map +0 -1
  914. package/dist/tools/kb-promote.d.ts.map +0 -1
  915. package/dist/tools/kb-promote.js.map +0 -1
  916. package/dist/tools/kb-query.d.ts.map +0 -1
  917. package/dist/tools/kb-query.js.map +0 -1
  918. package/dist/tools/kb-reconcile-prefilter.d.ts.map +0 -1
  919. package/dist/tools/kb-reconcile-prefilter.js.map +0 -1
  920. package/dist/tools/kb-resolve-contradiction.d.ts.map +0 -1
  921. package/dist/tools/kb-resolve-contradiction.js.map +0 -1
  922. package/dist/tools/kb-session-prime.d.ts.map +0 -1
  923. package/dist/tools/kb-session-prime.js.map +0 -1
  924. package/dist/tools/kb-setup.d.ts.map +0 -1
  925. package/dist/tools/kb-setup.js.map +0 -1
  926. package/dist/tools/kb-stats.d.ts.map +0 -1
  927. package/dist/tools/kb-stats.js.map +0 -1
  928. package/dist/tools/list-members.d.ts.map +0 -1
  929. package/dist/tools/list-members.js.map +0 -1
  930. package/dist/tools/member-detail.d.ts.map +0 -1
  931. package/dist/tools/member-detail.js.map +0 -1
  932. package/dist/tools/member-reservation.d.ts.map +0 -1
  933. package/dist/tools/member-reservation.js.map +0 -1
  934. package/dist/tools/monitor-task.d.ts.map +0 -1
  935. package/dist/tools/monitor-task.js.map +0 -1
  936. package/dist/tools/provision-auth.d.ts.map +0 -1
  937. package/dist/tools/provision-auth.js.map +0 -1
  938. package/dist/tools/provision-vcs-auth.d.ts.map +0 -1
  939. package/dist/tools/provision-vcs-auth.js.map +0 -1
  940. package/dist/tools/receive-files.d.ts.map +0 -1
  941. package/dist/tools/receive-files.js.map +0 -1
  942. package/dist/tools/register-member.d.ts.map +0 -1
  943. package/dist/tools/register-member.js.map +0 -1
  944. package/dist/tools/remove-member.d.ts.map +0 -1
  945. package/dist/tools/remove-member.js.map +0 -1
  946. package/dist/tools/report-status.d.ts.map +0 -1
  947. package/dist/tools/report-status.js.map +0 -1
  948. package/dist/tools/respond-to-message.d.ts.map +0 -1
  949. package/dist/tools/respond-to-message.js.map +0 -1
  950. package/dist/tools/revoke-vcs-auth.d.ts.map +0 -1
  951. package/dist/tools/revoke-vcs-auth.js.map +0 -1
  952. package/dist/tools/send-email.d.ts.map +0 -1
  953. package/dist/tools/send-email.js.map +0 -1
  954. package/dist/tools/send-files.d.ts.map +0 -1
  955. package/dist/tools/send-files.js.map +0 -1
  956. package/dist/tools/send-message.d.ts.map +0 -1
  957. package/dist/tools/send-message.js.map +0 -1
  958. package/dist/tools/setup-git-app.d.ts.map +0 -1
  959. package/dist/tools/setup-git-app.js.map +0 -1
  960. package/dist/tools/setup-ssh-key.d.ts.map +0 -1
  961. package/dist/tools/setup-ssh-key.js.map +0 -1
  962. package/dist/tools/shutdown-server.d.ts.map +0 -1
  963. package/dist/tools/shutdown-server.js.map +0 -1
  964. package/dist/tools/stop-prompt.d.ts.map +0 -1
  965. package/dist/tools/stop-prompt.js.map +0 -1
  966. package/dist/tools/update-agent-cli.d.ts.map +0 -1
  967. package/dist/tools/update-agent-cli.js.map +0 -1
  968. package/dist/tools/update-member.d.ts.map +0 -1
  969. package/dist/tools/update-member.js.map +0 -1
  970. package/dist/tools/vcs-credential-exec.d.ts.map +0 -1
  971. package/dist/tools/vcs-credential-exec.js.map +0 -1
  972. package/dist/tools/version.d.ts.map +0 -1
  973. package/dist/tools/version.js.map +0 -1
  974. package/dist/types.d.ts.map +0 -1
  975. package/dist/types.js.map +0 -1
  976. package/dist/utils/agent-helpers.d.ts.map +0 -1
  977. package/dist/utils/agent-helpers.js.map +0 -1
  978. package/dist/utils/ansi.d.ts.map +0 -1
  979. package/dist/utils/ansi.js.map +0 -1
  980. package/dist/utils/auth-env.d.ts.map +0 -1
  981. package/dist/utils/auth-env.js.map +0 -1
  982. package/dist/utils/collect-secret.d.ts.map +0 -1
  983. package/dist/utils/collect-secret.js.map +0 -1
  984. package/dist/utils/credential-validation.d.ts.map +0 -1
  985. package/dist/utils/credential-validation.js.map +0 -1
  986. package/dist/utils/crypto.d.ts.map +0 -1
  987. package/dist/utils/crypto.js.map +0 -1
  988. package/dist/utils/deep-merge.d.ts.map +0 -1
  989. package/dist/utils/deep-merge.js.map +0 -1
  990. package/dist/utils/file-permissions.d.ts.map +0 -1
  991. package/dist/utils/file-permissions.js.map +0 -1
  992. package/dist/utils/gpu-parser.d.ts.map +0 -1
  993. package/dist/utils/gpu-parser.js.map +0 -1
  994. package/dist/utils/log-helpers.d.ts.map +0 -1
  995. package/dist/utils/log-helpers.js.map +0 -1
  996. package/dist/utils/oob-timeout.d.ts.map +0 -1
  997. package/dist/utils/oob-timeout.js.map +0 -1
  998. package/dist/utils/opencode-model-validation.d.ts.map +0 -1
  999. package/dist/utils/opencode-model-validation.js.map +0 -1
  1000. package/dist/utils/pid-helpers.d.ts.map +0 -1
  1001. package/dist/utils/pid-helpers.js.map +0 -1
  1002. package/dist/utils/platform.d.ts.map +0 -1
  1003. package/dist/utils/platform.js.map +0 -1
  1004. package/dist/utils/process-utils.d.ts.map +0 -1
  1005. package/dist/utils/process-utils.js.map +0 -1
  1006. package/dist/utils/prompt-errors.d.ts.map +0 -1
  1007. package/dist/utils/prompt-errors.js.map +0 -1
  1008. package/dist/utils/resolve-member.d.ts.map +0 -1
  1009. package/dist/utils/resolve-member.js.map +0 -1
  1010. package/dist/utils/secure-input.d.ts.map +0 -1
  1011. package/dist/utils/secure-input.js.map +0 -1
  1012. package/dist/utils/session-caller.d.ts.map +0 -1
  1013. package/dist/utils/session-caller.js.map +0 -1
  1014. package/dist/utils/shell-escape.d.ts.map +0 -1
  1015. package/dist/utils/shell-escape.js.map +0 -1
  1016. package/dist/utils/skill-matrix.d.ts.map +0 -1
  1017. package/dist/utils/skill-matrix.js.map +0 -1
  1018. package/dist/utils/ssh-error-messages.d.ts.map +0 -1
  1019. package/dist/utils/ssh-error-messages.js.map +0 -1
  1020. package/dist/utils/vcs-provider-detect.d.ts.map +0 -1
  1021. package/dist/utils/vcs-provider-detect.js.map +0 -1
  1022. package/dist/utils/work-folder-validation.d.ts.map +0 -1
  1023. package/dist/utils/work-folder-validation.js.map +0 -1
  1024. package/dist/utils/workspace-trust.d.ts.map +0 -1
  1025. package/dist/utils/workspace-trust.js.map +0 -1
  1026. package/dist/version.d.ts.map +0 -1
  1027. 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.
53
- *
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.
61
- *
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).
59
+ * The injection rule for every engine-built knowledge block: only CONFIRMED
60
+ * entries that sit outside any unresolved contradiction reach a role prompt.
61
+ * INFERRED/UNVERIFIED entries are the sprint's own unreviewed captures, and a
62
+ * flagged or contradiction_of entry is one the KB itself says is disputed --
63
+ * neither is knowledge a role should build on without checking.
64
+ *
65
+ * kb_query is ASKED for exactly this set (confidence + exclude_disputed), but
66
+ * the engine re-applies it on every path regardless: an older fleet server
67
+ * ignores the unknown params, kb_session_prime has no such filter, and a
68
+ * hand-edited bible can carry anything. Defense in depth, not duplication.
69
+ *
70
+ * @param {object} e
71
+ * @returns {boolean}
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);
@@ -109,6 +119,7 @@ export function vetKbWork(role, result) {
109
119
  const captures = [];
110
120
  const promotions = [];
111
121
  const refused = [];
122
+ const demotions = [];
112
123
 
113
124
  const rawCaptures = (result && Array.isArray(result.kb_captures)) ? result.kb_captures : [];
114
125
  for (const c of rawCaptures) {
@@ -158,29 +169,477 @@ export function vetKbWork(role, result) {
158
169
  }
159
170
  }
160
171
 
161
- return { captures, promotions, refused };
172
+ // kb_discards: the reviewer's DISCARD judgement on a promotion candidate.
173
+ // Same role gate and evidence bar as kb_promotions -- a discard removes an
174
+ // entry from every read, so it is no less consequential than a promotion.
175
+ const discards = [];
176
+ const rawDiscards = (result && Array.isArray(result.kb_discards)) ? result.kb_discards : [];
177
+ if (rawDiscards.length > 0 && !KB_PROMOTER_ROLES.has(role)) {
178
+ refused.push(`${role}: kb_discards refused -- discard is reviewer-only`);
179
+ } else {
180
+ for (const d of rawDiscards) {
181
+ if (!d || typeof d.id !== 'string' || d.id.length === 0) {
182
+ refused.push(`${role}: discard missing id`);
183
+ continue;
184
+ }
185
+ if (typeof d.reason !== 'string' || d.reason.trim().length < KB_MIN_PROMOTE_REASON) {
186
+ refused.push(`${role}: discard ${d.id} has no recorded evidence`);
187
+ continue;
188
+ }
189
+ discards.push({ id: d.id, reason: d.reason.trim() });
190
+ }
191
+ }
192
+
193
+ // kb_demotions: the reviewer's DEMOTE judgement -- a CONFIRMED entry a
194
+ // re-check shows does not hold (less certain, or shown wrong), sent back to
195
+ // INFERRED. Same role gate and reason bar as kb_promotions
196
+ // and kb_discards, plus at least one evidence file: kb_demote refuses a
197
+ // demotion without one, so it is refused here before any call.
198
+ const rawDemotions = (result && Array.isArray(result.kb_demotions)) ? result.kb_demotions : [];
199
+ if (rawDemotions.length > 0 && !KB_PROMOTER_ROLES.has(role)) {
200
+ refused.push(`${role}: kb_demotions refused -- demotion is reviewer-only`);
201
+ } else {
202
+ for (const d of rawDemotions) {
203
+ if (!d || typeof d.id !== 'string' || d.id.length === 0) {
204
+ refused.push(`${role}: demotion missing id`);
205
+ continue;
206
+ }
207
+ if (typeof d.reason !== 'string' || d.reason.trim().length < KB_MIN_PROMOTE_REASON) {
208
+ refused.push(`${role}: demotion ${d.id} has no recorded evidence`);
209
+ continue;
210
+ }
211
+ const evidenceFiles = Array.isArray(d.evidence_files)
212
+ ? d.evidence_files.filter((f) => typeof f === 'string' && f.length > 0)
213
+ : [];
214
+ if (evidenceFiles.length === 0) {
215
+ refused.push(`${role}: demotion ${d.id} names no evidence file`);
216
+ continue;
217
+ }
218
+ demotions.push({ id: d.id, reason: d.reason.trim(), evidence_files: evidenceFiles });
219
+ }
220
+ }
221
+
222
+ // One output may not judge the same entry more than one way: an id in
223
+ // more than one of kb_promotions, kb_discards and kb_demotions is refused
224
+ // in EVERY list it appears in, with a refusal logged per side naming the
225
+ // other judgements. The pre-existing two-way promote/discard behaviour is
226
+ // preserved exactly for the cases it already covered.
227
+ const promotionIds = new Set(promotions.map((p) => p.id));
228
+ const discardIds = new Set(discards.map((d) => d.id));
229
+ const demotionIds = new Set(demotions.map((d) => d.id));
230
+ const conflicted = new Set();
231
+ for (const id of promotionIds) if (discardIds.has(id) || demotionIds.has(id)) conflicted.add(id);
232
+ for (const id of discardIds) if (promotionIds.has(id) || demotionIds.has(id)) conflicted.add(id);
233
+ for (const id of demotionIds) if (promotionIds.has(id) || discardIds.has(id)) conflicted.add(id);
234
+
235
+ const otherSidesFor = (id, excludeKind) => {
236
+ const sides = [];
237
+ if (excludeKind !== 'promotion' && promotionIds.has(id)) sides.push('promotes');
238
+ if (excludeKind !== 'discard' && discardIds.has(id)) sides.push('discards');
239
+ if (excludeKind !== 'demotion' && demotionIds.has(id)) sides.push('demotes');
240
+ return sides;
241
+ };
242
+ for (const p of promotions) {
243
+ if (conflicted.has(p.id)) refused.push(`${role}: promotion ${p.id} refused -- the same output also ${otherSidesFor(p.id, 'promotion').join(' and ')} it (promote reason: ${p.reason})`);
244
+ }
245
+ for (const d of discards) {
246
+ if (conflicted.has(d.id)) refused.push(`${role}: discard ${d.id} refused -- the same output also ${otherSidesFor(d.id, 'discard').join(' and ')} it (discard reason: ${d.reason})`);
247
+ }
248
+ for (const d of demotions) {
249
+ if (conflicted.has(d.id)) refused.push(`${role}: demotion ${d.id} refused -- the same output also ${otherSidesFor(d.id, 'demotion').join(' and ')} it (demote reason: ${d.reason})`);
250
+ }
251
+
252
+ return {
253
+ captures,
254
+ promotions: promotions.filter((p) => !conflicted.has(p.id)),
255
+ discards: discards.filter((d) => !conflicted.has(d.id)),
256
+ demotions: demotions.filter((d) => !conflicted.has(d.id)),
257
+ refused,
258
+ };
162
259
  }
163
260
 
164
261
  /** Max promotion candidates offered to one reviewer, so the prompt stays bounded. */
165
262
  export const KB_MAX_PROMOTION_CANDIDATES = 40;
166
263
 
264
+ /** Max demotion candidates offered to one reviewer, so the prompt stays bounded. */
265
+ export const KB_MAX_DEMOTION_CANDIDATES = 20;
266
+
267
+ /**
268
+ * How many owned CONFIRMED rows the demotion-candidate READ asks for, which is
269
+ * deliberately NOT the offer cap above.
270
+ *
271
+ * The cap is an OFFER cap -- how much of this prompt the candidate block may
272
+ * occupy. Using it as the read limit instead makes it a PRE-filter: a
273
+ * maintainer holding more owned CONFIRMED rows than the cap has an arbitrary
274
+ * 20 of them fetched, and the eligibility/changed-file filters then run over
275
+ * that arbitrary slice, so a genuinely relevant entry can be truncated away
276
+ * before anything ever looks at whether it is relevant. Read wide, filter,
277
+ * THEN cap.
278
+ */
279
+ export const KB_DEMOTION_READ_LIMIT = 500;
280
+
281
+ /**
282
+ * The EXACT kb_query arguments demotionCandidates issues, as a standalone
283
+ * pure function so the real read path can be exercised end-to-end against a
284
+ * real member session (tests/knowledge/) rather than only against a fake that
285
+ * re-states these arguments and therefore cannot catch them being wrong.
286
+ *
287
+ * Every field is load-bearing, and the previous shape of this read returned
288
+ * nothing in a real sprint:
289
+ *
290
+ * - `own_scope: true` is the whole fix. In a MEMBER session getSelfReadKb
291
+ * routes any read that does not explicitly name INFERRED/UNVERIFIED to the
292
+ * member's CHECKOUT BIBLE VIEW, and bible-import.ts stamps every row of
293
+ * that view `tags: []` -- so a CONFIRMED read filtered by a member tag can
294
+ * never match anything, in any sprint. own_scope forces the PER-REPO DB
295
+ * with the caller's own ownerTag applied, which is exactly the row set
296
+ * kb_demote's ownerTag check can act on.
297
+ * - `tag` is still required: kb_query refuses a call carrying neither
298
+ * `query`, `tag` nor `flagged_only`, and this is a listing, not a search.
299
+ * It names the same member tag own_scope's server-side ownerTag applies.
300
+ * - `confidence: ['CONFIRMED']` -- kb_demote refuses anything else
301
+ * (E-DEMOTE-NOT-CONFIRMED).
302
+ * - `include_stale: true` and `exclude_disputed: false` ADMIT the rows most
303
+ * worth demoting. SqliteProvider.demote() documents a STALE entry as
304
+ * demotable on purpose (staleness is a freshness verdict; trust is a
305
+ * separate axis), and a contradiction-flagged row is likewise demotable.
306
+ * The default read drops both, which silently excluded the best
307
+ * candidates.
308
+ * - include_stale ALSO admits SUPERSEDED rows (kb_query maps the one input
309
+ * flag onto both provider options), and kb_demote refuses those
310
+ * (E-DEMOTE-SUPERSEDED) -- so the caller must drop them itself. See
311
+ * isDemotableCandidate below.
312
+ *
313
+ * @param {string} memberId the maintainer member uuid whose session the read runs in
314
+ * @returns {object} kb_query arguments
315
+ */
316
+ export function buildDemotionCandidateQuery(memberId) {
317
+ return {
318
+ tag: `member:${memberId}`,
319
+ own_scope: true,
320
+ confidence: ['CONFIRMED'],
321
+ include_stale: true,
322
+ exclude_disputed: false,
323
+ limit: KB_DEMOTION_READ_LIMIT,
324
+ };
325
+ }
326
+
327
+ /**
328
+ * Whether kb_demote would ACCEPT this entry from its owner's session -- the
329
+ * eligibility set read off SqliteProvider.demote()'s refusals rather than
330
+ * guessed at, so the reviewer is never offered an id that can only produce a
331
+ * refusal:
332
+ *
333
+ * superseded_at set -> E-DEMOTE-SUPERSEDED
334
+ * type user-directive -> E-DEMOTE-REFUSED-DIRECTIVE
335
+ * confidence != CONFIRMED -> E-DEMOTE-NOT-CONFIRMED
336
+ *
337
+ * Ownership ("Entry not found" for a row without the caller's member tag) is
338
+ * enforced by the read itself (own_scope's ownerTag), not re-checked here.
339
+ *
340
+ * NOT a refusal, and deliberately NOT filtered: `stale` and
341
+ * `flagged_for_review`/`contradiction_of`. demote() permits a stale entry
342
+ * explicitly and calls those the ones most worth demoting.
343
+ *
344
+ * @param {object} entry
345
+ * @returns {boolean}
346
+ */
347
+ export function isDemotableCandidate(entry) {
348
+ if (!entry || typeof entry.id !== 'string' || !entry.id) return false;
349
+ if (entry.confidence !== 'CONFIRMED') return false;
350
+ if (entry.type === 'user-directive') return false;
351
+ if (entry.superseded_at) return false;
352
+ return true;
353
+ }
354
+
355
+ /**
356
+ * D6 in-sprint ping-pong guard: true when `entry` was demoted DURING THIS
357
+ * SPRINT -- i.e. its `demoted_at` (an INFERRED entry's kb_query row carries
358
+ * this when it was ever demoted, per rowToEntry) falls at or after the
359
+ * sprint's start. `since` is the sprint start in ms
360
+ * (createKbWorkClient's sprintStartMs()); when it is null the guard cannot
361
+ * tell "this sprint" from "ever demoted", so it answers false -- the SAME
362
+ * permissive default promotionCandidates' own created_at window filter uses
363
+ * for an unknown sprint start, never a reason to exclude.
364
+ *
365
+ * @param {object} entry
366
+ * @param {number|null} since
367
+ * @returns {boolean}
368
+ */
369
+ export function wasDemotedThisSprint(entry, since) {
370
+ if (!entry || typeof entry.demoted_at !== 'string' || since === null) return false;
371
+ const t = Date.parse(entry.demoted_at);
372
+ return Number.isFinite(t) && t >= since;
373
+ }
374
+
375
+ /**
376
+ * D6 in-sprint ping-pong guard: true when EVERY file `basis` (an entry's
377
+ * demoted_basis_hashes snapshot, taken AS THE FILES WERE ON DISK AT DEMOTE
378
+ * TIME) cites still hashes, in `current` (this moment's re-read), to the
379
+ * SAME value -- i.e. nothing the demotion was based on has changed since.
380
+ *
381
+ * NEVER A MATCH -- so the entry stays offered rather than silently
382
+ * ping-ponged out forever on an unprovable basis -- when: `basis` is
383
+ * missing or empty (a legacy row, or one demoted before this snapshot
384
+ * existed); `current` is missing (the disk-hash callback was never wired,
385
+ * or its read failed); or any cited file is absent from `current` (deleted,
386
+ * unreadable, or moved outside the checkout). This mirrors
387
+ * isDemotableCandidate's own "never falsely suppress" rule for an
388
+ * unparseable basis.
389
+ *
390
+ * @param {Record<string,string>|undefined} basis
391
+ * @param {Record<string,string>|undefined} current
392
+ * @returns {boolean}
393
+ */
394
+ export function demotionBasisUnchanged(basis, current) {
395
+ const files = basis ? Object.keys(basis) : [];
396
+ if (files.length === 0 || !current) return false;
397
+ return files.every((f) => typeof current[f] === 'string' && current[f] === basis[f]);
398
+ }
399
+
400
+ /** Display label for a member record in log lines. */
401
+ function memberLabel(member) {
402
+ return (member && (member.name || member.id)) || 'unknown member';
403
+ }
404
+
405
+ /** The committed bible, relative to the maintainer's checkout root. */
406
+ const BIBLE_FILE = '.fleet/kb-canonical.json';
407
+
408
+ /**
409
+ * kb_bible_commit skip reasons the engine keeps queued: the cause can clear on
410
+ * its own (uncommitted edits, entries captured against commits the maintainer
411
+ * has not pulled yet), so the id is offered again at the next round. Every
412
+ * other reason (not_confirmed_or_unknown, no_source_files, or one this engine
413
+ * does not know) cannot change by retrying and drops the id.
414
+ */
415
+ const KB_RETRYABLE_SKIP_REASONS = Object.freeze(new Set(['basis_mismatch']));
416
+
417
+ /**
418
+ * How many bible-commit rounds in a row an id may be skipped with a retryable
419
+ * reason before it is dropped with a WARN, so a permanently drifted entry
420
+ * cannot sit in the queue forever.
421
+ */
422
+ export const KB_BIBLE_SKIP_RETRY_ROUNDS = 3;
423
+
424
+ /**
425
+ * memberCall error codes that mean the TOOL refused the call (the member was
426
+ * reached and answered). Every other coded error -- a connect failure, a
427
+ * send_files failure, an unparseable remote reply -- means the member could
428
+ * not be reached, so the write stays queued for a later attempt.
429
+ */
430
+ const KB_TOOL_REJECTION_CODES = Object.freeze(new Set(['E-TOOL', 'E-USAGE', 'E-ARGS-FILE', 'E-CALL']));
431
+
432
+ /** True when a thrown memberCall error means the member was unreachable. */
433
+ function isUnreachableError(err) {
434
+ return !!(err && typeof err.code === 'string' && err.code.length > 0 && !KB_TOOL_REJECTION_CODES.has(err.code));
435
+ }
436
+
437
+ /**
438
+ * The error codes a remote (http) KB provider throws for a write the server
439
+ * never handled, each with the reason the engine logs:
440
+ * - E-KB-HTTP-UNREACHABLE: the KB server cannot be reached, or refused the
441
+ * request before handling it (429, 503);
442
+ * - E-KB-HTTP-AUTH: the KB server token (a named secret) is missing,
443
+ * expired or refused; the identical write succeeds once it is fixed.
444
+ * The provider queues nothing, so the engine owns the retry: a write that
445
+ * fails with one of these stays queued for the next flush.
446
+ */
447
+ const KB_SERVER_KEEP_CODES = Object.freeze([
448
+ ['E-KB-HTTP-UNREACHABLE', 'KB server unreachable'],
449
+ ['E-KB-HTTP-AUTH', 'KB server token refused'],
450
+ ]);
451
+
452
+ /** The keep-queued reason when a kb_* tool's error text carries one of KB_SERVER_KEEP_CODES, else null. */
453
+ function kbServerKeepReason(text) {
454
+ if (typeof text !== 'string') return null;
455
+ for (const [code, reason] of KB_SERVER_KEEP_CODES) {
456
+ if (new RegExp(`(^|[^A-Z-])${code}\\b`).test(text)) return reason;
457
+ }
458
+ return null;
459
+ }
460
+
461
+ /** The member name a kb work call names (a member record or a bare name). */
462
+ function memberNameOf(member) {
463
+ if (typeof member === 'string') return member;
464
+ return (member && typeof member.name === 'string') ? member.name : null;
465
+ }
466
+
467
+ /**
468
+ * Every KB write for a repository goes through that repository's
469
+ * kb_maintainer (kb-maintainer.mjs), in the maintainer's MEMBER session --
470
+ * never through the member whose dispatch produced it, and never through the
471
+ * orchestrator's own session.
472
+ *
473
+ * - apply() vets a role's kb_captures / kb_promotions / kb_demotions, then
474
+ * QUEUES them per repository and flushes that repository's queue.
475
+ * - A flush runs the existing G-pull (opts.gPull -> git-sync's bracketed
476
+ * syncMemberBefore) on the maintainer BEFORE the batch, so the
477
+ * maintainer's checkout holds the files a capture cites and the KB's
478
+ * basis check passes. A G-pull failure means the maintainer is
479
+ * unreachable: the batch stays queued and a WARN is logged.
480
+ * - A maintainer that is mid-dispatch (it is usually also a doer) is BUSY:
481
+ * its repository's writes stay queued and are applied between its
482
+ * dispatches, never during one. runner.js reports the dispatch lifecycle
483
+ * through dispatchStarted()/dispatchEnded(); the end of a dispatch
484
+ * flushes whatever queued up behind it.
485
+ * - A capture from a member whose work folder is not a repository has no
486
+ * maintainer and is dropped with a WARN.
487
+ * - A write the maintainer cannot be reached for mid-batch is put back at
488
+ * the head of the queue: nothing is lost and nothing is silently dropped.
489
+ * The same holds when the maintainer answers but its remote KB server
490
+ * cannot be reached or refuses the request before handling it
491
+ * (E-KB-HTTP-UNREACHABLE), or refuses its token (E-KB-HTTP-AUTH): the
492
+ * http provider queues nothing, so the engine keeps the write and
493
+ * retries it next flush.
494
+ *
495
+ * The bible commit (commitRound): every promotion the maintainer applied is
496
+ * remembered per repository as a CONFIRMATION, and every successful demotion
497
+ * as a pending DEMOTION, both awaiting the bible. After each review round
498
+ * (reviewer, final reviewer, harvester) the engine calls commitRound(), which
499
+ * per repository with confirmations and/or demotions runs, on the
500
+ * maintainer: G-pull, kb_bible_commit {ids, demoted_ids, baseBranch,
501
+ * baseCommit}, G-push -- ids and demoted_ids are ALWAYS sent in the same
502
+ * call, so a round that both confirms and demotes entries makes exactly one
503
+ * kb_bible_commit call. baseBranch is the sprint's TARGET BASE branch and
504
+ * baseCommit the base commit the entries were verified against (opts.bibleBase
505
+ * resolves both on the maintainer). A rejected G-push is retried exactly
506
+ * once: abort any in-progress rebase, G-pull onto the new remote tip,
507
+ * kb_bible_commit again with the same ids and demoted_ids (it merges at entry
508
+ * level, so the concurrent change's entries survive with no manual merge) and
509
+ * G-push again. A second failure keeps the ids/demoted_ids queued for the
510
+ * next round with a WARN. When kb_bible_commit commits nothing
511
+ * (committed:false) the ids leave the queue only once origin is shown to hold
512
+ * the bible (opts.bibleUnpushed): an earlier round's bible commit still
513
+ * unpushed on the maintainer is G-pushed (same retry and reset guards), and
514
+ * an undecidable check keeps the ids queued with a WARN. After seal() (a FAIL
515
+ * verdict or an aborted sprint) nothing further is committed.
516
+ * An id kb_bible_commit skips with basis_mismatch stays queued and is offered
517
+ * again next round (the mismatch can be transient), for at most
518
+ * opts.bibleSkipRetryRounds (default KB_BIBLE_SKIP_RETRY_ROUNDS) skipped
519
+ * rounds in a row, then is dropped with a WARN naming it and the reason; any
520
+ * other skip reason drops the id at once. A skipped demotion
521
+ * (not_demoted_or_unknown) always leaves the queue: it never resolves itself
522
+ * without a new kb_demote.
523
+ *
524
+ * @param {{
525
+ * memberCall?: (member: object, name: string, args: object, opts?: { kbMaintainer?: boolean }) => Promise<any>,
526
+ * maintainers?: object|(() => object),
527
+ * gPull?: (memberName: string, options?: { resetToRemoteTip?: boolean }) => Promise<any>,
528
+ * gPush?: (memberName: string) => Promise<any>,
529
+ * abortRebase?: (memberName: string) => Promise<any>,
530
+ * bibleBase?: (memberName: string) => Promise<{ baseBranch: string, baseCommit: string }|null>,
531
+ * canResetCheckout?: (memberName: string, bibleFile: string) => Promise<{ safe: boolean, reason?: string }>,
532
+ * checkedOutBranch?: (memberName: string) => Promise<{ branch: string|null, sprintBranch: string|null }>,
533
+ * bibleUnpushed?: (memberName: string, bibleFile: string) => Promise<{ unpushed: boolean|null, reason?: string }>,
534
+ * unpushedOnlyBible?: (memberName: string, bibleFile: string) => Promise<{ onlyBible: boolean, reason?: string }>,
535
+ * roundChangedFiles?: (memberName: string) => Promise<string[]>,
536
+ * sprintChangedFiles?: (memberName: string) => Promise<string[]>,
537
+ * sprintStartMs?: number|(() => number),
538
+ * bibleSkipRetryRounds?: number,
539
+ * log?: Function,
540
+ * }} opts
541
+ */
542
+ /**
543
+ * memberCall options for a call made AS a repository's kb_maintainer: the
544
+ * session carries the kb_maintainer grant, so the server also serves it
545
+ * kb_promote, kb_resolve_contradiction and kb_reconcile_prefilter (see
546
+ * member-call.mjs).
547
+ */
548
+ export const KB_MAINTAINER_CALL = Object.freeze({ kbMaintainer: true });
549
+
167
550
  export function createKbWorkClient(opts = {}) {
168
- const { callTool, log = () => {}, remoteUrlFor } = opts;
169
- const active = typeof callTool === 'function';
551
+ const {
552
+ memberCall, gPull, gPush, abortRebase, bibleBase, canResetCheckout, checkedOutBranch, bibleUnpushed, unpushedOnlyBible,
553
+ // THIS REVIEW ROUND's changed-file set for
554
+ // demotionCandidates() -- (memberName: string) => Promise<string[]>.
555
+ // Injected rather than computed here because the fetch/fast-forward
556
+ // merge and the git diff are git operations kb.mjs has no access to
557
+ // (every kb_* call here goes through memberCall, never a shell); see
558
+ // runner.js's wiring for how this fetches, merges and diffs from the
559
+ // previous round's tip (never the cumulative sprint diff diffFiles
560
+ // computes for the KB-injection hint context -- that caller and
561
+ // promotionCandidates are both left unchanged).
562
+ roundChangedFiles,
563
+ // The CUMULATIVE sprint changed-file set (baseBranch...branch) for a
564
+ // demotionCandidates({ scope: 'sprint' }) read -- the FINAL review's
565
+ // scope, because final review judges the whole sprint diff and so has
566
+ // no "this round" to speak of. Injected for the same reason
567
+ // roundChangedFiles is (the fetch/merge and git diff are git
568
+ // operations kb.mjs has no access to), and kept a SEPARATE injection
569
+ // rather than a flag on one callback so which diff a scope means is
570
+ // decided once, in runner.js's wiring, instead of inside a git helper.
571
+ sprintChangedFiles,
572
+ // D6 in-sprint ping-pong guard's disk-hash read --
573
+ // (memberName: string, files: string[]) => Promise<Record<string, string>>,
574
+ // the CURRENT sha256 of each file in `files` on `memberName`'s own
575
+ // checkout (absent files are simply missing from the result, never a
576
+ // fabricated hash). Injected for the same reason roundChangedFiles is:
577
+ // kb.mjs has no shell/fs access of its own, and this is the one disk
578
+ // fact kb_query cannot answer -- demoted_basis_hashes (surfaced on an
579
+ // INFERRED entry's kb_query row) is a demote-TIME snapshot, not a live
580
+ // one. MUST hash the SAME way SqliteProvider's demoteBasisHashes does
581
+ // (plain sha256 of the raw bytes) so the two sides compare like for
582
+ // like; see promotionCandidates' guard below. Optional: when not
583
+ // wired, the guard degrades to "never exclude" (see
584
+ // demotionBasisUnchanged), never to a failed or wrongly-filtered read.
585
+ currentFileHashes,
586
+ log = () => {},
587
+ } = opts;
588
+ /** The sprint's start time (ms since epoch) from the sprint state, or null when unknown. */
589
+ const sprintStartMs = () => {
590
+ const v = typeof opts.sprintStartMs === 'function' ? opts.sprintStartMs() : opts.sprintStartMs;
591
+ return (typeof v === 'number' && Number.isFinite(v)) ? v : null;
592
+ };
593
+ const active = typeof memberCall === 'function';
594
+ // Reviewer demotion loop switch (sprint arg kb_demotion_loop, CLI
595
+ // --kb-demotion-loop): 'on' (default when absent) or 'off'. Any other value
596
+ // fails loudly rather than silently falling back to a default.
597
+ const demotionLoopSetting = opts.demotionLoop === undefined ? 'on' : opts.demotionLoop;
598
+ if (demotionLoopSetting !== 'on' && demotionLoopSetting !== 'off') {
599
+ throw new Error(`[kb-work] Invalid demotionLoop ${JSON.stringify(demotionLoopSetting)}: must be 'on' (default) or 'off'.`);
600
+ }
601
+ const demotionLoopOn = demotionLoopSetting === 'on';
602
+
603
+ /** The kb_maintainer selector (createKbMaintainerSelector), or null. */
604
+ function selector() {
605
+ const m = typeof opts.maintainers === 'function' ? opts.maintainers() : opts.maintainers;
606
+ return (m && typeof m.maintainerForMember === 'function') ? m : null;
607
+ }
170
608
 
609
+ /** repo -> queued writes, oldest first: { kind, role, payload }. */
610
+ const queues = new Map();
611
+ /** repo -> Set of candidate ids the latest promotionCandidates() call offered. */
612
+ const offeredCandidates = new Map();
613
+ /** repo -> Set of candidate ids the latest demotionCandidates() call offered. */
614
+ const offeredDemotions = new Map();
615
+ /** repo -> tail of the serialized flush chain for that repository. */
616
+ const flushChains = new Map();
617
+ /** member name -> open dispatch count (nested brackets count once each). */
618
+ const busy = new Map();
619
+ /** member name -> the write currently in flight to it, if any. */
620
+ const inFlight = new Map();
621
+ /** repo -> ids the maintainer CONFIRMED that are not yet in a pushed bible commit (insertion order). */
622
+ const confirmations = new Map();
623
+ /** repo -> ids the maintainer DEMOTED that are not yet in a pushed bible commit (insertion order). */
624
+ const demotedPending = new Map();
625
+ /** repo -> (id -> rounds in a row kb_bible_commit skipped it with a retryable reason). */
626
+ const skipRounds = new Map();
627
+ const skipRetryRounds = Number.isInteger(opts.bibleSkipRetryRounds) && opts.bibleSkipRetryRounds > 0
628
+ ? opts.bibleSkipRetryRounds
629
+ : KB_BIBLE_SKIP_RETRY_ROUNDS;
171
630
  /**
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.
631
+ * Repositories whose maintainer may hold bible retirements not yet in a
632
+ * bible commit: a kb_invalidate discard was applied there since the last
633
+ * successful kb_bible_commit. kb_bible_commit removes superseded and
634
+ * invalidated entries at every call, so such a repository gets a call
635
+ * (with ids [] when nothing is confirmed) even in a round that promoted
636
+ * nothing.
180
637
  */
181
- function scopeOf(repoPath) {
182
- return kbScope(typeof remoteUrlFor === 'function' ? remoteUrlFor(repoPath) : null);
183
- }
638
+ const retirements = new Set();
639
+ /** Why the bible commit was sealed (a FAIL verdict, an abort), or null while open. */
640
+ let sealedReason = null;
641
+
642
+ const isBusy = (memberName) => (busy.get(memberName) || 0) > 0;
184
643
 
185
644
  /** Best-effort JSON out of an MCP result (string, content-block, or plain object). */
186
645
  function parseResult(result) {
@@ -191,7 +650,805 @@ export function createKbWorkClient(opts = {}) {
191
650
  return (result && typeof result === 'object') ? result : null;
192
651
  }
193
652
 
653
+ /**
654
+ * The maintainer selection ({repo, member, record}) KB writes produced by
655
+ * `memberName` go to, or null. A member whose own work folder is not a
656
+ * repository has none.
657
+ */
658
+ function maintainerFor(memberName) {
659
+ const sel = selector();
660
+ if (!sel || !memberName) return null;
661
+ const m = sel.maintainerForMember(memberName);
662
+ return (m && m.member && m.record) ? m : null;
663
+ }
664
+
665
+ /**
666
+ * The maintainer a REVIEWER's candidates come from and its CONFIRM/DISCARD
667
+ * judgements go to: the reviewer's own repository's maintainer, or -- for
668
+ * a reviewer whose work folder is not a checkout -- the sprint's only
669
+ * maintainer when exactly one repository has one.
670
+ */
671
+ function reviewMaintainerFor(memberName) {
672
+ if (!memberName) return null;
673
+ const own = maintainerFor(memberName);
674
+ if (own) return own;
675
+ const sel = selector();
676
+ if (!sel || typeof sel.maintainers !== 'function' || typeof sel.getKbMaintainer !== 'function') return null;
677
+ const repos = [...sel.maintainers()].filter(([, m]) => m && m.member).map(([repo]) => repo);
678
+ if (repos.length !== 1) return null;
679
+ const m = sel.getKbMaintainer(repos[0]);
680
+ return (m && m.member && m.record) ? m : null;
681
+ }
682
+
683
+ /**
684
+ * The record knowledge reads run as: the repository kb_maintainer of
685
+ * `member`'s repository (see reviewMaintainerFor). Without a selector at
686
+ * all (unit-test seam) the member itself, when it is a record.
687
+ */
688
+ function readTarget(member) {
689
+ const sel = selector();
690
+ if (!sel) return (member && typeof member === 'object' && member.id) ? member : null;
691
+ const m = reviewMaintainerFor(memberNameOf(member));
692
+ return m ? m.record : null;
693
+ }
694
+
695
+ /** kb_query on the target: CONFIRMED, undisputed entries (direct hits, then graph-related). */
696
+ async function queryEntries(record, query) {
697
+ try {
698
+ const res = await memberCall(record, 'kb_query', {
699
+ query,
700
+ limit: KB_MAX_KNOWLEDGE_ENTRIES,
701
+ expand_related: true,
702
+ confidence: ['CONFIRMED'],
703
+ exclude_disputed: true,
704
+ });
705
+ // apra-fleet-23c: a tool-level failure RESOLVES with {isError:true}
706
+ // rather than throwing; log it instead of reading it as "no hits".
707
+ if (isToolError(res)) {
708
+ log(`[kb-work] kb_query rejected for ${memberLabel(record)} (non-fatal): ${toolErrorText(res)}`);
709
+ return [];
710
+ }
711
+ const parsed = parseResult(res);
712
+ if (!parsed) return [];
713
+ const hits = Array.isArray(parsed.l1_results) ? parsed.l1_results : [];
714
+ const related = Array.isArray(parsed.related_claims) ? parsed.related_claims : [];
715
+ const seen = new Set();
716
+ const out = [];
717
+ for (const e of hits) {
718
+ if (typeof e?.id !== 'string' || !isInjectableKbEntry(e) || seen.has(e.id)) continue;
719
+ seen.add(e.id);
720
+ out.push(e);
721
+ }
722
+ // Related claims sit BELOW every direct hit and carry a marker.
723
+ for (const e of related) {
724
+ if (typeof e?.id !== 'string' || !isInjectableKbEntry(e) || seen.has(e.id)) continue;
725
+ seen.add(e.id);
726
+ out.push({ ...e, via: 'kb-graph' });
727
+ }
728
+ return out.slice(0, KB_MAX_KNOWLEDGE_ENTRIES);
729
+ } catch (err) {
730
+ log(`[kb-work] kb_query failed for ${memberLabel(record)} (non-fatal): ${err.message}`);
731
+ return [];
732
+ }
733
+ }
734
+
735
+ /** kb_session_prime with the role's hints; only injectable entries survive. */
736
+ async function primeEntries(record, hintSymbols, hintModules) {
737
+ try {
738
+ const res = await memberCall(record, 'kb_session_prime', {
739
+ ...(hintSymbols.length > 0 ? { hint_symbols: hintSymbols } : {}),
740
+ ...(hintModules.length > 0 ? { hint_modules: hintModules } : {}),
741
+ confidence: ['CONFIRMED'],
742
+ });
743
+ if (isToolError(res)) {
744
+ log(`[kb-work] kb_session_prime rejected for ${memberLabel(record)} (non-fatal): ${toolErrorText(res)}`);
745
+ return [];
746
+ }
747
+ const parsed = parseResult(res);
748
+ const top = parsed && Array.isArray(parsed.top_entries) ? parsed.top_entries : [];
749
+ return top.filter((e) => typeof e?.id === 'string' && isInjectableKbEntry(e)).slice(0, KB_MAX_KNOWLEDGE_ENTRIES);
750
+ } catch (err) {
751
+ log(`[kb-work] kb_session_prime failed for ${memberLabel(record)} (non-fatal): ${err.message}`);
752
+ return [];
753
+ }
754
+ }
755
+
756
+ const zeroCounts = () => ({ captured: 0, promoted: 0, discarded: 0, demoted: 0 });
757
+
758
+ const OPS = {
759
+ capture: {
760
+ tool: 'kb_capture',
761
+ args: (p) => ({ ...p }),
762
+ subject: (p) => `"${p.title}"`,
763
+ counter: 'captured',
764
+ },
765
+ promote: {
766
+ tool: 'kb_promote',
767
+ args: (p) => ({ id: p.id, reason: p.reason }),
768
+ subject: (p) => p.id,
769
+ counter: 'promoted',
770
+ },
771
+ discard: {
772
+ tool: 'kb_invalidate',
773
+ args: (p) => ({ ids: [p.id] }),
774
+ subject: (p) => p.id,
775
+ counter: 'discarded',
776
+ // kb_invalidate {ids} answers {discarded, not_found,
777
+ // already_discarded}. Every candidate is maintainer-tagged by
778
+ // construction, so a not-found means the entry is gone: logged,
779
+ // non-fatal, and not counted as a discard.
780
+ accept: (p, res) => {
781
+ const parsed = parseResult(res);
782
+ if (parsed && Array.isArray(parsed.not_found) && parsed.not_found.includes(p.id)) {
783
+ log(`[kb-work] kb_invalidate: entry ${p.id} not found on the maintainer -- already gone (non-fatal)`);
784
+ return false;
785
+ }
786
+ if (parsed && Array.isArray(parsed.already_discarded) && parsed.already_discarded.includes(p.id)) {
787
+ log(`[kb-work] kb_invalidate: entry ${p.id} was already discarded (non-fatal)`);
788
+ return false;
789
+ }
790
+ return true;
791
+ },
792
+ },
793
+ demote: {
794
+ tool: 'kb_demote',
795
+ args: (p) => ({ id: p.id, reason: p.reason, ...(Array.isArray(p.evidence_files) ? { evidence_files: p.evidence_files } : {}) }),
796
+ subject: (p) => p.id,
797
+ counter: 'demoted',
798
+ },
799
+ };
800
+
801
+ /**
802
+ * Apply one repository's queue in the maintainer's session. Never throws.
803
+ * @returns {Promise<{captured: number, promoted: number, discarded: number}>}
804
+ */
805
+ async function flushRepo(repo) {
806
+ const counts = zeroCounts();
807
+ const queue = queues.get(repo);
808
+ if (!queue || queue.length === 0) return counts;
809
+ const sel = selector();
810
+ const target = sel && typeof sel.getKbMaintainer === 'function' ? sel.getKbMaintainer(repo) : null;
811
+ if (!target || !target.record) {
812
+ log(`[kb-work] WARN: repository ${repo} has no kb_maintainer -- ${queue.length} KB write(s) stay queued`);
813
+ return counts;
814
+ }
815
+ const maintainer = target.member;
816
+ if (isBusy(maintainer)) {
817
+ log(`[kb-work] maintainer '${maintainer}' is mid-dispatch -- ${queue.length} KB write(s) for ${repo} stay queued until its dispatch ends`);
818
+ return counts;
819
+ }
820
+ // G-pull BEFORE every batch: the maintainer's checkout must hold the
821
+ // files the queued captures cite before kb_capture's basis check runs.
822
+ if (typeof gPull === 'function') {
823
+ // Same sprint-branch guard as the bible commit path: a pull on any
824
+ // other branch would move that branch, so nothing runs there.
825
+ if (!(await onSprintBranch(maintainer, repo, queue.length, 'KB write'))) return counts;
826
+ // Register the pull in inFlight so dispatchStarted() waits it out
827
+ // instead of running its own G-pull concurrently on the same checkout.
828
+ const pull = Promise.resolve().then(() => gPull(maintainer));
829
+ inFlight.set(maintainer, pull.then(() => {}, () => {}));
830
+ try {
831
+ await pull;
832
+ } catch (err) {
833
+ 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`);
834
+ return counts;
835
+ } finally {
836
+ inFlight.delete(maintainer);
837
+ }
838
+ }
839
+ const batch = queue.splice(0, queue.length);
840
+ // The KB server (not the maintainer) cannot be reached or refused the
841
+ // token: this write and every one behind it go back to the head of the
842
+ // queue for the next flush.
843
+ const keepForServer = (i, spec, op, text, reason) => {
844
+ queue.unshift(...batch.slice(i));
845
+ log(`[kb-work] WARN: ${reason} during ${spec.tool} for ${spec.subject(op.payload)} on maintainer '${maintainer}' (${text}) -- ${batch.length - i} KB write(s) for ${repo} stay queued`);
846
+ };
847
+ for (let i = 0; i < batch.length; i++) {
848
+ const op = batch[i];
849
+ if (isBusy(maintainer)) {
850
+ // A dispatch started on the maintainer while this batch ran:
851
+ // no write may land during it.
852
+ queue.unshift(...batch.slice(i));
853
+ log(`[kb-work] maintainer '${maintainer}' started a dispatch -- ${batch.length - i} KB write(s) for ${repo} stay queued until it ends`);
854
+ break;
855
+ }
856
+ const spec = OPS[op.kind];
857
+ // AS the kb_maintainer: the grant is what lets the session see
858
+ // kb_promote (no other member session is served it).
859
+ const call = memberCall(target.record, spec.tool, spec.args(op.payload), KB_MAINTAINER_CALL);
860
+ inFlight.set(maintainer, call.then(() => {}, () => {}));
861
+ let res;
862
+ try {
863
+ res = await call;
864
+ } catch (err) {
865
+ if (err && err.code === E_MEMBER_FLEET_TOO_OLD) {
866
+ // The maintainer's install cannot open the kb_maintainer
867
+ // grant: nothing in this batch can land until it is
868
+ // upgraded, so all of it stays queued.
869
+ queue.unshift(...batch.slice(i));
870
+ log(`[kb-work] WARNING: maintainer '${maintainer}' cannot run ${spec.tool}: ${err.message} -- ${batch.length - i} KB write(s) for ${repo} stay queued`);
871
+ break;
872
+ }
873
+ if (isUnreachableError(err)) {
874
+ queue.unshift(...batch.slice(i));
875
+ 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`);
876
+ break;
877
+ }
878
+ const thrownReason = kbServerKeepReason(err && err.message);
879
+ if (thrownReason) {
880
+ keepForServer(i, spec, op, err.message, thrownReason);
881
+ break;
882
+ }
883
+ log(`[kb-work] ${spec.tool} failed for ${spec.subject(op.payload)} (non-fatal): ${err && err.message ? err.message : String(err)}`);
884
+ continue;
885
+ } finally {
886
+ inFlight.delete(maintainer);
887
+ }
888
+ // apra-fleet-23c: an MCP client RESOLVES with {isError:true} on a
889
+ // tool-level failure rather than throwing, so a non-throwing call
890
+ // is not by itself a success.
891
+ if (isToolError(res)) {
892
+ const text = toolErrorText(res);
893
+ const resultReason = kbServerKeepReason(text);
894
+ if (resultReason) {
895
+ keepForServer(i, spec, op, text, resultReason);
896
+ break;
897
+ }
898
+ log(`[kb-work] ${spec.tool} rejected for ${spec.subject(op.payload)} (non-fatal): ${text}`);
899
+ continue;
900
+ }
901
+ if (typeof spec.accept === 'function' && !spec.accept(op.payload, res)) continue;
902
+ counts[spec.counter]++;
903
+ if (op.kind === 'discard') retirements.add(repo);
904
+ if (op.kind === 'promote') {
905
+ if (!confirmations.has(repo)) confirmations.set(repo, new Set());
906
+ confirmations.get(repo).add(op.payload.id);
907
+ }
908
+ if (op.kind === 'demote') {
909
+ if (!demotedPending.has(repo)) demotedPending.set(repo, new Set());
910
+ demotedPending.get(repo).add(op.payload.id);
911
+ }
912
+ }
913
+ if (counts.captured || counts.promoted || counts.discarded || counts.demoted) {
914
+ log(`[kb-work] maintainer '${maintainer}' (${repo}): captured ${counts.captured}, promoted ${counts.promoted}, discarded ${counts.discarded}, demoted ${counts.demoted}`);
915
+ }
916
+ return counts;
917
+ }
918
+
919
+ /**
920
+ * Serialize every maintainer operation per repository (queue flushes and
921
+ * bible commits) so two never interleave on one checkout.
922
+ */
923
+ function serialize(repo, fn) {
924
+ const prev = flushChains.get(repo) || Promise.resolve();
925
+ const next = prev.then(fn, fn);
926
+ flushChains.set(repo, next.then(() => {}, () => {}));
927
+ return next;
928
+ }
929
+
930
+ function flush(repo) {
931
+ return serialize(repo, () => flushRepo(repo));
932
+ }
933
+
934
+ const errText = (err) => (err && err.message ? err.message : String(err));
935
+
936
+ /**
937
+ * Log-message phrase for a (confirmation count, demotion count) pair,
938
+ * read naturally in every combination and -- critically -- IDENTICAL to
939
+ * the pre-existing "N confirmation(s)" wording when there are no pending
940
+ * demotions, so every pre-existing bible-commit log assertion (written
941
+ * before demotion support existed) keeps matching byte-for-byte.
942
+ */
943
+ const describeCounts = (n, m) => {
944
+ if (m === 0) return `${n} confirmation(s)`;
945
+ if (n === 0) return `${m} demotion(s)`;
946
+ return `${n} confirmation(s) and ${m} demotion(s)`;
947
+ };
948
+
949
+ /**
950
+ * What a bible commit carries, for its log lines: the confirmations and
951
+ * demotions, or -- for a removal-only call (no ids, no demotions) -- the
952
+ * pending bible removals.
953
+ */
954
+ const bibleLoad = (ids, demoteIds) => (ids.length + demoteIds.length > 0
955
+ ? describeCounts(ids.length, demoteIds.length)
956
+ : 'the pending bible removal(s)');
957
+ /** onSprintBranch for a bible commit carrying `ids` and `demoteIds` (see bibleLoad). */
958
+ const bibleOnSprintBranch = (maintainer, repo, ids, demoteIds) => (ids.length + demoteIds.length > 0
959
+ ? onSprintBranch(maintainer, repo, ids.length + demoteIds.length)
960
+ : onSprintBranch(maintainer, repo, 'the', 'pending bible removal'));
961
+
962
+ /**
963
+ * One kb_bible_commit attempt on the maintainer: G-pull, resolve the
964
+ * base, kb_bible_commit, then G-push when a commit was made. Returns
965
+ * { ok: true, result } or { ok: false, stage, error } -- never throws.
966
+ * `resetToRemoteTip` is the retry's G-pull: after a rejected push the
967
+ * maintainer holds a local bible commit the remote tip does not, so a
968
+ * fast-forward pull would fail by construction; kb_bible_commit re-merges
969
+ * the same ids at entry level on top of the new tip instead.
970
+ *
971
+ * `demoteIds` (defaulting to none) are this round's successful
972
+ * kb_demote() ids, passed as kb_bible_commit's `demoted_ids` in the SAME
973
+ * call as `ids` -- a round confirming some entries and demoting others
974
+ * produces exactly one kb_bible_commit call, never two.
975
+ */
976
+ async function bibleAttempt(target, repo, ids, demoteIds = [], { resetToRemoteTip = false } = {}) {
977
+ const maintainer = target.member;
978
+ if (!(await bibleOnSprintBranch(maintainer, repo, ids, demoteIds))) return { ok: false, stage: 'branch check', error: 'the maintainer is not on the sprint branch', branchBlocked: true };
979
+ try {
980
+ await gPull(maintainer, resetToRemoteTip ? { resetToRemoteTip: true } : {});
981
+ } catch (err) {
982
+ return { ok: false, stage: 'G-pull', error: errText(err) };
983
+ }
984
+ let base;
985
+ try {
986
+ base = await bibleBase(maintainer);
987
+ } catch (err) {
988
+ return { ok: false, stage: 'base resolution', error: errText(err) };
989
+ }
990
+ if (!base || typeof base.baseBranch !== 'string' || !base.baseBranch || typeof base.baseCommit !== 'string' || !base.baseCommit) {
991
+ return { ok: false, stage: 'base resolution', error: 'the base branch or base commit could not be resolved on the maintainer' };
992
+ }
993
+ if (!(await bibleOnSprintBranch(maintainer, repo, ids, demoteIds))) return { ok: false, stage: 'branch check', error: 'the maintainer is not on the sprint branch', branchBlocked: true };
994
+ let res;
995
+ try {
996
+ res = await memberCall(target.record, 'kb_bible_commit', {
997
+ ids,
998
+ ...(demoteIds.length > 0 ? { demoted_ids: demoteIds } : {}),
999
+ baseBranch: base.baseBranch,
1000
+ baseCommit: base.baseCommit,
1001
+ }, KB_MAINTAINER_CALL);
1002
+ } catch (err) {
1003
+ return { ok: false, stage: 'kb_bible_commit', error: errText(err), fleetTooOld: !!(err && err.code === E_MEMBER_FLEET_TOO_OLD) };
1004
+ }
1005
+ if (isToolError(res)) return { ok: false, stage: 'kb_bible_commit', error: toolErrorText(res) };
1006
+ const result = parseResult(res) || {};
1007
+ // The tool skipped the whole call (e.g. the project KB is remote and has
1008
+ // no bible to commit to): nothing was committed, so there is nothing to
1009
+ // check or push. Return before the publication check and the G-push.
1010
+ if (result.bible_skipped === true) return { ok: true, result, pushed: false, bibleSkipped: true };
1011
+ // Nothing committed (every id skipped, or the entry set unchanged).
1012
+ // That alone does not mean the entries are published: an earlier
1013
+ // round's bible commit may still sit unpushed on the maintainer (its
1014
+ // G-push was rejected and the reset onto the remote tip was refused to
1015
+ // protect unrelated local work). Only origin decides: when it already
1016
+ // holds the checkout's bible there is nothing to push; when a local
1017
+ // commit holds it, push that commit; otherwise (or when it cannot be
1018
+ // established) the ids stay queued.
1019
+ if (result.committed === false) {
1020
+ const where = await bibleOnOrigin(maintainer);
1021
+ if (where.unpushed === false) return { ok: true, result, pushed: false };
1022
+ if (where.unpushed !== true) return { ok: false, stage: 'publication check', error: where.reason || 'whether origin holds the bible could not be established' };
1023
+ 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`);
1024
+ }
1025
+ if (!(await bibleOnSprintBranch(maintainer, repo, ids, demoteIds))) return { ok: false, stage: 'branch check', error: 'the maintainer is not on the sprint branch', branchBlocked: true };
1026
+ // A bible push must publish the bible commit(s) only: never a doer
1027
+ // commit that sits unpushed underneath them. Without an injected
1028
+ // probe the push is allowed.
1029
+ if (typeof unpushedOnlyBible === 'function') {
1030
+ let verdict;
1031
+ try { verdict = await unpushedOnlyBible(maintainer, BIBLE_FILE); } catch (err) { verdict = { onlyBible: false, reason: errText(err) }; }
1032
+ if (!verdict || verdict.onlyBible !== true) {
1033
+ 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, demoteIds)} stay queued for the next round`);
1034
+ return { ok: false, stage: 'push guard', error: (verdict && verdict.reason) || 'unpushed non-bible commits', branchBlocked: true };
1035
+ }
1036
+ }
1037
+ try {
1038
+ await gPush(maintainer);
1039
+ } catch (err) {
1040
+ return { ok: false, stage: 'G-push', error: errText(err) };
1041
+ }
1042
+ return { ok: true, result, pushed: true };
1043
+ }
1044
+
1045
+ /**
1046
+ * Whether origin's sprint branch already holds the maintainer checkout's
1047
+ * bible, through the injected bibleUnpushed probe. Resolves
1048
+ * { unpushed: false } when it does, { unpushed: true } when a local-only
1049
+ * commit holds the bible, or { unpushed: null, reason } when that cannot
1050
+ * be established (no probe wired, a git failure, a bible change that is
1051
+ * not committed) -- never assumes published. Never throws.
1052
+ */
1053
+ async function bibleOnOrigin(maintainer) {
1054
+ if (typeof bibleUnpushed !== 'function') return { unpushed: null, reason: 'no publication check is wired for the bible commit' };
1055
+ let r;
1056
+ try { r = await bibleUnpushed(maintainer, BIBLE_FILE); } catch (err) { return { unpushed: null, reason: errText(err) }; }
1057
+ if (r && (r.unpushed === true || r.unpushed === false)) return { unpushed: r.unpushed };
1058
+ return { unpushed: null, reason: (r && r.reason) || 'the publication check returned no answer' };
1059
+ }
1060
+
1061
+ /**
1062
+ * True when a hard reset onto the remote tip would drop nothing but the
1063
+ * bible commit. When it would drop anything else (or that cannot be
1064
+ * established), logs a WARN and returns false -- the caller keeps the ids
1065
+ * queued and does not reset. Without an injected guard the reset is allowed.
1066
+ */
1067
+ async function resetIsSafe(maintainer, repo) {
1068
+ if (typeof canResetCheckout !== 'function') return true;
1069
+ let verdict;
1070
+ try { verdict = await canResetCheckout(maintainer, BIBLE_FILE); } catch (err) { verdict = { safe: false, reason: errText(err) }; }
1071
+ if (verdict && verdict.safe) return true;
1072
+ 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`);
1073
+ return false;
1074
+ }
1075
+
1076
+ /**
1077
+ * True when the maintainer's checked-out branch is the sprint branch.
1078
+ * Checked before the first G-pull of a bible commit and before every
1079
+ * reset onto the remote tip, so no pull, reset --hard, commit or push
1080
+ * ever runs on any other branch. When the branch differs (or cannot be
1081
+ * read), logs a WARN naming the maintainer and both branches and returns
1082
+ * false -- the caller keeps the ids queued. Without an injected guard
1083
+ * the check passes.
1084
+ */
1085
+ async function onSprintBranch(maintainer, repo, count, what = 'confirmation') {
1086
+ if (typeof checkedOutBranch !== 'function') return true;
1087
+ let found = null;
1088
+ let sprintBranch = null;
1089
+ let readError = null;
1090
+ try {
1091
+ const r = await checkedOutBranch(maintainer);
1092
+ found = r && typeof r.branch === 'string' && r.branch ? r.branch : null;
1093
+ sprintBranch = r && typeof r.sprintBranch === 'string' && r.sprintBranch ? r.sprintBranch : null;
1094
+ } catch (err) {
1095
+ readError = errText(err);
1096
+ }
1097
+ if (found && sprintBranch && found === sprintBranch) return true;
1098
+ const foundText = found ? `'${found}'` : `an unreadable branch${readError ? ` (${readError})` : ''}`;
1099
+ 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`);
1100
+ return false;
1101
+ }
1102
+
1103
+ /**
1104
+ * Commit one repository's pending confirmations AND pending demotions to
1105
+ * the bible on its maintainer, in a single kb_bible_commit call (`ids` and
1106
+ * `demoted_ids` together -- see bibleAttempt). Never throws; ids that do
1107
+ * not reach a pushed commit stay pending for the next round.
1108
+ * @returns {Promise<{ committed: number, pending: number }>}
1109
+ */
1110
+ async function commitRepo(repo) {
1111
+ const pending = confirmations.get(repo);
1112
+ const pendingDemoted = demotedPending.get(repo);
1113
+ const ids = pending ? [...pending] : [];
1114
+ const demoteIds = pendingDemoted ? [...pendingDemoted] : [];
1115
+ // No confirmations, no demotions and no retirements: no call at all (no
1116
+ // member traffic). Retirements alone make a removal-only call with ids [].
1117
+ if (ids.length === 0 && demoteIds.length === 0 && !retirements.has(repo)) return { committed: 0, pending: 0 };
1118
+ const totalPending = () => ids.length + demoteIds.length;
1119
+ const load = bibleLoad(ids, demoteIds);
1120
+ if (sealedReason) return { committed: 0, pending: totalPending() };
1121
+ const sel = selector();
1122
+ const target = sel && typeof sel.getKbMaintainer === 'function' ? sel.getKbMaintainer(repo) : null;
1123
+ if (!target || !target.record) {
1124
+ log(`[kb-work] WARN: repository ${repo} has no kb_maintainer -- ${load} stay queued for the bible`);
1125
+ return { committed: 0, pending: totalPending() };
1126
+ }
1127
+ const maintainer = target.member;
1128
+ if (typeof gPull !== 'function' || typeof gPush !== 'function' || typeof bibleBase !== 'function') {
1129
+ log(`[kb-work] WARN: no git sync wired for the bible commit -- ${load} for ${repo} stay queued`);
1130
+ return { committed: 0, pending: totalPending() };
1131
+ }
1132
+ if (isBusy(maintainer)) {
1133
+ log(`[kb-work] WARN: maintainer '${maintainer}' is mid-dispatch -- ${load} for ${repo} stay queued for the next round's bible commit`);
1134
+ return { committed: 0, pending: totalPending() };
1135
+ }
1136
+ let release;
1137
+ inFlight.set(maintainer, new Promise((r) => { release = r; }));
1138
+ try {
1139
+ let outcome = await bibleAttempt(target, repo, ids, demoteIds);
1140
+ if (!outcome.ok && outcome.stage === 'G-push') {
1141
+ 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`);
1142
+ if (typeof abortRebase === 'function' && (await bibleOnSprintBranch(maintainer, repo, ids, demoteIds))) {
1143
+ try { await abortRebase(maintainer); } catch (err) { log(`[kb-work] rebase --abort on maintainer '${maintainer}' failed (non-fatal): ${errText(err)}`); }
1144
+ }
1145
+ // The reset throws away the maintainer's local-only commits and
1146
+ // uncommitted changes; it is usually also a doer, so only reset
1147
+ // when that is the bible commit alone.
1148
+ if (!(await bibleOnSprintBranch(maintainer, repo, ids, demoteIds))) return { committed: 0, pending: totalPending() };
1149
+ if (!(await resetIsSafe(maintainer, repo))) return { committed: 0, pending: totalPending() };
1150
+ outcome = await bibleAttempt(target, repo, ids, demoteIds, { resetToRemoteTip: true });
1151
+ if (!outcome.ok && (outcome.stage === 'G-push' || outcome.stage === 'kb_bible_commit')) {
1152
+ // Leave the checkout on the remote tip: an unpushed bible
1153
+ // commit would make the maintainer's next fast-forward
1154
+ // G-pull fail. The ids stay queued and are re-merged by
1155
+ // the next round's kb_bible_commit.
1156
+ if (typeof abortRebase === 'function' && !outcome.branchBlocked && (await bibleOnSprintBranch(maintainer, repo, ids, demoteIds))) {
1157
+ try { await abortRebase(maintainer); } catch { /* best-effort */ }
1158
+ }
1159
+ try { if ((await bibleOnSprintBranch(maintainer, repo, ids, demoteIds)) && (await resetIsSafe(maintainer, repo))) await gPull(maintainer, { resetToRemoteTip: true }); } catch (err) {
1160
+ log(`[kb-work] WARN: could not reset maintainer '${maintainer}' onto the remote tip after the failed bible commit: ${errText(err)}`);
1161
+ }
1162
+ }
1163
+ }
1164
+ if (!outcome.ok && outcome.branchBlocked) return { committed: 0, pending: totalPending() };
1165
+ if (!outcome.ok && outcome.fleetTooOld) {
1166
+ log(`[kb-work] WARNING: bible commit for ${repo} cannot run on maintainer '${maintainer}': ${outcome.error} -- ${load} stay queued for the next round`);
1167
+ return { committed: 0, pending: totalPending() };
1168
+ }
1169
+ if (!outcome.ok) {
1170
+ log(`[kb-work] WARN: bible commit for ${repo} on maintainer '${maintainer}' failed at ${outcome.stage} (${outcome.error}) -- ${load} stay queued for the next round`);
1171
+ return { committed: 0, pending: totalPending() };
1172
+ }
1173
+ if (outcome.bibleSkipped) {
1174
+ // The skip is provider-wide, so a retry cannot succeed: drop the
1175
+ // repo's queue state (as for any non-retryable skip) so later
1176
+ // rounds do not repeat the call or warn about pending ids. The
1177
+ // demotion queue goes too: over a KB server the demotion already
1178
+ // happened on the server, and there is no bible to tombstone.
1179
+ const reason = typeof outcome.result.reason === 'string' && outcome.result.reason ? outcome.result.reason : 'no reason given';
1180
+ confirmations.delete(repo);
1181
+ demotedPending.delete(repo);
1182
+ skipRounds.delete(repo);
1183
+ retirements.delete(repo);
1184
+ log(`[kb-work] kb_bible_commit skipped for ${repo} on maintainer '${maintainer}': ${reason} -- ${ids.length} confirmation(s) and ${demoteIds.length} demotion(s) dropped from the bible queue.`);
1185
+ return { committed: 0, pending: 0 };
1186
+ }
1187
+ // The call succeeded: whatever retirements the maintainer held were
1188
+ // removed by it (kb_bible_commit drops them at every call).
1189
+ retirements.delete(repo);
1190
+ const skipped = Array.isArray(outcome.result.skipped) ? outcome.result.skipped : [];
1191
+ // A skip whose cause can clear on its own (basis_mismatch: the cited
1192
+ // files at the maintainer's HEAD differ from the recorded basis, e.g.
1193
+ // the entry was captured against commits not pulled yet) stays queued
1194
+ // and is offered again next round, for a bounded number of rounds.
1195
+ // Any other skip (not CONFIRMED or unknown, no source files) cannot
1196
+ // change by retrying and leaves the queue. Merged ids leave it too.
1197
+ // A round can carry demotions only, so pending may be absent.
1198
+ if (!skipRounds.has(repo)) skipRounds.set(repo, new Map());
1199
+ const rounds = skipRounds.get(repo);
1200
+ const retained = [];
1201
+ const dropped = [];
1202
+ const exhausted = [];
1203
+ for (const x of skipped) {
1204
+ if (!x || typeof x.id !== 'string') continue;
1205
+ if (!KB_RETRYABLE_SKIP_REASONS.has(x.reason)) { dropped.push(x); continue; }
1206
+ const n = (rounds.get(x.id) || 0) + 1;
1207
+ if (n >= skipRetryRounds) { exhausted.push({ ...x, rounds: n }); continue; }
1208
+ rounds.set(x.id, n);
1209
+ retained.push(x);
1210
+ }
1211
+ const keep = new Set(retained.map((x) => x.id));
1212
+ for (const id of ids) {
1213
+ if (keep.has(id)) continue;
1214
+ if (pending) pending.delete(id);
1215
+ rounds.delete(id);
1216
+ }
1217
+ if (pending && pending.size === 0) confirmations.delete(repo);
1218
+ if (rounds.size === 0) skipRounds.delete(repo);
1219
+ // Every demoted id leaves the queue, skipped ones included: a skipped
1220
+ // demotion (not_demoted_or_unknown) never resolves itself without a
1221
+ // new kb_demote.
1222
+ for (const id of demoteIds) if (pendingDemoted) pendingDemoted.delete(id);
1223
+ if (pendingDemoted && pendingDemoted.size === 0) demotedPending.delete(repo);
1224
+ const skippedIds = new Set(skipped.map((x) => x && x.id));
1225
+ const merged = Array.isArray(outcome.result.merged) ? outcome.result.merged.length
1226
+ : ids.length - ids.filter((id) => skippedIds.has(id)).length;
1227
+ const demoted = Array.isArray(outcome.result.demoted) ? outcome.result.demoted.length
1228
+ : demoteIds.length - demoteIds.filter((id) => skippedIds.has(id)).length;
1229
+ const describe = (list) => list.map((x) => (x.reason ? `${x.id} (${x.reason})` : x.id)).join(', ');
1230
+ if (dropped.length > 0) {
1231
+ 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)}`);
1232
+ }
1233
+ if (retained.length > 0) {
1234
+ 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)}`);
1235
+ }
1236
+ for (const x of exhausted) {
1237
+ 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`);
1238
+ }
1239
+ // Bible entries the maintainer KB holds as superseded or invalidated
1240
+ // are removed by the tool at every call; name each one here so the
1241
+ // removal is visible in the run log, not only in the commit message.
1242
+ const removed = Array.isArray(outcome.result.removed) ? outcome.result.removed.filter((x) => x && typeof x.id === 'string') : [];
1243
+ if (removed.length > 0) {
1244
+ log(`[kb-work] kb_bible_commit removed ${removed.length} superseded/invalidated entry(ies) from the bible for ${repo}: ${describe(removed)}`);
1245
+ }
1246
+ if (ids.length === 0 && demoteIds.length === 0) {
1247
+ 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'}`);
1248
+ } else {
1249
+ log(`[kb-work] bible commit for ${repo} on maintainer '${maintainer}': ${describeCounts(merged, demoted)} ${outcome.pushed ? 'committed and pushed' : 'already in the bible -- nothing to push'}`);
1250
+ }
1251
+ return { committed: outcome.pushed ? merged + demoted : 0, pending: (pending ? pending.size : 0) + (pendingDemoted ? pendingDemoted.size : 0) };
1252
+ } finally {
1253
+ inFlight.delete(maintainer);
1254
+ release();
1255
+ }
1256
+ }
1257
+
1258
+ /**
1259
+ * The body of demotionCandidates(), run inside its isBusy/inFlight
1260
+ * bracket. Never throws.
1261
+ * @returns {Promise<object[]>}
1262
+ */
1263
+ async function readDemotionCandidates(target, changedFilesFor, scopeLabel) {
1264
+ // Same branch guard flushRepo/commitRepo apply before every G-pull
1265
+ // on the maintainer: a fast-forward merge does not care what
1266
+ // branch HEAD is currently on, only that HEAD is an ancestor of
1267
+ // the fetched tip, so pulling on a maintainer not actually on the
1268
+ // sprint branch could silently advance the wrong branch.
1269
+ if (!(await onSprintBranch(target.member, target.repo, 0, 'demotion candidate read'))) return [];
1270
+ let changed;
1271
+ try {
1272
+ changed = await changedFilesFor(target.member);
1273
+ } catch (err) {
1274
+ log(`[kb-work] could not compute ${scopeLabel} changed files on maintainer '${target.member}' (non-fatal): ${err.message}`);
1275
+ return [];
1276
+ }
1277
+ const files = Array.isArray(changed) ? changed.filter((f) => typeof f === 'string' && f.trim()) : [];
1278
+ if (files.length === 0) return [];
1279
+ try {
1280
+ const res = await memberCall(target.record, 'kb_query', buildDemotionCandidateQuery(target.record.id));
1281
+ if (isToolError(res)) {
1282
+ const text = toolErrorText(res);
1283
+ // A KB server that does not serve the optional demote route:
1284
+ // there is nothing the reviewer could demote, so offer nothing.
1285
+ if (/E-KB-HTTP-UNSUPPORTED/.test(text)) {
1286
+ log(`[kb-work] the KB server for ${target.repo} does not serve demote: offering no demotion candidates (${text})`);
1287
+ return [];
1288
+ }
1289
+ log(`[kb-work] kb_query for demotion candidates rejected on maintainer '${target.member}' (non-fatal): ${text}`);
1290
+ return [];
1291
+ }
1292
+ const parsed = parseResult(res);
1293
+ const results = parsed && Array.isArray(parsed.l1_results) ? parsed.l1_results
1294
+ : (parsed && Array.isArray(parsed.results) ? parsed.results : []);
1295
+ const fileSet = new Set(files);
1296
+ const touchesChangedFiles = (e) => Array.isArray(e.source_files) && e.source_files.some((f) => fileSet.has(f));
1297
+ // Filter the WHOLE read first (eligibility, then relevance),
1298
+ // and only cap the survivors -- see the method comment.
1299
+ const offered = results
1300
+ .filter((e) => isDemotableCandidate(e) && touchesChangedFiles(e))
1301
+ .slice(0, KB_MAX_DEMOTION_CANDIDATES);
1302
+ offeredDemotions.set(target.repo, new Set(offered.map((e) => e.id)));
1303
+ return offered;
1304
+ } catch (err) {
1305
+ log(`[kb-work] could not read demotion candidates from maintainer '${target.member}' (non-fatal): ${err.message}`);
1306
+ return [];
1307
+ }
1308
+ }
1309
+
1310
+ function enqueue(repo, kind, role, payload) {
1311
+ if (!queues.has(repo)) queues.set(repo, []);
1312
+ queues.get(repo).push({ kind, role, payload });
1313
+ }
1314
+
1315
+ /** Repositories whose maintainer is `memberName`. */
1316
+ function reposMaintainedBy(memberName) {
1317
+ const sel = selector();
1318
+ if (!sel || typeof sel.maintainers !== 'function') return [];
1319
+ const out = [];
1320
+ for (const [repo, m] of sel.maintainers()) if (m && m.member === memberName) out.push(repo);
1321
+ return out;
1322
+ }
1323
+
194
1324
  return {
1325
+ /**
1326
+ * Dispatch lifecycle: a dispatch is starting on `memberName`. Marks it
1327
+ * busy (no queued KB write starts on it from here on) and waits out a
1328
+ * write already in flight to it. Never throws.
1329
+ */
1330
+ async dispatchStarted(memberName) {
1331
+ if (!memberName) return;
1332
+ busy.set(memberName, (busy.get(memberName) || 0) + 1);
1333
+ const pending = inFlight.get(memberName);
1334
+ if (pending) await pending;
1335
+ },
1336
+ /**
1337
+ * Dispatch lifecycle: a dispatch on `memberName` ended. When it was the
1338
+ * last open one, apply the writes that queued up behind it for every
1339
+ * repository it maintains. Never throws.
1340
+ */
1341
+ async dispatchEnded(memberName) {
1342
+ if (!memberName) return;
1343
+ const n = (busy.get(memberName) || 0) - 1;
1344
+ if (n > 0) { busy.set(memberName, n); return; }
1345
+ busy.delete(memberName);
1346
+ for (const repo of reposMaintainedBy(memberName)) {
1347
+ try { await flush(repo); } catch (err) { log(`[kb-work] flush for ${repo} failed (non-fatal): ${err.message}`); }
1348
+ }
1349
+ },
1350
+ /** Try every repository's queue (e.g. before the final review's bible commit). Never throws. */
1351
+ async flushAll() {
1352
+ const counts = zeroCounts();
1353
+ for (const repo of [...queues.keys()]) {
1354
+ const c = await flush(repo);
1355
+ for (const k of Object.keys(counts)) counts[k] += c[k];
1356
+ }
1357
+ return counts;
1358
+ },
1359
+ /** Number of KB writes still queued (all repositories, or one). */
1360
+ pendingCount(repo) {
1361
+ if (repo) return (queues.get(repo) || []).length;
1362
+ let n = 0;
1363
+ for (const q of queues.values()) n += q.length;
1364
+ return n;
1365
+ },
1366
+ /** Log a WARN for every repository that still has queued writes, confirmations or demotions. */
1367
+ warnPending() {
1368
+ for (const [repo, q] of queues) {
1369
+ if (q.length > 0) log(`[kb-work] WARN: ${q.length} KB write(s) for ${repo} are still queued (maintainer busy or unreachable, or KB server unreachable or its token refused) -- not applied`);
1370
+ }
1371
+ for (const [repo, ids] of confirmations) {
1372
+ 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})` : ''}`);
1373
+ }
1374
+ for (const [repo, ids] of demotedPending) {
1375
+ if (ids.size > 0) log(`[kb-work] WARN: ${ids.size} demotion(s) for ${repo} are not in a pushed bible commit${sealedReason ? ` (bible commits sealed: ${sealedReason})` : ''}`);
1376
+ }
1377
+ for (const repo of retirements) {
1378
+ if (!confirmations.has(repo) && !demotedPending.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})` : ''}`);
1379
+ }
1380
+ },
1381
+ /**
1382
+ * The review-round bible commit: apply whatever is still queued, then
1383
+ * for every repository with confirmations and/or demotions, on its
1384
+ * maintainer: G-pull, kb_bible_commit (ids and demoted_ids together),
1385
+ * G-push (see the client header for the retry). A repository with neither
1386
+ * but a discard applied since its
1387
+ * last bible commit gets a removal-only call (ids []). A round with
1388
+ * neither makes no call at all. A no-op once sealed. Never throws.
1389
+ * @param {string} [label] the round, for the log
1390
+ * @returns {Promise<{ committed: number, pending: number }>}
1391
+ */
1392
+ async commitRound(label = 'review round') {
1393
+ const out = { committed: 0, pending: 0 };
1394
+ if (!active) return out;
1395
+ if (sealedReason) {
1396
+ let n = 0;
1397
+ for (const ids of confirmations.values()) n += ids.size;
1398
+ for (const ids of demotedPending.values()) n += ids.size;
1399
+ if (n > 0) log(`[kb-work] ${label}: bible commits are sealed (${sealedReason}) -- ${n} confirmation(s)/demotion(s) not committed`);
1400
+ return { committed: 0, pending: n };
1401
+ }
1402
+ for (const repo of [...queues.keys()]) {
1403
+ if (queues.get(repo).length > 0) await flush(repo);
1404
+ }
1405
+ for (const repo of new Set([...confirmations.keys(), ...demotedPending.keys(), ...retirements])) {
1406
+ const r = await serialize(repo, () => commitRepo(repo));
1407
+ out.committed += r.committed;
1408
+ out.pending += r.pending;
1409
+ }
1410
+ return out;
1411
+ },
1412
+ /**
1413
+ * Stop every further bible commit: a FAIL verdict or an aborted
1414
+ * sprint commits nothing more, and the confirmation/demotion queues
1415
+ * are not flushed. Idempotent; the first reason wins.
1416
+ */
1417
+ seal(reason) {
1418
+ if (sealedReason) return;
1419
+ sealedReason = String(reason || 'sealed');
1420
+ let n = 0;
1421
+ for (const ids of confirmations.values()) n += ids.size;
1422
+ for (const ids of demotedPending.values()) n += ids.size;
1423
+ log(`[kb-work] bible commits sealed (${sealedReason})${n > 0 ? ` -- ${n} confirmation(s)/demotion(s) will not be committed` : ''}`);
1424
+ },
1425
+ /** Confirmations not yet in a pushed bible commit (all repositories, or one). */
1426
+ pendingConfirmations(repo) {
1427
+ if (repo) return [...(confirmations.get(repo) || [])];
1428
+ const out = [];
1429
+ for (const ids of confirmations.values()) out.push(...ids);
1430
+ return out;
1431
+ },
1432
+ /**
1433
+ * Per repository, the confirmations not yet in a pushed bible commit,
1434
+ * for the persisted sprint analysis: [{ repo, count }] (repositories
1435
+ * with none are left out), plus why bible commits were sealed, if
1436
+ * they were.
1437
+ * @returns {{ repos: Array<{ repo: string, count: number }>, sealedReason: string|null }}
1438
+ */
1439
+ unpublishedBible() {
1440
+ const repos = [];
1441
+ for (const [repo, ids] of confirmations) if (ids.size > 0) repos.push({ repo, count: ids.size });
1442
+ return { repos, sealedReason };
1443
+ },
1444
+ /**
1445
+ * The maintainer member record a reviewer's KB reads and judgements
1446
+ * go to (its repository's maintainer, or the sprint's only one), or null.
1447
+ */
1448
+ maintainerRecordFor(member) {
1449
+ const m = reviewMaintainerFor(memberNameOf(member));
1450
+ return m ? m.record : null;
1451
+ },
195
1452
  /**
196
1453
  * apra-fleet-0ef: the INFERRED entries this reviewer may promote.
197
1454
  *
@@ -207,30 +1464,210 @@ export function createKbWorkClient(opts = {}) {
207
1464
  *
208
1465
  * Best-effort by design -- a cold or unreachable KB must degrade to
209
1466
  * "nothing to promote", never fail the review dispatch.
1467
+ *
1468
+ * D6 IN-SPRINT PING-PONG GUARD. Without this, an entry the reviewer
1469
+ * demoted in round N is offered right back for promotion in round
1470
+ * N+1 -- promotionCandidates' own in-window filter admits it (an
1471
+ * INFERRED entry created this sprint still matches, whether it got
1472
+ * there by a fresh capture or by a demotion of a CONFIRMED one), and
1473
+ * nothing has changed about it to re-judge. An entry wasDemotedThisSprint
1474
+ * (its demoted_at falls at or after sprintStartMs()) is excluded when
1475
+ * demotionBasisUnchanged is true for it -- i.e. unless at least one
1476
+ * of its cited files now hashes differently from the
1477
+ * demoted_basis_hashes snapshot taken at demote time (currentFileHashes,
1478
+ * read ONLY for the files these candidates actually cite, never
1479
+ * recomputed from scratch). A changed basis is new evidence, so that
1480
+ * entry stays offered. The guard runs HERE, at offering time -- a
1481
+ * ping-ponged id is never in the candidate block apply() later checks
1482
+ * offeredCandidates against, never merely refused there.
210
1483
  */
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 [];
1484
+ async promotionCandidates(member) {
1485
+ // The candidates live in the reviewer's repository MAINTAINER's KB
1486
+ // (every KB write is routed there), tagged member:<maintainer uuid>
1487
+ // by its MEMBER session. Without a maintainer there is no session
1488
+ // to read them from; refuse rather than read some other KB (the
1489
+ // apra-fleet-tm7 repo-blindness class).
1490
+ const target = active ? reviewMaintainerFor(memberNameOf(member)) : null;
1491
+ if (!target) return [];
1492
+ // Replace (never accumulate) this review scope's offered set up
1493
+ // front, so a failed read leaves nothing offered from a prior round.
1494
+ offeredCandidates.set(target.repo, new Set());
1495
+ // Writes still queued for this repository (a capture from this
1496
+ // very round) get their chance to land before the read.
1497
+ if (queues.has(target.repo)) await flush(target.repo);
216
1498
  try {
217
- const parsed = parseResult(await callTool('kb_list', {
218
- repo_path: repoPath,
219
- ...scopeOf(repoPath),
220
- confidence: 'INFERRED',
1499
+ const res = await memberCall(target.record, 'kb_query', {
1500
+ tag: `member:${target.record.id}`,
1501
+ confidence: ['INFERRED'],
221
1502
  limit: KB_MAX_PROMOTION_CANDIDATES,
222
- }));
223
- const results = parsed && Array.isArray(parsed.results) ? parsed.results : [];
224
- return results
1503
+ });
1504
+ if (isToolError(res)) {
1505
+ log(`[kb-work] kb_query for promotion candidates rejected on maintainer '${target.member}' (non-fatal): ${toolErrorText(res)}`);
1506
+ return [];
1507
+ }
1508
+ const parsed = parseResult(res);
1509
+ const results = parsed && Array.isArray(parsed.l1_results) ? parsed.l1_results
1510
+ : (parsed && Array.isArray(parsed.results) ? parsed.results : []);
1511
+ // The sprint window: only entries captured during THIS sprint
1512
+ // are this sprint's to judge. An entry whose created_at cannot
1513
+ // be read cannot be shown to be in the window.
1514
+ const since = sprintStartMs();
1515
+ const inWindow = (e) => {
1516
+ if (since === null) return true;
1517
+ const t = typeof e.created_at === 'string' ? Date.parse(e.created_at) : NaN;
1518
+ return Number.isFinite(t) && t >= since;
1519
+ };
1520
+ const eligible = results
225
1521
  // promote() refuses type='user-directive' outright (activation
226
1522
  // is human-terminal, CLI-only), so offering one as a candidate
227
1523
  // can only produce a guaranteed refusal.
228
- .filter((e) => e && typeof e.id === 'string' && e.type !== 'user-directive')
229
- .slice(0, KB_MAX_PROMOTION_CANDIDATES);
1524
+ .filter((e) => e && typeof e.id === 'string' && e.type !== 'user-directive' && inWindow(e));
1525
+ // D6 ping-pong guard (see the method comment): only entries
1526
+ // demoted THIS sprint are even candidates for exclusion, and
1527
+ // only a disk re-hash can tell whether their basis moved on
1528
+ // since. Reading is bounded to exactly the files THESE
1529
+ // candidates cite -- never every file in the repository --
1530
+ // and skipped entirely when there is nothing to check or no
1531
+ // callback wired, so the common case (no in-sprint demotion)
1532
+ // costs nothing extra.
1533
+ const pingPonged = eligible.filter((e) => wasDemotedThisSprint(e, since));
1534
+ let unchanged = new Set();
1535
+ if (pingPonged.length > 0 && typeof currentFileHashes === 'function') {
1536
+ const files = new Set();
1537
+ for (const e of pingPonged) for (const f of Object.keys(e.demoted_basis_hashes || {})) files.add(f);
1538
+ if (files.size > 0) {
1539
+ try {
1540
+ const current = await currentFileHashes(target.member, [...files]);
1541
+ for (const e of pingPonged) {
1542
+ if (demotionBasisUnchanged(e.demoted_basis_hashes, current)) unchanged.add(e.id);
1543
+ }
1544
+ } catch (err) {
1545
+ log(`[kb-work] could not re-hash the in-sprint ping-pong basis on maintainer '${target.member}' (non-fatal, nothing excluded): ${err.message}`);
1546
+ }
1547
+ }
1548
+ }
1549
+ const offered = eligible.filter((e) => !unchanged.has(e.id)).slice(0, KB_MAX_PROMOTION_CANDIDATES);
1550
+ offeredCandidates.set(target.repo, new Set(offered.map((e) => e.id)));
1551
+ return offered;
230
1552
  } catch (err) {
231
- log(`[kb-work] could not list promotion candidates for ${repoPath} (non-fatal): ${err.message}`);
1553
+ log(`[kb-work] could not read promotion candidates from maintainer '${target.member}' (non-fatal): ${err.message}`);
1554
+ return [];
1555
+ }
1556
+ },
1557
+ /**
1558
+ * The CONFIRMED entries this reviewer may demote back to INFERRED,
1559
+ * scoped to the review that is about to run.
1560
+ *
1561
+ * Mirrors promotionCandidates in every structural respect it shares
1562
+ * with it -- reviewMaintainerFor to resolve the reviewer's repository
1563
+ * MAINTAINER (refusing rather than reading some other KB when there is
1564
+ * none), replacing (never accumulating) the offered set up front so a
1565
+ * failed read leaves nothing offered from a prior round, and flushing
1566
+ * any writes still queued for that repository before the read -- and
1567
+ * reads the SAME owner-tagged rows at the OTHER confidence tier
1568
+ * (CONFIRMED rather than INFERRED). Every offered id is therefore one
1569
+ * kb_demote can actually apply: reviewMaintainerFor resolves exactly
1570
+ * the maintainer whose session kb_demote's ownerTag check requires.
1571
+ *
1572
+ * THE READ. buildDemotionCandidateQuery (above) is the whole of it,
1573
+ * and its `own_scope: true` is why this returns anything at all: a
1574
+ * MEMBER-session CONFIRMED read without it is answered from the
1575
+ * checkout bible view, whose rows are all untagged, so the owner
1576
+ * filter could never match and this offered nothing in every real
1577
+ * sprint. The read is also deliberately WIDE -- stale and
1578
+ * contradiction-flagged rows included, since kb_demote accepts both
1579
+ * and they are the ones most worth re-checking -- and limited to
1580
+ * KB_DEMOTION_READ_LIMIT rather than the offer cap.
1581
+ *
1582
+ * THEN FILTER, THEN CAP, in that order. Eligibility
1583
+ * (isDemotableCandidate: drops superseded, user-directive and any
1584
+ * non-CONFIRMED row the read let through) and changed-file relevance
1585
+ * run over the WHOLE read; only the survivors are capped at
1586
+ * KB_MAX_DEMOTION_CANDIDATES. Capping first would make the offer cap
1587
+ * a read pre-filter and let a maintainer with many owned CONFIRMED
1588
+ * rows have every genuinely relevant one truncated away before
1589
+ * anything checked whether it was relevant.
1590
+ *
1591
+ * SCOPE IS AN ARGUMENT, NOT A GUESS ABOUT THE CALLER. UNLIKE
1592
+ * promotionCandidates (windowed by sprint start time), an entry is
1593
+ * kept only when it touches a file in the changed-file set of the
1594
+ * review being prepared, and WHICH set that is comes from
1595
+ * `opts.scope`, never from inspecting who called:
1596
+ *
1597
+ * 'round' (default) -- a PER-ROUND review. `roundChangedFiles`
1598
+ * fetches and fast-forward-merges the maintainer's checkout, THEN
1599
+ * diffs from the previous round's merged tip (or, on the first
1600
+ * round, the sprint's base branch) to the new one. Computed AFTER
1601
+ * the merge so it reflects this round's commits rather than a
1602
+ * stale pre-merge snapshot.
1603
+ * 'sprint' -- the FINAL review, which judges the whole sprint diff
1604
+ * and therefore has no "this round": `sprintChangedFiles` gives
1605
+ * the CUMULATIVE baseBranch...branch diff.
1606
+ *
1607
+ * Neither is kbInjection's `diffFiles` (the KB-injection hint
1608
+ * context's own cumulative diff), and promotionCandidates is
1609
+ * unchanged by all of this.
1610
+ *
1611
+ * Demoting a CONFIRMED claim this review never re-checked is never
1612
+ * this review's to offer, so an empty changed-file set offers
1613
+ * nothing.
1614
+ *
1615
+ * Best-effort like every other KB read here: no maintainer, an
1616
+ * unreachable one, no changed-files callback wired for the requested
1617
+ * scope, a diff that could not be computed, or an erroring/rejecting
1618
+ * kb_query all degrade to [] and must never fail the review dispatch
1619
+ * -- per-round or final.
1620
+ *
1621
+ * @param {object} member
1622
+ * @param {{ scope?: 'round'|'sprint' }} [opts]
1623
+ * @returns {Promise<object[]>}
1624
+ */
1625
+ async demotionCandidates(member, { scope = 'round' } = {}) {
1626
+ // Explicit, and explicitly validated: an unknown scope is a wiring
1627
+ // bug, and silently falling back to the round diff at FINAL review
1628
+ // would offer the reviewer a set scoped to a round that does not
1629
+ // exist. Degrade to nothing rather than to the wrong scope.
1630
+ if (!demotionLoopOn) {
1631
+ log("[kb-work] reviewer demotion loop is disabled by the kb_demotion_loop setting ('off'): offering no demotion candidates.");
1632
+ offeredDemotions.clear();
1633
+ return [];
1634
+ }
1635
+ if (scope !== 'round' && scope !== 'sprint') {
1636
+ log(`[kb-work] demotion candidates requested with unknown scope '${scope}' (non-fatal): offering none.`);
1637
+ return [];
1638
+ }
1639
+ const changedFilesFor = scope === 'sprint' ? sprintChangedFiles : roundChangedFiles;
1640
+ const scopeLabel = scope === 'sprint' ? "this sprint's cumulative" : "this round's";
1641
+ const target = active ? reviewMaintainerFor(memberNameOf(member)) : null;
1642
+ if (!target) return [];
1643
+ // Replace (never accumulate) this review scope's offered set up
1644
+ // front, so a failed read leaves nothing offered from a prior
1645
+ // round -- and so the FINAL review's call cannot inherit the last
1646
+ // per-round call's offers either.
1647
+ offeredDemotions.set(target.repo, new Set());
1648
+ // Writes still queued for this repository (a capture or a
1649
+ // promotion/discard from this very round) get their chance to
1650
+ // land before the read, same as promotionCandidates.
1651
+ if (queues.has(target.repo)) await flush(target.repo);
1652
+ if (typeof changedFilesFor !== 'function') return [];
1653
+ // Same isBusy/inFlight bracket flushRepo and commitRepo use: the
1654
+ // read below G-pulls the maintainer's checkout and runs git and
1655
+ // kb_query there, so it must neither start while a dispatch is
1656
+ // running on the maintainer nor run concurrently with one that
1657
+ // starts mid-read (dispatchStarted() awaits the inFlight entry).
1658
+ // Taken AFTER flush() above, which brackets itself.
1659
+ if (isBusy(target.member)) {
1660
+ log(`[kb-work] maintainer '${target.member}' is mid-dispatch -- no pull and no demotion candidate read over ${scopeLabel} changed files for ${target.repo}; offering none`);
232
1661
  return [];
233
1662
  }
1663
+ let release;
1664
+ inFlight.set(target.member, new Promise((r) => { release = r; }));
1665
+ try {
1666
+ return await readDemotionCandidates(target, changedFilesFor, scopeLabel);
1667
+ } finally {
1668
+ inFlight.delete(target.member);
1669
+ release();
1670
+ }
234
1671
  },
235
1672
  /**
236
1673
  * KB audit follow-up: the per-dispatch, relevance-ranked read.
@@ -245,160 +1682,159 @@ export function createKbWorkClient(opts = {}) {
245
1682
  * been writing `refines` and `contradiction_of` edges since AUDN
246
1683
  * shipped and traversing none of them: 554 edges, 0 reads. A role about
247
1684
  * 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).
1685
+ * newer framing -- a CONFIRMED refinement arrives as a related claim.
252
1686
  *
253
- * Best-effort, like every other KB read here: no repo path, no terms, a
1687
+ * Only CONFIRMED, undisputed entries are requested and kept (see
1688
+ * isInjectableKbEntry). A contradiction pair is excluded on BOTH sides
1689
+ * rather than shown as a dispute: confidence tier does NOT track
1690
+ * correctness across a contradiction chain (the warehouse chain-A
1691
+ * shape, where the incorrect entry outranks both of its corrections),
1692
+ * so neither side is safe to hand a role as knowledge until the pair is
1693
+ * resolved.
1694
+ *
1695
+ * Best-effort, like every other KB read here: no member, no terms, a
254
1696
  * cold KB or an unreachable one all degrade to "no knowledge", never to
255
1697
  * a failed dispatch.
256
1698
  */
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 [];
1699
+ async relevantKnowledge(member, hints) {
1700
+ return (await this.knowledgeFor(member, hints)).entries;
1701
+ },
1702
+ /**
1703
+ * The per-dispatch read behind the KNOWLEDGE BANK block: the entries
1704
+ * AND the source they really came from.
1705
+ *
1706
+ * Read from the repository's kb_maintainer through memberCall -- never
1707
+ * from the dispatched member (whose own KB may be cold, absent or on
1708
+ * a different checkout) and never from the orchestrator session. A
1709
+ * client built without a maintainer selector (unit-test seam) reads as
1710
+ * the member it is given.
1711
+ *
1712
+ * `hints` is either a bare term list or {terms, hintSymbols,
1713
+ * hintModules} (kb-hints.mjs roleHints). Order: kb_query on the
1714
+ * terms; when that finds nothing, kb_session_prime ranked by
1715
+ * hint_symbols/hint_modules; when that finds nothing too, NOTHING --
1716
+ * there is deliberately no fall-back to an arbitrary set.
1717
+ *
1718
+ * @returns {Promise<{ entries: object[], source: 'query'|'prime' }>}
1719
+ */
1720
+ async knowledgeFor(member, hints) {
1721
+ const h = Array.isArray(hints)
1722
+ ? { terms: hints, hintSymbols: [], hintModules: [] }
1723
+ : { terms: [], hintSymbols: [], hintModules: [], ...(hints || {}) };
1724
+ const strs = (v) => (Array.isArray(v) ? v.filter((t) => typeof t === 'string' && t.trim()) : []);
1725
+ const terms = strs(h.terms);
1726
+ const hintSymbols = strs(h.hintSymbols);
1727
+ const hintModules = strs(h.hintModules);
1728
+ const nothing = { entries: [], source: terms.length > 0 || hintSymbols.length + hintModules.length === 0 ? 'query' : 'prime' };
1729
+ if (!active || !member) return nothing;
1730
+ if (terms.length === 0 && hintSymbols.length === 0 && hintModules.length === 0) return nothing;
1731
+ const target = readTarget(member);
1732
+ if (!target) {
1733
+ log(`[kb-work] no kb_maintainer to read knowledge from for ${memberLabel(member)} -- no knowledge this dispatch`);
1734
+ return nothing;
1735
+ }
1736
+ if (terms.length > 0) {
1737
+ const queried = await queryEntries(target, terms.join(' '));
1738
+ if (queried.length > 0) return { entries: queried, source: 'query' };
304
1739
  }
1740
+ if (hintSymbols.length > 0 || hintModules.length > 0) {
1741
+ const primed = await primeEntries(target, hintSymbols, hintModules);
1742
+ if (primed.length > 0) return { entries: primed, source: 'prime' };
1743
+ }
1744
+ return nothing;
305
1745
  },
306
- async apply(role, repoPath, result) {
307
- const { captures, promotions, refused } = vetKbWork(role, result);
1746
+ /**
1747
+ * Vet a role's KB work and route it to the producing member's
1748
+ * repository maintainer: queued per repository, then applied in the
1749
+ * maintainer's MEMBER session after a G-pull (see the client header).
1750
+ * `member` names the member whose dispatch produced `result` (a member
1751
+ * record or a bare name); it decides WHICH repository, never which
1752
+ * session -- no write is ever sent to it unless it is the maintainer.
1753
+ *
1754
+ * @returns {Promise<{captured: number, promoted: number, discarded: number, demoted: number, refused: number}>}
1755
+ * counts of the writes applied by this call's flush (writes left
1756
+ * queued for a busy or unreachable maintainer are not counted).
1757
+ */
1758
+ async apply(role, member, result) {
1759
+ const vetted = vetKbWork(role, result);
1760
+ const { captures, promotions, discards, refused } = vetted;
1761
+ let demotions = vetted.demotions;
1762
+ if (!demotionLoopOn && demotions.length > 0) {
1763
+ log(`[kb-work] reviewer demotion loop is disabled by the kb_demotion_loop setting ('off'): ${demotions.length} demotion(s) from ${role} dropped, no kb_demote issued.`);
1764
+ demotions = [];
1765
+ }
308
1766
 
309
1767
  for (const r of refused) log(`[kb-work] refused -- ${r}`);
310
1768
  // Log every promotion with its stated evidence BEFORE attempting it.
311
1769
  // This log is the audit trail the bible never had.
312
1770
  for (const p of promotions) log(`[kb-work] promote ${p.id} (${role}): ${p.reason}`);
1771
+ for (const d of discards) log(`[kb-work] discard ${d.id} (${role}): ${d.reason}`);
1772
+ for (const d of demotions) log(`[kb-work] demote ${d.id} (${role}): ${d.reason}`);
313
1773
 
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
- }
1774
+ let extraRefused = 0;
1775
+ const done = (counts) => ({ ...counts, refused: refused.length + extraRefused });
1776
+ if (captures.length === 0 && promotions.length === 0 && discards.length === 0 && demotions.length === 0) return done(zeroCounts());
1777
+ const dropped = `${captures.length} capture(s), ${promotions.length} promotion(s), ${discards.length} discard(s) and ${demotions.length} demotion(s) dropped`;
322
1778
 
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
- }
1779
+ const producer = memberNameOf(member);
1780
+ // Without a resolved member there is no repository the writes
1781
+ // belong to -- the tm7 defect. Refuse rather than guess.
1782
+ if (!active || !producer) {
1783
+ log(`[kb-work] WARN: no member resolved for ${role} -- ${dropped}`);
1784
+ return done(zeroCounts());
340
1785
  }
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;
1786
+ const sel = selector();
1787
+ const nonRepo = !!(sel && typeof sel.isNonRepoMember === 'function' && sel.isNonRepoMember(producer));
1788
+ // A capture belongs to the PRODUCER's repository: a member whose
1789
+ // work folder is not a repository has none, so its captures are
1790
+ // dropped. Review judgements (CONFIRM/DISCARD/DEMOTE) act on
1791
+ // candidates read from the reviewer's maintainer
1792
+ // (reviewMaintainerFor), so they follow the same resolution as
1793
+ // the candidate read.
1794
+ let target = null;
1795
+ if (captures.length > 0) {
1796
+ if (nonRepo) {
1797
+ log(`[kb-work] WARN: member '${producer}' (${role}): work folder is not a repository -- ${captures.length} capture(s) dropped`);
1798
+ } else {
1799
+ target = maintainerFor(producer);
1800
+ if (target) {
1801
+ for (const c of captures) enqueue(target.repo, 'capture', role, c);
1802
+ } else {
1803
+ log(`[kb-work] WARN: no kb_maintainer for member '${producer}' (${role}) -- ${captures.length} capture(s) dropped`);
354
1804
  }
355
- promoted++;
356
- } catch (err) {
357
- log(`[kb-work] kb_promote failed for ${p.id} (non-fatal): ${err.message}`);
358
1805
  }
359
1806
  }
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;
1807
+ const repos = new Set(target ? [target.repo] : []);
1808
+ if (promotions.length > 0 || discards.length > 0 || demotions.length > 0) {
1809
+ const review = reviewMaintainerFor(producer);
1810
+ if (review) {
1811
+ // Only ids offered in this dispatch's candidate block may be
1812
+ // judged; anything else is refused before any kb_* call.
1813
+ // Demotions are filtered against their OWN offered set
1814
+ // (offeredDemotions), never the promotion one -- an id
1815
+ // offered for promotion is not thereby offered for demotion.
1816
+ const offered = offeredCandidates.get(review.repo) || new Set();
1817
+ const offeredToDemote = offeredDemotions.get(review.repo) || new Set();
1818
+ const inBlock = (kind, x, offeredSet) => {
1819
+ if (offeredSet.has(x.id)) return true;
1820
+ log(`[kb-work] refused -- ${role}: ${kind} ${x.id} not in this dispatch's candidate block`);
1821
+ extraRefused += 1;
1822
+ return false;
1823
+ };
1824
+ for (const p of promotions) if (inBlock('promotion', p, offered)) enqueue(review.repo, 'promote', role, p);
1825
+ for (const d of discards) if (inBlock('discard', d, offered)) enqueue(review.repo, 'discard', role, d);
1826
+ for (const d of demotions) if (inBlock('demotion', d, offeredToDemote)) enqueue(review.repo, 'demote', role, d);
1827
+ repos.add(review.repo);
1828
+ } else {
1829
+ log(`[kb-work] WARN: no kb_maintainer for member '${producer}' (${role}) -- ${promotions.length} promotion(s), ${discards.length} discard(s) and ${demotions.length} demotion(s) dropped`);
395
1830
  }
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
1831
  }
1832
+ const counts = zeroCounts();
1833
+ for (const repo of repos) {
1834
+ const c = await flush(repo);
1835
+ for (const k of Object.keys(counts)) counts[k] += c[k];
1836
+ }
1837
+ return done(counts);
402
1838
  },
403
1839
  };
404
1840
  }
@@ -407,32 +1843,62 @@ export function createKbWorkClient(opts = {}) {
407
1843
  * apra-fleet-e28 / KB trust pipeline Phase 2: KB priming for the fleet-sprint
408
1844
  * engine, which had none -- it lived only in the Claude workflow copy.
409
1845
  *
410
- * `callTool` is injected exactly like `createMemberReservationClient`'s, so this
411
- * stays transport-agnostic and unit-testable without a live fleet server.
1846
+ * `callTool` (the orchestrator's own session, used only for member_detail) and
1847
+ * `memberCall` (member-call.mjs: a MEMBER-scoped session on that member) are
1848
+ * injected, so this stays transport-agnostic and unit-testable without a live
1849
+ * fleet server.
412
1850
  *
413
- * WHY PER MEMBER, NOT PER SPRINT: this engine has no repo path of its own. It
1851
+ * WHY PER MEMBER, NOT PER SPRINT: this engine has no repo of its own. It
414
1852
  * 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.
1853
+ * possibly on a different host at a different path. A kb_* call operates on
1854
+ * the CALLING SESSION's own KB -- a member session resolves that member's
1855
+ * registered work folder -- so each member is primed through its own member
1856
+ * session. Priming through the orchestrator's session would read whichever
1857
+ * repo the fleet server sits in (the apra-fleet-tm7 / apra-fleet-3zl
1858
+ * repo-blindness defect). member_detail supplies the member's id and type
1859
+ * (what memberCall needs) and its work folder.
422
1860
  *
423
1861
  * 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.
1862
+ * that cannot be resolved, or whose prime call fails, is logged and skipped. A
1863
+ * sprint must not fail because the KB is cold -- priming is an optimisation,
1864
+ * and every role contract's Step 0 already degrades gracefully when the KB
1865
+ * tools are unavailable.
428
1866
  *
429
- * @param {{ callTool?: (name: string, args: object) => Promise<any>, members?: string[], log?: Function }} opts
1867
+ * @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
1868
  * @returns {{ primeAll: () => Promise<{primed: number, skipped: number}> }}
431
1869
  */
432
1870
 
433
1871
  export function createKbPrimingClient(opts = {}) {
434
- const { callTool, members = [], log = () => {} } = opts;
435
- const active = typeof callTool === 'function' && members.length > 0;
1872
+ const { callTool, memberCall, members = [], log = () => {} } = opts;
1873
+ // A plain branch name only (it becomes refs/remotes/origin/<base>).
1874
+ const baseBranch = (typeof opts.baseBranch === 'string' && /^[A-Za-z0-9_][A-Za-z0-9._/-]*$/.test(opts.baseBranch) && !opts.baseBranch.includes('..'))
1875
+ ? opts.baseBranch : null;
1876
+ const maintainerSel = () => {
1877
+ const m = typeof opts.maintainers === 'function' ? opts.maintainers() : opts.maintainers;
1878
+ return (m && typeof m.maintainerForMember === 'function') ? m : null;
1879
+ };
1880
+ /**
1881
+ * True when `target`'s kb_import accepts `ref`: always for a local member
1882
+ * (served by this process); for a remote member only when its tools/list
1883
+ * advertises the property. Any doubt (no listTools, an unreadable answer)
1884
+ * is false.
1885
+ */
1886
+ async function supportsImportRef(target) {
1887
+ if (String(target && (target.type || target.agentType) || '').toLowerCase() === 'local') return true;
1888
+ if (typeof opts.listTools !== 'function') return false;
1889
+ try {
1890
+ const list = parseResult(await opts.listTools(target));
1891
+ const tools = Array.isArray(list) ? list : (list && Array.isArray(list.tools) ? list.tools : []);
1892
+ const imp = tools.find((t) => t && t.name === 'kb_import');
1893
+ const props = imp && imp.inputSchema && imp.inputSchema.properties;
1894
+ return !!(props && typeof props === 'object' && Object.prototype.hasOwnProperty.call(props, 'ref'));
1895
+ } catch {
1896
+ return false;
1897
+ }
1898
+ }
1899
+ /** maintainer record id -> entries primed there (a repository is imported and primed once). */
1900
+ const primedByTarget = new Map();
1901
+ const active = typeof callTool === 'function' && typeof memberCall === 'function' && members.length > 0;
436
1902
 
437
1903
  function parseResult(result) {
438
1904
  if (result && typeof result === 'string') { try { return JSON.parse(result); } catch { return null; } }
@@ -442,42 +1908,34 @@ export function createKbPrimingClient(opts = {}) {
442
1908
  return (result && typeof result === 'object') ? result : null;
443
1909
  }
444
1910
 
445
- async function scopeFor(member) {
1911
+ async function resolveMember(member) {
446
1912
  // apra-fleet-n78: format:'json' is REQUIRED. member_detail defaults to
447
1913
  // 'compact', whose renderer emits no folder at all -- `folder` is set only
448
1914
  // on the json path (src/tools/member-detail.ts). Omitting it made this
449
1915
  // return null for every member, so the KB was never primed for anyone.
450
1916
  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));
1917
+ const d = detail && (detail.member && typeof detail.member === 'object' ? { ...detail.member, ...detail } : detail);
1918
+ const folder = d && d.folder;
1919
+ const id = d && d.id;
457
1920
  return {
458
1921
  folder: (typeof folder === 'string' && folder.length > 0) ? folder : null,
459
- remoteUrl: (typeof url === 'string' && url.length > 0) ? url : null,
1922
+ // The record memberCall needs: the member's id (session identity)
1923
+ // and type (local -> in-process session, remote/relay -> the member's
1924
+ // own `apra-fleet call`).
1925
+ record: (typeof id === 'string' && id.length > 0)
1926
+ ? { id, name: member, type: typeof d.type === 'string' ? d.type : undefined }
1927
+ : null,
460
1928
  };
461
1929
  }
462
1930
 
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.
1931
+ // member -> work folder, populated by primeAll(). Informational: no kb_*
1932
+ // call takes it any more (the member session resolves it server-side).
466
1933
  const folders = new Map();
467
1934
 
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');
1935
+ // member name -> the member record memberCall needs ({id, name, type}).
1936
+ // createKbWorkClient's calls take this record, so a capture lands in the
1937
+ // KB of the member that actually did the work.
1938
+ const records = new Map();
481
1939
 
482
1940
  // member -> the entries kb_session_prime returned for that member.
483
1941
  //
@@ -497,24 +1955,9 @@ export function createKbPrimingClient(opts = {}) {
497
1955
  folderOf(member) {
498
1956
  return folders.get(member) || null;
499
1957
  },
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;
1958
+ /** The member record ({id, name, type}) kb work for `member` runs as, or null. */
1959
+ memberOf(member) {
1960
+ return records.get(member) || null;
518
1961
  },
519
1962
  knowledgeOf(member) {
520
1963
  return knowledge.get(member) || [];
@@ -525,25 +1968,34 @@ export function createKbPrimingClient(opts = {}) {
525
1968
  let skipped = 0;
526
1969
  for (const member of members) {
527
1970
  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)`);
1971
+ const { folder, record } = await resolveMember(member);
1972
+ if (folder) folders.set(member, folder);
1973
+ if (!record) {
1974
+ // No member id means no member session to scope the KB to.
1975
+ // Priming any other way would read the fleet server's own
1976
+ // KB, so skip instead.
1977
+ log(`[kb-prime] could not resolve member '${member}' -- skipping (KB stays cold)`);
544
1978
  skipped++;
545
1979
  continue;
546
1980
  }
1981
+ records.set(member, record);
1982
+ // Knowledge is read from the repository's kb_maintainer, not
1983
+ // the member itself. A sprint without a selector primes the
1984
+ // member's own session (unit-test seam).
1985
+ const sel = maintainerSel();
1986
+ const m = sel ? sel.maintainerForMember(member) : null;
1987
+ const target = sel ? (m && m.record ? m.record : null) : record;
1988
+ if (!target) {
1989
+ log(`[kb-prime] no kb_maintainer for member '${member}' -- no knowledge primed`);
1990
+ primed++;
1991
+ continue;
1992
+ }
1993
+ if (primedByTarget.has(target.id)) {
1994
+ const shared = primedByTarget.get(target.id);
1995
+ if (shared.length > 0) knowledge.set(member, shared);
1996
+ primed++;
1997
+ continue;
1998
+ }
547
1999
  // Land the committed bible in the WARM KB before priming.
548
2000
  //
549
2001
  // Without this the bible is reachable only through
@@ -563,26 +2015,77 @@ export function createKbPrimingClient(opts = {}) {
563
2015
  // sprint start that staled 16 of 17 CONFIRMED entries purely
564
2016
  // because the repo had moved on since capture, and the
565
2017
  // damage cascaded: retrieval fell to one matchable entry,
566
- // kb_export attempted a 17 -> 9 bible truncation, and
2018
+ // the whole-bible publish attempted a 17 -> 9 truncation, and
567
2019
  // kb_list (stale=0) returned an EMPTY promotion candidate
568
2020
  // list -- reinstating apra-fleet-0ef, "kb_promote can never
569
2021
  // fire". This import exists to WARM the KB, never to audit
570
2022
  // it; prime()'s own bounded checkFreshness still guards each
571
2023
  // entry it actually returns.
2024
+ //
2025
+ // The import on a repository's kb_maintainer runs WITH the
2026
+ // kb_maintainer grant. A session without the grant imports
2027
+ // a committed bible only when the maintainer side already
2028
+ // recorded it as trusted in the hub-side KB, so a bible
2029
+ // this hub never saw (a fresh hub, or a bible merged in
2030
+ // from elsewhere) would never land. The grant import is
2031
+ // the trusted seeding path, and the bible it imports is
2032
+ // marked trusted for every member of the repository -- so
2033
+ // it must not come from the maintainer's work tree or
2034
+ // HEAD. Nothing has cleaned that checkout yet: launch
2035
+ // alignment runs only for some launch modes, branch-ensure
2036
+ // runs after priming, and a reused local branch keeps
2037
+ // local-only commits. The grant import therefore reads the
2038
+ // bible committed on the base branch's remote-tracking ref
2039
+ // (full ref name, so a local branch named origin/<base>
2040
+ // cannot shadow it), which the server verifies against its
2041
+ // blob id. No base branch: no grant import. A sprint
2042
+ // without a maintainer selector (unit-test seam) imports
2043
+ // without the grant, which never records trust.
572
2044
  try {
573
- const imported = parseResult(await callTool('kb_import', { repo_path: repoPath, ...kbScope(remoteUrl), skip_sweep: true }));
574
- 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}`);
2045
+ // No `path`: the session imports its OWN folder's
2046
+ // bible (.fleet/kb-canonical.json), here at `ref`.
2047
+ let imported = null;
2048
+ if (!sel) {
2049
+ imported = parseResult(await memberCall(target, 'kb_import', { skip_sweep: true }));
2050
+ } else if (baseBranch) {
2051
+ const ref = 'refs/remotes/origin/' + baseBranch;
2052
+ // A REMOTE maintainer runs its own apra-fleet: an
2053
+ // older one drops the unknown `ref` key and would
2054
+ // grant-import (and trust) its WORK-TREE bible. Fail
2055
+ // closed: import only when its kb_import advertises
2056
+ // `ref`. A local member runs in this server.
2057
+ if (await supportsImportRef(target)) {
2058
+ imported = parseResult(await memberCall(target, 'kb_import', { skip_sweep: true, ref }, KB_MAINTAINER_CALL));
2059
+ if (imported && imported.bible_source !== ref) {
2060
+ 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`);
2061
+ }
2062
+ } else {
2063
+ 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`);
2064
+ }
2065
+ } else {
2066
+ log(`[kb-prime] no base branch -- bible import skipped for '${member}' (the kb_maintainer imports only the base branch's committed bible)`);
2067
+ }
2068
+ if (imported && imported.bible_skipped === true) {
2069
+ // An http project KB: the KB server is the source of
2070
+ // truth, so the member imported nothing.
2071
+ log(`[kb-prime] no bible import for '${member}': ${imported.reason || 'the KB is served over http'}`);
2072
+ } else if (imported && typeof imported.imported === 'number' && imported.imported > 0) {
2073
+ log(`[kb-prime] imported ${imported.imported} bible entr(ies) into the warm KB for '${member}'`);
576
2074
  }
577
2075
  } catch (err) {
578
- log(`[kb-prime] kb_import skipped for ${repoPath} (non-fatal): ${err.message}`);
2076
+ log(`[kb-prime] kb_import skipped for '${member}' (non-fatal): ${err.message}`);
579
2077
  }
580
2078
 
581
- const primeResult = parseResult(await callTool('kb_session_prime', { repo_path: repoPath, ...kbScope(remoteUrl) }));
2079
+ const primeResult = parseResult(await memberCall(target, 'kb_session_prime', {}));
2080
+ // Same injection rule as relevantKnowledge, applied BEFORE the
2081
+ // cap so a prime dominated by INFERRED captures does not
2082
+ // crowd out the CONFIRMED entries behind them.
582
2083
  const entries = (primeResult && Array.isArray(primeResult.top_entries))
583
- ? primeResult.top_entries.filter((e) => e && typeof e.id === 'string')
2084
+ ? primeResult.top_entries.filter((e) => typeof e?.id === 'string' && isInjectableKbEntry(e))
584
2085
  : [];
585
- if (entries.length > 0) knowledge.set(member, entries.slice(0, KB_MAX_KNOWLEDGE_ENTRIES));
2086
+ const capped = entries.slice(0, KB_MAX_KNOWLEDGE_ENTRIES);
2087
+ primedByTarget.set(target.id, capped);
2088
+ if (capped.length > 0) knowledge.set(member, capped);
586
2089
  primed++;
587
2090
  } catch (err) {
588
2091
  log(`[kb-prime] failed for member '${member}' (non-fatal): ${err.message}`);
@@ -625,9 +2128,11 @@ export function createKbPrimingClient(opts = {}) {
625
2128
  * (an apra-pm orchestrator session running these contracts as local subagents,
626
2129
  * where the MCP server is present), so both paths now get knowledge.
627
2130
  *
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.
2131
+ * Only CONFIRMED, undisputed entries are rendered (isInjectableKbEntry) --
2132
+ * every caller's source is already filtered, and this is the last chokepoint
2133
+ * before the prompt. CONFIRMED means a reviewer verified the claim when it was
2134
+ * captured, not that it is currently true of this branch's tree, which is why
2135
+ * the header still tells the role the code wins.
631
2136
  *
632
2137
  * Returns a single-element array (or an empty one) so callers can spread it
633
2138
  * into their prompt-section list, matching kbPromotionBlock.
@@ -661,32 +2166,62 @@ export const KB_SELF_INJECTING_ROLES = Object.freeze(new Set([ROLE_DOER, ROLE_RE
661
2166
  * @returns {string[]}
662
2167
  */
663
2168
  export function kbQueryTerms(beads, beadIds) {
664
- const terms = [];
2169
+ // Bead TITLES only: tracker ids and stopwords are stripped (they match
2170
+ // nothing useful and only add ranking noise), so a bead id in `beadIds`
2171
+ // never reaches the query -- it is passed solely so a stray id inside a
2172
+ // title is recognised and dropped too.
2173
+ const titles = [];
665
2174
  for (const b of Array.isArray(beads) ? beads : []) {
666
- if (b && typeof b.title === 'string' && b.title.trim()) terms.push(b.title.trim());
667
- }
668
- for (const id of Array.isArray(beadIds) ? beadIds : []) {
669
- if (typeof id === 'string' && id.trim()) terms.push(id.trim());
2175
+ if (b && typeof b.title === 'string' && b.title.trim()) titles.push(b.title.trim());
670
2176
  }
671
- return terms;
2177
+ const knownIds = (Array.isArray(beadIds) ? beadIds : []).filter((id) => typeof id === 'string' && id.trim());
2178
+ return cleanQueryTerms(titles, { knownIds });
672
2179
  }
673
2180
 
674
- export function kbKnowledgeBlock(entries) {
675
- if (!Array.isArray(entries) || entries.length === 0) return [];
2181
+ // `captureChannel` (default true, the doer/reviewer/final-review prompt
2182
+ // builders' case) says whether the recipient's returned `kb_captures` field is
2183
+ // actually applied by the engine (a 'kb-apply' postResult step -- see
2184
+ // role-policies.mjs agentTypeAppliesKbCaptures). When it is not, the block
2185
+ // must not promise that the orchestrator records a capture: those roles'
2186
+ // prompts tell them to note the finding in their own report instead.
2187
+ export function kbKnowledgeBlock(entries, { captureChannel = true, source = 'prime', reportEmpty = false } = {}) {
2188
+ if (!Array.isArray(entries)) return [];
2189
+ // CONFIRMED-first, capped at KB_MAX_KNOWLEDGE_ENTRIES. The sources
2190
+ // (relevantKnowledge, primeAll) hand entries over in relevance order, so a
2191
+ // stable CONFIRMED filter + slice keeps the most relevant ones.
2192
+ const injectable = entries.filter(isInjectableKbEntry).slice(0, KB_MAX_KNOWLEDGE_ENTRIES);
2193
+ // The label names where the entries really came from: a per-dispatch
2194
+ // kb_query or the hint-driven kb_session_prime.
2195
+ const label = source === 'query' ? 'kb_query --top_entries' : 'kb_session_prime --top_entries';
2196
+ const captureLine = captureChannel
2197
+ ? 'If you discover something non-obvious and durable while working, report it in the '
2198
+ + '`kb_captures` field of your structured output and the orchestrator will record it.\n'
2199
+ : 'If you discover something non-obvious and durable while working, note it in your '
2200
+ + 'own report.\n';
2201
+ if (injectable.length === 0) {
2202
+ if (!reportEmpty) return [];
2203
+ // Nothing relevant matched: say so explicitly rather than falling back
2204
+ // to an arbitrary set of entries.
2205
+ return [
2206
+ 'KNOWLEDGE BANK -- what this repo already knows. No relevant CONFIRMED knowledge-bank '
2207
+ + 'entries were found for this task (source: ' + (source === 'query' ? 'kb_query' : 'kb_session_prime') + '). '
2208
+ + 'Nothing relevant was found, so no entries are provided; proceed from the code itself.\n'
2209
+ + captureLine,
2210
+ ];
2211
+ }
676
2212
  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) => ({
2213
+ 'KNOWLEDGE BANK -- what this repo already knows. These entries were captured during '
2214
+ + 'earlier work on this repository and are provided so you do not rediscover them the '
2215
+ + 'hard way. Read them BEFORE you start.\n'
2216
+ + 'Only CONFIRMED entries are included: a reviewer promoted each claim on evidence when '
2217
+ + 'it was captured. An entry describes the tree it was captured against, so if one '
2218
+ + 'contradicts what you actually observe in the code right now, the code wins -- say so '
2219
+ + 'in your notes rather than bending your work to fit the entry.\n'
2220
+ + 'You do not need a kb_* tool to read these entries; they do not replace any kb_* lookup '
2221
+ + 'your role instructions call for. '
2222
+ + captureLine
2223
+ + wrapUntrustedBlock(label, JSON.stringify(
2224
+ injectable.map((e) => ({
690
2225
  confidence: e.confidence,
691
2226
  title: e.title,
692
2227
  summary: e.summary,
@@ -698,14 +2233,65 @@ export function kbKnowledgeBlock(entries) {
698
2233
  ];
699
2234
  }
700
2235
 
2236
+ /**
2237
+ * KNOWLEDGE BANK -- demotion candidates. Same bounded shape as
2238
+ * kbPromotionBlock (list the offered ids with enough context to judge, say
2239
+ * nothing when the list is empty) -- the two are read side by side in the
2240
+ * reviewer prompt and must not drift.
2241
+ *
2242
+ * Demotion is CONFIRMED -> INFERRED only, and only for an id actually
2243
+ * offered here (the engine refuses any other id, same as promotion/discard).
2244
+ * ONE judgement: a re-check during this review shows the claim does not hold
2245
+ * -- the reviewer is less certain of it, or has shown it wrong. A drifted or
2246
+ * removed basis is NOT a demote case -- the freshness sweep and the bible
2247
+ * basis predicate already handle that without reviewer judgment.
2248
+ *
2249
+ * @param {object[]|undefined} kbCandidates
2250
+ * @returns {string[]}
2251
+ */
2252
+ export function kbDemotionBlock(kbCandidates) {
2253
+ if (!Array.isArray(kbCandidates) || kbCandidates.length === 0) return [];
2254
+ return [
2255
+ 'KNOWLEDGE BANK -- demotion candidates. These entries are currently CONFIRMED. You are '
2256
+ + 'the only role that can demote one back to INFERRED. Do NOT call any '
2257
+ + 'kb_* tool yourself: return your decisions in your structured output and the '
2258
+ + 'orchestrator executes them -- `kb_demotions` as [{id, reason, evidence_files}] for '
2259
+ + 'entries to demote back to INFERRED.\n'
2260
+ + 'Demote when a re-check during THIS review shows the claim does not hold -- whether '
2261
+ + 'you are now less certain of it or have shown it wrong, it is the same judgement and '
2262
+ + 'the same route. `evidence_files` names the files you re-checked: at least one, each a '
2263
+ + 'real file in the repo; a demotion without one is refused. This is NOT the route for a '
2264
+ + 'drifted or removed basis (the cited code changed or vanished) -- freshness staling and '
2265
+ + 'the bible basis predicate already handle that case without you. Discarding an '
2266
+ + 'unconfirmed (INFERRED) capture you showed to be wrong is `kb_discards` (Step 5), never '
2267
+ + 'a demotion -- demotion only ever applies to an already-CONFIRMED entry.\n'
2268
+ + 'The `reason` must state what you checked this review that contradicts the claim '
2269
+ + '(at least 20 characters, e.g. "re-ran the reopen test cited by this entry and it now '
2270
+ + 'fails"). Demoting nothing is a valid outcome; return [] in that case. Never list the '
2271
+ + 'same id in more than one of `kb_promotions`, `kb_discards` and `kb_demotions`; the '
2272
+ + 'orchestrator refuses it in every list it appears in.\n'
2273
+ + wrapUntrustedBlock('kb_query --tag member:<maintainer> --confidence CONFIRMED', JSON.stringify(
2274
+ kbCandidates.map((e) => ({
2275
+ id: e.id,
2276
+ title: e.title,
2277
+ summary: e.summary,
2278
+ source_files: e.source_files,
2279
+ })),
2280
+ null,
2281
+ 2
2282
+ )),
2283
+ ];
2284
+ }
2285
+
701
2286
  export function kbPromotionBlock(kbCandidates) {
702
2287
  if (!Array.isArray(kbCandidates) || kbCandidates.length === 0) return [];
703
2288
  return [
704
2289
  'KNOWLEDGE BANK -- promotion candidates. These entries were captured during this '
705
2290
  + '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'
2291
+ + 'CONFIRMED, or discard them. Do NOT call any kb_* tool yourself: return your '
2292
+ + 'decisions in your structured output and the orchestrator executes them -- '
2293
+ + '`kb_promotions` as [{id, reason}] for entries to CONFIRM, `kb_discards` as '
2294
+ + '[{id, reason}] for entries to DISCARD.\n'
709
2295
  + 'Promote ONLY entries whose claim you independently verified during THIS review '
710
2296
  + '-- by reading the diff, running the tests, or checking the cited files yourself. '
711
2297
  + 'The `reason` must state that evidence (at least 20 characters, e.g. "verified '
@@ -714,7 +2300,12 @@ export function kbPromotionBlock(kbCandidates) {
714
2300
  + 'resting state, and a wrong CONFIRMED entry is worse than no entry. Never '
715
2301
  + 'blanket-promote, and never promote by module, tag or timestamp. Promoting '
716
2302
  + 'nothing is a valid outcome; return [] in that case.\n'
717
- + wrapUntrustedBlock('kb_list --confidence INFERRED', JSON.stringify(
2303
+ + 'Discard ONLY entries you showed to be WRONG during this review, with the same '
2304
+ + 'evidence bar: the `reason` states what you checked that contradicts the claim. '
2305
+ + 'A discarded entry drops out of every later read. An entry you cannot confirm '
2306
+ + 'is not thereby wrong -- leave it INFERRED. Never list the same id in both '
2307
+ + 'fields; the orchestrator refuses both.\n'
2308
+ + wrapUntrustedBlock('kb_query --tag member:<maintainer> --confidence INFERRED', JSON.stringify(
718
2309
  kbCandidates.map((e) => ({
719
2310
  id: e.id,
720
2311
  title: e.title,