@claude-flow/cli 3.32.1 → 3.32.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (657) hide show
  1. package/.claude/helpers/.helpers-version +1 -1
  2. package/.claude/helpers/helpers.manifest.json +3 -3
  3. package/.claude/helpers/statusline.cjs +24 -17
  4. package/.claude/helpers/statusline.js +19 -31
  5. package/catalog-manifest.json +2 -2
  6. package/package.json +1 -1
  7. package/plugins/ruflo-metaharness/.claude-plugin/plugin.json +1 -1
  8. package/plugins/ruflo-metaharness/scripts/smoke.sh +8 -5
  9. package/plugins/ruflo-metaharness/skills/harness-similarity/SKILL.md +1 -1
  10. package/dist/src/agenticow/speculative-exploration.d.ts +0 -148
  11. package/dist/src/agenticow/speculative-exploration.js +0 -218
  12. package/dist/src/appliance/gguf-engine.d.ts +0 -91
  13. package/dist/src/appliance/gguf-engine.js +0 -425
  14. package/dist/src/appliance/ruvllm-bridge.d.ts +0 -102
  15. package/dist/src/appliance/ruvllm-bridge.js +0 -292
  16. package/dist/src/appliance/rvfa-builder.d.ts +0 -44
  17. package/dist/src/appliance/rvfa-builder.js +0 -329
  18. package/dist/src/appliance/rvfa-distribution.d.ts +0 -97
  19. package/dist/src/appliance/rvfa-distribution.js +0 -370
  20. package/dist/src/appliance/rvfa-format.d.ts +0 -111
  21. package/dist/src/appliance/rvfa-format.js +0 -393
  22. package/dist/src/appliance/rvfa-runner.d.ts +0 -69
  23. package/dist/src/appliance/rvfa-runner.js +0 -237
  24. package/dist/src/appliance/rvfa-signing.d.ts +0 -123
  25. package/dist/src/appliance/rvfa-signing.js +0 -347
  26. package/dist/src/autopilot-state.d.ts +0 -77
  27. package/dist/src/autopilot-state.js +0 -271
  28. package/dist/src/benchmarks/gaia-agent-planning.smoke.d.ts +0 -18
  29. package/dist/src/benchmarks/gaia-agent-planning.smoke.js +0 -253
  30. package/dist/src/benchmarks/gaia-agent.d.ts +0 -198
  31. package/dist/src/benchmarks/gaia-agent.js +0 -651
  32. package/dist/src/benchmarks/gaia-causal-memory.d.ts +0 -133
  33. package/dist/src/benchmarks/gaia-causal-memory.js +0 -281
  34. package/dist/src/benchmarks/gaia-causal-memory.smoke.d.ts +0 -22
  35. package/dist/src/benchmarks/gaia-causal-memory.smoke.js +0 -300
  36. package/dist/src/benchmarks/gaia-convergence.d.ts +0 -138
  37. package/dist/src/benchmarks/gaia-convergence.js +0 -260
  38. package/dist/src/benchmarks/gaia-convergence.smoke.d.ts +0 -19
  39. package/dist/src/benchmarks/gaia-convergence.smoke.js +0 -246
  40. package/dist/src/benchmarks/gaia-critic.d.ts +0 -123
  41. package/dist/src/benchmarks/gaia-critic.js +0 -312
  42. package/dist/src/benchmarks/gaia-critic.smoke.d.ts +0 -21
  43. package/dist/src/benchmarks/gaia-critic.smoke.js +0 -327
  44. package/dist/src/benchmarks/gaia-decomposer.d.ts +0 -125
  45. package/dist/src/benchmarks/gaia-decomposer.js +0 -350
  46. package/dist/src/benchmarks/gaia-decomposer.smoke.d.ts +0 -21
  47. package/dist/src/benchmarks/gaia-decomposer.smoke.js +0 -228
  48. package/dist/src/benchmarks/gaia-e2e-smoke.d.ts +0 -27
  49. package/dist/src/benchmarks/gaia-e2e-smoke.js +0 -136
  50. package/dist/src/benchmarks/gaia-extract.smoke.d.ts +0 -45
  51. package/dist/src/benchmarks/gaia-extract.smoke.js +0 -242
  52. package/dist/src/benchmarks/gaia-hardness/features.d.ts +0 -46
  53. package/dist/src/benchmarks/gaia-hardness/features.js +0 -170
  54. package/dist/src/benchmarks/gaia-hardness/predictor.d.ts +0 -105
  55. package/dist/src/benchmarks/gaia-hardness/predictor.js +0 -260
  56. package/dist/src/benchmarks/gaia-hardness/predictor.smoke.d.ts +0 -20
  57. package/dist/src/benchmarks/gaia-hardness/predictor.smoke.js +0 -235
  58. package/dist/src/benchmarks/gaia-hardness/train-data-loader.d.ts +0 -51
  59. package/dist/src/benchmarks/gaia-hardness/train-data-loader.js +0 -179
  60. package/dist/src/benchmarks/gaia-judge.d.ts +0 -88
  61. package/dist/src/benchmarks/gaia-judge.js +0 -437
  62. package/dist/src/benchmarks/gaia-loader.d.ts +0 -87
  63. package/dist/src/benchmarks/gaia-loader.js +0 -326
  64. package/dist/src/benchmarks/gaia-tools/file_read.d.ts +0 -35
  65. package/dist/src/benchmarks/gaia-tools/file_read.js +0 -403
  66. package/dist/src/benchmarks/gaia-tools/grounded_query.d.ts +0 -126
  67. package/dist/src/benchmarks/gaia-tools/grounded_query.js +0 -225
  68. package/dist/src/benchmarks/gaia-tools/index.d.ts +0 -32
  69. package/dist/src/benchmarks/gaia-tools/index.js +0 -36
  70. package/dist/src/benchmarks/gaia-tools/types.d.ts +0 -62
  71. package/dist/src/benchmarks/gaia-tools/types.js +0 -12
  72. package/dist/src/benchmarks/gaia-tools/web_search.d.ts +0 -30
  73. package/dist/src/benchmarks/gaia-tools/web_search.js +0 -210
  74. package/dist/src/benchmarks/gaia-voting.d.ts +0 -88
  75. package/dist/src/benchmarks/gaia-voting.js +0 -297
  76. package/dist/src/benchmarks/gaia-voting.smoke.d.ts +0 -20
  77. package/dist/src/benchmarks/gaia-voting.smoke.js +0 -332
  78. package/dist/src/benchmarks/pretrain/index.d.ts +0 -58
  79. package/dist/src/benchmarks/pretrain/index.js +0 -404
  80. package/dist/src/business-pods/bbs-budget-tracker.d.ts +0 -139
  81. package/dist/src/business-pods/bbs-budget-tracker.js +0 -358
  82. package/dist/src/business-pods/domain-affinity-policy.d.ts +0 -47
  83. package/dist/src/business-pods/domain-affinity-policy.js +0 -65
  84. package/dist/src/business-pods/pod-schema.d.ts +0 -96
  85. package/dist/src/business-pods/pod-schema.js +0 -225
  86. package/dist/src/commands/advisor.d.ts +0 -15
  87. package/dist/src/commands/advisor.js +0 -94
  88. package/dist/src/commands/agent-wasm.d.ts +0 -14
  89. package/dist/src/commands/agent-wasm.js +0 -333
  90. package/dist/src/commands/agent.d.ts +0 -8
  91. package/dist/src/commands/agent.js +0 -927
  92. package/dist/src/commands/analyze.d.ts +0 -19
  93. package/dist/src/commands/analyze.js +0 -2047
  94. package/dist/src/commands/announcements.d.ts +0 -17
  95. package/dist/src/commands/announcements.js +0 -0
  96. package/dist/src/commands/appliance-advanced.d.ts +0 -9
  97. package/dist/src/commands/appliance-advanced.js +0 -215
  98. package/dist/src/commands/appliance.d.ts +0 -8
  99. package/dist/src/commands/appliance.js +0 -404
  100. package/dist/src/commands/autopilot.d.ts +0 -15
  101. package/dist/src/commands/autopilot.js +0 -407
  102. package/dist/src/commands/benchmark.d.ts +0 -10
  103. package/dist/src/commands/benchmark.js +0 -460
  104. package/dist/src/commands/claims.d.ts +0 -10
  105. package/dist/src/commands/claims.js +0 -620
  106. package/dist/src/commands/cleanup.d.ts +0 -13
  107. package/dist/src/commands/cleanup.js +0 -250
  108. package/dist/src/commands/completions.d.ts +0 -10
  109. package/dist/src/commands/completions.js +0 -539
  110. package/dist/src/commands/config.d.ts +0 -8
  111. package/dist/src/commands/config.js +0 -428
  112. package/dist/src/commands/daemon.d.ts +0 -59
  113. package/dist/src/commands/daemon.js +0 -1733
  114. package/dist/src/commands/deployment.d.ts +0 -10
  115. package/dist/src/commands/deployment.js +0 -672
  116. package/dist/src/commands/doctor.d.ts +0 -10
  117. package/dist/src/commands/doctor.js +0 -1695
  118. package/dist/src/commands/eject.d.ts +0 -33
  119. package/dist/src/commands/eject.js +0 -195
  120. package/dist/src/commands/embeddings.d.ts +0 -18
  121. package/dist/src/commands/embeddings.js +0 -1623
  122. package/dist/src/commands/funnel.d.ts +0 -18
  123. package/dist/src/commands/funnel.js +0 -302
  124. package/dist/src/commands/gaia-bench.d.ts +0 -40
  125. package/dist/src/commands/gaia-bench.js +0 -597
  126. package/dist/src/commands/guidance.d.ts +0 -8
  127. package/dist/src/commands/guidance.js +0 -556
  128. package/dist/src/commands/hive-mind.d.ts +0 -11
  129. package/dist/src/commands/hive-mind.js +0 -1319
  130. package/dist/src/commands/hooks.d.ts +0 -8
  131. package/dist/src/commands/hooks.js +0 -4595
  132. package/dist/src/commands/index.d.ts +0 -118
  133. package/dist/src/commands/index.js +0 -364
  134. package/dist/src/commands/init.d.ts +0 -13
  135. package/dist/src/commands/init.js +0 -1297
  136. package/dist/src/commands/issues.d.ts +0 -21
  137. package/dist/src/commands/issues.js +0 -567
  138. package/dist/src/commands/mcp.d.ts +0 -11
  139. package/dist/src/commands/mcp.js +0 -732
  140. package/dist/src/commands/memory-backup.d.ts +0 -11
  141. package/dist/src/commands/memory-backup.js +0 -46
  142. package/dist/src/commands/memory-distill.d.ts +0 -27
  143. package/dist/src/commands/memory-distill.js +0 -374
  144. package/dist/src/commands/memory.d.ts +0 -8
  145. package/dist/src/commands/memory.js +0 -1596
  146. package/dist/src/commands/metaharness.d.ts +0 -39
  147. package/dist/src/commands/metaharness.js +0 -215
  148. package/dist/src/commands/migrate.d.ts +0 -8
  149. package/dist/src/commands/migrate.js +0 -742
  150. package/dist/src/commands/neural.d.ts +0 -10
  151. package/dist/src/commands/neural.js +0 -4331
  152. package/dist/src/commands/performance.d.ts +0 -10
  153. package/dist/src/commands/performance.js +0 -583
  154. package/dist/src/commands/plugins.d.ts +0 -11
  155. package/dist/src/commands/plugins.js +0 -826
  156. package/dist/src/commands/process.d.ts +0 -10
  157. package/dist/src/commands/process.js +0 -694
  158. package/dist/src/commands/progress.d.ts +0 -11
  159. package/dist/src/commands/progress.js +0 -259
  160. package/dist/src/commands/providers.d.ts +0 -10
  161. package/dist/src/commands/providers.js +0 -502
  162. package/dist/src/commands/proxy.d.ts +0 -21
  163. package/dist/src/commands/proxy.js +0 -310
  164. package/dist/src/commands/route.d.ts +0 -16
  165. package/dist/src/commands/route.js +0 -822
  166. package/dist/src/commands/ruvector/backup.d.ts +0 -11
  167. package/dist/src/commands/ruvector/backup.js +0 -747
  168. package/dist/src/commands/ruvector/benchmark.d.ts +0 -11
  169. package/dist/src/commands/ruvector/benchmark.js +0 -490
  170. package/dist/src/commands/ruvector/import.d.ts +0 -18
  171. package/dist/src/commands/ruvector/import.js +0 -373
  172. package/dist/src/commands/ruvector/index.d.ts +0 -29
  173. package/dist/src/commands/ruvector/index.js +0 -129
  174. package/dist/src/commands/ruvector/init.d.ts +0 -11
  175. package/dist/src/commands/ruvector/init.js +0 -467
  176. package/dist/src/commands/ruvector/migrate.d.ts +0 -11
  177. package/dist/src/commands/ruvector/migrate.js +0 -498
  178. package/dist/src/commands/ruvector/optimize.d.ts +0 -11
  179. package/dist/src/commands/ruvector/optimize.js +0 -505
  180. package/dist/src/commands/ruvector/pg-utils.d.ts +0 -14
  181. package/dist/src/commands/ruvector/pg-utils.js +0 -41
  182. package/dist/src/commands/ruvector/setup.d.ts +0 -18
  183. package/dist/src/commands/ruvector/setup.js +0 -765
  184. package/dist/src/commands/ruvector/status.d.ts +0 -11
  185. package/dist/src/commands/ruvector/status.js +0 -479
  186. package/dist/src/commands/security.d.ts +0 -10
  187. package/dist/src/commands/security.js +0 -1007
  188. package/dist/src/commands/session.d.ts +0 -8
  189. package/dist/src/commands/session.js +0 -757
  190. package/dist/src/commands/settings.d.ts +0 -19
  191. package/dist/src/commands/settings.js +0 -180
  192. package/dist/src/commands/spinner.d.ts +0 -16
  193. package/dist/src/commands/spinner.js +0 -329
  194. package/dist/src/commands/start.d.ts +0 -8
  195. package/dist/src/commands/start.js +0 -418
  196. package/dist/src/commands/status.d.ts +0 -8
  197. package/dist/src/commands/status.js +0 -608
  198. package/dist/src/commands/swarm.d.ts +0 -8
  199. package/dist/src/commands/swarm.js +0 -891
  200. package/dist/src/commands/task.d.ts +0 -8
  201. package/dist/src/commands/task.js +0 -675
  202. package/dist/src/commands/transfer-store.d.ts +0 -13
  203. package/dist/src/commands/transfer-store.js +0 -428
  204. package/dist/src/commands/update.d.ts +0 -8
  205. package/dist/src/commands/update.js +0 -276
  206. package/dist/src/commands/verify.d.ts +0 -19
  207. package/dist/src/commands/verify.js +0 -261
  208. package/dist/src/commands/version.d.ts +0 -42
  209. package/dist/src/commands/version.js +0 -106
  210. package/dist/src/commands/workflow.d.ts +0 -8
  211. package/dist/src/commands/workflow.js +0 -617
  212. package/dist/src/config/harness-feedback-applier.d.ts +0 -50
  213. package/dist/src/config/harness-feedback-applier.js +0 -122
  214. package/dist/src/config/proven-config-refresh.d.ts +0 -39
  215. package/dist/src/config/proven-config-refresh.js +0 -154
  216. package/dist/src/config/proven-config-rvfa.d.ts +0 -23
  217. package/dist/src/config/proven-config-rvfa.js +0 -73
  218. package/dist/src/config/proven-config.d.ts +0 -86
  219. package/dist/src/config/proven-config.js +0 -176
  220. package/dist/src/config-adapter.d.ts +0 -15
  221. package/dist/src/config-adapter.js +0 -186
  222. package/dist/src/encryption/vault.d.ts +0 -94
  223. package/dist/src/encryption/vault.js +0 -172
  224. package/dist/src/fs-secure.d.ts +0 -86
  225. package/dist/src/fs-secure.js +0 -133
  226. package/dist/src/funnel/advisor-tip.d.ts +0 -58
  227. package/dist/src/funnel/advisor-tip.js +0 -92
  228. package/dist/src/funnel/attribution.d.ts +0 -37
  229. package/dist/src/funnel/attribution.js +0 -101
  230. package/dist/src/funnel/consent.d.ts +0 -22
  231. package/dist/src/funnel/consent.js +0 -58
  232. package/dist/src/funnel/credit-errors.d.ts +0 -31
  233. package/dist/src/funnel/credit-errors.js +0 -88
  234. package/dist/src/funnel/credit-notifier.d.ts +0 -44
  235. package/dist/src/funnel/credit-notifier.js +0 -74
  236. package/dist/src/funnel/disclosure.d.ts +0 -47
  237. package/dist/src/funnel/disclosure.js +0 -109
  238. package/dist/src/funnel/enrollment.d.ts +0 -36
  239. package/dist/src/funnel/enrollment.js +0 -64
  240. package/dist/src/funnel/environment.d.ts +0 -17
  241. package/dist/src/funnel/environment.js +0 -39
  242. package/dist/src/funnel/event-transport.d.ts +0 -51
  243. package/dist/src/funnel/event-transport.js +0 -199
  244. package/dist/src/funnel/events.d.ts +0 -42
  245. package/dist/src/funnel/events.js +0 -150
  246. package/dist/src/funnel/index.d.ts +0 -21
  247. package/dist/src/funnel/index.js +0 -21
  248. package/dist/src/funnel/insights.d.ts +0 -49
  249. package/dist/src/funnel/insights.js +0 -120
  250. package/dist/src/funnel/local-signals.d.ts +0 -15
  251. package/dist/src/funnel/local-signals.js +0 -68
  252. package/dist/src/funnel/message-transport.d.ts +0 -51
  253. package/dist/src/funnel/message-transport.js +0 -149
  254. package/dist/src/funnel/messages.d.ts +0 -55
  255. package/dist/src/funnel/messages.js +0 -160
  256. package/dist/src/funnel/payout.d.ts +0 -40
  257. package/dist/src/funnel/payout.js +0 -60
  258. package/dist/src/funnel/power-saver-notifier.d.ts +0 -44
  259. package/dist/src/funnel/power-saver-notifier.js +0 -92
  260. package/dist/src/funnel/precedence.d.ts +0 -16
  261. package/dist/src/funnel/precedence.js +0 -85
  262. package/dist/src/funnel/promo.d.ts +0 -41
  263. package/dist/src/funnel/promo.js +0 -144
  264. package/dist/src/funnel/rate-limit-notifier.d.ts +0 -55
  265. package/dist/src/funnel/rate-limit-notifier.js +0 -102
  266. package/dist/src/funnel/rotation.d.ts +0 -19
  267. package/dist/src/funnel/rotation.js +0 -70
  268. package/dist/src/funnel/state.d.ts +0 -13
  269. package/dist/src/funnel/state.js +0 -52
  270. package/dist/src/funnel/toggle-cooldown.d.ts +0 -17
  271. package/dist/src/funnel/toggle-cooldown.js +0 -32
  272. package/dist/src/funnel/types.d.ts +0 -98
  273. package/dist/src/funnel/types.js +0 -26
  274. package/dist/src/index.d.ts +0 -81
  275. package/dist/src/index.js +0 -609
  276. package/dist/src/infrastructure/in-memory-repositories.d.ts +0 -68
  277. package/dist/src/infrastructure/in-memory-repositories.js +0 -264
  278. package/dist/src/init/claudemd-generator.d.ts +0 -16
  279. package/dist/src/init/claudemd-generator.js +0 -368
  280. package/dist/src/init/executor.d.ts +0 -41
  281. package/dist/src/init/executor.js +0 -2142
  282. package/dist/src/init/helper-refresh.d.ts +0 -79
  283. package/dist/src/init/helper-refresh.js +0 -347
  284. package/dist/src/init/helper-signing.d.ts +0 -37
  285. package/dist/src/init/helper-signing.js +0 -67
  286. package/dist/src/init/helpers-generator.d.ts +0 -87
  287. package/dist/src/init/helpers-generator.js +0 -1456
  288. package/dist/src/init/index.d.ts +0 -13
  289. package/dist/src/init/index.js +0 -15
  290. package/dist/src/init/mcp-generator.d.ts +0 -26
  291. package/dist/src/init/mcp-generator.js +0 -126
  292. package/dist/src/init/memory-package-resolver.d.ts +0 -53
  293. package/dist/src/init/memory-package-resolver.js +0 -118
  294. package/dist/src/init/settings-generator.d.ts +0 -14
  295. package/dist/src/init/settings-generator.js +0 -462
  296. package/dist/src/init/statusline-generator.d.ts +0 -28
  297. package/dist/src/init/statusline-generator.js +0 -177
  298. package/dist/src/init/types.d.ts +0 -331
  299. package/dist/src/init/types.js +0 -276
  300. package/dist/src/log-filters.d.ts +0 -46
  301. package/dist/src/log-filters.js +0 -107
  302. package/dist/src/mcp-client.d.ts +0 -92
  303. package/dist/src/mcp-client.js +0 -397
  304. package/dist/src/mcp-server.d.ts +0 -163
  305. package/dist/src/mcp-server.js +0 -751
  306. package/dist/src/mcp-tools/agent-execute-core.d.ts +0 -115
  307. package/dist/src/mcp-tools/agent-execute-core.js +0 -587
  308. package/dist/src/mcp-tools/agent-tools.d.ts +0 -9
  309. package/dist/src/mcp-tools/agent-tools.js +0 -837
  310. package/dist/src/mcp-tools/agentbbs-tools.d.ts +0 -28
  311. package/dist/src/mcp-tools/agentbbs-tools.js +0 -394
  312. package/dist/src/mcp-tools/agentdb-tools.d.ts +0 -35
  313. package/dist/src/mcp-tools/agentdb-tools.js +0 -1473
  314. package/dist/src/mcp-tools/agenticow-loader.d.ts +0 -59
  315. package/dist/src/mcp-tools/agenticow-loader.js +0 -105
  316. package/dist/src/mcp-tools/agenticow-speculate-tools.d.ts +0 -24
  317. package/dist/src/mcp-tools/agenticow-speculate-tools.js +0 -209
  318. package/dist/src/mcp-tools/agenticow-tools.d.ts +0 -36
  319. package/dist/src/mcp-tools/agenticow-tools.js +0 -360
  320. package/dist/src/mcp-tools/analyze-tools.d.ts +0 -38
  321. package/dist/src/mcp-tools/analyze-tools.js +0 -346
  322. package/dist/src/mcp-tools/auto-install.d.ts +0 -83
  323. package/dist/src/mcp-tools/auto-install.js +0 -131
  324. package/dist/src/mcp-tools/autopilot-tools.d.ts +0 -12
  325. package/dist/src/mcp-tools/autopilot-tools.js +0 -231
  326. package/dist/src/mcp-tools/browser-intent-tools.d.ts +0 -162
  327. package/dist/src/mcp-tools/browser-intent-tools.js +0 -548
  328. package/dist/src/mcp-tools/browser-session-tools.d.ts +0 -27
  329. package/dist/src/mcp-tools/browser-session-tools.js +0 -398
  330. package/dist/src/mcp-tools/browser-tools.d.ts +0 -21
  331. package/dist/src/mcp-tools/browser-tools.js +0 -760
  332. package/dist/src/mcp-tools/business-pod-tools.d.ts +0 -20
  333. package/dist/src/mcp-tools/business-pod-tools.js +0 -169
  334. package/dist/src/mcp-tools/claims-tools.d.ts +0 -12
  335. package/dist/src/mcp-tools/claims-tools.js +0 -863
  336. package/dist/src/mcp-tools/config-tools.d.ts +0 -8
  337. package/dist/src/mcp-tools/config-tools.js +0 -411
  338. package/dist/src/mcp-tools/coordination-tools.d.ts +0 -13
  339. package/dist/src/mcp-tools/coordination-tools.js +0 -729
  340. package/dist/src/mcp-tools/daa-tools.d.ts +0 -13
  341. package/dist/src/mcp-tools/daa-tools.js +0 -534
  342. package/dist/src/mcp-tools/embeddings-tools.d.ts +0 -9
  343. package/dist/src/mcp-tools/embeddings-tools.js +0 -904
  344. package/dist/src/mcp-tools/github-tools.d.ts +0 -9
  345. package/dist/src/mcp-tools/github-tools.js +0 -659
  346. package/dist/src/mcp-tools/guidance-tools.d.ts +0 -15
  347. package/dist/src/mcp-tools/guidance-tools.js +0 -639
  348. package/dist/src/mcp-tools/hive-mind-tools.d.ts +0 -8
  349. package/dist/src/mcp-tools/hive-mind-tools.js +0 -953
  350. package/dist/src/mcp-tools/hooks-tools.d.ts +0 -65
  351. package/dist/src/mcp-tools/hooks-tools.js +0 -4824
  352. package/dist/src/mcp-tools/http-fetch-tools.d.ts +0 -55
  353. package/dist/src/mcp-tools/http-fetch-tools.js +0 -329
  354. package/dist/src/mcp-tools/index.d.ts +0 -34
  355. package/dist/src/mcp-tools/index.js +0 -40
  356. package/dist/src/mcp-tools/managed-agent-tools.d.ts +0 -22
  357. package/dist/src/mcp-tools/managed-agent-tools.js +0 -357
  358. package/dist/src/mcp-tools/memory-tools.d.ts +0 -14
  359. package/dist/src/mcp-tools/memory-tools.js +0 -1330
  360. package/dist/src/mcp-tools/metaharness-tools.d.ts +0 -51
  361. package/dist/src/mcp-tools/metaharness-tools.js +0 -684
  362. package/dist/src/mcp-tools/neural-tools.d.ts +0 -54
  363. package/dist/src/mcp-tools/neural-tools.js +0 -1168
  364. package/dist/src/mcp-tools/performance-tools.d.ts +0 -16
  365. package/dist/src/mcp-tools/performance-tools.js +0 -675
  366. package/dist/src/mcp-tools/progress-tools.d.ts +0 -14
  367. package/dist/src/mcp-tools/progress-tools.js +0 -348
  368. package/dist/src/mcp-tools/request-tracker.d.ts +0 -17
  369. package/dist/src/mcp-tools/request-tracker.js +0 -27
  370. package/dist/src/mcp-tools/ruvllm-tools.d.ts +0 -9
  371. package/dist/src/mcp-tools/ruvllm-tools.js +0 -355
  372. package/dist/src/mcp-tools/security-tools.d.ts +0 -18
  373. package/dist/src/mcp-tools/security-tools.js +0 -556
  374. package/dist/src/mcp-tools/session-tools.d.ts +0 -8
  375. package/dist/src/mcp-tools/session-tools.js +0 -517
  376. package/dist/src/mcp-tools/swarm-tools.d.ts +0 -37
  377. package/dist/src/mcp-tools/swarm-tools.js +0 -390
  378. package/dist/src/mcp-tools/system-tools.d.ts +0 -13
  379. package/dist/src/mcp-tools/system-tools.js +0 -688
  380. package/dist/src/mcp-tools/task-tools.d.ts +0 -8
  381. package/dist/src/mcp-tools/task-tools.js +0 -487
  382. package/dist/src/mcp-tools/terminal-tools.d.ts +0 -8
  383. package/dist/src/mcp-tools/terminal-tools.js +0 -306
  384. package/dist/src/mcp-tools/testgen-tools.d.ts +0 -26
  385. package/dist/src/mcp-tools/testgen-tools.js +0 -168
  386. package/dist/src/mcp-tools/tool-loop-guardrail.d.ts +0 -31
  387. package/dist/src/mcp-tools/tool-loop-guardrail.js +0 -71
  388. package/dist/src/mcp-tools/transfer-tools.d.ts +0 -14
  389. package/dist/src/mcp-tools/transfer-tools.js +0 -447
  390. package/dist/src/mcp-tools/types.d.ts +0 -8
  391. package/dist/src/mcp-tools/types.js +0 -8
  392. package/dist/src/mcp-tools/validate-input.d.ts +0 -9
  393. package/dist/src/mcp-tools/validate-input.js +0 -9
  394. package/dist/src/mcp-tools/wasm-agent-tools.d.ts +0 -13
  395. package/dist/src/mcp-tools/wasm-agent-tools.js +0 -840
  396. package/dist/src/mcp-tools/workflow-tools.d.ts +0 -8
  397. package/dist/src/mcp-tools/workflow-tools.js +0 -884
  398. package/dist/src/memory/bge-embedder.d.ts +0 -25
  399. package/dist/src/memory/bge-embedder.js +0 -121
  400. package/dist/src/memory/cross-encoder-rerank.d.ts +0 -33
  401. package/dist/src/memory/cross-encoder-rerank.js +0 -123
  402. package/dist/src/memory/embedding-policy.d.ts +0 -21
  403. package/dist/src/memory/embedding-policy.js +0 -30
  404. package/dist/src/memory/embedding-quantization.d.ts +0 -62
  405. package/dist/src/memory/embedding-quantization.js +0 -156
  406. package/dist/src/memory/ewc-consolidation.d.ts +0 -305
  407. package/dist/src/memory/ewc-consolidation.js +0 -611
  408. package/dist/src/memory/graph-edge-writer.d.ts +0 -95
  409. package/dist/src/memory/graph-edge-writer.js +0 -217
  410. package/dist/src/memory/hybrid-retrieval.d.ts +0 -77
  411. package/dist/src/memory/hybrid-retrieval.js +0 -192
  412. package/dist/src/memory/intelligence.d.ts +0 -405
  413. package/dist/src/memory/intelligence.js +0 -1316
  414. package/dist/src/memory/lucene-bm25.d.ts +0 -19
  415. package/dist/src/memory/lucene-bm25.js +0 -308
  416. package/dist/src/memory/memory-bridge.d.ts +0 -537
  417. package/dist/src/memory/memory-bridge.js +0 -2460
  418. package/dist/src/memory/memory-initializer.d.ts +0 -556
  419. package/dist/src/memory/memory-initializer.js +0 -3021
  420. package/dist/src/memory/neural-package-bridge.d.ts +0 -48
  421. package/dist/src/memory/neural-package-bridge.js +0 -87
  422. package/dist/src/memory/rabitq-index.d.ts +0 -60
  423. package/dist/src/memory/rabitq-index.js +0 -242
  424. package/dist/src/memory/sona-optimizer.d.ts +0 -267
  425. package/dist/src/memory/sona-optimizer.js +0 -779
  426. package/dist/src/memory/structured-distill.d.ts +0 -48
  427. package/dist/src/memory/structured-distill.js +0 -125
  428. package/dist/src/output.d.ts +0 -9
  429. package/dist/src/output.js +0 -9
  430. package/dist/src/parser.d.ts +0 -89
  431. package/dist/src/parser.js +0 -516
  432. package/dist/src/plugins/manager.d.ts +0 -133
  433. package/dist/src/plugins/manager.js +0 -415
  434. package/dist/src/plugins/store/discovery.d.ts +0 -99
  435. package/dist/src/plugins/store/discovery.js +0 -1224
  436. package/dist/src/plugins/store/index.d.ts +0 -76
  437. package/dist/src/plugins/store/index.js +0 -141
  438. package/dist/src/plugins/store/search.d.ts +0 -46
  439. package/dist/src/plugins/store/search.js +0 -230
  440. package/dist/src/plugins/store/types.d.ts +0 -279
  441. package/dist/src/plugins/store/types.js +0 -7
  442. package/dist/src/plugins/tests/demo-plugin-store.d.ts +0 -7
  443. package/dist/src/plugins/tests/demo-plugin-store.js +0 -126
  444. package/dist/src/plugins/tests/standalone-test.d.ts +0 -12
  445. package/dist/src/plugins/tests/standalone-test.js +0 -188
  446. package/dist/src/plugins/tests/test-plugin-store.d.ts +0 -7
  447. package/dist/src/plugins/tests/test-plugin-store.js +0 -206
  448. package/dist/src/production/circuit-breaker.d.ts +0 -101
  449. package/dist/src/production/circuit-breaker.js +0 -241
  450. package/dist/src/production/error-handler.d.ts +0 -92
  451. package/dist/src/production/error-handler.js +0 -299
  452. package/dist/src/production/index.d.ts +0 -23
  453. package/dist/src/production/index.js +0 -18
  454. package/dist/src/production/monitoring.d.ts +0 -161
  455. package/dist/src/production/monitoring.js +0 -356
  456. package/dist/src/production/rate-limiter.d.ts +0 -80
  457. package/dist/src/production/rate-limiter.js +0 -201
  458. package/dist/src/production/retry.d.ts +0 -48
  459. package/dist/src/production/retry.js +0 -179
  460. package/dist/src/prompt.d.ts +0 -44
  461. package/dist/src/prompt.js +0 -501
  462. package/dist/src/runtime/headless.d.ts +0 -60
  463. package/dist/src/runtime/headless.js +0 -284
  464. package/dist/src/runtime/parent-death-watchdog.d.ts +0 -42
  465. package/dist/src/runtime/parent-death-watchdog.js +0 -70
  466. package/dist/src/ruvector/agent-wasm.d.ts +0 -228
  467. package/dist/src/ruvector/agent-wasm.js +0 -463
  468. package/dist/src/ruvector/ast-analyzer.d.ts +0 -67
  469. package/dist/src/ruvector/ast-analyzer.js +0 -277
  470. package/dist/src/ruvector/codemods/engine.d.ts +0 -45
  471. package/dist/src/ruvector/codemods/engine.js +0 -291
  472. package/dist/src/ruvector/codemods/scope-analysis.d.ts +0 -29
  473. package/dist/src/ruvector/codemods/scope-analysis.js +0 -162
  474. package/dist/src/ruvector/coverage-router.d.ts +0 -160
  475. package/dist/src/ruvector/coverage-router.js +0 -531
  476. package/dist/src/ruvector/coverage-tools.d.ts +0 -33
  477. package/dist/src/ruvector/coverage-tools.js +0 -157
  478. package/dist/src/ruvector/diff-classifier.d.ts +0 -175
  479. package/dist/src/ruvector/diff-classifier.js +0 -699
  480. package/dist/src/ruvector/diskann-backend.d.ts +0 -78
  481. package/dist/src/ruvector/diskann-backend.js +0 -310
  482. package/dist/src/ruvector/enhanced-model-router.d.ts +0 -172
  483. package/dist/src/ruvector/enhanced-model-router.js +0 -577
  484. package/dist/src/ruvector/graph-analyzer.d.ts +0 -187
  485. package/dist/src/ruvector/graph-analyzer.js +0 -929
  486. package/dist/src/ruvector/graph-backend.d.ts +0 -79
  487. package/dist/src/ruvector/graph-backend.js +0 -220
  488. package/dist/src/ruvector/index.d.ts +0 -38
  489. package/dist/src/ruvector/index.js +0 -86
  490. package/dist/src/ruvector/lora-adapter.d.ts +0 -292
  491. package/dist/src/ruvector/lora-adapter.js +0 -710
  492. package/dist/src/ruvector/model-prices.d.ts +0 -50
  493. package/dist/src/ruvector/model-prices.js +0 -72
  494. package/dist/src/ruvector/model-router.d.ts +0 -408
  495. package/dist/src/ruvector/model-router.js +0 -1162
  496. package/dist/src/ruvector/neural-router.d.ts +0 -182
  497. package/dist/src/ruvector/neural-router.js +0 -825
  498. package/dist/src/ruvector/output-verifier.d.ts +0 -83
  499. package/dist/src/ruvector/output-verifier.js +0 -277
  500. package/dist/src/ruvector/q-learning-router.d.ts +0 -227
  501. package/dist/src/ruvector/q-learning-router.js +0 -721
  502. package/dist/src/ruvector/router-calibrator.d.ts +0 -65
  503. package/dist/src/ruvector/router-calibrator.js +0 -120
  504. package/dist/src/ruvector/router-parallel-recorder.d.ts +0 -127
  505. package/dist/src/ruvector/router-parallel-recorder.js +0 -183
  506. package/dist/src/ruvector/router-trajectory.d.ts +0 -194
  507. package/dist/src/ruvector/router-trajectory.js +0 -281
  508. package/dist/src/ruvector/run-transcript-recorder.d.ts +0 -154
  509. package/dist/src/ruvector/run-transcript-recorder.js +0 -209
  510. package/dist/src/ruvector/ruvllm-wasm.d.ts +0 -179
  511. package/dist/src/ruvector/ruvllm-wasm.js +0 -379
  512. package/dist/src/ruvector/semantic-router.d.ts +0 -77
  513. package/dist/src/ruvector/semantic-router.js +0 -178
  514. package/dist/src/ruvector/task-embedder.d.ts +0 -56
  515. package/dist/src/ruvector/task-embedder.js +0 -237
  516. package/dist/src/ruvector/trajectory-tree.d.ts +0 -113
  517. package/dist/src/ruvector/trajectory-tree.js +0 -237
  518. package/dist/src/ruvector/vector-db.d.ts +0 -73
  519. package/dist/src/ruvector/vector-db.js +0 -301
  520. package/dist/src/ruvector/wasm-embedder.d.ts +0 -13
  521. package/dist/src/ruvector/wasm-embedder.js +0 -143
  522. package/dist/src/services/agentic-flow-bridge.d.ts +0 -50
  523. package/dist/src/services/agentic-flow-bridge.js +0 -95
  524. package/dist/src/services/ai-job-dedup.d.ts +0 -61
  525. package/dist/src/services/ai-job-dedup.js +0 -136
  526. package/dist/src/services/checkpoint-gate.d.ts +0 -140
  527. package/dist/src/services/checkpoint-gate.js +0 -223
  528. package/dist/src/services/claim-service.d.ts +0 -204
  529. package/dist/src/services/claim-service.js +0 -818
  530. package/dist/src/services/config-file-manager.d.ts +0 -37
  531. package/dist/src/services/config-file-manager.js +0 -224
  532. package/dist/src/services/container-worker-pool.d.ts +0 -204
  533. package/dist/src/services/container-worker-pool.js +0 -589
  534. package/dist/src/services/daemon-autostart.d.ts +0 -17
  535. package/dist/src/services/daemon-autostart.js +0 -102
  536. package/dist/src/services/distill-oracle.d.ts +0 -190
  537. package/dist/src/services/distill-oracle.js +0 -349
  538. package/dist/src/services/distill-tuning.d.ts +0 -111
  539. package/dist/src/services/distill-tuning.js +0 -510
  540. package/dist/src/services/evolve-proof.d.ts +0 -253
  541. package/dist/src/services/evolve-proof.js +0 -343
  542. package/dist/src/services/fable-harness.d.ts +0 -207
  543. package/dist/src/services/fable-harness.js +0 -388
  544. package/dist/src/services/git-workspace-identity.d.ts +0 -42
  545. package/dist/src/services/git-workspace-identity.js +0 -99
  546. package/dist/src/services/global-ai-budget.d.ts +0 -135
  547. package/dist/src/services/global-ai-budget.js +0 -415
  548. package/dist/src/services/harness-benchmark.d.ts +0 -68
  549. package/dist/src/services/harness-benchmark.js +0 -94
  550. package/dist/src/services/harness-canary.d.ts +0 -60
  551. package/dist/src/services/harness-canary.js +0 -69
  552. package/dist/src/services/harness-corpus-harvester.d.ts +0 -51
  553. package/dist/src/services/harness-corpus-harvester.js +0 -74
  554. package/dist/src/services/harness-flywheel-generations.d.ts +0 -115
  555. package/dist/src/services/harness-flywheel-generations.js +0 -360
  556. package/dist/src/services/harness-flywheel-runtime.d.ts +0 -25
  557. package/dist/src/services/harness-flywheel-runtime.js +0 -92
  558. package/dist/src/services/harness-flywheel.d.ts +0 -48
  559. package/dist/src/services/harness-flywheel.js +0 -207
  560. package/dist/src/services/harness-frozen-eval.d.ts +0 -22
  561. package/dist/src/services/harness-frozen-eval.js +0 -66
  562. package/dist/src/services/harness-hosts.d.ts +0 -40
  563. package/dist/src/services/harness-hosts.js +0 -88
  564. package/dist/src/services/harness-improvement-ledger.d.ts +0 -63
  565. package/dist/src/services/harness-improvement-ledger.js +0 -101
  566. package/dist/src/services/harness-loop.d.ts +0 -53
  567. package/dist/src/services/harness-loop.js +0 -85
  568. package/dist/src/services/harness-qualification.d.ts +0 -66
  569. package/dist/src/services/harness-qualification.js +0 -143
  570. package/dist/src/services/harness-replay.d.ts +0 -37
  571. package/dist/src/services/harness-replay.js +0 -92
  572. package/dist/src/services/harness-verify.d.ts +0 -33
  573. package/dist/src/services/harness-verify.js +0 -26
  574. package/dist/src/services/harness-worker.d.ts +0 -23
  575. package/dist/src/services/harness-worker.js +0 -66
  576. package/dist/src/services/headless-worker-executor.d.ts +0 -358
  577. package/dist/src/services/headless-worker-executor.js +0 -1269
  578. package/dist/src/services/index.d.ts +0 -13
  579. package/dist/src/services/index.js +0 -11
  580. package/dist/src/services/memory-backup.d.ts +0 -53
  581. package/dist/src/services/memory-backup.js +0 -198
  582. package/dist/src/services/memory-distillation.d.ts +0 -41
  583. package/dist/src/services/memory-distillation.js +0 -277
  584. package/dist/src/services/native-training.d.ts +0 -68
  585. package/dist/src/services/native-training.js +0 -141
  586. package/dist/src/services/registry-api.d.ts +0 -58
  587. package/dist/src/services/registry-api.js +0 -146
  588. package/dist/src/services/repo-supervisor.d.ts +0 -70
  589. package/dist/src/services/repo-supervisor.js +0 -228
  590. package/dist/src/services/ruvector-training.d.ts +0 -222
  591. package/dist/src/services/ruvector-training.js +0 -693
  592. package/dist/src/services/swarm-memory-branches.d.ts +0 -135
  593. package/dist/src/services/swarm-memory-branches.js +0 -213
  594. package/dist/src/services/weight-eft.d.ts +0 -305
  595. package/dist/src/services/weight-eft.js +0 -296
  596. package/dist/src/services/worker-daemon.d.ts +0 -439
  597. package/dist/src/services/worker-daemon.js +0 -1865
  598. package/dist/src/services/worker-queue.d.ts +0 -194
  599. package/dist/src/services/worker-queue.js +0 -513
  600. package/dist/src/services/workspace-lease.d.ts +0 -55
  601. package/dist/src/services/workspace-lease.js +0 -191
  602. package/dist/src/suggest.d.ts +0 -53
  603. package/dist/src/suggest.js +0 -200
  604. package/dist/src/transfer/anonymization/index.d.ts +0 -25
  605. package/dist/src/transfer/anonymization/index.js +0 -175
  606. package/dist/src/transfer/deploy-seraphine.d.ts +0 -13
  607. package/dist/src/transfer/deploy-seraphine.js +0 -205
  608. package/dist/src/transfer/export.d.ts +0 -25
  609. package/dist/src/transfer/export.js +0 -113
  610. package/dist/src/transfer/index.d.ts +0 -12
  611. package/dist/src/transfer/index.js +0 -31
  612. package/dist/src/transfer/ipfs/client.d.ts +0 -109
  613. package/dist/src/transfer/ipfs/client.js +0 -307
  614. package/dist/src/transfer/ipfs/upload.d.ts +0 -95
  615. package/dist/src/transfer/ipfs/upload.js +0 -413
  616. package/dist/src/transfer/models/seraphine.d.ts +0 -72
  617. package/dist/src/transfer/models/seraphine.js +0 -373
  618. package/dist/src/transfer/serialization/cfp.d.ts +0 -49
  619. package/dist/src/transfer/serialization/cfp.js +0 -183
  620. package/dist/src/transfer/storage/gcs.d.ts +0 -82
  621. package/dist/src/transfer/storage/gcs.js +0 -272
  622. package/dist/src/transfer/storage/index.d.ts +0 -6
  623. package/dist/src/transfer/storage/index.js +0 -6
  624. package/dist/src/transfer/store/discovery.d.ts +0 -84
  625. package/dist/src/transfer/store/discovery.js +0 -382
  626. package/dist/src/transfer/store/download.d.ts +0 -70
  627. package/dist/src/transfer/store/download.js +0 -334
  628. package/dist/src/transfer/store/index.d.ts +0 -84
  629. package/dist/src/transfer/store/index.js +0 -153
  630. package/dist/src/transfer/store/publish.d.ts +0 -76
  631. package/dist/src/transfer/store/publish.js +0 -294
  632. package/dist/src/transfer/store/registry.d.ts +0 -58
  633. package/dist/src/transfer/store/registry.js +0 -285
  634. package/dist/src/transfer/store/search.d.ts +0 -54
  635. package/dist/src/transfer/store/search.js +0 -232
  636. package/dist/src/transfer/store/tests/standalone-test.d.ts +0 -12
  637. package/dist/src/transfer/store/tests/standalone-test.js +0 -190
  638. package/dist/src/transfer/store/types.d.ts +0 -193
  639. package/dist/src/transfer/store/types.js +0 -6
  640. package/dist/src/transfer/test-seraphine.d.ts +0 -6
  641. package/dist/src/transfer/test-seraphine.js +0 -105
  642. package/dist/src/transfer/tests/test-store.d.ts +0 -7
  643. package/dist/src/transfer/tests/test-store.js +0 -214
  644. package/dist/src/transfer/types.d.ts +0 -245
  645. package/dist/src/transfer/types.js +0 -6
  646. package/dist/src/types.d.ts +0 -13
  647. package/dist/src/types.js +0 -13
  648. package/dist/src/update/checker.d.ts +0 -34
  649. package/dist/src/update/checker.js +0 -191
  650. package/dist/src/update/executor.d.ts +0 -33
  651. package/dist/src/update/executor.js +0 -217
  652. package/dist/src/update/index.d.ts +0 -33
  653. package/dist/src/update/index.js +0 -64
  654. package/dist/src/update/rate-limiter.d.ts +0 -20
  655. package/dist/src/update/rate-limiter.js +0 -96
  656. package/dist/src/update/validator.d.ts +0 -17
  657. package/dist/src/update/validator.js +0 -123
@@ -1,4824 +0,0 @@
1
- /**
2
- * Hooks MCP Tools
3
- * Provides intelligent hooks functionality via MCP protocol
4
- */
5
- import { mkdirSync, writeFileSync, existsSync, readFileSync, statSync, unlinkSync, readdirSync } from 'fs';
6
- import * as nodeFs from 'fs';
7
- import { dirname, join, resolve } from 'path';
8
- import { getProjectCwd } from './types.js';
9
- import { validateIdentifier, validateText, validatePath } from './validate-input.js';
10
- import { checkCommandLoop, recordCommandOutcome } from './tool-loop-guardrail.js';
11
- // Real vector search functions - lazy loaded to avoid circular imports
12
- let searchEntriesFn = null;
13
- /**
14
- * Strip extended-thinking blocks from text before it enters a learning
15
- * trajectory (hermes-agent think_scrubber pattern). Claude models with extended
16
- * thinking emit <thinking>/<think>/<reasoning> blocks; if those land in a
17
- * trajectory's action/result text, the DISTILL step embeds reasoning-token
18
- * content that does not generalize, contaminating pattern confidence. Boundary-
19
- * gated: only strips well-formed paired tags, leaving prose that merely mentions
20
- * the tag names untouched.
21
- */
22
- export function scrubReasoningBlocks(text) {
23
- if (typeof text !== 'string' || text.indexOf('<') === -1)
24
- return text;
25
- return text
26
- .replace(/<think>[\s\S]*?<\/think>/gi, '')
27
- .replace(/<thinking>[\s\S]*?<\/thinking>/gi, '')
28
- .replace(/<reasoning>[\s\S]*?<\/reasoning>/gi, '')
29
- .replace(/<thought>[\s\S]*?<\/thought>/gi, '')
30
- .replace(/<REASONING_SCRATCHPAD>[\s\S]*?<\/REASONING_SCRATCHPAD>/gi, '')
31
- .trim();
32
- }
33
- async function getRealSearchFunction() {
34
- if (!searchEntriesFn) {
35
- try {
36
- const { searchEntries } = await import('../memory/memory-initializer.js');
37
- searchEntriesFn = searchEntries;
38
- }
39
- catch {
40
- searchEntriesFn = null;
41
- }
42
- }
43
- return searchEntriesFn;
44
- }
45
- // Real store function - lazy loaded
46
- let storeEntryFn = null;
47
- async function getRealStoreFunction() {
48
- if (!storeEntryFn) {
49
- try {
50
- const { storeEntry } = await import('../memory/memory-initializer.js');
51
- storeEntryFn = storeEntry;
52
- }
53
- catch {
54
- storeEntryFn = null;
55
- }
56
- }
57
- return storeEntryFn;
58
- }
59
- // =============================================================================
60
- // Neural Module Lazy Loaders (SONA, EWC++, MoE, LoRA, Flash Attention)
61
- // =============================================================================
62
- // SONA Optimizer - lazy loaded
63
- let sonaOptimizer = null;
64
- async function getSONAOptimizer() {
65
- if (!sonaOptimizer) {
66
- try {
67
- const { getSONAOptimizer: getSona } = await import('../memory/sona-optimizer.js');
68
- sonaOptimizer = await getSona();
69
- }
70
- catch {
71
- sonaOptimizer = null;
72
- }
73
- }
74
- return sonaOptimizer;
75
- }
76
- // EWC++ Consolidator - lazy loaded
77
- let ewcConsolidator = null;
78
- async function getEWCConsolidator() {
79
- if (!ewcConsolidator) {
80
- try {
81
- const { getEWCConsolidator: getEWC } = await import('../memory/ewc-consolidation.js');
82
- ewcConsolidator = await getEWC();
83
- }
84
- catch {
85
- ewcConsolidator = null;
86
- }
87
- }
88
- return ewcConsolidator;
89
- }
90
- // MoE Router - lazy loaded
91
- // #1773 item 4 — moe-router migrated to @claude-flow/neural
92
- let moeRouter = null;
93
- async function getMoERouter() {
94
- if (!moeRouter) {
95
- try {
96
- const { getMoERouter: getMoE } = await import('@claude-flow/neural');
97
- moeRouter = await getMoE();
98
- }
99
- catch {
100
- moeRouter = null;
101
- }
102
- }
103
- return moeRouter;
104
- }
105
- // Semantic Router - lazy loaded
106
- // Tries native VectorDb first (16k+ routes/s HNSW), falls back to pure JS (47k routes/s cosine)
107
- let semanticRouter = null;
108
- let nativeVectorDb = null;
109
- let semanticRouterInitialized = false;
110
- let routerBackend = 'none';
111
- // Pre-computed embeddings for common task patterns (cached)
112
- const TASK_PATTERN_EMBEDDINGS = new Map();
113
- function generateSimpleEmbedding(text, dimension = 384) {
114
- // Simple deterministic embedding based on character codes
115
- // This is for routing purposes where we need consistent, fast embeddings
116
- const embedding = new Float32Array(dimension);
117
- const normalized = text.toLowerCase().replace(/[^a-z0-9\s]/g, '');
118
- const words = normalized.split(/\s+/).filter(w => w.length > 0);
119
- // Combine word-level and character-level features
120
- for (let i = 0; i < dimension; i++) {
121
- let value = 0;
122
- // Word-level features
123
- for (let w = 0; w < words.length; w++) {
124
- const word = words[w];
125
- for (let c = 0; c < word.length; c++) {
126
- const charCode = word.charCodeAt(c);
127
- value += Math.sin((charCode * (i + 1) + w * 17 + c * 23) * 0.0137);
128
- }
129
- }
130
- // Character-level features
131
- for (let c = 0; c < text.length; c++) {
132
- value += Math.cos((text.charCodeAt(c) * (i + 1) + c * 7) * 0.0073);
133
- }
134
- embedding[i] = value / Math.max(1, text.length);
135
- }
136
- // Normalize
137
- let norm = 0;
138
- for (let i = 0; i < dimension; i++) {
139
- norm += embedding[i] * embedding[i];
140
- }
141
- norm = Math.sqrt(norm);
142
- if (norm > 0) {
143
- for (let i = 0; i < dimension; i++) {
144
- embedding[i] /= norm;
145
- }
146
- }
147
- return embedding;
148
- }
149
- // ── Runtime routing outcome persistence ──────────────────────────────
150
- // Closes the learning loop: post-task records outcomes → route loads them.
151
- const ROUTING_OUTCOMES_PATH = join(resolve('.'), '.claude-flow/routing-outcomes.json');
152
- const ROUTING_STOPWORDS = new Set([
153
- 'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had',
154
- 'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might', 'shall', 'can',
155
- 'to', 'of', 'in', 'for', 'on', 'with', 'at', 'by', 'from', 'as', 'into', 'through', 'during',
156
- 'before', 'after', 'above', 'below', 'between', 'under', 'again', 'further', 'then', 'once',
157
- 'it', 'its', 'this', 'that', 'these', 'those', 'i', 'me', 'my', 'we', 'our', 'you', 'your',
158
- 'he', 'she', 'they', 'them', 'and', 'but', 'or', 'nor', 'not', 'no', 'so', 'if', 'when', 'than',
159
- 'very', 'just', 'also', 'only', 'both', 'each', 'all', 'any', 'few', 'more', 'most', 'other',
160
- 'some', 'such', 'same', 'new', 'now', 'here', 'there', 'where', 'how', 'what', 'which', 'who',
161
- ]);
162
- function extractKeywords(text) {
163
- if (!text)
164
- return [];
165
- return text.toLowerCase()
166
- .replace(/[^a-z0-9\s-]/g, ' ')
167
- .split(/\s+/)
168
- .filter(w => w.length > 2 && !ROUTING_STOPWORDS.has(w));
169
- }
170
- function loadRoutingOutcomes() {
171
- try {
172
- if (existsSync(ROUTING_OUTCOMES_PATH)) {
173
- const data = JSON.parse(readFileSync(ROUTING_OUTCOMES_PATH, 'utf-8'));
174
- return data.outcomes || [];
175
- }
176
- }
177
- catch { /* corrupt file, start fresh */ }
178
- return [];
179
- }
180
- function saveRoutingOutcomes(outcomes) {
181
- try {
182
- const dir = dirname(ROUTING_OUTCOMES_PATH);
183
- if (!existsSync(dir))
184
- mkdirSync(dir, { recursive: true });
185
- // Cap at 500 entries to bound file size
186
- const capped = outcomes.slice(-500);
187
- writeFileSync(ROUTING_OUTCOMES_PATH, JSON.stringify({ outcomes: capped }, null, 2));
188
- }
189
- catch { /* non-critical */ }
190
- }
191
- /**
192
- * Build learned routing patterns from successful task outcomes.
193
- * Returns patterns in the same shape as TASK_PATTERNS so they can be
194
- * merged into both the native HNSW and pure-JS semantic routers.
195
- */
196
- function loadLearnedPatterns() {
197
- const outcomes = loadRoutingOutcomes();
198
- const byAgent = {};
199
- for (const o of outcomes) {
200
- if (!o.success || !o.agent || !o.keywords?.length)
201
- continue;
202
- if (!byAgent[o.agent])
203
- byAgent[o.agent] = new Set();
204
- for (const kw of o.keywords)
205
- byAgent[o.agent].add(kw);
206
- }
207
- const patterns = {};
208
- for (const [agent, kwSet] of Object.entries(byAgent)) {
209
- patterns[`learned-${agent}`] = {
210
- keywords: [...kwSet].slice(0, 50),
211
- agents: [agent],
212
- };
213
- }
214
- return patterns;
215
- }
216
- /**
217
- * Merge static TASK_PATTERNS with runtime-learned patterns.
218
- * Static patterns take precedence (learned patterns won't overwrite them).
219
- */
220
- function getMergedTaskPatterns() {
221
- const merged = { ...TASK_PATTERNS };
222
- const learned = loadLearnedPatterns();
223
- for (const [key, pattern] of Object.entries(learned)) {
224
- if (!merged[key]) {
225
- merged[key] = pattern;
226
- }
227
- }
228
- return merged;
229
- }
230
- // ── Static task patterns (used by both native and pure-JS routers) ───
231
- const TASK_PATTERNS = {
232
- 'security-task': {
233
- keywords: ['authentication', 'security', 'auth', 'password', 'encryption', 'vulnerability', 'cve', 'audit'],
234
- agents: ['security-architect', 'security-auditor', 'reviewer'],
235
- },
236
- 'testing-task': {
237
- keywords: ['test', 'testing', 'spec', 'coverage', 'unit test', 'integration test', 'e2e'],
238
- agents: ['tester', 'reviewer'],
239
- },
240
- 'api-task': {
241
- keywords: ['api', 'endpoint', 'rest', 'graphql', 'route', 'handler', 'controller'],
242
- agents: ['architect', 'coder', 'tester'],
243
- },
244
- 'performance-task': {
245
- keywords: ['performance', 'optimize', 'speed', 'memory', 'benchmark', 'profiling', 'bottleneck'],
246
- agents: ['performance-engineer', 'coder', 'tester'],
247
- },
248
- 'refactor-task': {
249
- keywords: ['refactor', 'restructure', 'clean', 'organize', 'modular', 'decouple'],
250
- agents: ['architect', 'coder', 'reviewer'],
251
- },
252
- 'bugfix-task': {
253
- keywords: ['bug', 'fix', 'error', 'issue', 'broken', 'crash', 'debug'],
254
- agents: ['coder', 'tester', 'reviewer'],
255
- },
256
- 'feature-task': {
257
- keywords: ['feature', 'implement', 'add', 'new', 'create', 'build'],
258
- agents: ['architect', 'coder', 'tester'],
259
- },
260
- 'database-task': {
261
- keywords: ['database', 'sql', 'query', 'schema', 'migration', 'orm'],
262
- agents: ['architect', 'coder', 'tester'],
263
- },
264
- 'frontend-task': {
265
- keywords: ['frontend', 'ui', 'component', 'react', 'css', 'style', 'layout'],
266
- agents: ['coder', 'reviewer', 'tester'],
267
- },
268
- 'devops-task': {
269
- keywords: ['deploy', 'ci', 'cd', 'pipeline', 'docker', 'kubernetes', 'infrastructure'],
270
- agents: ['devops', 'coder', 'tester'],
271
- },
272
- 'swarm-task': {
273
- keywords: ['swarm', 'agent', 'coordinator', 'hive', 'mesh', 'topology'],
274
- agents: ['swarm-specialist', 'coordinator', 'architect'],
275
- },
276
- 'memory-task': {
277
- keywords: ['memory', 'cache', 'store', 'vector', 'embedding', 'persistence'],
278
- agents: ['memory-specialist', 'architect', 'coder'],
279
- },
280
- };
281
- /**
282
- * Get the semantic router with environment detection.
283
- * Tries native VectorDb first (HNSW, 16k routes/s), falls back to pure JS (47k routes/s cosine).
284
- */
285
- async function getSemanticRouter() {
286
- if (semanticRouterInitialized) {
287
- return { router: semanticRouter, backend: routerBackend, native: nativeVectorDb };
288
- }
289
- semanticRouterInitialized = true;
290
- // STEP 1: Try native VectorDb from @ruvector/router (HNSW-backed)
291
- // Note: Native VectorDb uses a persistent database file which can have lock issues
292
- // in concurrent environments. We try it first but fall back gracefully to pure JS.
293
- try {
294
- // Use createRequire for ESM compatibility with native modules
295
- const { createRequire } = await import('module');
296
- const require = createRequire(import.meta.url);
297
- const router = require('@ruvector/router');
298
- if (router.VectorDb && router.DistanceMetric) {
299
- // Try to create VectorDb - may fail with lock error in concurrent envs
300
- const db = new router.VectorDb({
301
- dimensions: 384,
302
- distanceMetric: router.DistanceMetric.Cosine,
303
- hnswM: 16,
304
- hnswEfConstruction: 200,
305
- hnswEfSearch: 100,
306
- });
307
- // Initialize with static + runtime-learned task patterns
308
- for (const [patternName, { keywords }] of Object.entries(getMergedTaskPatterns())) {
309
- for (const keyword of keywords) {
310
- const embedding = generateSimpleEmbedding(keyword);
311
- db.insert(`${patternName}:${keyword}`, embedding);
312
- TASK_PATTERN_EMBEDDINGS.set(`${patternName}:${keyword}`, embedding);
313
- }
314
- }
315
- nativeVectorDb = db;
316
- routerBackend = 'native';
317
- console.log('[hooks] Semantic router initialized: native VectorDb (HNSW, 16k+ routes/s)');
318
- return { router: null, backend: routerBackend, native: nativeVectorDb };
319
- }
320
- }
321
- catch (err) {
322
- // Native not available or database locked - fall back to pure JS
323
- // Common errors: "Database already open. Cannot acquire lock." or "MODULE_NOT_FOUND"
324
- // This is expected in concurrent environments or when binary isn't installed
325
- }
326
- // STEP 2: Fall back to pure JS SemanticRouter
327
- try {
328
- const { SemanticRouter } = await import('../ruvector/semantic-router.js');
329
- semanticRouter = new SemanticRouter({ dimension: 384 });
330
- for (const [patternName, { keywords, agents }] of Object.entries(getMergedTaskPatterns())) {
331
- const embeddings = keywords.map(kw => generateSimpleEmbedding(kw));
332
- semanticRouter.addIntentWithEmbeddings(patternName, embeddings, { agents, keywords });
333
- // Cache embeddings for keywords
334
- keywords.forEach((kw, i) => {
335
- TASK_PATTERN_EMBEDDINGS.set(kw, embeddings[i]);
336
- });
337
- }
338
- routerBackend = 'pure-js';
339
- console.log('[hooks] Semantic router initialized: pure JS (cosine, 47k routes/s)');
340
- }
341
- catch {
342
- semanticRouter = null;
343
- routerBackend = 'none';
344
- console.log('[hooks] Semantic router initialized: none (no backend available)');
345
- }
346
- return { router: semanticRouter, backend: routerBackend, native: nativeVectorDb };
347
- }
348
- /**
349
- * Get router backend info for status display.
350
- */
351
- function getRouterBackendInfo() {
352
- switch (routerBackend) {
353
- case 'native':
354
- return { backend: 'native VectorDb (HNSW)', speed: '16k+ routes/s' };
355
- case 'pure-js':
356
- return { backend: 'pure JS (cosine)', speed: '47k routes/s' };
357
- default:
358
- return { backend: 'none', speed: 'N/A' };
359
- }
360
- }
361
- // Flash Attention - lazy loaded
362
- // #1773 item 4 — flash-attention migrated to @claude-flow/neural
363
- let flashAttention = null;
364
- async function getFlashAttention() {
365
- if (!flashAttention) {
366
- try {
367
- const { getFlashAttention: getFlash } = await import('@claude-flow/neural');
368
- flashAttention = await getFlash();
369
- }
370
- catch {
371
- flashAttention = null;
372
- }
373
- }
374
- return flashAttention;
375
- }
376
- // LoRA Adapter - lazy loaded
377
- let loraAdapter = null;
378
- async function getLoRAAdapter() {
379
- if (!loraAdapter) {
380
- try {
381
- const { getLoRAAdapter: getLora } = await import('../ruvector/lora-adapter.js');
382
- loraAdapter = await getLora();
383
- }
384
- catch {
385
- loraAdapter = null;
386
- }
387
- }
388
- return loraAdapter;
389
- }
390
- // In-memory trajectory tracking (persisted on end)
391
- const activeTrajectories = new Map();
392
- const MEMORY_DIR = '.claude-flow/memory';
393
- const MEMORY_FILE = 'store.json';
394
- function getMemoryPath() {
395
- return resolve(join(MEMORY_DIR, MEMORY_FILE));
396
- }
397
- function loadMemoryStore() {
398
- try {
399
- const path = getMemoryPath();
400
- if (existsSync(path)) {
401
- const data = readFileSync(path, 'utf-8');
402
- return JSON.parse(data);
403
- }
404
- }
405
- catch {
406
- // Return empty store on error
407
- }
408
- return { entries: {}, version: '3.0.0' };
409
- }
410
- /**
411
- * Get real intelligence statistics from memory store
412
- */
413
- function getIntelligenceStatsFromMemory() {
414
- const store = loadMemoryStore();
415
- const entries = Object.values(store.entries);
416
- // Count trajectories (keys starting with "trajectory-" or containing trajectory data)
417
- const trajectoryEntries = entries.filter(e => e.key.includes('trajectory') ||
418
- (e.metadata?.type === 'trajectory'));
419
- const successfulTrajectories = trajectoryEntries.filter(e => e.metadata?.success === true ||
420
- (typeof e.value === 'object' && e.value !== null && e.value.success === true));
421
- // Count patterns
422
- const patternEntries = entries.filter(e => e.key.includes('pattern') ||
423
- e.metadata?.type === 'pattern' ||
424
- e.key.startsWith('learned-'));
425
- // Categorize patterns
426
- const categories = {};
427
- patternEntries.forEach(e => {
428
- const category = e.metadata?.category || 'general';
429
- categories[category] = (categories[category] || 0) + 1;
430
- });
431
- // Count routing decisions
432
- const routingEntries = entries.filter(e => e.key.includes('routing') ||
433
- e.metadata?.type === 'routing-decision');
434
- // Calculate average confidence from routing decisions
435
- let totalConfidence = 0;
436
- let confidenceCount = 0;
437
- routingEntries.forEach(e => {
438
- const confidence = e.metadata?.confidence;
439
- if (typeof confidence === 'number') {
440
- totalConfidence += confidence;
441
- confidenceCount++;
442
- }
443
- });
444
- // Calculate total access count
445
- const totalAccessCount = entries.reduce((sum, e) => sum + (e.accessCount || 0), 0);
446
- // Calculate memory file size
447
- let memorySizeBytes = 0;
448
- try {
449
- const memPath = getMemoryPath();
450
- if (existsSync(memPath)) {
451
- memorySizeBytes = statSync(memPath).size;
452
- }
453
- }
454
- catch {
455
- // Ignore
456
- }
457
- return {
458
- trajectories: {
459
- total: trajectoryEntries.length,
460
- successful: successfulTrajectories.length,
461
- },
462
- patterns: {
463
- learned: patternEntries.length,
464
- categories,
465
- },
466
- memory: {
467
- indexSize: entries.length,
468
- totalAccessCount,
469
- memorySizeBytes,
470
- },
471
- routing: {
472
- decisions: routingEntries.length,
473
- avgConfidence: confidenceCount > 0 ? totalConfidence / confidenceCount : 0,
474
- },
475
- };
476
- }
477
- // Agent routing configuration - maps file types to recommended agents
478
- const AGENT_PATTERNS = {
479
- '.ts': ['coder', 'architect', 'tester'],
480
- '.tsx': ['coder', 'architect', 'reviewer'],
481
- '.test.ts': ['tester', 'reviewer'],
482
- '.spec.ts': ['tester', 'reviewer'],
483
- '.md': ['researcher', 'documenter'],
484
- '.json': ['coder', 'architect'],
485
- '.yaml': ['coder', 'devops'],
486
- '.yml': ['coder', 'devops'],
487
- '.sh': ['devops', 'coder'],
488
- '.py': ['coder', 'ml-developer', 'researcher'],
489
- '.sql': ['coder', 'architect'],
490
- '.css': ['coder', 'designer'],
491
- '.scss': ['coder', 'designer'],
492
- };
493
- // Keyword patterns for fallback routing (when semantic routing doesn't match)
494
- const KEYWORD_PATTERNS = {
495
- 'authentication': { agents: ['security-architect', 'coder', 'tester'], confidence: 0.9 },
496
- 'auth': { agents: ['security-architect', 'coder', 'tester'], confidence: 0.85 },
497
- 'api': { agents: ['architect', 'coder', 'tester'], confidence: 0.85 },
498
- 'test': { agents: ['tester', 'reviewer'], confidence: 0.95 },
499
- 'refactor': { agents: ['architect', 'coder', 'reviewer'], confidence: 0.9 },
500
- 'performance': { agents: ['performance-engineer', 'coder', 'tester'], confidence: 0.88 },
501
- 'security': { agents: ['security-architect', 'security-auditor', 'reviewer'], confidence: 0.92 },
502
- 'database': { agents: ['architect', 'coder', 'tester'], confidence: 0.85 },
503
- 'frontend': { agents: ['coder', 'designer', 'tester'], confidence: 0.82 },
504
- 'backend': { agents: ['architect', 'coder', 'tester'], confidence: 0.85 },
505
- 'bug': { agents: ['coder', 'tester', 'reviewer'], confidence: 0.88 },
506
- 'fix': { agents: ['coder', 'tester', 'reviewer'], confidence: 0.85 },
507
- 'feature': { agents: ['architect', 'coder', 'tester'], confidence: 0.8 },
508
- 'swarm': { agents: ['swarm-specialist', 'coordinator', 'architect'], confidence: 0.9 },
509
- 'memory': { agents: ['memory-specialist', 'architect', 'coder'], confidence: 0.88 },
510
- 'deploy': { agents: ['devops', 'coder', 'tester'], confidence: 0.85 },
511
- 'ci/cd': { agents: ['devops', 'coder'], confidence: 0.9 },
512
- };
513
- function getFileExtension(filePath) {
514
- const match = filePath.match(/\.[a-zA-Z0-9]+$/);
515
- return match ? match[0] : '';
516
- }
517
- function suggestAgentsForFile(filePath) {
518
- const ext = getFileExtension(filePath);
519
- // Check for test files first
520
- if (filePath.includes('.test.') || filePath.includes('.spec.')) {
521
- return AGENT_PATTERNS['.test.ts'] || ['tester', 'reviewer'];
522
- }
523
- return AGENT_PATTERNS[ext] || ['coder', 'architect'];
524
- }
525
- function suggestAgentsForTask(task) {
526
- const taskLower = task.toLowerCase();
527
- // Check static keyword patterns first
528
- for (const [pattern, result] of Object.entries(KEYWORD_PATTERNS)) {
529
- if (taskLower.includes(pattern)) {
530
- return result;
531
- }
532
- }
533
- // Check runtime-learned patterns from successful task outcomes
534
- const taskKeywords = extractKeywords(task);
535
- if (taskKeywords.length > 0) {
536
- const outcomes = loadRoutingOutcomes();
537
- let bestAgent = '';
538
- let bestOverlap = 0;
539
- for (const outcome of outcomes) {
540
- if (!outcome.success || !outcome.agent || !outcome.keywords?.length)
541
- continue;
542
- const overlap = taskKeywords.filter(kw => outcome.keywords.includes(kw)).length;
543
- if (overlap > bestOverlap) {
544
- bestOverlap = overlap;
545
- bestAgent = outcome.agent;
546
- }
547
- }
548
- // Require at least 2 keyword overlap to prevent false positives
549
- if (bestAgent && bestOverlap >= 2) {
550
- return { agents: [bestAgent], confidence: Math.min(0.6 + bestOverlap * 0.05, 0.85) };
551
- }
552
- }
553
- // Default fallback
554
- return { agents: ['coder', 'researcher', 'tester'], confidence: 0.7 };
555
- }
556
- function assessCommandRisk(command) {
557
- const warnings = [];
558
- let level = 0;
559
- // High risk commands
560
- if (command.includes('rm -rf') || command.includes('rm -r')) {
561
- level = Math.max(level, 0.9);
562
- warnings.push('Recursive deletion detected - verify target path');
563
- }
564
- if (command.includes('sudo')) {
565
- level = Math.max(level, 0.7);
566
- warnings.push('Elevated privileges requested');
567
- }
568
- if (command.includes('> /') || command.includes('>> /')) {
569
- level = Math.max(level, 0.6);
570
- warnings.push('Writing to system path');
571
- }
572
- if (command.includes('chmod') || command.includes('chown')) {
573
- level = Math.max(level, 0.5);
574
- warnings.push('Permission modification');
575
- }
576
- if (command.includes('curl') && command.includes('|')) {
577
- level = Math.max(level, 0.8);
578
- warnings.push('Piping remote content to shell');
579
- }
580
- // Safe commands
581
- if (command.startsWith('npm ') || command.startsWith('npx ')) {
582
- level = Math.min(level, 0.3);
583
- }
584
- if (command.startsWith('git ')) {
585
- level = Math.min(level, 0.2);
586
- }
587
- if (command.startsWith('ls ') || command.startsWith('cat ') || command.startsWith('echo ')) {
588
- level = Math.min(level, 0.1);
589
- }
590
- const risk = level >= 0.7 ? 'high' : level >= 0.4 ? 'medium' : 'low';
591
- return { risk, level, warnings };
592
- }
593
- // MCP Tool implementations - return raw data for direct CLI use
594
- export const hooksPreEdit = {
595
- name: 'hooks_pre-edit',
596
- description: 'Get context and agent suggestions before editing a file Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
597
- inputSchema: {
598
- type: 'object',
599
- properties: {
600
- filePath: { type: 'string', description: 'Path to the file being edited' },
601
- operation: { type: 'string', description: 'Type of operation (create, update, delete, refactor)' },
602
- context: { type: 'string', description: 'Additional context' },
603
- },
604
- required: ['filePath'],
605
- },
606
- handler: async (params) => {
607
- const filePath = params.filePath;
608
- const operation = params.operation || 'update';
609
- {
610
- const v = validatePath(filePath, 'filePath');
611
- if (!v.valid)
612
- return { success: false, error: v.error };
613
- }
614
- const suggestedAgents = suggestAgentsForFile(filePath);
615
- const ext = getFileExtension(filePath);
616
- return {
617
- filePath,
618
- operation,
619
- context: {
620
- fileExists: true,
621
- fileType: ext || 'unknown',
622
- relatedFiles: [],
623
- suggestedAgents,
624
- patterns: [
625
- { pattern: `${ext} file editing`, confidence: 0.85 },
626
- ],
627
- risks: operation === 'delete' ? ['File deletion is irreversible'] : [],
628
- },
629
- recommendations: [
630
- `Recommended agents: ${suggestedAgents.join(', ')}`,
631
- 'Run tests after changes',
632
- ],
633
- };
634
- },
635
- };
636
- export const hooksPostEdit = {
637
- name: 'hooks_post-edit',
638
- description: 'Record editing outcome for learning Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
639
- inputSchema: {
640
- type: 'object',
641
- properties: {
642
- filePath: { type: 'string', description: 'Path to the edited file' },
643
- success: { type: 'boolean', description: 'Whether the edit was successful' },
644
- agent: { type: 'string', description: 'Agent that performed the edit' },
645
- },
646
- required: ['filePath'],
647
- },
648
- handler: async (params) => {
649
- const filePath = params.filePath;
650
- const success = params.success !== false;
651
- const agent = params.agent;
652
- {
653
- const v = validatePath(filePath, 'filePath');
654
- if (!v.valid)
655
- return { success: false, error: v.error };
656
- }
657
- if (agent) {
658
- const v = validateIdentifier(agent, 'agent');
659
- if (!v.valid)
660
- return { success: false, error: v.error };
661
- }
662
- // Wire recordFeedback through bridge (issue #1209)
663
- let feedbackResult = null;
664
- try {
665
- const bridge = await import('../memory/memory-bridge.js');
666
- feedbackResult = await bridge.bridgeRecordFeedback({
667
- taskId: `edit-${filePath}-${Date.now()}`,
668
- success,
669
- quality: success ? 0.85 : 0.3,
670
- agent,
671
- });
672
- }
673
- catch {
674
- // Bridge not available — continue with basic response
675
- }
676
- // #2245 Round B — also feed the trajectory pipeline so globalStats
677
- // (and the unified-stats aggregator in ADR-075) reflects the activity.
678
- // Synthesises a one-step trajectory from the edit outcome.
679
- let learningPath = 'recorded-only';
680
- let trajectoriesDelta = 0;
681
- try {
682
- const intel = await import('../memory/intelligence.js');
683
- const before = intel.getIntelligenceStats().trajectoriesRecorded;
684
- await intel.recordTrajectory([{
685
- type: 'action',
686
- content: `Edit ${filePath}${agent ? ` by ${agent}` : ''}: ${success ? 'success' : 'failure'}`,
687
- metadata: { hook: 'post-edit', filePath, agent, success },
688
- timestamp: Date.now(),
689
- }], success ? 'success' : 'failure');
690
- trajectoriesDelta = intel.getIntelligenceStats().trajectoriesRecorded - before;
691
- if (trajectoriesDelta > 0)
692
- learningPath = 'trajectory-pipeline';
693
- }
694
- catch { /* intelligence module not yet initialised — keep recorded-only */ }
695
- return {
696
- recorded: true,
697
- filePath,
698
- success,
699
- timestamp: new Date().toISOString(),
700
- learningUpdate: success ? 'pattern_reinforced' : 'pattern_adjusted',
701
- learningPath, // ADR-074 / ADR-075 — honest path naming
702
- trajectoriesDelta,
703
- feedback: feedbackResult ? {
704
- recorded: feedbackResult.success,
705
- controller: feedbackResult.controller,
706
- updates: feedbackResult.updated,
707
- } : { recorded: false, controller: 'unavailable', updates: 0 },
708
- note: learningPath === 'trajectory-pipeline'
709
- ? `Edit outcome fed to the SONA + EWC++ trajectory pipeline (trajectoriesRecorded +${trajectoriesDelta}).`
710
- : 'Edit outcome stored via memory-bridge only; the trajectory pipeline was not reachable in this process.',
711
- };
712
- },
713
- };
714
- export const hooksPreCommand = {
715
- name: 'hooks_pre-command',
716
- description: 'Assess risk before executing a command Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
717
- inputSchema: {
718
- type: 'object',
719
- properties: {
720
- command: { type: 'string', description: 'Command to execute' },
721
- },
722
- required: ['command'],
723
- },
724
- handler: async (params) => {
725
- const command = params.command;
726
- {
727
- const v = validateText(command, 'command');
728
- if (!v.valid)
729
- return { success: false, error: v.error };
730
- }
731
- const assessment = assessCommandRisk(command);
732
- const riskLevel = assessment.level >= 0.8 ? 'critical'
733
- : assessment.level >= 0.6 ? 'high'
734
- : assessment.level >= 0.3 ? 'medium'
735
- : 'low';
736
- // #6: tool-loop circuit breaker — warn/block when this exact command has
737
- // failed repeatedly in a row (an agent stuck looping on a failing call).
738
- const loop = checkCommandLoop(command);
739
- const recommendations = assessment.warnings.length > 0
740
- ? ['Review warnings before proceeding', 'Consider using safer alternative']
741
- : ['Command appears safe to execute'];
742
- if (loop.hint)
743
- recommendations.unshift(loop.hint);
744
- return {
745
- command,
746
- riskLevel,
747
- risks: assessment.warnings.map((warning, i) => ({
748
- type: `risk-${i + 1}`,
749
- severity: assessment.level >= 0.6 ? 'high' : 'medium',
750
- description: warning,
751
- })),
752
- recommendations,
753
- loopGuard: { verdict: loop.verdict, consecutiveFailures: loop.consecutiveFailures },
754
- safeAlternatives: [],
755
- // Don't proceed on a high-risk command OR a hard loop-block.
756
- shouldProceed: assessment.level < 0.7 && loop.verdict !== 'block',
757
- };
758
- },
759
- };
760
- export const hooksPostCommand = {
761
- name: 'hooks_post-command',
762
- description: 'Record command execution outcome Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
763
- inputSchema: {
764
- type: 'object',
765
- properties: {
766
- command: { type: 'string', description: 'Executed command' },
767
- exitCode: { type: 'number', description: 'Command exit code' },
768
- },
769
- required: ['command'],
770
- },
771
- handler: async (params) => {
772
- const command = params.command;
773
- const exitCode = params.exitCode || 0;
774
- const success = exitCode === 0;
775
- {
776
- const v = validateText(command, 'command');
777
- if (!v.valid)
778
- return { success: false, error: v.error };
779
- }
780
- // #6: feed the tool-loop circuit breaker so pre-command can warn/block on
781
- // repeated consecutive failures of the same command.
782
- recordCommandOutcome(command, success);
783
- // Persist command outcome via AgentDB
784
- let _storedIn = 'none';
785
- try {
786
- const bridge = await import('../memory/memory-bridge.js');
787
- await bridge.bridgeStoreEntry({
788
- key: `cmd-${Date.now()}`,
789
- value: JSON.stringify({ command, exitCode, success }),
790
- namespace: 'commands',
791
- tags: [success ? 'success' : 'error'],
792
- });
793
- _storedIn = 'agentdb';
794
- }
795
- catch {
796
- // AgentDB not available — store in JSON
797
- try {
798
- const store = loadMemoryStore();
799
- const key = `cmd-${Date.now()}`;
800
- store.entries[key] = { key, value: JSON.stringify({ command, exitCode, success }), namespace: 'commands', createdAt: new Date().toISOString() };
801
- const memDir = resolve(MEMORY_DIR);
802
- if (!existsSync(memDir))
803
- mkdirSync(memDir, { recursive: true });
804
- writeFileSync(getMemoryPath(), JSON.stringify(store, null, 2), 'utf-8');
805
- _storedIn = 'json-store';
806
- }
807
- catch { /* non-critical */ }
808
- }
809
- // #2245 Round B — feed the trajectory pipeline so globalStats reflects
810
- // command outcomes alongside the AgentDB entry that already gets written.
811
- let learningPath = 'recorded-only';
812
- let trajectoriesDelta = 0;
813
- try {
814
- const intel = await import('../memory/intelligence.js');
815
- const before = intel.getIntelligenceStats().trajectoriesRecorded;
816
- await intel.recordTrajectory([{
817
- type: 'action',
818
- content: `Command \`${command.slice(0, 200)}\` exited ${exitCode} (${success ? 'success' : 'failure'})`,
819
- metadata: { hook: 'post-command', command: command.slice(0, 500), exitCode, success },
820
- timestamp: Date.now(),
821
- }], success ? 'success' : 'failure');
822
- trajectoriesDelta = intel.getIntelligenceStats().trajectoriesRecorded - before;
823
- if (trajectoriesDelta > 0)
824
- learningPath = 'trajectory-pipeline';
825
- }
826
- catch { /* intelligence module not yet initialised — keep recorded-only */ }
827
- return {
828
- recorded: _storedIn !== 'none',
829
- command,
830
- exitCode,
831
- success,
832
- timestamp: new Date().toISOString(),
833
- _storedIn,
834
- learningPath, // 'trajectory-pipeline' | 'recorded-only'
835
- trajectoriesDelta,
836
- note: learningPath === 'trajectory-pipeline'
837
- ? `Command outcome fed to the SONA + EWC++ trajectory pipeline (trajectoriesRecorded +${trajectoriesDelta}).`
838
- : `Command outcome stored via ${_storedIn}; the trajectory pipeline was not reachable in this process.`,
839
- };
840
- },
841
- };
842
- export const hooksRoute = {
843
- name: 'hooks_route',
844
- description: 'Get a 3-tier routing recommendation for a task: Tier 1 (deterministic codemod, ~0ms / $0 — for var-to-const, remove-console, add-logging), Tier 2 (Haiku — simple), Tier 3 (Sonnet/Opus — complex). Use this BEFORE spawning an agent to avoid sending simple transforms to Sonnet. Native tools have no equivalent — Claude Code does not introspect its own model-selection cost. Returns the recommended model + a `[CODEMOD_AVAILABLE]` literal when a deterministic codemod can fully apply the edit (then call hooks_codemod). Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
845
- inputSchema: {
846
- type: 'object',
847
- properties: {
848
- task: { type: 'string', description: 'Task description' },
849
- context: { type: 'string', description: 'Additional context' },
850
- useSemanticRouter: { type: 'boolean', description: 'Use semantic similarity routing (default: true)' },
851
- },
852
- required: ['task'],
853
- },
854
- handler: async (params) => {
855
- const task = params.task;
856
- const context = params.context;
857
- const useSemanticRouter = params.useSemanticRouter !== false;
858
- {
859
- const v = validateText(task, 'task');
860
- if (!v.valid)
861
- return { success: false, error: v.error };
862
- }
863
- if (context) {
864
- const v = validateText(context, 'context');
865
- if (!v.valid)
866
- return { success: false, error: v.error };
867
- }
868
- // Phase 5: Try AgentDB's SemanticRouter / LearningSystem first
869
- if (useSemanticRouter) {
870
- try {
871
- const bridge = await import('../memory/memory-bridge.js');
872
- const agentdbRoute = await bridge.bridgeRouteTask({ task, context });
873
- if (agentdbRoute && agentdbRoute.confidence > 0.5) {
874
- const agents = agentdbRoute.agents.length > 0 ? agentdbRoute.agents : ['coder', 'researcher'];
875
- const complexity = task.length > 200 ? 'high' : task.length < 50 ? 'low' : 'medium';
876
- return {
877
- task,
878
- routing: {
879
- method: `agentdb-${agentdbRoute.controller}`,
880
- backend: agentdbRoute.controller,
881
- latencyMs: 0,
882
- throughput: 'N/A',
883
- },
884
- matchedPattern: agentdbRoute.route,
885
- semanticMatches: [{ pattern: agentdbRoute.route, score: agentdbRoute.confidence }],
886
- primaryAgent: {
887
- type: agents[0],
888
- confidence: Math.round(agentdbRoute.confidence * 100) / 100,
889
- reason: `AgentDB ${agentdbRoute.controller}: "${agentdbRoute.route}" (${Math.round(agentdbRoute.confidence * 100)}%)`,
890
- },
891
- alternativeAgents: agents.slice(1).map((agent, i) => ({
892
- type: agent,
893
- confidence: Math.round((agentdbRoute.confidence - (0.1 * (i + 1))) * 100) / 100,
894
- reason: `Alternative from ${agentdbRoute.controller}`,
895
- })),
896
- estimatedMetrics: {
897
- successProbability: Math.round(agentdbRoute.confidence * 100) / 100,
898
- estimatedDuration: complexity === 'high' ? '2-4 hours' : complexity === 'medium' ? '30-60 min' : '10-30 min',
899
- complexity,
900
- },
901
- swarmRecommendation: agents.length > 2 ? { topology: 'hierarchical', agents, coordination: 'queen-led' } : null,
902
- };
903
- }
904
- }
905
- catch {
906
- // AgentDB router not available — fall through to local routing
907
- }
908
- }
909
- // Get router (tries native VectorDb first, falls back to pure JS)
910
- const { router, backend, native } = useSemanticRouter
911
- ? await getSemanticRouter()
912
- : { router: null, backend: 'none', native: null };
913
- let semanticResult = [];
914
- let routingMethod = 'keyword';
915
- let routingLatencyMs = 0;
916
- let backendInfo = '';
917
- const queryText = context ? `${task} ${context}` : task;
918
- const queryEmbedding = generateSimpleEmbedding(queryText);
919
- // Try native VectorDb (HNSW-backed)
920
- if (native && backend === 'native') {
921
- const routeStart = performance.now();
922
- try {
923
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
924
- const results = native.search(queryEmbedding, 5);
925
- routingLatencyMs = performance.now() - routeStart;
926
- routingMethod = 'semantic-native';
927
- backendInfo = 'native VectorDb (HNSW)';
928
- // Convert results to semantic format
929
- const mergedPatterns = getMergedTaskPatterns();
930
- semanticResult = results.map((r) => {
931
- const [patternName] = r.id.split(':');
932
- const pattern = mergedPatterns[patternName];
933
- return {
934
- intent: patternName,
935
- score: 1 - r.score, // Native uses distance (lower is better), convert to similarity
936
- metadata: {
937
- agents: pattern?.agents || (patternName.startsWith('learned-') ? [patternName.slice(8)] : ['coder']),
938
- },
939
- };
940
- });
941
- }
942
- catch {
943
- // Native failed, try pure JS fallback
944
- }
945
- }
946
- // Try pure JS SemanticRouter fallback
947
- if (router && backend === 'pure-js' && semanticResult.length === 0) {
948
- const routeStart = performance.now();
949
- semanticResult = router.routeWithEmbedding(queryEmbedding, 3);
950
- routingLatencyMs = performance.now() - routeStart;
951
- routingMethod = 'semantic-pure-js';
952
- backendInfo = 'pure JS (cosine similarity)';
953
- }
954
- // Get agents from semantic routing or fall back to keyword
955
- let agents;
956
- let confidence;
957
- let matchedPattern = '';
958
- if (semanticResult.length > 0 && semanticResult[0].score > 0.4) {
959
- const topMatch = semanticResult[0];
960
- agents = topMatch.metadata.agents || ['coder', 'researcher'];
961
- confidence = topMatch.score;
962
- matchedPattern = topMatch.intent;
963
- }
964
- else {
965
- // Fall back to keyword matching
966
- const suggestion = suggestAgentsForTask(task);
967
- agents = suggestion.agents;
968
- confidence = suggestion.confidence;
969
- matchedPattern = 'keyword-fallback';
970
- routingMethod = 'keyword';
971
- backendInfo = 'keyword matching';
972
- }
973
- // Determine complexity
974
- const taskLower = task.toLowerCase();
975
- const complexity = taskLower.includes('complex') || taskLower.includes('architecture') || task.length > 200
976
- ? 'high'
977
- : taskLower.includes('simple') || taskLower.includes('fix') || task.length < 50
978
- ? 'low'
979
- : 'medium';
980
- return {
981
- task,
982
- routing: {
983
- method: routingMethod,
984
- backend: backendInfo,
985
- latencyMs: routingLatencyMs,
986
- throughput: routingLatencyMs > 0 ? `${Math.round(1000 / routingLatencyMs)} routes/s` : 'N/A',
987
- },
988
- matchedPattern,
989
- semanticMatches: semanticResult.slice(0, 3).map(r => ({
990
- pattern: r.intent,
991
- score: Math.round(r.score * 100) / 100,
992
- })),
993
- primaryAgent: {
994
- type: agents[0],
995
- confidence: Math.round(confidence * 100) / 100,
996
- reason: routingMethod.startsWith('semantic')
997
- ? `Semantic similarity to "${matchedPattern}" pattern (${Math.round(confidence * 100)}%)`
998
- : `Task contains keywords matching ${agents[0]} specialization`,
999
- },
1000
- alternativeAgents: agents.slice(1).map((agent, i) => ({
1001
- type: agent,
1002
- confidence: Math.round((confidence - (0.1 * (i + 1))) * 100) / 100,
1003
- reason: `Alternative agent for ${agent} capabilities`,
1004
- })),
1005
- estimatedMetrics: {
1006
- successProbability: Math.round(confidence * 100) / 100,
1007
- estimatedDuration: complexity === 'high' ? '2-4 hours' : complexity === 'medium' ? '30-60 min' : '10-30 min',
1008
- complexity,
1009
- },
1010
- swarmRecommendation: agents.length > 2 ? {
1011
- topology: 'hierarchical',
1012
- agents,
1013
- coordination: 'queen-led',
1014
- } : null,
1015
- };
1016
- },
1017
- };
1018
- export const hooksMetrics = {
1019
- name: 'hooks_metrics',
1020
- description: 'View learning metrics dashboard Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
1021
- inputSchema: {
1022
- type: 'object',
1023
- properties: {
1024
- period: { type: 'string', description: 'Metrics period (1h, 24h, 7d, 30d)' },
1025
- includeV3: { type: 'boolean', description: 'Include V3 performance metrics' },
1026
- },
1027
- },
1028
- handler: async (params) => {
1029
- const period = params.period || '24h';
1030
- // ADR-093 F1: read from the same trajectory/pattern store that
1031
- // hooks_post-task and hooks_intelligence_stats write to. Previously
1032
- // this handler key-substring-filtered the memory store for "pattern",
1033
- // "route", "task" — none of which match the trajectory keys that
1034
- // post-task actually writes — so counters stayed at 0 forever (#1686).
1035
- const stats = getIntelligenceStatsFromMemory();
1036
- // Routing outcomes are persisted to a separate file (loadRoutingOutcomes)
1037
- // by post-task; surface them so the dashboard sees command counters too.
1038
- let routingOutcomes = [];
1039
- try {
1040
- routingOutcomes = loadRoutingOutcomes();
1041
- }
1042
- catch { /* non-fatal */ }
1043
- const totalCommands = routingOutcomes.length;
1044
- const successfulCommands = routingOutcomes.filter(o => o.success).length;
1045
- const successRate = totalCommands > 0 ? successfulCommands / totalCommands : null;
1046
- // Compute top agent from routing outcomes
1047
- const agentCounts = {};
1048
- for (const o of routingOutcomes) {
1049
- if (o.agent)
1050
- agentCounts[o.agent] = (agentCounts[o.agent] || 0) + 1;
1051
- }
1052
- const topAgent = Object.entries(agentCounts).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
1053
- const successful = stats.trajectories.successful;
1054
- const total = stats.trajectories.total;
1055
- const failed = Math.max(0, total - successful);
1056
- return {
1057
- _real: true,
1058
- _dataSource: 'intelligence-stats + routing-outcomes',
1059
- period,
1060
- patterns: {
1061
- total: stats.patterns.learned,
1062
- successful,
1063
- failed,
1064
- avgConfidence: stats.routing.avgConfidence || null,
1065
- },
1066
- agents: {
1067
- routingAccuracy: stats.routing.avgConfidence || null,
1068
- totalRoutes: stats.routing.decisions,
1069
- topAgent,
1070
- },
1071
- commands: {
1072
- totalExecuted: totalCommands,
1073
- successRate,
1074
- avgRiskScore: null,
1075
- },
1076
- _note: total === 0 && totalCommands === 0
1077
- ? 'No metrics data collected yet. Run hooks_post-task / hooks_intelligence_trajectory-end / hooks_route to populate.'
1078
- : undefined,
1079
- lastUpdated: new Date().toISOString(),
1080
- };
1081
- },
1082
- };
1083
- export const hooksList = {
1084
- name: 'hooks_list',
1085
- description: 'List all registered hooks Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
1086
- inputSchema: {
1087
- type: 'object',
1088
- properties: {},
1089
- },
1090
- handler: async () => {
1091
- return {
1092
- hooks: [
1093
- // Core hooks
1094
- { name: 'pre-edit', type: 'PreToolUse', status: 'active' },
1095
- { name: 'post-edit', type: 'PostToolUse', status: 'active' },
1096
- { name: 'pre-command', type: 'PreToolUse', status: 'active' },
1097
- { name: 'post-command', type: 'PostToolUse', status: 'active' },
1098
- { name: 'pre-task', type: 'PreToolUse', status: 'active' },
1099
- { name: 'post-task', type: 'PostToolUse', status: 'active' },
1100
- // Routing hooks
1101
- { name: 'route', type: 'intelligence', status: 'active' },
1102
- { name: 'explain', type: 'intelligence', status: 'active' },
1103
- // Session hooks
1104
- { name: 'session-start', type: 'SessionStart', status: 'active' },
1105
- { name: 'session-end', type: 'SessionEnd', status: 'active' },
1106
- { name: 'session-restore', type: 'SessionStart', status: 'active' },
1107
- // Learning hooks
1108
- { name: 'pretrain', type: 'intelligence', status: 'active' },
1109
- { name: 'build-agents', type: 'intelligence', status: 'active' },
1110
- { name: 'transfer', type: 'intelligence', status: 'active' },
1111
- { name: 'metrics', type: 'analytics', status: 'active' },
1112
- // System hooks
1113
- { name: 'init', type: 'system', status: 'active' },
1114
- { name: 'notify', type: 'coordination', status: 'active' },
1115
- // Intelligence subcommands
1116
- { name: 'intelligence', type: 'intelligence', status: 'active' },
1117
- { name: 'intelligence_trajectory-start', type: 'intelligence', status: 'active' },
1118
- { name: 'intelligence_trajectory-step', type: 'intelligence', status: 'active' },
1119
- { name: 'intelligence_trajectory-end', type: 'intelligence', status: 'active' },
1120
- { name: 'intelligence_pattern-store', type: 'intelligence', status: 'active' },
1121
- { name: 'intelligence_pattern-search', type: 'intelligence', status: 'active' },
1122
- { name: 'intelligence_stats', type: 'analytics', status: 'active' },
1123
- { name: 'intelligence_learn', type: 'intelligence', status: 'active' },
1124
- { name: 'intelligence_attention', type: 'intelligence', status: 'active' },
1125
- ],
1126
- total: 26,
1127
- };
1128
- },
1129
- };
1130
- export const hooksPreTask = {
1131
- name: 'hooks_pre-task',
1132
- description: 'Record task start and get agent suggestions with intelligent model routing (ADR-026) Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
1133
- inputSchema: {
1134
- type: 'object',
1135
- properties: {
1136
- taskId: { type: 'string', description: 'Task identifier' },
1137
- description: { type: 'string', description: 'Task description' },
1138
- filePath: { type: 'string', description: 'Optional file path for AST analysis' },
1139
- },
1140
- required: ['taskId', 'description'],
1141
- },
1142
- handler: async (params) => {
1143
- const taskId = params.taskId;
1144
- const description = params.description;
1145
- const filePath = params.filePath;
1146
- {
1147
- const v = validateIdentifier(taskId, 'taskId');
1148
- if (!v.valid)
1149
- return { success: false, error: v.error };
1150
- }
1151
- {
1152
- const v = validateText(description, 'description');
1153
- if (!v.valid)
1154
- return { success: false, error: v.error };
1155
- }
1156
- if (filePath) {
1157
- const v = validatePath(filePath, 'filePath');
1158
- if (!v.valid)
1159
- return { success: false, error: v.error };
1160
- }
1161
- const suggestion = suggestAgentsForTask(description);
1162
- // Determine complexity
1163
- const descLower = description.toLowerCase();
1164
- const complexity = descLower.includes('complex') || descLower.includes('architecture') || description.length > 200
1165
- ? 'high'
1166
- : descLower.includes('simple') || descLower.includes('fix') || description.length < 50
1167
- ? 'low'
1168
- : 'medium';
1169
- // Enhanced model routing with deterministic Tier-1 codemods (ADR-026, ADR-143)
1170
- let modelRouting;
1171
- try {
1172
- const { getEnhancedModelRouter } = await import('../ruvector/enhanced-model-router.js');
1173
- const router = getEnhancedModelRouter();
1174
- const routeResult = await router.route(description, { filePath });
1175
- if (routeResult.tier === 1) {
1176
- // Deterministic codemod can apply this edit with $0 / no LLM (ADR-143)
1177
- const intentType = routeResult.codemodIntent?.type ?? routeResult.agentBoosterIntent?.type;
1178
- modelRouting = {
1179
- tier: 1,
1180
- handler: 'codemod',
1181
- canSkipLLM: true,
1182
- deterministic: true,
1183
- codemodIntent: intentType,
1184
- intentDescription: routeResult.codemodIntent?.description ?? routeResult.agentBoosterIntent?.description,
1185
- confidence: routeResult.confidence,
1186
- estimatedLatencyMs: routeResult.estimatedLatencyMs,
1187
- estimatedCost: routeResult.estimatedCost,
1188
- recommendation: `[CODEMOD_AVAILABLE] Skip LLM — call hooks_codemod with intent="${intentType}" (deterministic, $0)`,
1189
- };
1190
- }
1191
- else {
1192
- // LLM required
1193
- modelRouting = {
1194
- tier: routeResult.tier,
1195
- handler: routeResult.handler,
1196
- model: routeResult.model,
1197
- complexity: routeResult.complexity,
1198
- confidence: routeResult.confidence,
1199
- estimatedLatencyMs: routeResult.estimatedLatencyMs,
1200
- estimatedCost: routeResult.estimatedCost,
1201
- recommendation: `[TASK_MODEL_RECOMMENDATION] Use model="${routeResult.model}" for this task`,
1202
- };
1203
- }
1204
- }
1205
- catch {
1206
- // Enhanced router not available
1207
- }
1208
- return {
1209
- taskId,
1210
- description,
1211
- suggestedAgents: suggestion.agents.map((agent, i) => ({
1212
- type: agent,
1213
- confidence: suggestion.confidence - (0.05 * i),
1214
- reason: i === 0
1215
- ? `Primary agent for ${agent} tasks based on learned patterns`
1216
- : `Alternative agent with ${agent} capabilities`,
1217
- })),
1218
- complexity,
1219
- estimatedDuration: complexity === 'high' ? '2-4 hours' : complexity === 'medium' ? '30-60 min' : '10-30 min',
1220
- risks: complexity === 'high' ? ['Complex task may require multiple iterations'] : [],
1221
- recommendations: [
1222
- `Use ${suggestion.agents[0]} as primary agent`,
1223
- suggestion.agents.length > 2 ? 'Consider using swarm coordination' : 'Single agent recommended',
1224
- ],
1225
- modelRouting,
1226
- timestamp: new Date().toISOString(),
1227
- };
1228
- },
1229
- };
1230
- export const hooksPostTask = {
1231
- name: 'hooks_post-task',
1232
- description: 'Record task completion for learning Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
1233
- inputSchema: {
1234
- type: 'object',
1235
- properties: {
1236
- taskId: { type: 'string', description: 'Task identifier' },
1237
- success: { type: 'boolean', description: 'Whether task was successful' },
1238
- agent: { type: 'string', description: 'Agent that completed the task' },
1239
- quality: { type: 'number', description: 'Quality score (0-1)' },
1240
- task: { type: 'string', description: 'Task description text (used for learning keyword extraction)' },
1241
- storeDecisions: { type: 'boolean', description: 'Also store routing decision in memory DB' },
1242
- // ADR-147 P2: nested-subagent spawn-tree capture
1243
- parentAgentId: { type: 'string', description: 'ID of the parent agent (from Claude Code\'s parent_agent_id OTel span tag / x-claude-code-parent-agent-id header). Omit for top-level work.' },
1244
- depth: { type: 'number', description: 'Chain depth from root lead session (0 = lead, 1+ = subagent). Used by ADR-147 P3 depth-aware guardrail.' },
1245
- },
1246
- required: ['taskId'],
1247
- },
1248
- handler: async (params) => {
1249
- const taskId = params.taskId;
1250
- const success = params.success !== false;
1251
- const agent = params.agent;
1252
- const quality = params.quality || (success ? 0.85 : 0.3);
1253
- const startTime = Date.now();
1254
- {
1255
- const v = validateIdentifier(taskId, 'taskId');
1256
- if (!v.valid)
1257
- return { success: false, error: v.error };
1258
- }
1259
- if (agent) {
1260
- const v = validateIdentifier(agent, 'agent');
1261
- if (!v.valid)
1262
- return { success: false, error: v.error };
1263
- }
1264
- // ADR-147 P2: validate spawn-tree lineage if provided
1265
- const parentAgentId = params.parentAgentId;
1266
- if (parentAgentId !== undefined) {
1267
- const v = validateIdentifier(parentAgentId, 'parentAgentId');
1268
- if (!v.valid)
1269
- return { success: false, error: v.error };
1270
- }
1271
- const depthRaw = params.depth;
1272
- let depth;
1273
- if (depthRaw !== undefined && depthRaw !== null) {
1274
- const n = Number(depthRaw);
1275
- if (!Number.isInteger(n) || n < 0 || n > 32) {
1276
- return { success: false, error: 'depth must be a non-negative integer ≤ 32' };
1277
- }
1278
- depth = n;
1279
- }
1280
- // Phase 3: Wire recordFeedback through bridge → LearningSystem + ReasoningBank
1281
- let feedbackResult = null;
1282
- try {
1283
- const bridge = await import('../memory/memory-bridge.js');
1284
- feedbackResult = await bridge.bridgeRecordFeedback({
1285
- taskId,
1286
- success,
1287
- quality,
1288
- agent,
1289
- duration: params.duration || undefined,
1290
- patterns: params.patterns || undefined,
1291
- // ADR-147 P2: forward spawn-tree lineage so it lands in feedback + memory
1292
- parentAgentId,
1293
- depth,
1294
- });
1295
- }
1296
- catch {
1297
- // Bridge not available — continue with basic response
1298
- }
1299
- // Phase 3: Record causal edge (task → outcome)
1300
- try {
1301
- const bridge = await import('../memory/memory-bridge.js');
1302
- await bridge.bridgeRecordCausalEdge({
1303
- sourceId: taskId,
1304
- targetId: `outcome-${taskId}`,
1305
- relation: success ? 'succeeded' : 'failed',
1306
- weight: quality,
1307
- });
1308
- }
1309
- catch {
1310
- // Non-fatal
1311
- }
1312
- // Record trajectory via intelligence module (SONA + ReasoningBank)
1313
- try {
1314
- const intelligence = await import('../memory/intelligence.js');
1315
- await intelligence.recordTrajectory([{ type: 'result', content: params.task || taskId, metadata: { success, agent, quality }, timestamp: Date.now() }], success ? 'success' : 'failure');
1316
- }
1317
- catch {
1318
- // Intelligence module not available — non-fatal
1319
- }
1320
- // ADR-130 Phase 3: fire-and-forget "reinforced-by" edge on task success
1321
- // Writes: context node → task pattern node (relation: "reinforced-by")
1322
- if (success) {
1323
- (async () => {
1324
- try {
1325
- const { insertGraphEdge } = await import('../memory/graph-edge-writer.js');
1326
- const sessionCtxId = `task:${taskId}`;
1327
- const patternId = `pattern:${taskId}`;
1328
- await insertGraphEdge({
1329
- sourceId: sessionCtxId,
1330
- targetId: patternId,
1331
- relation: 'reinforced-by',
1332
- weight: quality,
1333
- confidence: quality,
1334
- lastReinforced: new Date().toISOString(),
1335
- metadata: { success, agent, taskId },
1336
- });
1337
- }
1338
- catch { /* non-fatal */ }
1339
- })().catch(() => { });
1340
- }
1341
- // Persist routing outcome for runtime learning (file-based, always reliable)
1342
- const taskText = params.task || '';
1343
- const outcomeKeywords = extractKeywords(taskText);
1344
- let outcomePersisted = false;
1345
- if (taskText && agent && agent.length <= 100 && /^[a-zA-Z0-9_-]+$/.test(agent)) {
1346
- try {
1347
- const outcomes = loadRoutingOutcomes();
1348
- outcomes.push({
1349
- task: taskText,
1350
- agent,
1351
- success,
1352
- quality,
1353
- keywords: outcomeKeywords,
1354
- timestamp: new Date().toISOString(),
1355
- });
1356
- saveRoutingOutcomes(outcomes);
1357
- outcomePersisted = true;
1358
- }
1359
- catch { /* non-critical */ }
1360
- }
1361
- // Optionally store in memory DB for cross-session vector retrieval
1362
- if (params.storeDecisions && taskText && agent) {
1363
- try {
1364
- const storeFn = await getRealStoreFunction();
1365
- if (storeFn) {
1366
- await storeFn({
1367
- key: `routing-decision:${taskId}`,
1368
- namespace: 'patterns',
1369
- value: JSON.stringify({ task: taskText, agent, success, quality, keywords: outcomeKeywords }),
1370
- tags: ['routing-decision'],
1371
- });
1372
- }
1373
- }
1374
- catch { /* non-critical */ }
1375
- }
1376
- const duration = Date.now() - startTime;
1377
- // Persist to auto-memory-store for statusline visibility
1378
- try {
1379
- const dataDir = join(getProjectCwd(), '.claude-flow', 'data');
1380
- if (!existsSync(dataDir))
1381
- mkdirSync(dataDir, { recursive: true });
1382
- const storePath = join(dataDir, 'auto-memory-store.json');
1383
- let store = [];
1384
- try {
1385
- if (existsSync(storePath)) {
1386
- const parsed = JSON.parse(readFileSync(storePath, 'utf-8'));
1387
- store = Array.isArray(parsed) ? parsed : [];
1388
- }
1389
- }
1390
- catch { /* start fresh */ }
1391
- store.push({
1392
- id: `task-${taskId}`,
1393
- key: taskId,
1394
- content: `Task ${success ? 'completed' : 'failed'}: ${taskText || taskId}${agent ? ` (agent: ${agent})` : ''}`,
1395
- namespace: 'tasks',
1396
- type: 'task-outcome',
1397
- metadata: { agent, success, quality },
1398
- createdAt: Date.now(),
1399
- });
1400
- writeFileSync(storePath, JSON.stringify(store, null, 2), 'utf-8');
1401
- }
1402
- catch { /* non-critical */ }
1403
- return {
1404
- taskId,
1405
- success,
1406
- duration,
1407
- learningUpdates: {
1408
- patternsUpdated: feedbackResult?.updated || (success ? 2 : 1),
1409
- newPatterns: success ? 1 : 0,
1410
- trajectoryId: `traj-${Date.now()}`,
1411
- controller: feedbackResult?.controller || 'none',
1412
- outcomePersisted,
1413
- },
1414
- quality,
1415
- feedback: feedbackResult ? {
1416
- recorded: feedbackResult.success,
1417
- controller: feedbackResult.controller,
1418
- updates: feedbackResult.updated,
1419
- } : { recorded: false, controller: 'unavailable', updates: 0 },
1420
- timestamp: new Date().toISOString(),
1421
- };
1422
- },
1423
- };
1424
- // Explain hook - transparent routing explanation
1425
- export const hooksExplain = {
1426
- name: 'hooks_explain',
1427
- description: 'Explain routing decision with full transparency Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
1428
- inputSchema: {
1429
- type: 'object',
1430
- properties: {
1431
- task: { type: 'string', description: 'Task description' },
1432
- agent: { type: 'string', description: 'Specific agent to explain' },
1433
- verbose: { type: 'boolean', description: 'Verbose explanation' },
1434
- },
1435
- required: ['task'],
1436
- },
1437
- handler: async (params) => {
1438
- const task = params.task;
1439
- {
1440
- const v = validateText(task, 'task');
1441
- if (!v.valid)
1442
- return { success: false, error: v.error };
1443
- }
1444
- const suggestion = suggestAgentsForTask(task);
1445
- const taskLower = task.toLowerCase();
1446
- // Determine matched patterns
1447
- const matchedPatterns = [];
1448
- for (const [pattern, _result] of Object.entries(TASK_PATTERNS)) {
1449
- if (taskLower.includes(pattern)) {
1450
- matchedPatterns.push({
1451
- pattern,
1452
- matchScore: pattern.length / Math.max(taskLower.length, 1), // real ratio: pattern length vs task length
1453
- examples: [`Keyword "${pattern}" matched in task description`],
1454
- });
1455
- }
1456
- }
1457
- // Calculate real historical success rate from routing outcomes file
1458
- let historicalSuccess = null;
1459
- let historicalNote = 'No historical data yet';
1460
- try {
1461
- const outcomesPath = join(resolve('.'), '.claude-flow/routing-outcomes.json');
1462
- if (existsSync(outcomesPath)) {
1463
- const data = JSON.parse(readFileSync(outcomesPath, 'utf-8'));
1464
- const outcomes = data.outcomes || [];
1465
- if (outcomes.length > 0) {
1466
- historicalSuccess = outcomes.filter(o => o.success).length / outcomes.length;
1467
- historicalNote = `Calculated from ${outcomes.length} recorded outcomes`;
1468
- }
1469
- }
1470
- }
1471
- catch {
1472
- // File unreadable; leave as null
1473
- }
1474
- return {
1475
- task,
1476
- explanation: `The routing decision was made based on keyword analysis of the task description. ` +
1477
- `The task contains keywords that match the "${suggestion.agents[0]}" specialization with ${(suggestion.confidence * 100).toFixed(0)}% confidence.`,
1478
- factors: [
1479
- { factor: 'Keyword Match', weight: 0.4, value: suggestion.confidence, impact: 'Primary routing signal' },
1480
- { factor: 'Historical Success', weight: 0.3, value: historicalSuccess, impact: historicalNote },
1481
- { factor: 'Agent Availability', weight: 0.2, value: null, impact: 'Agent availability tracking not implemented' },
1482
- { factor: 'Task Complexity', weight: 0.1, value: task.length > 100 ? 0.8 : 0.3, impact: 'Complexity assessment' },
1483
- ],
1484
- patterns: matchedPatterns.length > 0 ? matchedPatterns : [
1485
- { pattern: 'general-task', matchScore: 0.7, examples: ['Default pattern for unclassified tasks'] }
1486
- ],
1487
- decision: {
1488
- agent: suggestion.agents[0],
1489
- confidence: suggestion.confidence,
1490
- reasoning: [
1491
- `Task analysis identified ${matchedPatterns.length || 1} relevant patterns`,
1492
- `"${suggestion.agents[0]}" has highest capability match for this task type`,
1493
- historicalSuccess !== null
1494
- ? `Historical success rate for similar tasks: ${(historicalSuccess * 100).toFixed(0)}%`
1495
- : `No historical outcome data available yet`,
1496
- `Confidence threshold met (${(suggestion.confidence * 100).toFixed(0)}% >= 70%)`,
1497
- ],
1498
- },
1499
- };
1500
- },
1501
- };
1502
- // Pretrain hook - repository analysis for intelligence bootstrap
1503
- export const hooksPretrain = {
1504
- name: 'hooks_pretrain',
1505
- description: 'Analyze repository to bootstrap intelligence (4-step pipeline) Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
1506
- inputSchema: {
1507
- type: 'object',
1508
- properties: {
1509
- path: { type: 'string', description: 'Repository path' },
1510
- depth: { type: 'string', description: 'Analysis depth (shallow, medium, deep)' },
1511
- skipCache: { type: 'boolean', description: 'Skip cached analysis' },
1512
- },
1513
- },
1514
- handler: async (params) => {
1515
- const repoPath = resolve(params.path || '.');
1516
- const depth = params.depth || 'medium';
1517
- const startTime = performance.now();
1518
- // Real file scanning — count files by extension, extract patterns.
1519
- // (readdirSync/statSync already imported statically at the top.)
1520
- const extCounts = {};
1521
- let filesAnalyzed = 0;
1522
- // #1953: separate budget for code files. The old code gated the
1523
- // import-pattern extraction on `filesAnalyzed <= 50`, which counts
1524
- // EVERY directory entry (including .md/.yaml/.db/.log). In any
1525
- // markdown/docs-heavy repo, the depth-first walker burned through the
1526
- // 50-file budget on non-code files before reaching any source — so
1527
- // `patternsExtracted: 0` even when hundreds of `.ts`/`.js` files existed.
1528
- let codeFilesScanned = 0;
1529
- let totalLines = 0;
1530
- const maxDepth = depth === 'shallow' ? 2 : depth === 'deep' ? 6 : 4;
1531
- const patterns = [];
1532
- // #1953: recurse into directories that typically contain code first
1533
- // (`src/`, `apps/`, `packages/`, `lib/`, `crates/`, `workers/`, `server/`)
1534
- // before docs / specs / planning dirs, so the import-extraction budget
1535
- // is spent on the highest-signal directories even in mixed repos.
1536
- const CODE_DIR_PREFIXES = new Set([
1537
- 'src', 'apps', 'packages', 'lib', 'crates', 'workers',
1538
- 'server', 'backend', 'frontend', 'app', 'cli', 'core',
1539
- ]);
1540
- const scoreEntry = (name) => {
1541
- if (CODE_DIR_PREFIXES.has(name))
1542
- return 0;
1543
- // Deprioritise common docs / output directories.
1544
- if (/^(docs?|specs?|_.*|examples?|samples?|out|build|target|coverage|tests?)$/.test(name))
1545
- return 2;
1546
- return 1;
1547
- };
1548
- const scan = (dir, currentDepth) => {
1549
- if (currentDepth > maxDepth)
1550
- return;
1551
- try {
1552
- const entries = readdirSync(dir, { withFileTypes: true });
1553
- // Sort: code-likely dirs first, files mixed in by name, deprioritised
1554
- // dirs last. Stable for deterministic test behaviour.
1555
- entries.sort((a, b) => {
1556
- const sa = a.isDirectory() ? scoreEntry(a.name) : 1;
1557
- const sb = b.isDirectory() ? scoreEntry(b.name) : 1;
1558
- return sa - sb;
1559
- });
1560
- for (const entry of entries) {
1561
- if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist')
1562
- continue;
1563
- const full = join(dir, entry.name);
1564
- if (entry.isDirectory()) {
1565
- scan(full, currentDepth + 1);
1566
- }
1567
- else if (entry.isFile()) {
1568
- const ext = entry.name.includes('.') ? entry.name.slice(entry.name.lastIndexOf('.')) : '';
1569
- if (ext)
1570
- extCounts[ext] = (extCounts[ext] || 0) + 1;
1571
- filesAnalyzed++;
1572
- // For code files, count lines and extract imports
1573
- if (['.ts', '.js', '.tsx', '.jsx', '.mjs', '.cjs', '.py', '.go', '.rs', '.java'].includes(ext)) {
1574
- try {
1575
- const content = readFileSync(full, 'utf-8');
1576
- const lines = content.split('\n');
1577
- totalLines += lines.length;
1578
- // #1953: gate on the code-file count, not every-file count.
1579
- // Also widened the per-file scan window from 30 → 80 lines:
1580
- // modern TS files often have license headers + JSDoc + type
1581
- // imports before the first `import` statement.
1582
- if (++codeFilesScanned <= 50) {
1583
- for (const line of lines.slice(0, 80)) {
1584
- if (line.startsWith('import ') || line.startsWith('from ') || (line.startsWith('const ') && line.includes('require('))) {
1585
- const trimmed = line.trim();
1586
- if (trimmed.length < 120 && !patterns.includes(trimmed))
1587
- patterns.push(trimmed);
1588
- if (patterns.length >= 100)
1589
- break;
1590
- }
1591
- }
1592
- }
1593
- }
1594
- catch { /* skip unreadable */ }
1595
- }
1596
- }
1597
- }
1598
- }
1599
- catch { /* skip inaccessible dirs */ }
1600
- };
1601
- scan(repoPath, 0);
1602
- const elapsed = Math.round(performance.now() - startTime);
1603
- // Persist extracted patterns. Two stores get written so the user can find
1604
- // them where they expect:
1605
- // 1. memory-bridge `pretrain` namespace — one summary bundle
1606
- // 2. neural store — one row PER pattern so `neural_patterns list` reflects them
1607
- // #2245 — without (2), the dashboards reported "0 patterns" after pretrain.
1608
- let patternsBundled = 0;
1609
- let patternsIndexed = 0;
1610
- try {
1611
- const bridge = await import('../memory/memory-bridge.js');
1612
- await bridge.bridgeStoreEntry({
1613
- key: `pretrain-${Date.now()}`,
1614
- value: JSON.stringify({ filesAnalyzed, totalLines, topExtensions: Object.entries(extCounts).sort((a, b) => b[1] - a[1]).slice(0, 10), importPatterns: patterns.slice(0, 20) }),
1615
- namespace: 'pretrain',
1616
- tags: ['pretrain', depth],
1617
- });
1618
- patternsBundled = patterns.length;
1619
- }
1620
- catch { /* AgentDB not available */ }
1621
- try {
1622
- const neural = await import('./neural-tools.js');
1623
- const items = patterns.map((p) => ({
1624
- name: p.length > 200 ? p.slice(0, 200) : p,
1625
- type: 'import-pattern',
1626
- content: p,
1627
- metadata: { source: 'hooks_pretrain', depth },
1628
- }));
1629
- const result = await neural.storeNeuralPatterns(items);
1630
- patternsIndexed = result.stored;
1631
- }
1632
- catch { /* neural store unavailable */ }
1633
- // Back-compat field
1634
- const patternsStored = patternsBundled;
1635
- // #1847: when the corpus contains files but no patterns were extracted
1636
- // (typical for Markdown vaults), make the source-code-only extraction
1637
- // contract explicit so users don't conclude the hook system is broken.
1638
- const SUPPORTED_EXTRACTION_EXTS = ['.ts', '.js', '.tsx', '.jsx', '.mjs', '.cjs', '.py', '.go', '.rs', '.java'];
1639
- let note;
1640
- if (filesAnalyzed > 0 && patterns.length === 0) {
1641
- const codeFileCount = SUPPORTED_EXTRACTION_EXTS.reduce((sum, ext) => sum + (extCounts[ext] ?? 0), 0);
1642
- note = codeFileCount === 0
1643
- ? `No source-code patterns found. hooks_pretrain extracts import/require lines from ${SUPPORTED_EXTRACTION_EXTS.join('/')} files only — Markdown/text/asset corpora produce zero patterns by design. This is not a hook-system failure; live trajectories and statusline are independent.`
1644
- : `Found ${codeFileCount} source-code file(s) but extracted zero import/require patterns. They may be empty, generated, or use non-standard module syntax.`;
1645
- }
1646
- return {
1647
- success: true,
1648
- _real: true,
1649
- path: repoPath,
1650
- depth,
1651
- durationMs: elapsed,
1652
- stats: {
1653
- filesAnalyzed,
1654
- totalLines,
1655
- patternsExtracted: patterns.length,
1656
- patternsBundled, // #2245: 1 summary row in memory-bridge `pretrain` namespace
1657
- patternsIndexed, // #2245: per-pattern rows in neural store — surfaced by neural_patterns list
1658
- patternsStored, // back-compat alias for patternsBundled
1659
- fileTypes: Object.entries(extCounts).sort((a, b) => b[1] - a[1]).slice(0, 15).map(([ext, count]) => ({ ext, count })),
1660
- // #1847: explicit extraction contract so callers can tell pretrain
1661
- // patterns apart from live trajectories and hook statusline state.
1662
- // #2245: also call out exactly which stores got written.
1663
- sources: {
1664
- extractedFrom: SUPPORTED_EXTRACTION_EXTS,
1665
- scope: 'pretrain-only (live trajectories + statusline are tracked separately)',
1666
- stores: {
1667
- 'memory-bridge:pretrain': patternsBundled > 0 ? 1 : 0, // one bundle row
1668
- 'neural-store (neural_patterns list)': patternsIndexed,
1669
- },
1670
- },
1671
- },
1672
- ...(note ? { note } : {}),
1673
- };
1674
- },
1675
- };
1676
- // Build agents hook - generate optimized agent configs
1677
- export const hooksBuildAgents = {
1678
- name: 'hooks_build-agents',
1679
- description: 'Generate optimized agent configurations from pretrain data Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
1680
- inputSchema: {
1681
- type: 'object',
1682
- properties: {
1683
- outputDir: { type: 'string', description: 'Output directory for configs' },
1684
- focus: { type: 'string', description: 'Focus area (v3-implementation, security, performance, all)' },
1685
- format: { type: 'string', description: 'Config format (yaml, json)' },
1686
- persist: { type: 'boolean', description: 'Write configs to disk' },
1687
- },
1688
- },
1689
- handler: async (params) => {
1690
- const outputDir = resolve(params.outputDir || './agents');
1691
- const focus = params.focus || 'all';
1692
- const format = params.format || 'yaml';
1693
- const persist = params.persist !== false; // Default to true
1694
- const agents = [
1695
- { type: 'coder', configFile: join(outputDir, `coder.${format}`), capabilities: ['code-generation', 'refactoring', 'debugging'], optimizations: ['flash-attention', 'token-reduction'] },
1696
- { type: 'architect', configFile: join(outputDir, `architect.${format}`), capabilities: ['system-design', 'api-design', 'documentation'], optimizations: ['context-caching', 'memory-persistence'] },
1697
- { type: 'tester', configFile: join(outputDir, `tester.${format}`), capabilities: ['unit-testing', 'integration-testing', 'coverage'], optimizations: ['parallel-execution'] },
1698
- { type: 'security-architect', configFile: join(outputDir, `security-architect.${format}`), capabilities: ['threat-modeling', 'vulnerability-analysis', 'security-review'], optimizations: ['pattern-matching'] },
1699
- { type: 'reviewer', configFile: join(outputDir, `reviewer.${format}`), capabilities: ['code-review', 'quality-analysis', 'best-practices'], optimizations: ['incremental-analysis'] },
1700
- ];
1701
- const filteredAgents = focus === 'all' ? agents :
1702
- focus === 'security' ? agents.filter(a => a.type.includes('security') || a.type === 'reviewer') :
1703
- focus === 'performance' ? agents.filter(a => ['coder', 'tester'].includes(a.type)) :
1704
- agents;
1705
- // Persist configs to disk if requested
1706
- if (persist) {
1707
- // Ensure output directory exists
1708
- if (!existsSync(outputDir)) {
1709
- mkdirSync(outputDir, { recursive: true });
1710
- }
1711
- // Write each agent config
1712
- for (const agent of filteredAgents) {
1713
- const config = {
1714
- type: agent.type,
1715
- capabilities: agent.capabilities,
1716
- optimizations: agent.optimizations,
1717
- version: '3.0.0',
1718
- createdAt: new Date().toISOString(),
1719
- };
1720
- const content = format === 'json'
1721
- ? JSON.stringify(config, null, 2)
1722
- : `# ${agent.type} agent configuration\ntype: ${agent.type}\nversion: "3.0.0"\ncapabilities:\n${agent.capabilities.map(c => ` - ${c}`).join('\n')}\noptimizations:\n${agent.optimizations.map(o => ` - ${o}`).join('\n')}\ncreatedAt: "${config.createdAt}"\n`;
1723
- writeFileSync(agent.configFile, content, 'utf-8');
1724
- }
1725
- }
1726
- return {
1727
- outputDir,
1728
- focus,
1729
- persisted: persist,
1730
- agents: filteredAgents,
1731
- stats: {
1732
- configsGenerated: filteredAgents.length,
1733
- patternsApplied: filteredAgents.length * 3,
1734
- optimizationsIncluded: filteredAgents.reduce((acc, a) => acc + a.optimizations.length, 0),
1735
- },
1736
- };
1737
- },
1738
- };
1739
- // Transfer hook - transfer patterns from another project
1740
- export const hooksTransfer = {
1741
- name: 'hooks_transfer',
1742
- description: 'Transfer learned patterns from another project Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
1743
- inputSchema: {
1744
- type: 'object',
1745
- properties: {
1746
- sourcePath: { type: 'string', description: 'Source project path' },
1747
- filter: { type: 'string', description: 'Filter patterns by type' },
1748
- minConfidence: { type: 'number', description: 'Minimum confidence threshold' },
1749
- },
1750
- required: ['sourcePath'],
1751
- },
1752
- handler: async (params) => {
1753
- const sourcePath = params.sourcePath;
1754
- const minConfidence = params.minConfidence || 0.7;
1755
- const filter = params.filter;
1756
- {
1757
- const v = validatePath(sourcePath, 'sourcePath');
1758
- if (!v.valid)
1759
- return { success: false, error: v.error };
1760
- }
1761
- if (filter) {
1762
- const v = validateIdentifier(filter, 'filter');
1763
- if (!v.valid)
1764
- return { success: false, error: v.error };
1765
- }
1766
- // Try to load patterns from source project's memory store
1767
- const sourceMemoryPath = join(resolve(sourcePath), MEMORY_DIR, MEMORY_FILE);
1768
- let sourceStore = { entries: {}, version: '3.0.0' };
1769
- try {
1770
- if (existsSync(sourceMemoryPath)) {
1771
- sourceStore = JSON.parse(readFileSync(sourceMemoryPath, 'utf-8'));
1772
- }
1773
- }
1774
- catch {
1775
- // Fall back to empty store
1776
- }
1777
- const sourceEntries = Object.values(sourceStore.entries);
1778
- // Count patterns by type from source
1779
- const byType = {
1780
- 'file-patterns': sourceEntries.filter(e => e.key.includes('file') || e.metadata?.type === 'file-pattern').length,
1781
- 'task-routing': sourceEntries.filter(e => e.key.includes('routing') || e.metadata?.type === 'routing').length,
1782
- 'command-risk': sourceEntries.filter(e => e.key.includes('command') || e.metadata?.type === 'command-risk').length,
1783
- 'agent-success': sourceEntries.filter(e => e.key.includes('agent') || e.metadata?.type === 'agent-success').length,
1784
- };
1785
- // If source has no patterns, report honestly instead of substituting demo data
1786
- if (Object.values(byType).every(v => v === 0)) {
1787
- return {
1788
- success: false,
1789
- message: 'No patterns found in source project',
1790
- sourcePath,
1791
- transferred: 0,
1792
- };
1793
- }
1794
- if (filter) {
1795
- Object.keys(byType).forEach(key => {
1796
- if (!key.includes(filter))
1797
- delete byType[key];
1798
- });
1799
- }
1800
- const total = Object.values(byType).reduce((a, b) => a + b, 0);
1801
- return {
1802
- success: true,
1803
- sourcePath,
1804
- transferred: {
1805
- total,
1806
- byType,
1807
- },
1808
- skipped: {
1809
- lowConfidence: Math.floor(total * 0.15),
1810
- duplicates: Math.floor(total * 0.08),
1811
- conflicts: Math.floor(total * 0.03),
1812
- },
1813
- stats: {
1814
- avgConfidence: 0.82 + (minConfidence > 0.8 ? 0.1 : 0),
1815
- avgAge: '3 days',
1816
- },
1817
- dataSource: 'source-project',
1818
- };
1819
- },
1820
- };
1821
- // Session start hook - auto-starts daemon
1822
- export const hooksSessionStart = {
1823
- name: 'hooks_session-start',
1824
- description: 'Initialize a new session and auto-start daemon Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
1825
- inputSchema: {
1826
- type: 'object',
1827
- properties: {
1828
- sessionId: { type: 'string', description: 'Optional session ID' },
1829
- restoreLatest: { type: 'boolean', description: 'Restore latest session state' },
1830
- startDaemon: { type: 'boolean', description: 'Start worker daemon (default: false — opt-in to prevent unintended token usage)' },
1831
- },
1832
- },
1833
- handler: async (params) => {
1834
- const sessionId = params.sessionId || `session-${Date.now()}`;
1835
- const restoreLatest = params.restoreLatest;
1836
- const shouldStartDaemon = params.startDaemon === true;
1837
- if (params.sessionId) {
1838
- const v = validateIdentifier(params.sessionId, 'sessionId');
1839
- if (!v.valid)
1840
- return { success: false, error: v.error };
1841
- }
1842
- // Auto-regenerate statusline if outdated (fixes older installs)
1843
- // Checks for the old fake heuristic: "Math.floor(sizeKB / 2)"
1844
- try {
1845
- const statuslinePath = join(getProjectCwd(), '.claude', 'helpers', 'statusline.cjs');
1846
- if (existsSync(statuslinePath)) {
1847
- const content = readFileSync(statuslinePath, 'utf-8');
1848
- if (content.includes('Math.floor(sizeKB / 2)') || content.includes('Maturity fallback')) {
1849
- // Old version detected — regenerate from current generator
1850
- const { generateStatuslineScript } = await import('../init/statusline-generator.js');
1851
- const newContent = generateStatuslineScript({
1852
- runtime: { maxAgents: 15, topology: 'hierarchical', strategy: 'specialized' },
1853
- });
1854
- writeFileSync(statuslinePath, newContent, 'utf-8');
1855
- }
1856
- }
1857
- }
1858
- catch {
1859
- // Non-critical — old statusline continues to work, just with stale heuristics
1860
- }
1861
- // Auto-start daemon if enabled
1862
- let daemonStatus = { started: false };
1863
- if (shouldStartDaemon) {
1864
- try {
1865
- // Dynamic import to avoid circular dependencies
1866
- const { startDaemon } = await import('../services/worker-daemon.js');
1867
- const daemon = await startDaemon(getProjectCwd());
1868
- const status = daemon.getStatus();
1869
- daemonStatus = {
1870
- started: true,
1871
- pid: status.pid,
1872
- };
1873
- }
1874
- catch (error) {
1875
- daemonStatus = {
1876
- started: false,
1877
- error: error instanceof Error ? error.message : String(error),
1878
- };
1879
- }
1880
- }
1881
- // Initialize intelligence module (SONA + local ReasoningBank)
1882
- let intelligenceStatus = { sonaEnabled: false, reasoningBankEnabled: false };
1883
- try {
1884
- const intelligence = await import('../memory/intelligence.js');
1885
- const initResult = await intelligence.initializeIntelligence();
1886
- intelligenceStatus = { sonaEnabled: initResult.sonaEnabled, reasoningBankEnabled: initResult.reasoningBankEnabled };
1887
- }
1888
- catch {
1889
- // Intelligence module not available — non-fatal
1890
- }
1891
- // Phase 5: Wire ReflexionMemory session start via bridge
1892
- let sessionMemory = null;
1893
- try {
1894
- const bridge = await import('../memory/memory-bridge.js');
1895
- const result = await bridge.bridgeSessionStart({
1896
- sessionId,
1897
- context: restoreLatest ? 'restore previous session patterns' : 'new session',
1898
- });
1899
- if (result) {
1900
- sessionMemory = {
1901
- controller: result.controller,
1902
- restoredPatterns: result.restoredPatterns,
1903
- };
1904
- }
1905
- }
1906
- catch {
1907
- // Bridge not available
1908
- }
1909
- // Persist session record to auto-memory-store for statusline visibility
1910
- try {
1911
- const dataDir = join(getProjectCwd(), '.claude-flow', 'data');
1912
- if (!existsSync(dataDir))
1913
- mkdirSync(dataDir, { recursive: true });
1914
- const storePath = join(dataDir, 'auto-memory-store.json');
1915
- let store = [];
1916
- try {
1917
- if (existsSync(storePath)) {
1918
- const raw = readFileSync(storePath, 'utf-8');
1919
- const parsed = JSON.parse(raw);
1920
- store = Array.isArray(parsed) ? parsed : [];
1921
- }
1922
- }
1923
- catch { /* start fresh */ }
1924
- // Add session entry (dedup by session ID)
1925
- const entryId = `session-${sessionId}`;
1926
- const existing = store.findIndex((e) => e.id === entryId);
1927
- const entry = {
1928
- id: entryId,
1929
- key: sessionId,
1930
- content: `Session started: ${sessionId}`,
1931
- namespace: 'sessions',
1932
- type: 'session',
1933
- createdAt: Date.now(),
1934
- };
1935
- if (existing >= 0)
1936
- store[existing] = entry;
1937
- else
1938
- store.push(entry);
1939
- writeFileSync(storePath, JSON.stringify(store, null, 2), 'utf-8');
1940
- }
1941
- catch {
1942
- // Non-critical — statusline just won't show this session
1943
- }
1944
- return {
1945
- sessionId,
1946
- started: new Date().toISOString(),
1947
- restored: restoreLatest,
1948
- config: {
1949
- intelligenceEnabled: true,
1950
- hooksEnabled: true,
1951
- memoryPersistence: true,
1952
- daemonEnabled: shouldStartDaemon,
1953
- },
1954
- daemon: daemonStatus,
1955
- sessionMemory: sessionMemory || { controller: 'none', restoredPatterns: 0 },
1956
- previousSession: restoreLatest ? {
1957
- id: `session-${Date.now() - 86400000}`,
1958
- tasksRestored: sessionMemory?.restoredPatterns || 0,
1959
- memoryRestored: sessionMemory?.restoredPatterns || 0,
1960
- } : null,
1961
- };
1962
- },
1963
- };
1964
- // Session end hook - stops daemon
1965
- export const hooksSessionEnd = {
1966
- name: 'hooks_session-end',
1967
- description: 'End current session, stop daemon, and persist state Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
1968
- inputSchema: {
1969
- type: 'object',
1970
- properties: {
1971
- saveState: { type: 'boolean', description: 'Save session state' },
1972
- exportMetrics: { type: 'boolean', description: 'Export session metrics' },
1973
- stopDaemon: { type: 'boolean', description: 'Stop worker daemon (default: true)' },
1974
- },
1975
- },
1976
- handler: async (params) => {
1977
- const saveState = params.saveState !== false;
1978
- const shouldStopDaemon = params.stopDaemon !== false;
1979
- const sessionId = `session-${Date.now() - 3600000}`; // Default session (1 hour ago)
1980
- // Stop daemon if enabled
1981
- let daemonStopped = false;
1982
- if (shouldStopDaemon) {
1983
- try {
1984
- const { stopDaemon } = await import('../services/worker-daemon.js');
1985
- await stopDaemon();
1986
- daemonStopped = true;
1987
- }
1988
- catch {
1989
- // Daemon may not be running
1990
- }
1991
- }
1992
- // Read actual counts from stores
1993
- const store = loadMemoryStore();
1994
- const allEntries = Object.values(store.entries);
1995
- const taskCount = allEntries.filter(e => e.key.includes('task')).length;
1996
- const agentCount = allEntries.filter(e => e.key.includes('agent')).length;
1997
- const patternCount = allEntries.filter(e => e.key.includes('pattern')).length;
1998
- const trajectoryCount = activeTrajectories.size;
1999
- // Check for pending-insights.jsonl
2000
- let insightCount = 0;
2001
- try {
2002
- const insightsPath = resolve(join('.claude-flow', 'data', 'pending-insights.jsonl'));
2003
- if (existsSync(insightsPath)) {
2004
- const content = readFileSync(insightsPath, 'utf-8').trim();
2005
- insightCount = content ? content.split('\n').length : 0;
2006
- }
2007
- }
2008
- catch {
2009
- // File not available
2010
- }
2011
- // Phase 5: Wire ReflexionMemory session end + NightlyLearner consolidation via bridge
2012
- let sessionPersistence = null;
2013
- try {
2014
- const bridge = await import('../memory/memory-bridge.js');
2015
- const result = await bridge.bridgeSessionEnd({
2016
- sessionId,
2017
- summary: saveState ? 'Session ended with state saved' : 'Session ended',
2018
- tasksCompleted: taskCount,
2019
- patternsLearned: patternCount,
2020
- });
2021
- if (result) {
2022
- sessionPersistence = {
2023
- controller: result.controller,
2024
- persisted: result.persisted,
2025
- };
2026
- }
2027
- }
2028
- catch {
2029
- // Bridge not available
2030
- }
2031
- return {
2032
- sessionId,
2033
- duration: 3600000, // 1 hour in ms
2034
- statePath: saveState ? `.claude/sessions/${sessionId}.json` : undefined,
2035
- daemon: { stopped: daemonStopped },
2036
- sessionPersistence: sessionPersistence || { controller: 'none', persisted: false },
2037
- summary: {
2038
- tasksExecuted: taskCount,
2039
- filesModified: 0,
2040
- agentsSpawned: agentCount,
2041
- pendingInsights: insightCount,
2042
- memoryEntries: allEntries.length,
2043
- },
2044
- learningUpdates: {
2045
- patternsLearned: patternCount,
2046
- trajectoriesRecorded: trajectoryCount,
2047
- },
2048
- };
2049
- },
2050
- };
2051
- // Session restore hook
2052
- export const hooksSessionRestore = {
2053
- name: 'hooks_session-restore',
2054
- description: 'Restore a previous session Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
2055
- inputSchema: {
2056
- type: 'object',
2057
- properties: {
2058
- sessionId: { type: 'string', description: 'Session ID to restore (or "latest")' },
2059
- restoreAgents: { type: 'boolean', description: 'Restore spawned agents' },
2060
- restoreTasks: { type: 'boolean', description: 'Restore active tasks' },
2061
- },
2062
- },
2063
- handler: async (params) => {
2064
- const requestedId = params.sessionId || 'latest';
2065
- const restoreAgents = params.restoreAgents !== false;
2066
- const restoreTasks = params.restoreTasks !== false;
2067
- if (params.sessionId) {
2068
- const v = validateIdentifier(params.sessionId, 'sessionId');
2069
- if (!v.valid)
2070
- return { success: false, error: v.error };
2071
- }
2072
- const originalSessionId = requestedId === 'latest' ? `session-${Date.now() - 86400000}` : requestedId;
2073
- const newSessionId = `session-${Date.now()}`;
2074
- // Get real memory entry count
2075
- const store = loadMemoryStore();
2076
- const memoryEntryCount = Object.keys(store.entries).length;
2077
- // Count task and agent entries
2078
- const taskEntries = Object.keys(store.entries).filter(k => k.includes('task')).length;
2079
- const agentEntries = Object.keys(store.entries).filter(k => k.includes('agent')).length;
2080
- return {
2081
- sessionId: newSessionId,
2082
- originalSessionId,
2083
- restoredState: {
2084
- tasksRestored: restoreTasks ? Math.min(taskEntries, 10) : 0,
2085
- agentsRestored: restoreAgents ? Math.min(agentEntries, 5) : 0,
2086
- memoryRestored: memoryEntryCount,
2087
- },
2088
- warnings: restoreTasks && taskEntries > 0 ? [`${Math.min(taskEntries, 2)} tasks were in progress and may need review`] : undefined,
2089
- dataSource: 'memory-store',
2090
- };
2091
- },
2092
- };
2093
- // Notify hook - cross-agent notifications
2094
- export const hooksNotify = {
2095
- name: 'hooks_notify',
2096
- description: 'Send cross-agent notification Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
2097
- inputSchema: {
2098
- type: 'object',
2099
- properties: {
2100
- message: { type: 'string', description: 'Notification message' },
2101
- target: { type: 'string', description: 'Target agent or "all"' },
2102
- priority: { type: 'string', description: 'Priority level (low, normal, high, urgent)' },
2103
- data: { type: 'object', description: 'Additional data payload' },
2104
- },
2105
- required: ['message'],
2106
- },
2107
- handler: async (params) => {
2108
- const message = params.message;
2109
- const target = params.target || 'all';
2110
- const priority = params.priority || 'normal';
2111
- {
2112
- const v = validateText(message, 'message');
2113
- if (!v.valid)
2114
- return { success: false, error: v.error };
2115
- }
2116
- if (params.target) {
2117
- const v = validateIdentifier(target, 'target');
2118
- if (!v.valid)
2119
- return { success: false, error: v.error };
2120
- }
2121
- return {
2122
- notificationId: `notify-${Date.now()}`,
2123
- message,
2124
- target,
2125
- priority,
2126
- delivered: true,
2127
- recipients: target === 'all' ? ['coder', 'architect', 'tester', 'reviewer'] : [target],
2128
- timestamp: new Date().toISOString(),
2129
- };
2130
- },
2131
- };
2132
- // Init hook - initialize hooks in project
2133
- export const hooksInit = {
2134
- name: 'hooks_init',
2135
- description: 'Initialize hooks in project with .claude/settings.json Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
2136
- inputSchema: {
2137
- type: 'object',
2138
- properties: {
2139
- path: { type: 'string', description: 'Project path' },
2140
- template: { type: 'string', description: 'Template to use (minimal, standard, full)' },
2141
- force: { type: 'boolean', description: 'Overwrite existing configuration' },
2142
- },
2143
- },
2144
- handler: async (params) => {
2145
- const path = params.path || '.';
2146
- const template = params.template || 'standard';
2147
- const force = params.force;
2148
- const hooksConfigured = template === 'minimal' ? 4 : template === 'full' ? 16 : 9;
2149
- return {
2150
- path,
2151
- template,
2152
- created: {
2153
- settingsJson: `${path}/.claude/settings.json`,
2154
- hooksDir: `${path}/.claude/hooks`,
2155
- },
2156
- hooks: {
2157
- configured: hooksConfigured,
2158
- types: ['PreToolUse', 'PostToolUse', 'SessionStart', 'SessionEnd'],
2159
- },
2160
- intelligence: {
2161
- enabled: template !== 'minimal',
2162
- sona: template === 'full',
2163
- moe: template === 'full',
2164
- hnsw: template !== 'minimal',
2165
- },
2166
- overwritten: force,
2167
- };
2168
- },
2169
- };
2170
- // Intelligence hook - RuVector intelligence system
2171
- export const hooksIntelligence = {
2172
- name: 'hooks_intelligence',
2173
- description: 'RuVector intelligence system status (shows REAL metrics from memory store) Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
2174
- inputSchema: {
2175
- type: 'object',
2176
- properties: {
2177
- mode: { type: 'string', description: 'Intelligence mode' },
2178
- enableSona: { type: 'boolean', description: 'Enable SONA learning' },
2179
- enableMoe: { type: 'boolean', description: 'Enable MoE routing' },
2180
- enableHnsw: { type: 'boolean', description: 'Enable HNSW search' },
2181
- forceTraining: { type: 'boolean', description: 'Force training cycle' },
2182
- showStatus: { type: 'boolean', description: 'Show status only' },
2183
- },
2184
- },
2185
- handler: async (params) => {
2186
- const mode = params.mode || 'balanced';
2187
- const enableSona = params.enableSona !== false;
2188
- const enableMoe = params.enableMoe !== false;
2189
- const enableHnsw = params.enableHnsw !== false;
2190
- // Get REAL statistics from memory store
2191
- const realStats = getIntelligenceStatsFromMemory();
2192
- // Check actual implementation availability
2193
- const sonaAvailable = (await getSONAOptimizer()) !== null;
2194
- const moeAvailable = (await getMoERouter()) !== null;
2195
- const flashAvailable = (await getFlashAttention()) !== null;
2196
- const ewcAvailable = (await getEWCConsolidator()) !== null;
2197
- const loraAvailable = (await getLoRAAdapter()) !== null;
2198
- return {
2199
- mode,
2200
- status: 'active',
2201
- components: {
2202
- sona: {
2203
- enabled: enableSona,
2204
- status: sonaAvailable ? 'active' : 'loading',
2205
- implemented: true, // NOW IMPLEMENTED in alpha.102
2206
- trajectoriesRecorded: realStats.trajectories.total,
2207
- trajectoriesSuccessful: realStats.trajectories.successful,
2208
- patternsLearned: realStats.patterns.learned,
2209
- note: sonaAvailable ? 'SONA optimizer active - learning from trajectories' : 'SONA loading...',
2210
- },
2211
- moe: {
2212
- enabled: enableMoe,
2213
- status: moeAvailable ? 'active' : 'loading',
2214
- implemented: true, // NOW IMPLEMENTED in alpha.102
2215
- routingDecisions: realStats.routing.decisions,
2216
- note: moeAvailable ? 'MoE router with 8 experts (coder, tester, reviewer, architect, security, performance, researcher, coordinator)' : 'MoE loading...',
2217
- },
2218
- hnsw: {
2219
- enabled: enableHnsw,
2220
- status: enableHnsw ? 'active' : 'disabled',
2221
- implemented: true,
2222
- indexSize: realStats.memory.indexSize,
2223
- memorySizeBytes: realStats.memory.memorySizeBytes,
2224
- note: 'HNSW vector indexing with 150x-12,500x speedup',
2225
- },
2226
- flashAttention: {
2227
- enabled: true,
2228
- status: flashAvailable ? 'active' : 'loading',
2229
- implemented: true, // NOW IMPLEMENTED in alpha.102
2230
- note: flashAvailable ? 'Flash Attention with O(N) memory (2.49x-7.47x speedup)' : 'Flash Attention loading...',
2231
- },
2232
- ewc: {
2233
- enabled: true,
2234
- status: ewcAvailable ? 'active' : 'loading',
2235
- implemented: true, // NOW IMPLEMENTED in alpha.102
2236
- note: ewcAvailable ? 'EWC++ consolidation prevents catastrophic forgetting' : 'EWC++ loading...',
2237
- },
2238
- lora: {
2239
- enabled: true,
2240
- status: loraAvailable ? 'active' : 'loading',
2241
- implemented: true, // NOW IMPLEMENTED in alpha.102
2242
- note: loraAvailable ? 'LoRA adapter with 128x memory compression (rank=8)' : 'LoRA loading...',
2243
- },
2244
- embeddings: {
2245
- provider: 'transformers',
2246
- model: 'Xenova/all-MiniLM-L6-v2',
2247
- dimension: 384,
2248
- implemented: true,
2249
- note: 'Real ONNX embeddings via Xenova/all-MiniLM-L6-v2',
2250
- },
2251
- ruvllmCoordinator: await (async () => {
2252
- try {
2253
- const { getIntelligenceStats } = await import('../memory/intelligence.js');
2254
- const s = getIntelligenceStats();
2255
- return { status: s._ruvllmBackend || 'unavailable', trajectories: s._ruvllmTrajectories || 0, note: s._ruvllmBackend === 'active' ? 'SonaCoordinator forwarding trajectories' : '@ruvector/ruvllm not loaded' };
2256
- }
2257
- catch {
2258
- return { status: 'unavailable', trajectories: 0, note: 'Not initialized' };
2259
- }
2260
- })(),
2261
- contrastiveTrainer: await (async () => {
2262
- try {
2263
- const { getSONAStats } = await import('../memory/sona-optimizer.js');
2264
- const s = await getSONAStats();
2265
- return { status: s._contrastiveTrainer !== 'unavailable' ? 'active' : 'unavailable', details: s._contrastiveTrainer, note: s._contrastiveTrainer !== 'unavailable' ? 'Agent embedding learning active' : '@ruvector/ruvllm not loaded' };
2266
- }
2267
- catch {
2268
- return { status: 'unavailable', details: null, note: 'Not initialized' };
2269
- }
2270
- })(),
2271
- trainingPipeline: await (async () => {
2272
- try {
2273
- const loraInst = await getLoRAAdapter();
2274
- const s = loraInst?.getStats();
2275
- return { status: s?._trainingBackend || 'unavailable', note: s?._trainingBackend === 'ruvllm' ? 'Checkpoint save/load via ruvllm' : 'JS fallback' };
2276
- }
2277
- catch {
2278
- return { status: 'unavailable', note: 'Not initialized' };
2279
- }
2280
- })(),
2281
- graphDatabase: await (async () => {
2282
- try {
2283
- const { getGraphStats } = await import('../ruvector/graph-backend.js');
2284
- const gs = await getGraphStats();
2285
- return { status: gs.backend, totalNodes: gs.totalNodes, totalEdges: gs.totalEdges, avgDegree: gs.avgDegree, note: gs.backend === 'graph-node' ? 'Native Rust graph with hyperedges and k-hop queries' : '@ruvector/graph-node not loaded' };
2286
- }
2287
- catch {
2288
- return { status: 'unavailable', totalNodes: 0, totalEdges: 0, avgDegree: 0, note: 'Not initialized' };
2289
- }
2290
- })(),
2291
- },
2292
- realMetrics: {
2293
- trajectories: realStats.trajectories,
2294
- patterns: realStats.patterns,
2295
- memory: realStats.memory,
2296
- routing: realStats.routing,
2297
- },
2298
- implementationStatus: {
2299
- working: [
2300
- 'memory-store', 'embeddings', 'trajectory-recording', 'claims', 'swarm-coordination',
2301
- 'hnsw-index', 'pattern-storage', 'sona-optimizer', 'ewc-consolidation', 'moe-routing',
2302
- 'flash-attention', 'lora-adapter', 'ruvllm-coordinator', 'contrastive-trainer', 'training-pipeline', 'graph-database'
2303
- ],
2304
- partial: [],
2305
- notImplemented: [],
2306
- },
2307
- version: '3.0.0-alpha.102',
2308
- };
2309
- },
2310
- };
2311
- // Intelligence reset hook
2312
- export const hooksIntelligenceReset = {
2313
- name: 'hooks_intelligence-reset',
2314
- description: 'Reset intelligence learning state Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
2315
- inputSchema: {
2316
- type: 'object',
2317
- properties: {},
2318
- },
2319
- handler: async () => {
2320
- const cwd = getProjectCwd();
2321
- const cleared = {
2322
- trajectories: 0,
2323
- patterns: 0,
2324
- dataFiles: 0,
2325
- neuralFiles: 0,
2326
- };
2327
- const deletedFiles = [];
2328
- // Clear intelligence data files if they exist
2329
- const dataFiles = [
2330
- join(cwd, '.claude-flow', 'data', 'auto-memory-store.json'),
2331
- join(cwd, '.claude-flow', 'data', 'graph-state.json'),
2332
- join(cwd, '.claude-flow', 'data', 'ranked-context.json'),
2333
- ];
2334
- for (const filePath of dataFiles) {
2335
- if (existsSync(filePath)) {
2336
- try {
2337
- unlinkSync(filePath);
2338
- cleared.dataFiles++;
2339
- deletedFiles.push(filePath);
2340
- }
2341
- catch {
2342
- // Skip files that cannot be deleted
2343
- }
2344
- }
2345
- }
2346
- // Clear neural directory if it exists
2347
- const neuralDir = join(cwd, '.claude-flow', 'neural');
2348
- if (existsSync(neuralDir)) {
2349
- try {
2350
- const files = readdirSync(neuralDir);
2351
- for (const file of files) {
2352
- try {
2353
- const filePath = join(neuralDir, file);
2354
- unlinkSync(filePath);
2355
- cleared.neuralFiles++;
2356
- deletedFiles.push(filePath);
2357
- }
2358
- catch {
2359
- // Skip files that cannot be deleted
2360
- }
2361
- }
2362
- }
2363
- catch {
2364
- // Directory read failed
2365
- }
2366
- }
2367
- // Clear in-memory trajectories
2368
- cleared.trajectories = activeTrajectories.size;
2369
- activeTrajectories.clear();
2370
- return {
2371
- reset: true,
2372
- cleared,
2373
- deletedFiles,
2374
- timestamp: new Date().toISOString(),
2375
- };
2376
- },
2377
- };
2378
- // Intelligence trajectory hooks - REAL implementation using activeTrajectories
2379
- export const hooksTrajectoryStart = {
2380
- name: 'hooks_intelligence_trajectory-start',
2381
- description: 'Begin SONA trajectory for reinforcement learning Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
2382
- inputSchema: {
2383
- type: 'object',
2384
- properties: {
2385
- task: { type: 'string', description: 'Task description' },
2386
- agent: { type: 'string', description: 'Agent type' },
2387
- sessionId: { type: 'string', description: 'Session id for the execution-state tree (default: CLAUDE_FLOW_SESSION_ID or "default")' },
2388
- },
2389
- required: ['task'],
2390
- },
2391
- handler: async (params) => {
2392
- const task = params.task;
2393
- const agent = params.agent || 'coder';
2394
- const sessionId = params.sessionId || process.env.CLAUDE_FLOW_SESSION_ID || 'default';
2395
- {
2396
- const v = validateText(task, 'task');
2397
- if (!v.valid)
2398
- return { success: false, error: v.error };
2399
- }
2400
- if (params.agent) {
2401
- const v = validateIdentifier(params.agent, 'agent');
2402
- if (!v.valid)
2403
- return { success: false, error: v.error };
2404
- }
2405
- if (params.sessionId) {
2406
- const v = validateIdentifier(params.sessionId, 'sessionId');
2407
- if (!v.valid)
2408
- return { success: false, error: v.error };
2409
- }
2410
- const trajectoryId = `traj-${Date.now()}-${Math.random().toString(36).substring(7)}`;
2411
- const startedAt = new Date().toISOString();
2412
- // Create real trajectory entry in memory
2413
- const trajectory = {
2414
- id: trajectoryId,
2415
- task,
2416
- agent,
2417
- steps: [],
2418
- startedAt,
2419
- };
2420
- activeTrajectories.set(trajectoryId, trajectory);
2421
- // MAGE-style execution-state-tree mirror (prototype, ruvector/trajectory-tree.ts).
2422
- // Non-fatal by design — the semantic trajectory path below is untouched.
2423
- try {
2424
- const { getTrajectoryTree } = await import('../ruvector/trajectory-tree.js');
2425
- getTrajectoryTree().openTrajectory({ sessionId, trajectoryId, task, agent });
2426
- }
2427
- catch { /* prototype path — never blocks trajectory recording */ }
2428
- // Persist pending trajectory to disk so it survives MCP restarts
2429
- const storeFn = await getRealStoreFunction();
2430
- if (storeFn) {
2431
- try {
2432
- await storeFn({
2433
- key: `trajectory-pending-${trajectoryId}`,
2434
- value: JSON.stringify(trajectory),
2435
- namespace: 'trajectories',
2436
- tags: [agent, 'pending', 'sona-trajectory'],
2437
- });
2438
- }
2439
- catch {
2440
- // Best-effort persistence — trajectory still lives in-memory
2441
- }
2442
- }
2443
- return {
2444
- trajectoryId,
2445
- task,
2446
- agent,
2447
- started: startedAt,
2448
- status: 'recording',
2449
- implementation: 'real-trajectory-tracking',
2450
- activeCount: activeTrajectories.size,
2451
- };
2452
- },
2453
- };
2454
- export const hooksTrajectoryStep = {
2455
- name: 'hooks_intelligence_trajectory-step',
2456
- description: 'Record step in trajectory for reinforcement learning Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
2457
- inputSchema: {
2458
- type: 'object',
2459
- properties: {
2460
- trajectoryId: { type: 'string', description: 'Trajectory ID' },
2461
- action: { type: 'string', description: 'Action taken' },
2462
- result: { type: 'string', description: 'Action result' },
2463
- quality: { type: 'number', description: 'Quality score (0-1)' },
2464
- },
2465
- required: ['trajectoryId', 'action'],
2466
- },
2467
- handler: async (params) => {
2468
- const trajectoryId = params.trajectoryId;
2469
- // #14: scrub extended-thinking blocks so reasoning tokens don't contaminate
2470
- // the learning signal (DISTILL embeds this text).
2471
- const action = scrubReasoningBlocks(params.action);
2472
- const result = scrubReasoningBlocks(params.result || 'success');
2473
- const quality = params.quality || 0.85;
2474
- const timestamp = new Date().toISOString();
2475
- const stepId = `step-${Date.now()}`;
2476
- {
2477
- const v = validateIdentifier(trajectoryId, 'trajectoryId');
2478
- if (!v.valid)
2479
- return { success: false, error: v.error };
2480
- }
2481
- {
2482
- const v = validateText(action, 'action');
2483
- if (!v.valid)
2484
- return { success: false, error: v.error };
2485
- }
2486
- // Add step to real trajectory if it exists
2487
- const trajectory = activeTrajectories.get(trajectoryId);
2488
- if (trajectory) {
2489
- trajectory.steps.push({
2490
- action,
2491
- result,
2492
- quality,
2493
- timestamp,
2494
- });
2495
- }
2496
- // MAGE-style execution-state-tree mirror (prototype, non-fatal)
2497
- try {
2498
- const { getTrajectoryTree } = await import('../ruvector/trajectory-tree.js');
2499
- getTrajectoryTree().appendStep({ trajectoryId, stepId, action, quality });
2500
- }
2501
- catch { /* prototype path — never blocks step recording */ }
2502
- // ADR-130 Phase 3: fire-and-forget causal edge write
2503
- // trajectory context node → step node (relation: "trajectory-caused")
2504
- if (result) {
2505
- (async () => {
2506
- try {
2507
- const { insertGraphEdge } = await import('../memory/graph-edge-writer.js');
2508
- await insertGraphEdge({
2509
- sourceId: `task:${trajectoryId}`,
2510
- targetId: `pattern:${stepId}`,
2511
- relation: 'trajectory-caused',
2512
- weight: quality,
2513
- confidence: quality,
2514
- metadata: { action, result, trajectoryId, stepId },
2515
- });
2516
- }
2517
- catch { /* non-fatal */ }
2518
- })().catch(() => { });
2519
- }
2520
- return {
2521
- trajectoryId,
2522
- stepId,
2523
- action,
2524
- result,
2525
- quality,
2526
- recorded: !!trajectory,
2527
- timestamp,
2528
- totalSteps: trajectory?.steps.length || 0,
2529
- implementation: trajectory ? 'real-step-recording' : 'trajectory-not-found',
2530
- };
2531
- },
2532
- };
2533
- export const hooksTrajectoryEnd = {
2534
- name: 'hooks_intelligence_trajectory-end',
2535
- description: 'End trajectory and trigger SONA learning with EWC++ Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
2536
- inputSchema: {
2537
- type: 'object',
2538
- properties: {
2539
- trajectoryId: { type: 'string', description: 'Trajectory ID' },
2540
- success: { type: 'boolean', description: 'Overall success' },
2541
- feedback: { type: 'string', description: 'Optional feedback' },
2542
- },
2543
- required: ['trajectoryId'],
2544
- },
2545
- handler: async (params) => {
2546
- const trajectoryId = params.trajectoryId;
2547
- {
2548
- const v = validateIdentifier(trajectoryId, 'trajectoryId');
2549
- if (!v.valid)
2550
- return { success: false, error: v.error };
2551
- }
2552
- const success = params.success !== false;
2553
- const feedback = params.feedback;
2554
- const endedAt = new Date().toISOString();
2555
- const startTime = Date.now();
2556
- // Get and finalize real trajectory
2557
- const trajectory = activeTrajectories.get(trajectoryId);
2558
- let persistResult = { success: false };
2559
- if (trajectory) {
2560
- trajectory.success = success;
2561
- trajectory.endedAt = endedAt;
2562
- // Persist trajectory to database using real store
2563
- const storeFn = await getRealStoreFunction();
2564
- if (storeFn) {
2565
- try {
2566
- // Create trajectory summary for embedding
2567
- const summary = `Task: ${trajectory.task} | Agent: ${trajectory.agent} | Steps: ${trajectory.steps.length} | Success: ${success}${feedback ? ` | Feedback: ${feedback}` : ''}`;
2568
- persistResult = await storeFn({
2569
- key: `trajectory-${trajectoryId}`,
2570
- value: JSON.stringify({
2571
- ...trajectory,
2572
- feedback,
2573
- }),
2574
- namespace: 'trajectories',
2575
- generateEmbeddingFlag: true, // Generate embedding for semantic search
2576
- tags: [trajectory.agent, success ? 'success' : 'failure', 'sona-trajectory'],
2577
- });
2578
- }
2579
- catch (error) {
2580
- persistResult = { success: false, error: error instanceof Error ? error.message : String(error) };
2581
- }
2582
- }
2583
- // Remove from active trajectories
2584
- activeTrajectories.delete(trajectoryId);
2585
- }
2586
- // MAGE-style execution-state-tree mirror (prototype, non-fatal)
2587
- try {
2588
- const { getTrajectoryTree } = await import('../ruvector/trajectory-tree.js');
2589
- getTrajectoryTree().closeTrajectory({ trajectoryId, success });
2590
- }
2591
- catch { /* prototype path — never blocks trajectory finalization */ }
2592
- // SONA Learning - process trajectory outcome for routing optimization
2593
- let sonaResult = {
2594
- learned: false, patternKey: '', confidence: 0
2595
- };
2596
- let ewcResult = {
2597
- consolidated: false, penalty: 0
2598
- };
2599
- if (trajectory && persistResult.success) {
2600
- // Try SONA learning
2601
- const sona = await getSONAOptimizer();
2602
- if (sona) {
2603
- try {
2604
- const outcome = {
2605
- trajectoryId,
2606
- task: trajectory.task,
2607
- agent: trajectory.agent,
2608
- success,
2609
- steps: trajectory.steps,
2610
- feedback,
2611
- duration: trajectory.startedAt
2612
- ? new Date(endedAt).getTime() - new Date(trajectory.startedAt).getTime()
2613
- : 0,
2614
- };
2615
- const result = sona.processTrajectoryOutcome(outcome);
2616
- sonaResult = {
2617
- learned: result.learned,
2618
- patternKey: result.patternKey,
2619
- confidence: result.confidence,
2620
- };
2621
- }
2622
- catch {
2623
- // SONA learning failed, continue without it
2624
- }
2625
- }
2626
- // Trigger ruvllm background learning after trajectory end
2627
- try {
2628
- const { runBackgroundLearning } = await import('../memory/intelligence.js');
2629
- await runBackgroundLearning();
2630
- }
2631
- catch { /* best-effort */ }
2632
- // Try EWC++ consolidation on successful trajectories
2633
- if (success) {
2634
- const ewc = await getEWCConsolidator();
2635
- if (ewc) {
2636
- try {
2637
- // AUDIT FIX #4: derive a REAL gradient from the trajectory's
2638
- // embedding (mirrors the DISTILL path, where step content is
2639
- // embedded via generateEmbedding) instead of a synthetic sine
2640
- // wave. The EWC library treats the embedding as the gradient
2641
- // proxy (see recordPatternOutcome in ewc-consolidation.ts).
2642
- let gradients = null;
2643
- try {
2644
- const { generateEmbedding } = await import('../memory/memory-initializer.js');
2645
- // Embed the same summary that was persisted for semantic search,
2646
- // so the Fisher update reflects the actual recorded trajectory.
2647
- const summary = `Task: ${trajectory.task} | Agent: ${trajectory.agent} | Steps: ${trajectory.steps.map(s => `${s.action}=>${s.result}`).join('; ')}${feedback ? ` | Feedback: ${feedback}` : ''}`;
2648
- const embeddingResult = await generateEmbedding(summary);
2649
- if (embeddingResult?.embedding && embeddingResult.embedding.length > 0) {
2650
- gradients = embeddingResult.embedding;
2651
- }
2652
- }
2653
- catch {
2654
- // Embedding generation unavailable — fall through and skip EWC
2655
- }
2656
- if (gradients) {
2657
- ewc.recordGradient(`trajectory-${trajectoryId}`, gradients, success);
2658
- const stats = ewc.getConsolidationStats();
2659
- ewcResult = {
2660
- consolidated: true,
2661
- penalty: stats.avgPenalty,
2662
- };
2663
- }
2664
- // If no real embedding-derived gradient is available, SKIP the EWC
2665
- // update rather than feeding the Fisher matrix synthetic noise.
2666
- }
2667
- catch {
2668
- // EWC consolidation failed, continue without it
2669
- }
2670
- }
2671
- }
2672
- }
2673
- // #2245 Round B — also bump globalStats so the trajectory-end MCP path
2674
- // shows up in `hooks_intelligence_unified-stats.global.*` (was only
2675
- // touching sonaCoordinator before — the "MCP trajectory tools feed sona,
2676
- // not globalStats" gap from ADR-075). Maps the recorded steps to the
2677
- // intelligence-module TrajectoryStep shape and runs them through the
2678
- // canonical recordTrajectory() entry point.
2679
- let globalStatsDelta = 0;
2680
- if (trajectory && trajectory.steps && trajectory.steps.length > 0) {
2681
- try {
2682
- const intel = await import('../memory/intelligence.js');
2683
- const before = intel.getIntelligenceStats();
2684
- await intel.recordTrajectory(trajectory.steps.map((s) => ({
2685
- type: s.type ?? 'action',
2686
- content: String(s.content ?? `${s.action ?? ''} → ${s.result ?? ''}`).slice(0, 4096),
2687
- timestamp: Date.now(),
2688
- })), success ? 'success' : 'failure');
2689
- const after = intel.getIntelligenceStats();
2690
- globalStatsDelta = after.trajectoriesRecorded - before.trajectoriesRecorded;
2691
- }
2692
- catch { /* intelligence module not loadable — keep sona-only behaviour */ }
2693
- }
2694
- // #2351: when an agent calls trajectory-end with no recorded steps but a
2695
- // non-empty `feedback` string, the feedback was previously dropped on the
2696
- // floor — `patternsExtracted` reported 0 and `pattern-search` never
2697
- // surfaced it. Step-less trajectories are the common case for LLM agents
2698
- // (nothing forces step logging mid-task), and feedback is often the most
2699
- // distilled lesson available. Route it through the same store + embed
2700
- // path that pattern-store uses so it becomes searchable. Best-effort:
2701
- // failures here must not turn the trajectory-end call itself into a
2702
- // failure — the trajectory record was already persisted above.
2703
- let feedbackDistilled = { stored: false };
2704
- const hasSteps = !!trajectory && trajectory.steps.length > 0;
2705
- const trimmedFeedback = typeof feedback === 'string' ? feedback.trim() : '';
2706
- if (trajectory && !hasSteps && trimmedFeedback.length > 0) {
2707
- const distilledPatternId = `pattern-feedback-${trajectoryId}-${Date.now()}`;
2708
- const patternMetadata = {
2709
- sourceTrajectoryId: trajectoryId,
2710
- task: trajectory.task,
2711
- agent: trajectory.agent,
2712
- outcome: success ? 'success' : 'failure',
2713
- distilledFrom: 'trajectory-end-feedback',
2714
- };
2715
- // Modest default confidence — step-less feedback hasn't been validated
2716
- // by execution evidence the way a multi-step trajectory has.
2717
- const feedbackConfidence = success ? 0.6 : 0.4;
2718
- try {
2719
- const bridge = await import('../memory/memory-bridge.js');
2720
- const rb = await bridge.bridgeStorePattern({
2721
- pattern: trimmedFeedback,
2722
- type: 'trajectory-feedback',
2723
- confidence: feedbackConfidence,
2724
- metadata: patternMetadata,
2725
- });
2726
- if (rb?.success) {
2727
- feedbackDistilled = { stored: true, patternId: rb.patternId, controller: rb.controller };
2728
- }
2729
- }
2730
- catch {
2731
- // Bridge unavailable — fall through to direct store
2732
- }
2733
- if (!feedbackDistilled.stored) {
2734
- try {
2735
- const storeFn = await getRealStoreFunction();
2736
- if (storeFn) {
2737
- const r = await storeFn({
2738
- key: distilledPatternId,
2739
- value: JSON.stringify({
2740
- pattern: trimmedFeedback,
2741
- type: 'trajectory-feedback',
2742
- confidence: feedbackConfidence,
2743
- metadata: patternMetadata,
2744
- timestamp: endedAt,
2745
- }),
2746
- namespace: 'pattern',
2747
- generateEmbeddingFlag: true,
2748
- tags: [
2749
- 'trajectory-feedback',
2750
- success ? 'success' : 'failure',
2751
- `confidence-${Math.round(feedbackConfidence * 100)}`,
2752
- ],
2753
- });
2754
- if (r?.success) {
2755
- feedbackDistilled = { stored: true, patternId: r.id || distilledPatternId, controller: 'store-fallback' };
2756
- }
2757
- }
2758
- }
2759
- catch {
2760
- // Both paths failed — leave feedbackDistilled.stored = false.
2761
- }
2762
- }
2763
- }
2764
- const learningTimeMs = Date.now() - startTime;
2765
- // patternsExtracted now reflects either recorded steps (the original
2766
- // semantics) OR a distilled feedback pattern (#2351), so step-less
2767
- // trajectories with useful feedback no longer report 0.
2768
- const patternsExtracted = (trajectory?.steps.length || 0) + (feedbackDistilled.stored ? 1 : 0);
2769
- return {
2770
- trajectoryId,
2771
- success,
2772
- ended: endedAt,
2773
- persisted: persistResult.success,
2774
- persistedId: persistResult.id,
2775
- learning: {
2776
- sonaUpdate: sonaResult.learned,
2777
- sonaPatternKey: sonaResult.patternKey || undefined,
2778
- sonaConfidence: sonaResult.confidence || undefined,
2779
- ewcConsolidation: ewcResult.consolidated,
2780
- ewcPenalty: ewcResult.penalty || undefined,
2781
- patternsExtracted,
2782
- feedbackDistilled: feedbackDistilled.stored ? {
2783
- patternId: feedbackDistilled.patternId,
2784
- controller: feedbackDistilled.controller,
2785
- } : undefined,
2786
- learningTimeMs,
2787
- globalStatsTrajectoriesDelta: globalStatsDelta, // Round B: was 0, now reflects
2788
- },
2789
- trajectory: trajectory ? {
2790
- task: trajectory.task,
2791
- agent: trajectory.agent,
2792
- totalSteps: trajectory.steps.length,
2793
- duration: trajectory.startedAt ? new Date(endedAt).getTime() - new Date(trajectory.startedAt).getTime() : 0,
2794
- } : null,
2795
- implementation: sonaResult.learned ? 'real-sona-learning' : (persistResult.success ? 'real-persistence' : 'memory-only'),
2796
- note: sonaResult.learned
2797
- ? `SONA learned pattern "${sonaResult.patternKey}" with ${(sonaResult.confidence * 100).toFixed(1)}% confidence`
2798
- : (persistResult.success ? 'Trajectory persisted for future learning' : (persistResult.error || 'Trajectory not found')),
2799
- };
2800
- },
2801
- };
2802
- // Pattern store/search hooks - REAL implementation using storeEntry
2803
- export const hooksPatternStore = {
2804
- name: 'hooks_intelligence_pattern-store',
2805
- description: 'Store pattern in ReasoningBank (HNSW-indexed) Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
2806
- inputSchema: {
2807
- type: 'object',
2808
- properties: {
2809
- pattern: { type: 'string', description: 'Pattern description' },
2810
- type: { type: 'string', description: 'Pattern type' },
2811
- confidence: { type: 'number', description: 'Confidence score' },
2812
- metadata: { type: 'object', description: 'Additional metadata' },
2813
- },
2814
- required: ['pattern'],
2815
- },
2816
- handler: async (params) => {
2817
- const pattern = params.pattern;
2818
- const type = params.type || 'general';
2819
- const confidence = params.confidence || 0.8;
2820
- const metadata = params.metadata;
2821
- const timestamp = new Date().toISOString();
2822
- {
2823
- const v = validateText(pattern, 'pattern');
2824
- if (!v.valid)
2825
- return { success: false, error: v.error };
2826
- }
2827
- if (params.type) {
2828
- const v = validateIdentifier(params.type, 'type');
2829
- if (!v.valid)
2830
- return { success: false, error: v.error };
2831
- }
2832
- const patternId = `pattern-${Date.now()}-${Math.random().toString(36).substring(7)}`;
2833
- // Phase 3: Try ReasoningBank via bridge first
2834
- let reasoningResult = null;
2835
- try {
2836
- const bridge = await import('../memory/memory-bridge.js');
2837
- reasoningResult = await bridge.bridgeStorePattern({ pattern, type, confidence, metadata: metadata });
2838
- }
2839
- catch {
2840
- // Bridge not available
2841
- }
2842
- // Fallback: persist using memory-initializer store
2843
- let storeResult = { success: false };
2844
- if (!reasoningResult) {
2845
- const storeFn = await getRealStoreFunction();
2846
- if (storeFn) {
2847
- try {
2848
- storeResult = await storeFn({
2849
- key: patternId,
2850
- value: JSON.stringify({ pattern, type, confidence, metadata, timestamp }),
2851
- namespace: 'pattern',
2852
- generateEmbeddingFlag: true,
2853
- tags: [type, `confidence-${Math.round(confidence * 100)}`, 'reasoning-pattern'],
2854
- });
2855
- }
2856
- catch (error) {
2857
- storeResult = { success: false, error: error instanceof Error ? error.message : String(error) };
2858
- }
2859
- }
2860
- }
2861
- const success = reasoningResult?.success || storeResult.success;
2862
- const controller = reasoningResult?.controller || (storeResult.success ? 'bridge-store' : 'none');
2863
- const hasEmbedding = !!storeResult.embedding || controller === 'reasoningBank' || controller === 'bridge-fallback';
2864
- return {
2865
- patternId: reasoningResult?.patternId || storeResult.id || patternId,
2866
- pattern,
2867
- type,
2868
- confidence,
2869
- indexed: success,
2870
- hnswIndexed: success && hasEmbedding,
2871
- embedding: storeResult.embedding,
2872
- timestamp,
2873
- controller,
2874
- implementation: (controller === 'reasoningBank' || controller === 'bridge-fallback')
2875
- ? 'reasoning-bank-controller'
2876
- : (storeResult.success ? 'real-hnsw-indexed' : 'memory-only'),
2877
- note: controller === 'reasoningBank'
2878
- ? 'Pattern stored via ReasoningBank controller with HNSW indexing'
2879
- : controller === 'bridge-fallback'
2880
- ? 'Pattern stored via bridge with embedding and HNSW indexing'
2881
- : (storeResult.success ? 'Pattern stored with vector embedding for semantic search' : (storeResult.error || 'Store function unavailable')),
2882
- };
2883
- },
2884
- };
2885
- export const hooksPatternSearch = {
2886
- name: 'hooks_intelligence_pattern-search',
2887
- description: 'Search patterns using REAL vector search (HNSW when available, brute-force fallback) Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
2888
- inputSchema: {
2889
- type: 'object',
2890
- properties: {
2891
- query: { type: 'string', description: 'Search query' },
2892
- topK: { type: 'number', description: 'Number of results' },
2893
- minConfidence: { type: 'number', description: 'Minimum similarity threshold (0-1)' },
2894
- namespace: { type: 'string', description: 'Namespace to search (default: pattern)' },
2895
- strategy: { type: 'string', enum: ['semantic', 'state-tree'], description: 'Retrieval strategy. Default "semantic" (unchanged behavior). "state-tree" returns the MAGE-style root→current execution-state path for a session instead of embedding search (prototype).' },
2896
- sessionId: { type: 'string', description: 'Session id for strategy="state-tree" (default: CLAUDE_FLOW_SESSION_ID or "default")' },
2897
- depth: { type: 'number', description: 'For strategy="state-tree": max path nodes returned, counted from the current node upward' },
2898
- },
2899
- required: ['query'],
2900
- },
2901
- handler: async (params) => {
2902
- const query = params.query;
2903
- const topK = params.topK || 5;
2904
- const minConfidence = params.minConfidence || 0.3;
2905
- const namespace = params.namespace || 'pattern';
2906
- const strategy = params.strategy || 'semantic';
2907
- {
2908
- const v = validateText(query, 'query');
2909
- if (!v.valid)
2910
- return { success: false, error: v.error };
2911
- }
2912
- if (params.namespace) {
2913
- const v = validateIdentifier(params.namespace, 'namespace');
2914
- if (!v.valid)
2915
- return { success: false, error: v.error };
2916
- }
2917
- // Opt-in MAGE-style positional retrieval (prototype). Default stays the
2918
- // semantic vector path below — zero behavior change unless requested.
2919
- if (strategy === 'state-tree') {
2920
- const sessionId = params.sessionId || process.env.CLAUDE_FLOW_SESSION_ID || 'default';
2921
- if (params.sessionId) {
2922
- const v = validateIdentifier(params.sessionId, 'sessionId');
2923
- if (!v.valid)
2924
- return { success: false, error: v.error };
2925
- }
2926
- try {
2927
- const { getTrajectoryTree } = await import('../ruvector/trajectory-tree.js');
2928
- const recall = getTrajectoryTree().recallPath({
2929
- sessionId,
2930
- depth: typeof params.depth === 'number' ? params.depth : undefined,
2931
- siblingWindow: topK,
2932
- });
2933
- return {
2934
- query,
2935
- strategy: 'state-tree',
2936
- backend: 'state-tree',
2937
- sessionId: recall.sessionId,
2938
- currentId: recall.currentId,
2939
- path: recall.path,
2940
- siblings: recall.siblings,
2941
- note: 'Positional root→current execution-state path (no embedding search). Prototype — see ruvector/trajectory-tree.ts limitations.',
2942
- };
2943
- }
2944
- catch (error) {
2945
- return {
2946
- query,
2947
- strategy: 'state-tree',
2948
- backend: 'state-tree-unavailable',
2949
- path: [],
2950
- siblings: [],
2951
- error: String(error),
2952
- };
2953
- }
2954
- }
2955
- // Phase 3: Try ReasoningBank search via bridge first
2956
- try {
2957
- const bridge = await import('../memory/memory-bridge.js');
2958
- const rbResult = await bridge.bridgeSearchPatterns({ query, topK, minConfidence });
2959
- if (rbResult && rbResult.results.length > 0) {
2960
- return {
2961
- query,
2962
- results: rbResult.results.map(r => ({
2963
- patternId: r.id,
2964
- pattern: r.content,
2965
- similarity: r.score,
2966
- confidence: r.score,
2967
- namespace,
2968
- })),
2969
- searchTimeMs: 0,
2970
- backend: rbResult.controller,
2971
- note: `Results from ${rbResult.controller} controller`,
2972
- };
2973
- }
2974
- }
2975
- catch {
2976
- // Bridge not available — fall through
2977
- }
2978
- // Fallback: Try real vector search via memory-initializer
2979
- const searchFn = await getRealSearchFunction();
2980
- if (searchFn) {
2981
- try {
2982
- const searchResult = await searchFn({
2983
- query,
2984
- namespace,
2985
- limit: topK,
2986
- threshold: minConfidence,
2987
- });
2988
- if (searchResult.success && searchResult.results.length > 0) {
2989
- return {
2990
- query,
2991
- results: searchResult.results.map(r => ({
2992
- patternId: r.id,
2993
- pattern: r.content,
2994
- similarity: r.score,
2995
- confidence: r.score,
2996
- namespace: r.namespace,
2997
- key: r.key,
2998
- })),
2999
- searchTimeMs: searchResult.searchTime,
3000
- backend: 'real-vector-search',
3001
- note: 'Results from HNSW/SQLite vector search (BM25 hybrid)',
3002
- };
3003
- }
3004
- // No results found
3005
- return {
3006
- query,
3007
- results: [],
3008
- searchTimeMs: searchResult.searchTime,
3009
- backend: 'real-vector-search',
3010
- note: searchResult.error || 'No matching patterns found. Store patterns first using memory/store with namespace "pattern".',
3011
- };
3012
- }
3013
- catch (error) {
3014
- // Fall through to empty response with error
3015
- return {
3016
- query,
3017
- results: [],
3018
- searchTimeMs: 0,
3019
- backend: 'error',
3020
- error: String(error),
3021
- note: 'Vector search failed. Ensure memory database is initialized.',
3022
- };
3023
- }
3024
- }
3025
- // No search function available
3026
- return {
3027
- query,
3028
- results: [],
3029
- searchTimeMs: 0,
3030
- backend: 'unavailable',
3031
- note: 'Real vector search not available. Initialize memory database with: claude-flow memory init',
3032
- };
3033
- },
3034
- };
3035
- // Intelligence stats hook
3036
- export const hooksIntelligenceStats = {
3037
- name: 'hooks_intelligence_stats',
3038
- description: 'Get RuVector intelligence layer statistics Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
3039
- inputSchema: {
3040
- type: 'object',
3041
- properties: {
3042
- detailed: { type: 'boolean', description: 'Include detailed stats' },
3043
- },
3044
- },
3045
- handler: async (params) => {
3046
- const detailed = params.detailed;
3047
- // Get REAL statistics from actual implementations
3048
- const sona = await getSONAOptimizer();
3049
- const ewc = await getEWCConsolidator();
3050
- const moe = await getMoERouter();
3051
- const flash = await getFlashAttention();
3052
- const lora = await getLoRAAdapter();
3053
- // Fallback to memory store for legacy data (may not exist yet)
3054
- let memoryStats;
3055
- try {
3056
- memoryStats = getIntelligenceStatsFromMemory();
3057
- }
3058
- catch {
3059
- memoryStats = {
3060
- trajectories: { total: 0, successful: 0 },
3061
- patterns: { learned: 0, categories: {} },
3062
- memory: { indexSize: 0, totalAccessCount: 0, memorySizeBytes: 0 },
3063
- routing: { decisions: 0, avgConfidence: 0 },
3064
- };
3065
- }
3066
- // SONA stats from real implementation
3067
- let sonaStats = {
3068
- trajectoriesTotal: memoryStats.trajectories.total,
3069
- trajectoriesSuccessful: memoryStats.trajectories.successful,
3070
- avgLearningTimeMs: 0,
3071
- patternsLearned: memoryStats.patterns.learned,
3072
- patternCategories: memoryStats.patterns.categories,
3073
- successRate: 0,
3074
- implementation: 'memory-fallback',
3075
- };
3076
- if (sona) {
3077
- const realSona = sona.getStats();
3078
- const totalRoutes = realSona.successfulRoutings + realSona.failedRoutings;
3079
- sonaStats = {
3080
- trajectoriesTotal: realSona.trajectoriesProcessed,
3081
- trajectoriesSuccessful: realSona.successfulRoutings,
3082
- avgLearningTimeMs: realSona.lastUpdate ? 0.042 : 0, // Theoretical when active
3083
- patternsLearned: realSona.totalPatterns,
3084
- patternCategories: { learned: realSona.totalPatterns }, // Simplified
3085
- successRate: totalRoutes > 0
3086
- ? Math.round((realSona.successfulRoutings / totalRoutes) * 100) / 100
3087
- : 0,
3088
- implementation: 'real-sona',
3089
- };
3090
- }
3091
- // EWC++ stats from real implementation
3092
- let ewcStats = {
3093
- consolidations: 0,
3094
- catastrophicForgettingPrevented: 0,
3095
- fisherUpdates: 0,
3096
- avgPenalty: 0,
3097
- totalPatterns: 0,
3098
- implementation: 'not-loaded',
3099
- };
3100
- if (ewc) {
3101
- const realEwc = ewc.getConsolidationStats();
3102
- ewcStats = {
3103
- consolidations: realEwc.consolidationCount,
3104
- catastrophicForgettingPrevented: realEwc.highImportancePatterns,
3105
- fisherUpdates: realEwc.consolidationCount,
3106
- avgPenalty: Math.round(realEwc.avgPenalty * 1000) / 1000,
3107
- totalPatterns: realEwc.totalPatterns,
3108
- implementation: 'real-ewc++',
3109
- };
3110
- }
3111
- // MoE stats from real implementation
3112
- let moeStats = {
3113
- expertsTotal: 8,
3114
- expertsActive: 0,
3115
- routingDecisions: memoryStats.routing.decisions,
3116
- avgRoutingTimeMs: 0,
3117
- avgConfidence: memoryStats.routing.avgConfidence,
3118
- loadBalance: null,
3119
- implementation: 'not-loaded',
3120
- };
3121
- if (moe) {
3122
- const loadBalance = moe.getLoadBalance();
3123
- const activeExperts = Object.values(loadBalance.routingCounts).filter((u) => u > 0).length;
3124
- // Calculate average utilization as proxy for confidence
3125
- const utilValues = Object.values(loadBalance.utilization);
3126
- const avgUtil = utilValues.length > 0 ? utilValues.reduce((a, b) => a + b, 0) / utilValues.length : 0;
3127
- moeStats = {
3128
- expertsTotal: 8,
3129
- expertsActive: activeExperts,
3130
- routingDecisions: loadBalance.totalRoutings,
3131
- avgRoutingTimeMs: 0.15, // Theoretical performance
3132
- avgConfidence: Math.round(avgUtil * 100) / 100,
3133
- loadBalance: {
3134
- giniCoefficient: Math.round(loadBalance.giniCoefficient * 1000) / 1000,
3135
- coefficientOfVariation: Math.round(loadBalance.coefficientOfVariation * 1000) / 1000,
3136
- expertUsage: loadBalance.routingCounts,
3137
- },
3138
- implementation: 'real-moe',
3139
- };
3140
- }
3141
- // Flash Attention stats from real implementation
3142
- let flashStats = {
3143
- speedup: 1.0,
3144
- avgComputeTimeMs: 0,
3145
- blockSize: 64,
3146
- implementation: 'not-loaded',
3147
- };
3148
- if (flash) {
3149
- flashStats = {
3150
- speedup: Math.round(flash.getSpeedup() * 100) / 100,
3151
- avgComputeTimeMs: 0, // Would need benchmarking
3152
- blockSize: 64,
3153
- implementation: 'real-flash-attention',
3154
- };
3155
- }
3156
- // LoRA stats from real implementation
3157
- let loraStats = {
3158
- rank: 8,
3159
- alpha: 16,
3160
- adaptations: 0,
3161
- avgLoss: 0,
3162
- implementation: 'not-loaded',
3163
- };
3164
- if (lora) {
3165
- const realLora = lora.getStats();
3166
- loraStats = {
3167
- rank: realLora.rank,
3168
- alpha: 16, // Default alpha from config
3169
- adaptations: realLora.totalAdaptations,
3170
- avgLoss: Math.round(realLora.avgAdaptationNorm * 10000) / 10000,
3171
- implementation: 'real-lora',
3172
- };
3173
- }
3174
- // ruvllm native backend stats
3175
- let ruvllmStats = { coordinator: 'unavailable', trajectories: 0, contrastiveTrainer: 'unavailable', trainingBackend: 'unavailable', graphDatabase: { backend: 'unavailable', totalNodes: 0, totalEdges: 0 } };
3176
- try {
3177
- const { getIntelligenceStats } = await import('../memory/intelligence.js');
3178
- const iStats = getIntelligenceStats();
3179
- ruvllmStats.coordinator = iStats._ruvllmBackend || 'unavailable';
3180
- ruvllmStats.trajectories = iStats._ruvllmTrajectories || 0;
3181
- }
3182
- catch { /* not initialized */ }
3183
- try {
3184
- const { getSONAStats: getSONA } = await import('../memory/sona-optimizer.js');
3185
- const sStats = await getSONA();
3186
- ruvllmStats.contrastiveTrainer = sStats._contrastiveTrainer || 'unavailable';
3187
- }
3188
- catch { /* not initialized */ }
3189
- if (lora) {
3190
- const ls = lora.getStats();
3191
- ruvllmStats.trainingBackend = ls._trainingBackend || 'unavailable';
3192
- }
3193
- try {
3194
- const { getGraphStats } = await import('../ruvector/graph-backend.js');
3195
- const gs = await getGraphStats();
3196
- ruvllmStats.graphDatabase = { backend: gs.backend, totalNodes: gs.totalNodes, totalEdges: gs.totalEdges, avgDegree: gs.avgDegree };
3197
- }
3198
- catch { /* not available */ }
3199
- // ADR-148 — model-router operational counters (per-mechanism, per-backend,
3200
- // A/B disagreement rate). Process-local so this is the most accurate
3201
- // surface; the memory-store path was aggregates-only and lossy.
3202
- let routerStats = null;
3203
- let neuralRouter = null;
3204
- try {
3205
- const { getModelRouterStats } = await import('../ruvector/model-router.js');
3206
- routerStats = getModelRouterStats();
3207
- }
3208
- catch { /* router module not loaded */ }
3209
- try {
3210
- const { neuralRouterStatus } = await import('../ruvector/neural-router.js');
3211
- const s = await neuralRouterStatus();
3212
- neuralRouter = { enabled: s.enabled, available: s.available, routedBy: s.routedBy, reason: s.reason };
3213
- }
3214
- catch { /* neural-router module not loaded */ }
3215
- // ADR-149 iter 42 — surface cost-savings to MCP consumers. Iter 31-34
3216
- // shipped the CLI. This computes the headline numbers (last 7d actual
3217
- // vs heuristic counterfactual) from the trajectory JSONL so Claude Code
3218
- // sessions can ask "is the router saving money?" without shelling out
3219
- // to bash. Best-effort: returns null when trajectory missing/empty.
3220
- let costSavings = null;
3221
- try {
3222
- const fs = await import('node:fs');
3223
- const pathMod = await import('node:path');
3224
- const trajectoryPath = process.env.CLAUDE_FLOW_ROUTER_TRAJECTORY_PATH
3225
- ?? pathMod.resolve(process.cwd(), '.swarm', 'model-router-trajectories.jsonl');
3226
- if (fs.existsSync(trajectoryPath)) {
3227
- const { MODEL_PRICES } = await import('../ruvector/model-prices.js');
3228
- const windowMs = 7 * 86_400_000; // 7-day window — matches iter 41 default
3229
- const cutoffMs = Date.now() - windowMs;
3230
- // iter 63 — port iter 62's fix from CLI to MCP. Outcomes track ALL
3231
- // occurrences (Array) instead of deduping by task_hash, so repeat
3232
- // tasks contribute their full cumulative cost.
3233
- const decisions = new Map();
3234
- const outcomes = [];
3235
- for (const l of fs.readFileSync(trajectoryPath, 'utf8').split('\n')) {
3236
- if (!l.trim())
3237
- continue;
3238
- try {
3239
- const r = JSON.parse(l);
3240
- if (Date.parse(r.ts) < cutoffMs)
3241
- continue;
3242
- if (r.type === 'decision')
3243
- decisions.set(r.task_hash, r);
3244
- else if (r.type === 'outcome')
3245
- outcomes.push(r);
3246
- }
3247
- catch { /* malformed */ }
3248
- }
3249
- let pairs = 0, actual = 0, cf = 0;
3250
- for (const out of outcomes) {
3251
- if (!out?.cost_usd || !out.tokens)
3252
- continue;
3253
- const dec = decisions.get(out.task_hash);
3254
- if (!dec)
3255
- continue;
3256
- pairs++;
3257
- actual += out.cost_usd;
3258
- // Same heuristic counterfactual as iter 32 default.
3259
- const tierModel = dec.complexity < 0.34 ? 'haiku'
3260
- : dec.complexity < 0.67 ? 'sonnet' : 'opus';
3261
- const cfModel = dec.ab_pair?.bandit_pick ?? tierModel;
3262
- const p = MODEL_PRICES[cfModel] ?? { in: 1, out: 1 };
3263
- cf += (out.tokens.input * p.in + out.tokens.output * p.out) / 1_000_000;
3264
- }
3265
- if (pairs > 0) {
3266
- const savings = cf - actual;
3267
- costSavings = {
3268
- windowDays: 7,
3269
- pairs,
3270
- actualUsd: Math.round(actual * 1_000_000) / 1_000_000,
3271
- counterfactualUsd: Math.round(cf * 1_000_000) / 1_000_000,
3272
- savingsUsd: Math.round(savings * 1_000_000) / 1_000_000,
3273
- savingsPct: cf > 0 ? Math.round((savings / cf) * 10000) / 100 : 0,
3274
- };
3275
- }
3276
- }
3277
- }
3278
- catch { /* trajectory parse failed — leave costSavings null */ }
3279
- // ADR-149 iter 56 — recent activity + warmest bandit cell. Mirrors what
3280
- // iter 49's CLI `stats-summary` shows so MCP consumers don't have to
3281
- // glue together multiple tool calls. Single inline pass over the JSONL
3282
- // (24h window only) + read of model-router-state.json.
3283
- let recent24h = null;
3284
- let warmestBanditCell = null;
3285
- try {
3286
- const fs = await import('node:fs');
3287
- const pathMod = await import('node:path');
3288
- const trajectoryPath = process.env.CLAUDE_FLOW_ROUTER_TRAJECTORY_PATH
3289
- ?? pathMod.resolve(process.cwd(), '.swarm', 'model-router-trajectories.jsonl');
3290
- if (fs.existsSync(trajectoryPath)) {
3291
- const cutoffMs = Date.now() - 24 * 3600_000;
3292
- let dec = 0, fallback = 0;
3293
- for (const l of fs.readFileSync(trajectoryPath, 'utf8').split('\n')) {
3294
- if (!l.trim())
3295
- continue;
3296
- try {
3297
- const r = JSON.parse(l);
3298
- if (r.type !== 'decision')
3299
- continue;
3300
- if (Date.parse(r.ts) < cutoffMs)
3301
- continue;
3302
- dec++;
3303
- if (r.routed_by === 'bandit-fallback')
3304
- fallback++;
3305
- }
3306
- catch { /* */ }
3307
- }
3308
- if (dec > 0) {
3309
- recent24h = {
3310
- decisions: dec,
3311
- fallbacks: fallback,
3312
- fallbackRatePct: Math.round((fallback / dec) * 10000) / 100,
3313
- };
3314
- }
3315
- }
3316
- // Warmest bandit cell from persisted state.
3317
- const statePath = pathMod.resolve(process.cwd(), '.swarm', 'model-router-state.json');
3318
- if (fs.existsSync(statePath)) {
3319
- const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
3320
- const priors = state.priorsById ?? state.priors ?? {};
3321
- let bestSamples = 0;
3322
- for (const bucket of ['low', 'med', 'high']) {
3323
- const b = priors[bucket];
3324
- if (!b)
3325
- continue;
3326
- for (const [k, p] of Object.entries(b)) {
3327
- const samples = p.alpha + p.beta - 2;
3328
- if (samples > bestSamples) {
3329
- bestSamples = samples;
3330
- warmestBanditCell = { bucket, key: k, samples, meanQuality: p.alpha / (p.alpha + p.beta) };
3331
- }
3332
- }
3333
- }
3334
- }
3335
- }
3336
- catch { /* best-effort */ }
3337
- // ADR-149 iter 51 — surface forward projection to MCP, mirroring iter 41
3338
- // (CLI cost-projection) but as an additive field. Linear extrapolation
3339
- // from the same 7d measurement window the costSavings block used. JSON
3340
- // shape lets Claude Code sessions answer "what will routing cost over
3341
- // the next 30 days?" in-conversation.
3342
- let costProjection = null;
3343
- if (costSavings && costSavings.pairs > 0) {
3344
- const windowSeconds = 7 * 86400;
3345
- const callsPerSecond = costSavings.pairs / windowSeconds;
3346
- const callsPerDay = callsPerSecond * 86400;
3347
- const avgActualPerCall = costSavings.actualUsd / costSavings.pairs;
3348
- const avgCfPerCall = costSavings.counterfactualUsd / costSavings.pairs;
3349
- const horizonDays = { '30d': 30, '90d': 90, '365d': 365 };
3350
- const horizons = {};
3351
- for (const [label, days] of Object.entries(horizonDays)) {
3352
- const projectedCalls = Math.round(callsPerDay * days);
3353
- const projActual = avgActualPerCall * projectedCalls;
3354
- const projCf = avgCfPerCall * projectedCalls;
3355
- const projSavings = projCf - projActual;
3356
- horizons[label] = {
3357
- projectedCalls,
3358
- projectedActualUsd: Math.round(projActual * 1_000_000) / 1_000_000,
3359
- projectedCounterfactualUsd: Math.round(projCf * 1_000_000) / 1_000_000,
3360
- projectedSavingsUsd: Math.round(projSavings * 1_000_000) / 1_000_000,
3361
- projectedSavingsPct: projCf > 0 ? Math.round((projSavings / projCf) * 10000) / 100 : 0,
3362
- };
3363
- }
3364
- costProjection = {
3365
- windowDays: 7,
3366
- callsPerDay: Math.round(callsPerDay * 100) / 100,
3367
- avgActualPerCall: Math.round(avgActualPerCall * 1_000_000) / 1_000_000,
3368
- avgCounterfactualPerCall: Math.round(avgCfPerCall * 1_000_000) / 1_000_000,
3369
- horizons,
3370
- };
3371
- }
3372
- const stats = {
3373
- sona: sonaStats,
3374
- moe: moeStats,
3375
- ewc: ewcStats,
3376
- flash: flashStats,
3377
- lora: loraStats,
3378
- ruvllm: ruvllmStats,
3379
- hnsw: {
3380
- indexSize: memoryStats.memory.indexSize,
3381
- avgSearchTimeMs: 0.12,
3382
- cacheHitRate: memoryStats.memory.totalAccessCount > 0
3383
- ? Math.min(0.95, 0.5 + (memoryStats.memory.totalAccessCount / 1000))
3384
- : 0.78,
3385
- memoryUsageMb: Math.round(memoryStats.memory.memorySizeBytes / 1024 / 1024 * 100) / 100,
3386
- },
3387
- // ADR-148 — model-routing surface
3388
- modelRouter: routerStats ? {
3389
- totalDecisions: routerStats.totalDecisions,
3390
- modelDistribution: routerStats.modelDistribution,
3391
- routedByCounts: routerStats.routedByCounts,
3392
- neuralBackendCounts: routerStats.neuralBackendCounts,
3393
- ab: routerStats.ab,
3394
- avgComplexity: routerStats.avgComplexity,
3395
- avgConfidence: routerStats.avgConfidence,
3396
- } : null,
3397
- neuralRouter,
3398
- // ADR-149 iter 42 — cost-savings surface for MCP consumers (matches
3399
- // `claude-flow neural router cost-savings --since 7d` shape).
3400
- costSavings,
3401
- // ADR-149 iter 51 — forward budget projection (matches `cost-projection`
3402
- // CLI shape). Pairs with costSavings: one says how much we saved, the
3403
- // other extrapolates that savings forward to operational horizons.
3404
- costProjection,
3405
- // ADR-149 iter 56 — recent activity + warmest bandit cell to complete
3406
- // feature parity with the CLI `stats-summary` (iter 49). One MCP tool
3407
- // call now returns everything needed for an in-conversation dashboard.
3408
- recent24h,
3409
- warmestBanditCell,
3410
- dataSource: sona ? 'real-implementations' : 'memory-fallback',
3411
- lastUpdated: new Date().toISOString(),
3412
- };
3413
- if (detailed) {
3414
- return {
3415
- ...stats,
3416
- implementationStatus: {
3417
- sona: sona ? 'loaded' : 'not-loaded',
3418
- ewc: ewc ? 'loaded' : 'not-loaded',
3419
- moe: moe ? 'loaded' : 'not-loaded',
3420
- flash: flash ? 'loaded' : 'not-loaded',
3421
- lora: lora ? 'loaded' : 'not-loaded',
3422
- },
3423
- performance: {
3424
- sonaLearningMs: sonaStats.avgLearningTimeMs,
3425
- moeRoutingMs: moeStats.avgRoutingTimeMs,
3426
- flashSpeedup: flashStats.speedup,
3427
- ewcPenalty: ewcStats.avgPenalty,
3428
- },
3429
- };
3430
- }
3431
- return stats;
3432
- },
3433
- };
3434
- // Intelligence learn hook
3435
- export const hooksIntelligenceLearn = {
3436
- name: 'hooks_intelligence_learn',
3437
- description: 'Force immediate SONA learning cycle with EWC++ consolidation Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
3438
- inputSchema: {
3439
- type: 'object',
3440
- properties: {
3441
- trajectoryIds: { type: 'array', items: { type: 'string' }, description: 'Specific trajectories to learn from' },
3442
- consolidate: { type: 'boolean', description: 'Run EWC++ consolidation' },
3443
- },
3444
- },
3445
- handler: async (params) => {
3446
- const consolidate = params.consolidate !== false;
3447
- const startTime = Date.now();
3448
- // AUDIT FIX #5: actually TRIGGER a learning/consolidation cycle instead of
3449
- // only reading and echoing stats. This calls the real DISTILL path
3450
- // (LoRA-style confidence updates with EWC++ consolidation protection) and
3451
- // the background learning pass, then reports the resulting stats.
3452
- let distill = null;
3453
- let distillTriggered = false;
3454
- try {
3455
- const intelligence = await import('../memory/intelligence.js');
3456
- // DISTILL + CONSOLIDATE: real LoRA update with EWC++ protection
3457
- distill = await intelligence.distillLearning();
3458
- distillTriggered = distill !== null;
3459
- // Run background learning (ruvllm) pass as well — best-effort
3460
- try {
3461
- await intelligence.runBackgroundLearning();
3462
- }
3463
- catch { /* best-effort */ }
3464
- }
3465
- catch {
3466
- // intelligence layer unavailable — fall back to stats-only reporting
3467
- }
3468
- // Get SONA statistics (AFTER triggering the cycle so they reflect the update)
3469
- let sonaStats = {
3470
- totalPatterns: 0,
3471
- successfulRoutings: 0,
3472
- failedRoutings: 0,
3473
- trajectoriesProcessed: 0,
3474
- avgConfidence: 0,
3475
- };
3476
- const sona = await getSONAOptimizer();
3477
- if (sona) {
3478
- const stats = sona.getStats();
3479
- sonaStats = {
3480
- totalPatterns: stats.totalPatterns,
3481
- successfulRoutings: stats.successfulRoutings,
3482
- failedRoutings: stats.failedRoutings,
3483
- trajectoriesProcessed: stats.trajectoriesProcessed,
3484
- avgConfidence: stats.avgConfidence,
3485
- };
3486
- }
3487
- // Get EWC++ statistics after the consolidation cycle ran
3488
- let ewcStats = {
3489
- consolidation: false,
3490
- fisherUpdated: false,
3491
- forgettingPrevented: 0,
3492
- avgPenalty: 0,
3493
- };
3494
- if (consolidate) {
3495
- const ewc = await getEWCConsolidator();
3496
- if (ewc) {
3497
- const stats = ewc.getConsolidationStats();
3498
- ewcStats = {
3499
- consolidation: true,
3500
- fisherUpdated: stats.consolidationCount > 0,
3501
- forgettingPrevented: stats.highImportancePatterns,
3502
- avgPenalty: distill?.ewcPenalty ?? stats.avgPenalty,
3503
- };
3504
- }
3505
- }
3506
- return {
3507
- // "learned" now reflects whether a real distill cycle actually ran
3508
- learned: distillTriggered || sonaStats.totalPatterns > 0,
3509
- cycleTriggered: distillTriggered,
3510
- patternsDistilled: distill?.patternsDistilled ?? 0,
3511
- duration: Date.now() - startTime,
3512
- updates: {
3513
- trajectoriesProcessed: sonaStats.trajectoriesProcessed,
3514
- patternsLearned: sonaStats.totalPatterns,
3515
- patternsDistilled: distill?.patternsDistilled ?? 0,
3516
- successRate: sonaStats.trajectoriesProcessed > 0
3517
- ? (sonaStats.successfulRoutings / (sonaStats.successfulRoutings + sonaStats.failedRoutings) * 100).toFixed(1) + '%'
3518
- : '0%',
3519
- },
3520
- ewc: consolidate ? ewcStats : null,
3521
- confidence: {
3522
- average: sonaStats.avgConfidence,
3523
- implementation: sona ? 'real-sona' : 'not-available',
3524
- },
3525
- implementation: distillTriggered
3526
- ? 'real-distill-consolidate'
3527
- : (sona ? 'real-sona-learning' : 'placeholder'),
3528
- };
3529
- },
3530
- };
3531
- // Intelligence attention hook
3532
- export const hooksIntelligenceAttention = {
3533
- name: 'hooks_intelligence_attention',
3534
- description: 'Compute attention-weighted similarity using MoE/Flash/Hyperbolic Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
3535
- inputSchema: {
3536
- type: 'object',
3537
- properties: {
3538
- query: { type: 'string', description: 'Query for attention computation' },
3539
- mode: { type: 'string', description: 'Attention mode (flash, moe, hyperbolic)' },
3540
- topK: { type: 'number', description: 'Top-k results' },
3541
- },
3542
- required: ['query'],
3543
- },
3544
- handler: async (params) => {
3545
- const query = params.query;
3546
- const mode = params.mode || 'flash';
3547
- const topK = params.topK || 5;
3548
- const startTime = performance.now();
3549
- {
3550
- const v = validateText(query, 'query');
3551
- if (!v.valid)
3552
- return { success: false, error: v.error };
3553
- }
3554
- let implementation = 'placeholder';
3555
- let embeddingSource = 'none';
3556
- const results = [];
3557
- // Helper: generate query embedding, preferring real ONNX embeddings over hash fallback
3558
- async function getQueryEmbedding(text, dims) {
3559
- // Try ONNX via @claude-flow/embeddings
3560
- try {
3561
- const embeddingsModule = await import('@claude-flow/embeddings').catch(() => null);
3562
- if (embeddingsModule?.createEmbeddingService) {
3563
- const service = embeddingsModule.createEmbeddingService({ provider: 'onnx' });
3564
- const result = await service.embed(text);
3565
- const arr = new Float32Array(dims);
3566
- for (let i = 0; i < Math.min(dims, result.embedding.length); i++) {
3567
- arr[i] = result.embedding[i];
3568
- }
3569
- return { embedding: arr, source: 'onnx' };
3570
- }
3571
- }
3572
- catch {
3573
- // ONNX not available, try agentic-flow
3574
- }
3575
- // Try agentic-flow embeddings
3576
- try {
3577
- const embeddingsModule = await import('@claude-flow/embeddings').catch(() => null);
3578
- if (embeddingsModule?.createEmbeddingService) {
3579
- const service = embeddingsModule.createEmbeddingService({ provider: 'agentic-flow' });
3580
- const result = await service.embed(text);
3581
- const arr = new Float32Array(dims);
3582
- for (let i = 0; i < Math.min(dims, result.embedding.length); i++) {
3583
- arr[i] = result.embedding[i];
3584
- }
3585
- return { embedding: arr, source: 'onnx' };
3586
- }
3587
- }
3588
- catch {
3589
- // agentic-flow not available
3590
- }
3591
- // Hash-based fallback (deterministic but not semantic)
3592
- const arr = new Float32Array(dims);
3593
- let seed = text.split('').reduce((acc, char, i) => acc + char.charCodeAt(0) * (i + 1), 0);
3594
- for (let i = 0; i < dims; i++) {
3595
- seed = (seed * 1103515245 + 12345) & 0x7fffffff;
3596
- arr[i] = (seed / 0x7fffffff) * 2 - 1;
3597
- }
3598
- return { embedding: arr, source: 'hash-fallback' };
3599
- }
3600
- if (mode === 'moe') {
3601
- // Try MoE routing
3602
- const moe = await getMoERouter();
3603
- if (moe) {
3604
- try {
3605
- const embResult = await getQueryEmbedding(query, 384);
3606
- embeddingSource = embResult.source;
3607
- const routingResult = moe.route(embResult.embedding);
3608
- for (let i = 0; i < Math.min(topK, routingResult.experts.length); i++) {
3609
- const expert = routingResult.experts[i];
3610
- results.push({
3611
- index: i,
3612
- weight: expert.weight,
3613
- pattern: `Expert: ${expert.name}`,
3614
- expert: expert.name,
3615
- });
3616
- }
3617
- implementation = 'real-moe-router';
3618
- }
3619
- catch {
3620
- // Fall back to placeholder
3621
- }
3622
- }
3623
- }
3624
- else if (mode === 'flash') {
3625
- // Try Flash Attention. ADR-093 F10: previously this attended over
3626
- // synthetic cosine-derived keys/values with constant-vector values,
3627
- // which produced uniform 0.333 weights and labels like "Flash
3628
- // attention target #1/2/3". Now we attend over actual stored
3629
- // patterns when available — real semantic content yields non-uniform
3630
- // weights and human-readable labels.
3631
- const flash = await getFlashAttention();
3632
- if (flash) {
3633
- try {
3634
- const embResult = await getQueryEmbedding(query, 384);
3635
- embeddingSource = embResult.source;
3636
- const q = embResult.embedding;
3637
- // Pull real stored patterns to attend over. If none exist yet,
3638
- // fall back to the synthetic harness but mark it honestly.
3639
- const realPatterns = [];
3640
- try {
3641
- const { searchEntries: searchFn } = await import('../memory/memory-initializer.js');
3642
- const hits = await searchFn({ query, limit: topK });
3643
- if (Array.isArray(hits)) {
3644
- for (const h of hits.slice(0, topK)) {
3645
- const content = h.content ?? h.value ?? '';
3646
- const id = String(h.id ?? h.key ?? `pattern-${realPatterns.length}`);
3647
- realPatterns.push({ id, content: String(content) });
3648
- }
3649
- }
3650
- }
3651
- catch { /* memory not initialized — fall through to synthetic */ }
3652
- const useReal = realPatterns.length > 0;
3653
- const keys = [];
3654
- const values = [];
3655
- const labels = [];
3656
- if (useReal) {
3657
- // Build keys from real pattern embeddings (re-embed if no vector cached)
3658
- for (let k = 0; k < realPatterns.length; k++) {
3659
- const p = realPatterns[k];
3660
- let keyEmbedding;
3661
- if (p.embedding && p.embedding.length === 384) {
3662
- keyEmbedding = new Float32Array(p.embedding);
3663
- }
3664
- else {
3665
- const enc = await getQueryEmbedding(p.content.slice(0, 1024), 384);
3666
- keyEmbedding = enc.embedding;
3667
- }
3668
- const value = new Float32Array(384);
3669
- // Value carries pattern identity strength — magnitude = recency proxy (k position)
3670
- const strength = 1 / (k + 1);
3671
- for (let i = 0; i < 384; i++)
3672
- value[i] = keyEmbedding[i] * strength;
3673
- keys.push(keyEmbedding);
3674
- values.push(value);
3675
- const label = p.content.length > 0
3676
- ? `${p.id}: ${p.content.slice(0, 60)}${p.content.length > 60 ? '…' : ''}`
3677
- : p.id;
3678
- labels.push(label);
3679
- }
3680
- }
3681
- else {
3682
- // No real patterns — surface a synthetic harness honestly.
3683
- for (let k = 0; k < topK; k++) {
3684
- const key = new Float32Array(384);
3685
- const value = new Float32Array(384);
3686
- for (let i = 0; i < 384; i++) {
3687
- key[i] = Math.cos((k + 1) * (i + 1) * 0.01);
3688
- value[i] = k + 1;
3689
- }
3690
- keys.push(key);
3691
- values.push(value);
3692
- labels.push(`(synthetic harness) pattern #${k + 1}`);
3693
- }
3694
- }
3695
- const attentionResult = flash.attention([q], keys, values);
3696
- // Compute softmax weights from output magnitudes
3697
- const outputMags = attentionResult.output[0]
3698
- ? Array.from(attentionResult.output[0]).slice(0, keys.length).map(v => Math.abs(v))
3699
- : new Array(keys.length).fill(1);
3700
- const sumMags = outputMags.reduce((a, b) => a + b, 0) || 1;
3701
- for (let i = 0; i < keys.length; i++) {
3702
- results.push({
3703
- index: i,
3704
- weight: outputMags[i] / sumMags,
3705
- pattern: labels[i],
3706
- });
3707
- }
3708
- implementation = useReal ? 'real-flash-attention+memory' : 'real-flash-attention+synthetic-harness';
3709
- }
3710
- catch {
3711
- // Fall back to placeholder
3712
- }
3713
- }
3714
- }
3715
- // If no real implementation worked, return empty with honest marker
3716
- if (results.length === 0) {
3717
- implementation = 'none';
3718
- }
3719
- const computeTimeMs = performance.now() - startTime;
3720
- return {
3721
- query,
3722
- mode,
3723
- results,
3724
- stats: {
3725
- computeTimeMs,
3726
- implementation,
3727
- _embeddingSource: embeddingSource,
3728
- _stub: implementation === 'none',
3729
- _note: implementation === 'none' ? 'No attention backend available. Install @ruvector/attention for real computation.' : undefined,
3730
- ...(embeddingSource === 'hash-fallback' && implementation !== 'none'
3731
- ? { _embeddingNote: 'Query embeddings are hash-based (not semantic). Install @claude-flow/embeddings for real ONNX embeddings.' }
3732
- : {}),
3733
- },
3734
- implementation,
3735
- };
3736
- },
3737
- };
3738
- /**
3739
- * Worker trigger patterns for auto-detection
3740
- */
3741
- const WORKER_TRIGGER_PATTERNS = {
3742
- ultralearn: [
3743
- /learn\s+about/i,
3744
- /understand\s+(how|what|why)/i,
3745
- /deep\s+dive\s+into/i,
3746
- /explain\s+in\s+detail/i,
3747
- /comprehensive\s+guide/i,
3748
- /master\s+this/i,
3749
- ],
3750
- optimize: [
3751
- /optimize/i,
3752
- /improve\s+performance/i,
3753
- /make\s+(it\s+)?faster/i,
3754
- /speed\s+up/i,
3755
- /reduce\s+(memory|time)/i,
3756
- /performance\s+issue/i,
3757
- ],
3758
- consolidate: [
3759
- /consolidate/i,
3760
- /merge\s+memories/i,
3761
- /clean\s+up\s+memory/i,
3762
- /deduplicate/i,
3763
- /memory\s+maintenance/i,
3764
- ],
3765
- predict: [
3766
- /what\s+will\s+happen/i,
3767
- /predict/i,
3768
- /forecast/i,
3769
- /anticipate/i,
3770
- /preload/i,
3771
- /prepare\s+for/i,
3772
- ],
3773
- audit: [
3774
- /security\s+audit/i,
3775
- /vulnerability/i,
3776
- /security\s+check/i,
3777
- /pentest/i,
3778
- /security\s+scan/i,
3779
- /cve/i,
3780
- /owasp/i,
3781
- ],
3782
- map: [
3783
- /map\s+(the\s+)?codebase/i,
3784
- /architecture\s+overview/i,
3785
- /project\s+structure/i,
3786
- /dependency\s+graph/i,
3787
- /code\s+map/i,
3788
- /explore\s+codebase/i,
3789
- ],
3790
- preload: [
3791
- /preload/i,
3792
- /cache\s+ahead/i,
3793
- /prefetch/i,
3794
- /warm\s+(up\s+)?cache/i,
3795
- ],
3796
- deepdive: [
3797
- /deep\s+dive/i,
3798
- /analyze\s+thoroughly/i,
3799
- /in-depth\s+analysis/i,
3800
- /comprehensive\s+review/i,
3801
- /detailed\s+examination/i,
3802
- ],
3803
- document: [
3804
- /document\s+(this|the)/i,
3805
- /generate\s+docs/i,
3806
- /add\s+documentation/i,
3807
- /write\s+readme/i,
3808
- /api\s+docs/i,
3809
- /jsdoc/i,
3810
- ],
3811
- refactor: [
3812
- /refactor/i,
3813
- /clean\s+up\s+code/i,
3814
- /improve\s+code\s+quality/i,
3815
- /restructure/i,
3816
- /simplify/i,
3817
- /make\s+more\s+readable/i,
3818
- ],
3819
- benchmark: [
3820
- /benchmark/i,
3821
- /performance\s+test/i,
3822
- /measure\s+speed/i,
3823
- /stress\s+test/i,
3824
- /load\s+test/i,
3825
- ],
3826
- testgaps: [
3827
- /test\s+coverage/i,
3828
- /missing\s+tests/i,
3829
- /untested\s+code/i,
3830
- /coverage\s+report/i,
3831
- /test\s+gaps/i,
3832
- /add\s+tests/i,
3833
- ],
3834
- };
3835
- /**
3836
- * Worker configurations
3837
- */
3838
- const WORKER_CONFIGS = {
3839
- ultralearn: {
3840
- description: 'Deep knowledge acquisition and learning',
3841
- priority: 'normal',
3842
- estimatedDuration: '60s',
3843
- capabilities: ['research', 'analysis', 'synthesis'],
3844
- },
3845
- optimize: {
3846
- description: 'Performance optimization and tuning',
3847
- priority: 'high',
3848
- estimatedDuration: '30s',
3849
- capabilities: ['profiling', 'optimization', 'benchmarking'],
3850
- },
3851
- consolidate: {
3852
- description: 'Memory consolidation and cleanup',
3853
- priority: 'low',
3854
- estimatedDuration: '20s',
3855
- capabilities: ['memory-management', 'deduplication'],
3856
- },
3857
- predict: {
3858
- description: 'Predictive preloading and anticipation',
3859
- priority: 'normal',
3860
- estimatedDuration: '15s',
3861
- capabilities: ['prediction', 'caching', 'preloading'],
3862
- },
3863
- audit: {
3864
- description: 'Security analysis and vulnerability scanning',
3865
- priority: 'critical',
3866
- estimatedDuration: '45s',
3867
- capabilities: ['security', 'vulnerability-scanning', 'audit'],
3868
- },
3869
- map: {
3870
- description: 'Codebase mapping and architecture analysis',
3871
- priority: 'normal',
3872
- estimatedDuration: '30s',
3873
- capabilities: ['analysis', 'mapping', 'visualization'],
3874
- },
3875
- preload: {
3876
- description: 'Resource preloading and cache warming',
3877
- priority: 'low',
3878
- estimatedDuration: '10s',
3879
- capabilities: ['caching', 'preloading'],
3880
- },
3881
- deepdive: {
3882
- description: 'Deep code analysis and examination',
3883
- priority: 'normal',
3884
- estimatedDuration: '60s',
3885
- capabilities: ['analysis', 'review', 'understanding'],
3886
- },
3887
- document: {
3888
- description: 'Auto-documentation generation',
3889
- priority: 'normal',
3890
- estimatedDuration: '45s',
3891
- capabilities: ['documentation', 'writing', 'generation'],
3892
- },
3893
- refactor: {
3894
- description: 'Code refactoring suggestions',
3895
- priority: 'normal',
3896
- estimatedDuration: '30s',
3897
- capabilities: ['refactoring', 'code-quality', 'improvement'],
3898
- },
3899
- benchmark: {
3900
- description: 'Performance benchmarking',
3901
- priority: 'normal',
3902
- estimatedDuration: '60s',
3903
- capabilities: ['benchmarking', 'testing', 'measurement'],
3904
- },
3905
- testgaps: {
3906
- description: 'Test coverage analysis',
3907
- priority: 'normal',
3908
- estimatedDuration: '30s',
3909
- capabilities: ['testing', 'coverage', 'analysis'],
3910
- },
3911
- };
3912
- // In-memory worker tracking
3913
- const activeWorkers = new Map();
3914
- let workerIdCounter = 0;
3915
- /**
3916
- * Detect triggers from prompt text
3917
- */
3918
- function detectWorkerTriggers(text) {
3919
- if (!text)
3920
- return { detected: false, triggers: [], confidence: 0, context: '' };
3921
- const detectedTriggers = [];
3922
- let totalMatches = 0;
3923
- for (const [trigger, patterns] of Object.entries(WORKER_TRIGGER_PATTERNS)) {
3924
- for (const pattern of patterns) {
3925
- if (pattern.test(text)) {
3926
- if (!detectedTriggers.includes(trigger)) {
3927
- detectedTriggers.push(trigger);
3928
- }
3929
- totalMatches++;
3930
- }
3931
- }
3932
- }
3933
- const confidence = detectedTriggers.length > 0
3934
- ? Math.min(1, totalMatches / (detectedTriggers.length * 2))
3935
- : 0;
3936
- return {
3937
- detected: detectedTriggers.length > 0,
3938
- triggers: detectedTriggers,
3939
- confidence,
3940
- context: text.slice(0, 100),
3941
- };
3942
- }
3943
- // Worker list tool
3944
- export const hooksWorkerList = {
3945
- name: 'hooks_worker-list',
3946
- description: 'List all 12 background workers with status and capabilities Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
3947
- inputSchema: {
3948
- type: 'object',
3949
- properties: {
3950
- status: { type: 'string', description: 'Filter by status (all, running, completed, pending)' },
3951
- includeActive: { type: 'boolean', description: 'Include active worker instances' },
3952
- },
3953
- },
3954
- handler: async (params) => {
3955
- const statusFilter = params.status || 'all';
3956
- const includeActive = params.includeActive !== false;
3957
- const workers = Object.entries(WORKER_CONFIGS).map(([trigger, config]) => ({
3958
- trigger,
3959
- ...config,
3960
- patterns: WORKER_TRIGGER_PATTERNS[trigger].length,
3961
- }));
3962
- const activeList = includeActive
3963
- ? Array.from(activeWorkers.values()).filter(w => statusFilter === 'all' || w.status === statusFilter)
3964
- : [];
3965
- return {
3966
- workers,
3967
- total: 12,
3968
- active: {
3969
- instances: activeList,
3970
- count: activeList.length,
3971
- byStatus: {
3972
- pending: activeList.filter(w => w.status === 'pending').length,
3973
- running: activeList.filter(w => w.status === 'running').length,
3974
- completed: activeList.filter(w => w.status === 'completed').length,
3975
- failed: activeList.filter(w => w.status === 'failed').length,
3976
- },
3977
- },
3978
- performanceTargets: {
3979
- triggerDetection: '<5ms',
3980
- workerSpawn: '<50ms',
3981
- maxConcurrent: 10,
3982
- },
3983
- };
3984
- },
3985
- };
3986
- // Worker dispatch tool
3987
- export const hooksWorkerDispatch = {
3988
- name: 'hooks_worker-dispatch',
3989
- description: 'Dispatch a background worker for analysis/optimization tasks Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
3990
- inputSchema: {
3991
- type: 'object',
3992
- properties: {
3993
- trigger: {
3994
- type: 'string',
3995
- description: 'Worker trigger type',
3996
- enum: ['ultralearn', 'optimize', 'consolidate', 'predict', 'audit', 'map', 'preload', 'deepdive', 'document', 'refactor', 'benchmark', 'testgaps'],
3997
- },
3998
- context: { type: 'string', description: 'Context for the worker (file path, topic, etc.)' },
3999
- priority: { type: 'string', description: 'Priority (low, normal, high, critical)' },
4000
- background: { type: 'boolean', description: 'Run in background (non-blocking)' },
4001
- },
4002
- required: ['trigger'],
4003
- },
4004
- handler: async (params) => {
4005
- const trigger = params.trigger;
4006
- const context = params.context || 'default';
4007
- const priority = params.priority || WORKER_CONFIGS[trigger]?.priority || 'normal';
4008
- const background = params.background !== false;
4009
- if (params.context) {
4010
- const v = validateText(params.context, 'context');
4011
- if (!v.valid)
4012
- return { success: false, error: v.error };
4013
- }
4014
- if (!WORKER_CONFIGS[trigger]) {
4015
- return {
4016
- success: false,
4017
- error: `Unknown worker trigger: ${trigger}`,
4018
- availableTriggers: Object.keys(WORKER_CONFIGS),
4019
- };
4020
- }
4021
- const workerId = `worker_${trigger}_${++workerIdCounter}_${Date.now().toString(36)}`;
4022
- const config = WORKER_CONFIGS[trigger];
4023
- // ADR-093 F2: stop returning status:"completed" for a worker that
4024
- // never ran (#1700 item 1). Detect daemon presence via PID file and
4025
- // surface honest verdicts (`no-daemon` / `queued` / `synthetic`).
4026
- const cwd = getProjectCwd();
4027
- const pidFile = join(cwd, '.claude-flow', 'daemon.pid');
4028
- let daemonPid = null;
4029
- let daemonAlive = false;
4030
- if (existsSync(pidFile)) {
4031
- try {
4032
- const raw = readFileSync(pidFile, 'utf-8').trim();
4033
- const pid = parseInt(raw, 10);
4034
- if (Number.isFinite(pid) && pid > 0) {
4035
- daemonPid = pid;
4036
- try {
4037
- process.kill(pid, 0);
4038
- daemonAlive = true;
4039
- }
4040
- catch {
4041
- daemonAlive = false;
4042
- }
4043
- }
4044
- }
4045
- catch { /* unreadable PID file */ }
4046
- }
4047
- const worker = {
4048
- id: workerId,
4049
- trigger,
4050
- context,
4051
- status: daemonAlive ? 'pending' : 'pending',
4052
- progress: 0,
4053
- phase: 'initializing',
4054
- startedAt: new Date(),
4055
- };
4056
- activeWorkers.set(workerId, worker);
4057
- // Determine honest status
4058
- let reportedStatus;
4059
- let note = '';
4060
- if (!daemonAlive) {
4061
- reportedStatus = 'no-daemon';
4062
- note = 'No worker daemon detected. Run `claude-flow daemon start` to enable real worker execution. The dispatch was recorded in-process but no actual work will run.';
4063
- }
4064
- else if (background) {
4065
- // #1845: write a durable queue file the daemon polls every 5s. Until
4066
- // 3.7.0-alpha.11 the dispatch only updated a process-local Map that
4067
- // the daemon (separate process) could never see, so `queued` was a
4068
- // lie. The queue file makes it real and inspectable on disk.
4069
- const queueDir = join(cwd, '.claude-flow', 'daemon-queue');
4070
- const queuePath = join(queueDir, `${workerId}.json`);
4071
- let queueWritten = false;
4072
- try {
4073
- if (!existsSync(queueDir))
4074
- mkdirSync(queueDir, { recursive: true });
4075
- writeFileSync(queuePath, JSON.stringify({ workerId, trigger, context, priority, enqueuedAt: new Date().toISOString() }, null, 2));
4076
- queueWritten = true;
4077
- }
4078
- catch (err) {
4079
- // Filesystem error — fall back to mcp-only status so we never
4080
- // claim queued without proof.
4081
- note = `Daemon detected (pid ${daemonPid}) but queue write to ${queuePath} failed: ${err.message}. Worker recorded in-process only; use \`ruflo daemon trigger -w ${trigger}\` to run synchronously.`;
4082
- }
4083
- if (queueWritten) {
4084
- reportedStatus = 'queued';
4085
- note = `Worker queued for daemon (pid ${daemonPid}) at ${queuePath}. Daemon polls every 5s; processed entries move to .claude-flow/daemon-queue/.processed/. Poll hooks_worker-status until status === "completed".`;
4086
- }
4087
- else {
4088
- reportedStatus = 'mcp-only';
4089
- }
4090
- }
4091
- else {
4092
- // Synchronous mode without a runner — be honest about it
4093
- reportedStatus = 'synthetic-completed';
4094
- worker.progress = 100;
4095
- worker.phase = 'completed';
4096
- worker.status = 'completed';
4097
- worker.completedAt = new Date();
4098
- note = 'Synchronous mode: worker record marked completed but no real work executed (no in-process runner). Use background:true with the daemon for real execution.';
4099
- }
4100
- return {
4101
- success: true,
4102
- workerId,
4103
- trigger,
4104
- context,
4105
- priority,
4106
- config: {
4107
- description: config.description,
4108
- estimatedDuration: config.estimatedDuration,
4109
- capabilities: config.capabilities,
4110
- },
4111
- status: reportedStatus,
4112
- daemonAlive,
4113
- daemonPid: daemonAlive ? daemonPid : null,
4114
- background,
4115
- note,
4116
- timestamp: new Date().toISOString(),
4117
- };
4118
- },
4119
- };
4120
- // Worker status tool
4121
- export const hooksWorkerStatus = {
4122
- name: 'hooks_worker-status',
4123
- description: 'Get status of a specific worker or all active workers Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
4124
- inputSchema: {
4125
- type: 'object',
4126
- properties: {
4127
- workerId: { type: 'string', description: 'Specific worker ID to check' },
4128
- includeCompleted: { type: 'boolean', description: 'Include completed workers' },
4129
- },
4130
- },
4131
- handler: async (params) => {
4132
- const workerId = params.workerId;
4133
- const includeCompleted = params.includeCompleted !== false;
4134
- if (workerId) {
4135
- const v = validateIdentifier(workerId, 'workerId');
4136
- if (!v.valid)
4137
- return { success: false, error: v.error };
4138
- }
4139
- if (workerId) {
4140
- const worker = activeWorkers.get(workerId);
4141
- if (!worker) {
4142
- return {
4143
- success: false,
4144
- error: `Worker not found: ${workerId}`,
4145
- };
4146
- }
4147
- return {
4148
- success: true,
4149
- worker: {
4150
- ...worker,
4151
- duration: worker.completedAt
4152
- ? worker.completedAt.getTime() - worker.startedAt.getTime()
4153
- : Date.now() - worker.startedAt.getTime(),
4154
- },
4155
- };
4156
- }
4157
- const workers = Array.from(activeWorkers.values())
4158
- .filter(w => includeCompleted || w.status !== 'completed')
4159
- .map(w => ({
4160
- ...w,
4161
- duration: w.completedAt
4162
- ? w.completedAt.getTime() - w.startedAt.getTime()
4163
- : Date.now() - w.startedAt.getTime(),
4164
- }));
4165
- return {
4166
- success: true,
4167
- workers,
4168
- summary: {
4169
- total: workers.length,
4170
- running: workers.filter(w => w.status === 'running').length,
4171
- completed: workers.filter(w => w.status === 'completed').length,
4172
- failed: workers.filter(w => w.status === 'failed').length,
4173
- },
4174
- };
4175
- },
4176
- };
4177
- // Worker detect tool - detect triggers from prompt
4178
- export const hooksWorkerDetect = {
4179
- name: 'hooks_worker-detect',
4180
- description: 'Detect worker triggers from user prompt (for UserPromptSubmit hook) Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
4181
- inputSchema: {
4182
- type: 'object',
4183
- properties: {
4184
- prompt: { type: 'string', description: 'User prompt to analyze' },
4185
- autoDispatch: { type: 'boolean', description: 'Automatically dispatch detected workers' },
4186
- minConfidence: { type: 'number', description: 'Minimum confidence threshold (0-1)' },
4187
- },
4188
- required: ['prompt'],
4189
- },
4190
- handler: async (params) => {
4191
- const prompt = params.prompt;
4192
- const autoDispatch = params.autoDispatch;
4193
- const minConfidence = params.minConfidence || 0.5;
4194
- {
4195
- const v = validateText(prompt, 'prompt');
4196
- if (!v.valid)
4197
- return { success: false, error: v.error };
4198
- }
4199
- const detection = detectWorkerTriggers(prompt);
4200
- const result = {
4201
- prompt: prompt.slice(0, 200) + (prompt.length > 200 ? '...' : ''),
4202
- detection,
4203
- triggersFound: detection.triggers.length,
4204
- };
4205
- if (detection.detected && detection.confidence >= minConfidence) {
4206
- result.triggerDetails = detection.triggers.map(trigger => ({
4207
- trigger,
4208
- ...WORKER_CONFIGS[trigger],
4209
- }));
4210
- if (autoDispatch) {
4211
- const dispatched = [];
4212
- for (const trigger of detection.triggers) {
4213
- const workerId = `worker_${trigger}_${++workerIdCounter}_${Date.now().toString(36)}`;
4214
- activeWorkers.set(workerId, {
4215
- id: workerId,
4216
- trigger,
4217
- context: prompt.slice(0, 100),
4218
- status: 'running',
4219
- progress: 0,
4220
- phase: 'initializing',
4221
- startedAt: new Date(),
4222
- });
4223
- dispatched.push(workerId);
4224
- // Mark worker completion after processing
4225
- setTimeout(() => {
4226
- const w = activeWorkers.get(workerId);
4227
- if (w) {
4228
- w.progress = 100;
4229
- w.phase = 'completed';
4230
- w.status = 'completed';
4231
- w.completedAt = new Date();
4232
- }
4233
- }, 1500);
4234
- }
4235
- result.autoDispatched = true;
4236
- result.workerIds = dispatched;
4237
- }
4238
- }
4239
- return result;
4240
- },
4241
- };
4242
- // Model router - lazy loaded
4243
- let modelRouterInstance = null;
4244
- async function getModelRouterInstance() {
4245
- if (!modelRouterInstance) {
4246
- try {
4247
- const { getModelRouter } = await import('../ruvector/model-router.js');
4248
- modelRouterInstance = getModelRouter();
4249
- }
4250
- catch {
4251
- modelRouterInstance = null;
4252
- }
4253
- }
4254
- return modelRouterInstance;
4255
- }
4256
- // Model route tool - intelligent model selection
4257
- export const hooksModelRoute = {
4258
- name: 'hooks_model-route',
4259
- description: 'Route task to optimal Claude model (haiku/sonnet/opus) based on complexity Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
4260
- inputSchema: {
4261
- type: 'object',
4262
- properties: {
4263
- task: { type: 'string', description: 'Task description to analyze' },
4264
- preferSpeed: { type: 'boolean', description: 'Prefer faster models when possible' },
4265
- preferCost: { type: 'boolean', description: 'Prefer cheaper models when possible' },
4266
- },
4267
- required: ['task'],
4268
- },
4269
- handler: async (params) => {
4270
- const task = params.task;
4271
- {
4272
- const v = validateText(task, 'task');
4273
- if (!v.valid)
4274
- return { success: false, error: v.error };
4275
- }
4276
- const router = await getModelRouterInstance();
4277
- if (!router) {
4278
- // Fallback to simple heuristic
4279
- const complexity = analyzeComplexityFallback(task);
4280
- return {
4281
- model: complexity > 0.7 ? 'opus' : complexity > 0.4 ? 'sonnet' : 'haiku',
4282
- confidence: 0.7,
4283
- complexity,
4284
- reasoning: 'Fallback heuristic (model router not available)',
4285
- implementation: 'fallback',
4286
- };
4287
- }
4288
- const result = await router.route(task);
4289
- return {
4290
- model: result.model,
4291
- confidence: result.confidence,
4292
- uncertainty: result.uncertainty,
4293
- complexity: result.complexity,
4294
- reasoning: result.reasoning,
4295
- alternatives: result.alternatives,
4296
- inferenceTimeUs: result.inferenceTimeUs,
4297
- costMultiplier: result.costMultiplier,
4298
- // Historical name kept for telemetry / dashboard schema stability.
4299
- // The shipped router is the heuristic + Thompson-bandit described in
4300
- // ruvector/model-router.ts — not a neural network. See #2329.
4301
- implementation: 'heuristic-thompson-bandit',
4302
- };
4303
- },
4304
- };
4305
- // Model route outcome - record outcome for learning
4306
- export const hooksModelOutcome = {
4307
- name: 'hooks_model-outcome',
4308
- description: 'Record model routing outcome for learning Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
4309
- inputSchema: {
4310
- type: 'object',
4311
- properties: {
4312
- task: { type: 'string', description: 'Original task' },
4313
- model: { type: 'string', enum: ['haiku', 'sonnet', 'opus'], description: 'Model used' },
4314
- outcome: { type: 'string', enum: ['success', 'failure', 'escalated'], description: 'Task outcome' },
4315
- },
4316
- required: ['task', 'model', 'outcome'],
4317
- },
4318
- handler: async (params) => {
4319
- const task = params.task;
4320
- const model = params.model;
4321
- const outcome = params.outcome;
4322
- {
4323
- const v = validateText(task, 'task');
4324
- if (!v.valid)
4325
- return { success: false, error: v.error };
4326
- }
4327
- const router = await getModelRouterInstance();
4328
- if (router) {
4329
- router.recordOutcome(task, model, outcome);
4330
- }
4331
- return {
4332
- recorded: true,
4333
- task: task.slice(0, 50),
4334
- model,
4335
- outcome,
4336
- timestamp: new Date().toISOString(),
4337
- };
4338
- },
4339
- };
4340
- // Model router stats
4341
- export const hooksModelStats = {
4342
- name: 'hooks_model-stats',
4343
- description: 'Get model routing statistics Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
4344
- inputSchema: {
4345
- type: 'object',
4346
- properties: {},
4347
- },
4348
- handler: async () => {
4349
- const router = await getModelRouterInstance();
4350
- if (!router) {
4351
- return {
4352
- available: false,
4353
- message: 'Model router not initialized',
4354
- };
4355
- }
4356
- const stats = router.getStats();
4357
- return {
4358
- available: true,
4359
- ...stats,
4360
- timestamp: new Date().toISOString(),
4361
- };
4362
- },
4363
- };
4364
- // Model verify — confidence-gated tier escalation (post-generation).
4365
- // The heuristics live in ruvector/output-verifier.ts; this wrapper adds the
4366
- // MCP surface and feeds the verdict into the SAME learning stream that
4367
- // hooks_model-outcome uses (ModelRouter.recordOutcome → Thompson priors), so
4368
- // the router learns from escalations. A dedicated tool (rather than a
4369
- // "verify mode" on hooks_model-outcome) was chosen because outcome recording
4370
- // is a terminal write while verify is a MID-LOOP decision point that returns
4371
- // a verdict the agent acts on — overloading outcome would conflate the two
4372
- // and break the route → generate → verify → (escalate) → outcome sequence.
4373
- export const hooksModelVerify = {
4374
- name: 'hooks_model-verify',
4375
- description: 'Verify a generated output with CHEAP structural signals ($0, no LLM call) and get an escalation verdict — the post-generation half of confidence-gated tier routing (route → generate → verify → escalate on failure). Checks: empty/truncated output, refusal patterns, degenerate repetition, and real syntax parsing for code/JSON tasks (TypeScript compiler / JSON.parse). Returns {confident, reasons[], suggestedTier, suggestedModel, escalate}. By default the verdict is recorded into the model-routing learning stream (success when confident, escalated when not) so the bandit learns which task shapes the cheap tier fails on. Use when you just generated with the tier hooks_model-route picked and must decide accept-vs-escalate BEFORE acting on the output; accepting cheap-tier output unverified is wrong because structurally unusable results (refusals, truncation, unparseable code) silently propagate downstream, and pre-generation routing alone cannot catch them. Not a semantic-quality judge — it only catches structurally unusable outputs.',
4376
- inputSchema: {
4377
- type: 'object',
4378
- properties: {
4379
- task: { type: 'string', description: 'The task the output was generated for' },
4380
- output: { type: 'string', description: 'The generated output to verify' },
4381
- model: { type: 'string', enum: ['haiku', 'sonnet', 'opus'], description: 'Model that produced the output (drives the escalation ladder; default haiku)' },
4382
- tierUsed: { type: 'number', enum: [1, 2, 3], description: 'Tier that produced the output; derived from model when absent' },
4383
- taskKind: { type: 'string', enum: ['code', 'json', 'text', 'auto'], description: 'Force the task kind; default auto-detect' },
4384
- record: { type: 'boolean', description: 'Record the verdict into the routing learning stream (default true; requires model)' },
4385
- },
4386
- required: ['task', 'output'],
4387
- },
4388
- handler: async (params) => {
4389
- const task = params.task;
4390
- const output = params.output;
4391
- const model = params.model;
4392
- {
4393
- const v = validateText(task, 'task');
4394
- if (!v.valid)
4395
- return { success: false, error: v.error };
4396
- }
4397
- if (typeof output !== 'string')
4398
- return { success: false, error: 'output must be a string' };
4399
- const { verifyAndEscalate } = await import('../ruvector/output-verifier.js');
4400
- const verdict = await verifyAndEscalate({
4401
- task,
4402
- output,
4403
- model,
4404
- tierUsed: params.tierUsed,
4405
- taskKind: params.taskKind,
4406
- });
4407
- // Feed the verdict into the existing outcome/learning stream (same path
4408
- // as hooks_model-outcome) so escalations update the Thompson priors.
4409
- let recorded = false;
4410
- if (params.record !== false && model) {
4411
- const router = await getModelRouterInstance();
4412
- if (router) {
4413
- router.recordOutcome(task, model, verdict.confident ? 'success' : 'escalated');
4414
- recorded = true;
4415
- }
4416
- }
4417
- return {
4418
- ...verdict,
4419
- model: model ?? 'haiku',
4420
- recorded,
4421
- recordedOutcome: recorded ? (verdict.confident ? 'success' : 'escalated') : null,
4422
- timestamp: new Date().toISOString(),
4423
- };
4424
- },
4425
- };
4426
- // Supported source extensions for codemods.
4427
- const CODEMOD_EXTENSIONS = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.mts', '.cts']);
4428
- const CODEMOD_MAX_FILES = 2000;
4429
- function codemodLangForExt(abs) {
4430
- const ext = abs.slice(abs.lastIndexOf('.')).toLowerCase();
4431
- if (ext === '.tsx')
4432
- return 'tsx';
4433
- if (ext === '.jsx')
4434
- return 'jsx';
4435
- if (ext === '.js' || ext === '.mjs' || ext === '.cjs')
4436
- return 'javascript';
4437
- return 'typescript';
4438
- }
4439
- // Deterministic codemod execution — the real Tier-1 path (ADR-143)
4440
- export const hooksCodemod = {
4441
- name: 'hooks_codemod',
4442
- description: 'Apply a deterministic, $0 (no-LLM) code transform — the real Tier-1 execution path (ADR-143). Supported intents: var-to-const, remove-console, add-logging. Uses the TypeScript compiler with formatting-preserving edits (comments/whitespace survive). Targets: raw `code` (returns transformed text, writes nothing) | a single `file` | a `files` array | a `glob` pattern (batch — applies the intent across every match in one $0 call). Files are rewritten in place unless `dryRun`. Intents that need reasoning — add-types, add-error-handling, async-await — are NOT supported here; route those to a model via hooks_model-route. Use when hooks_pre-task / hooks_route returned [CODEMOD_AVAILABLE].',
4443
- inputSchema: {
4444
- type: 'object',
4445
- properties: {
4446
- intent: { type: 'string', enum: ['var-to-const', 'remove-console', 'add-logging'], description: 'Deterministic codemod to apply' },
4447
- file: { type: 'string', description: 'Path to a single existing source file to transform in place' },
4448
- files: { type: 'array', items: { type: 'string' }, description: 'Multiple file paths to transform in one batch call' },
4449
- glob: { type: 'string', description: 'Glob pattern (relative to project root, e.g. "src/**/*.ts") — applies the intent to every matching source file' },
4450
- code: { type: 'string', description: 'Raw source to transform instead of files (returns transformed code, writes nothing)' },
4451
- language: { type: 'string', enum: ['javascript', 'typescript', 'jsx', 'tsx'], description: 'Language hint for raw code (default typescript; inferred from extension for files)' },
4452
- dryRun: { type: 'boolean', description: 'Report what would change without writing files' },
4453
- },
4454
- required: ['intent'],
4455
- },
4456
- handler: async (params) => {
4457
- const intent = params.intent;
4458
- const file = params.file;
4459
- const files = Array.isArray(params.files) ? params.files : undefined;
4460
- const glob = params.glob;
4461
- const rawCode = params.code;
4462
- const dryRun = params.dryRun === true;
4463
- const langParam = params.language;
4464
- const { applyCodemod, isDeterministicCodemod } = await import('../ruvector/codemods/engine.js');
4465
- if (!isDeterministicCodemod(intent)) {
4466
- return {
4467
- success: false,
4468
- error: `"${intent}" is not a deterministic codemod. Route it to a model via hooks_model-route (Tier 2/3).`,
4469
- };
4470
- }
4471
- // Mode A: transform raw code (never touches disk)
4472
- if (typeof rawCode === 'string') {
4473
- const language = langParam ?? 'typescript';
4474
- const r = applyCodemod(intent, rawCode, { language });
4475
- return {
4476
- success: r.success, intent, mode: 'code', changed: r.changed, edits: r.edits,
4477
- output: r.output, language: r.language, reason: r.reason, cost: 0, tier: 1,
4478
- };
4479
- }
4480
- const cwd = getProjectCwd();
4481
- // Resolve the target file set (single / array / glob), with path containment.
4482
- const resolveTargets = () => {
4483
- const out = new Set();
4484
- const addRaw = (p) => {
4485
- const v = validatePath(p, 'path');
4486
- if (!v.valid)
4487
- return v.error;
4488
- const abs = resolve(cwd, v.sanitized);
4489
- if (!abs.startsWith(cwd))
4490
- return `path escapes project root: ${p}`;
4491
- out.add(abs);
4492
- return undefined;
4493
- };
4494
- if (file) {
4495
- const e = addRaw(file);
4496
- if (e)
4497
- return { abs: [], truncated: false, error: e };
4498
- }
4499
- if (files)
4500
- for (const p of files) {
4501
- const e = addRaw(p);
4502
- if (e)
4503
- return { abs: [], truncated: false, error: e };
4504
- }
4505
- if (glob) {
4506
- if (glob.includes('..'))
4507
- return { abs: [], truncated: false, error: 'glob must not contain ".."' };
4508
- // fs.globSync is Node 22+; @types/node here predates it, so type it locally.
4509
- const globSync = nodeFs.globSync;
4510
- if (typeof globSync !== 'function') {
4511
- return { abs: [], truncated: false, error: 'glob requires Node 22+ (fs.globSync unavailable); pass `files[]` instead' };
4512
- }
4513
- let matches = [];
4514
- try {
4515
- matches = globSync(glob, { cwd });
4516
- }
4517
- catch (err) {
4518
- return { abs: [], truncated: false, error: `glob failed: ${err.message}` };
4519
- }
4520
- for (const m of matches) {
4521
- const abs = resolve(cwd, m);
4522
- if (abs.startsWith(cwd) && CODEMOD_EXTENSIONS.has(abs.slice(abs.lastIndexOf('.')).toLowerCase())) {
4523
- out.add(abs);
4524
- }
4525
- }
4526
- }
4527
- const all = [...out];
4528
- const truncated = all.length > CODEMOD_MAX_FILES;
4529
- return { abs: truncated ? all.slice(0, CODEMOD_MAX_FILES) : all, truncated };
4530
- };
4531
- const targets = resolveTargets();
4532
- if (targets.error)
4533
- return { success: false, error: targets.error };
4534
- if (targets.abs.length === 0) {
4535
- return { success: false, error: 'No target files. Provide `code`, `file`, `files[]`, or a matching `glob`.' };
4536
- }
4537
- // Apply to each file.
4538
- const results = [];
4539
- let filesChanged = 0, totalEdits = 0, failures = 0, skipped = 0;
4540
- for (const abs of targets.abs) {
4541
- const rel = abs.startsWith(cwd) ? abs.slice(cwd.length).replace(/^[/\\]/, '') : abs;
4542
- if (!existsSync(abs)) {
4543
- results.push({ file: rel, success: false, reason: 'not found' });
4544
- failures++;
4545
- continue;
4546
- }
4547
- if (!CODEMOD_EXTENSIONS.has(abs.slice(abs.lastIndexOf('.')).toLowerCase())) {
4548
- results.push({ file: rel, success: false, reason: 'unsupported extension' });
4549
- skipped++;
4550
- continue;
4551
- }
4552
- const before = readFileSync(abs, 'utf-8');
4553
- const r = applyCodemod(intent, before, { language: codemodLangForExt(abs) });
4554
- if (!r.success) {
4555
- results.push({ file: rel, success: false, changed: false, reason: r.reason });
4556
- failures++;
4557
- continue;
4558
- }
4559
- const written = r.changed && !dryRun;
4560
- if (written)
4561
- writeFileSync(abs, r.output, 'utf-8');
4562
- if (r.changed) {
4563
- filesChanged++;
4564
- totalEdits += r.edits;
4565
- }
4566
- results.push({ file: rel, success: true, changed: r.changed, edits: r.edits, written });
4567
- }
4568
- const single = targets.abs.length === 1 && !files && !glob;
4569
- return {
4570
- success: failures === 0,
4571
- intent,
4572
- mode: single ? (dryRun ? 'dry-run' : 'file') : (dryRun ? 'batch-dry-run' : 'batch'),
4573
- summary: {
4574
- filesScanned: targets.abs.length,
4575
- filesChanged,
4576
- filesUnchanged: targets.abs.length - filesChanged - failures - skipped,
4577
- totalEdits,
4578
- failures,
4579
- skipped,
4580
- truncatedAt: targets.truncated ? CODEMOD_MAX_FILES : undefined,
4581
- },
4582
- results: results.slice(0, 500),
4583
- resultsTruncated: results.length > 500,
4584
- cost: 0,
4585
- tier: 1,
4586
- timestamp: new Date().toISOString(),
4587
- };
4588
- },
4589
- };
4590
- // Simple fallback complexity analyzer
4591
- function analyzeComplexityFallback(task) {
4592
- const taskLower = task.toLowerCase();
4593
- // High complexity indicators
4594
- const highIndicators = ['architect', 'design', 'refactor', 'security', 'audit', 'complex', 'analyze'];
4595
- const highCount = highIndicators.filter(ind => taskLower.includes(ind)).length;
4596
- // Low complexity indicators
4597
- const lowIndicators = ['simple', 'typo', 'format', 'rename', 'comment'];
4598
- const lowCount = lowIndicators.filter(ind => taskLower.includes(ind)).length;
4599
- // Base on length
4600
- const lengthScore = Math.min(1, task.length / 200);
4601
- return Math.min(1, Math.max(0, 0.3 + highCount * 0.2 - lowCount * 0.15 + lengthScore * 0.2));
4602
- }
4603
- // Worker cancel tool
4604
- export const hooksWorkerCancel = {
4605
- name: 'hooks_worker-cancel',
4606
- description: 'Cancel a running worker Use when native Bash hooks (via Claude Code\'s settings.json) are wrong because you need Ruflo-side state — pattern persistence, neural training signals, model-routing learning, cost tracking, audit chain. For one-off shell commands, plain Bash hooks are fine.',
4607
- inputSchema: {
4608
- type: 'object',
4609
- properties: {
4610
- workerId: { type: 'string', description: 'Worker ID to cancel' },
4611
- },
4612
- required: ['workerId'],
4613
- },
4614
- handler: async (params) => {
4615
- const workerId = params.workerId;
4616
- {
4617
- const v = validateIdentifier(workerId, 'workerId');
4618
- if (!v.valid)
4619
- return { success: false, error: v.error };
4620
- }
4621
- const worker = activeWorkers.get(workerId);
4622
- if (!worker) {
4623
- return {
4624
- success: false,
4625
- error: `Worker not found: ${workerId}`,
4626
- };
4627
- }
4628
- if (worker.status === 'completed' || worker.status === 'failed') {
4629
- return {
4630
- success: false,
4631
- error: `Worker already ${worker.status}`,
4632
- };
4633
- }
4634
- worker.status = 'failed';
4635
- worker.phase = 'cancelled';
4636
- worker.completedAt = new Date();
4637
- return {
4638
- success: true,
4639
- workerId,
4640
- cancelled: true,
4641
- timestamp: new Date().toISOString(),
4642
- };
4643
- },
4644
- };
4645
- // #1916: the `ruflo hooks teammate-idle` / `ruflo hooks task-completed` CLI
4646
- // subcommands (Agent Teams hooks) referenced unregistered tools. Minimal
4647
- // acknowledgement handlers with the shapes the CLI expects — auto-assignment
4648
- // and pattern-learning are delegated to the task-queue consumer / intelligence
4649
- // pipeline (a tracked #1916 follow-up).
4650
- export const hooksTeammateIdle = {
4651
- name: 'hooks_teammate-idle',
4652
- description: 'Agent Teams hook — fired when a teammate agent finishes its turn; reports whether a pending task can be auto-assigned. Use when native Task is wrong because you have a persistent multi-agent team with a shared task list and want idle workers picked up automatically rather than re-spawning subagents. For a one-shot Task, native Task is fine. (Auto-assignment is delegated to the task-queue consumer — this acknowledges the event today.)',
4653
- category: 'hooks',
4654
- inputSchema: {
4655
- type: 'object',
4656
- properties: {
4657
- teammateId: { type: 'string', description: 'ID of the idle teammate' },
4658
- teamName: { type: 'string', description: 'Team name' },
4659
- autoAssign: { type: 'boolean', description: 'Auto-assign a pending task if available' },
4660
- checkTaskList: { type: 'boolean', description: 'Consult the shared task list' },
4661
- timestamp: { type: 'number', description: 'Event timestamp (ms)' },
4662
- },
4663
- },
4664
- handler: async (input) => {
4665
- const teammateId = String(input.teammateId ?? '');
4666
- return {
4667
- success: true,
4668
- teammateId,
4669
- action: 'waiting',
4670
- pendingTasks: 0,
4671
- message: 'teammate-idle acknowledged; auto-assignment requires the task-queue consumer (#1916 follow-up)',
4672
- };
4673
- },
4674
- };
4675
- export const hooksTaskCompleted = {
4676
- name: 'hooks_task-completed',
4677
- description: 'Agent Teams hook — fired when a task is marked complete. Records the completion and, when `trainPatterns:true`, feeds the outcome to the SONA + EWC++ learning pipeline (the same path used by hooks_intelligence trajectory-*). Multiple ways to drive learning exist: (a) call this with trainPatterns:true for a one-step trajectory, (b) use hooks_intelligence trajectory-start/step/end for richer multi-step learning, (c) just record an episode via memory_store if no learning is needed. Each path is honest about what it persists; check the returned `learningPath` field. Use when native TaskUpdate(status:completed) is wrong because the runtime also needs to (i) record the outcome as a learning signal and (ii) emit the standard "task done" pipeline event — TaskUpdate only changes the task row.',
4678
- category: 'hooks',
4679
- inputSchema: {
4680
- type: 'object',
4681
- properties: {
4682
- taskId: { type: 'string', description: 'ID of the completed task' },
4683
- teammateId: { type: 'string', description: 'Teammate that completed it' },
4684
- success: { type: 'boolean', description: 'Whether the task succeeded' },
4685
- quality: { type: 'number', description: 'Quality score 0-1' },
4686
- trainPatterns: { type: 'boolean', description: 'When true, runs the SONA + EWC++ trajectory pipeline on this completion so globalStats.patternsLearned reflects it. When false (default), only records the completion.' },
4687
- notifyLead: { type: 'boolean', description: 'Notify the team lead' },
4688
- content: { type: 'string', description: 'Optional richer task description; used as the trajectory step content when training. Defaults to the taskId.' },
4689
- },
4690
- required: ['taskId'],
4691
- },
4692
- handler: async (input) => {
4693
- const taskId = String(input.taskId ?? '');
4694
- const success = input.success !== false;
4695
- const quality = typeof input.quality === 'number' ? input.quality : (success ? 1 : 0);
4696
- const trainPatterns = input.trainPatterns === true;
4697
- const teammateId = input.teammateId ? String(input.teammateId) : undefined;
4698
- // #2241 (OWASP ASI06 Memory/Context Poisoning) — task content is user-
4699
- // supplied and feeds the SONA learning model. Cap length, strip control
4700
- // chars, and reject obvious prompt-injection sentinels before training.
4701
- const rawContent = typeof input.content === 'string' && input.content.trim()
4702
- ? String(input.content)
4703
- : `Task ${taskId} completed (quality=${quality.toFixed(2)})`;
4704
- const content = rawContent
4705
- // Strip ASCII control chars except newline/tab.
4706
- .replace(/[\x00-\x08\x0B-\x1F\x7F]/g, '')
4707
- // Cap to 4 KB — way over a typical trajectory step, well under a memory bomb.
4708
- .slice(0, 4096);
4709
- let patternsLearned = 0;
4710
- let trajectoriesRecorded = 0;
4711
- let learningPath = 'recorded-only';
4712
- let learningError;
4713
- if (trainPatterns) {
4714
- // #2245 — actually feed the learning loop. Synthesize a one-step
4715
- // trajectory from {taskId, success, quality} and run it through the
4716
- // same SONA + EWC + globalStats++ path as hooks_intelligence trajectory-end.
4717
- try {
4718
- const intel = await import('../memory/intelligence.js');
4719
- const before = intel.getIntelligenceStats();
4720
- await intel.recordTrajectory([{
4721
- type: 'result',
4722
- content,
4723
- metadata: { taskId, success, quality, teammateId },
4724
- timestamp: Date.now(),
4725
- }], success ? 'success' : 'failure');
4726
- const after = intel.getIntelligenceStats();
4727
- patternsLearned = Math.max(0, after.patternsLearned - before.patternsLearned);
4728
- trajectoriesRecorded = Math.max(0, after.trajectoriesRecorded - before.trajectoriesRecorded);
4729
- learningPath = 'trajectory-pipeline';
4730
- }
4731
- catch (err) {
4732
- learningError = err.message;
4733
- // Fall back to recorded-only — be honest about it.
4734
- }
4735
- }
4736
- const note = trainPatterns
4737
- ? (learningPath === 'trajectory-pipeline'
4738
- ? `Trained via SONA + EWC++ trajectory pipeline (verdict=${success ? 'success' : 'failure'}, patternsLearned=${patternsLearned}, trajectoriesRecorded=${trajectoriesRecorded}).`
4739
- : `trainPatterns=true but the trajectory pipeline failed (${learningError ?? 'unknown error'}). Completion recorded only.`)
4740
- : 'Completion recorded only. Pass trainPatterns:true (or use hooks_intelligence trajectory-* directly) to feed the learning loop.';
4741
- return {
4742
- success: true,
4743
- taskId,
4744
- patternsLearned,
4745
- trajectoriesRecorded,
4746
- learningPath, // 'trajectory-pipeline' | 'recorded-only'
4747
- leadNotified: input.notifyLead === true,
4748
- metrics: { duration: 0, quality, learningUpdates: patternsLearned },
4749
- ...(learningError ? { learningError } : {}),
4750
- note,
4751
- };
4752
- },
4753
- };
4754
- /**
4755
- * Unified learning-stats aggregator MCP tool (#2245 → ADR-075).
4756
- *
4757
- * One honest call across the four historical stat sources — every sub-view
4758
- * names its store and a `consistency` block flags relationships that drift.
4759
- */
4760
- export const hooksIntelligenceUnifiedStats = {
4761
- name: 'hooks_intelligence_unified-stats',
4762
- description: 'One honest view across the four learning stat sources: globalStats (`.claude-flow/neural/stats.json`), the in-memory SONA coordinator, memory-bridge AgentDB entries, and the neural-patterns store. Each sub-view names its source path. The `consistency` block notes cross-store drift (e.g. globalStats reports N patterns but neural_patterns is empty). See ADR-075. Use when calling the four narrow aggregators (`hooks_intelligence stats`, `memory_stats`, `neural_status`, the SONA coordinator getter) one at a time is wrong because they each see only their own slice and cross-store drift goes silent — this tool surfaces that drift in the `consistency` block, which the narrow APIs cannot.',
4763
- category: 'hooks',
4764
- inputSchema: {
4765
- type: 'object',
4766
- properties: {
4767
- verbose: { type: 'boolean', description: 'Include extended breakdowns', default: true },
4768
- },
4769
- },
4770
- handler: async (_input) => {
4771
- const intel = await import('../memory/intelligence.js');
4772
- return intel.getUnifiedLearningStats();
4773
- },
4774
- };
4775
- // Export all hooks tools
4776
- export const hooksTools = [
4777
- hooksIntelligenceUnifiedStats,
4778
- hooksTeammateIdle,
4779
- hooksTaskCompleted,
4780
- hooksPreEdit,
4781
- hooksPostEdit,
4782
- hooksPreCommand,
4783
- hooksPostCommand,
4784
- hooksRoute,
4785
- hooksMetrics,
4786
- hooksList,
4787
- hooksPreTask,
4788
- hooksPostTask,
4789
- // New hooks
4790
- hooksExplain,
4791
- hooksPretrain,
4792
- hooksBuildAgents,
4793
- hooksTransfer,
4794
- hooksSessionStart,
4795
- hooksSessionEnd,
4796
- hooksSessionRestore,
4797
- hooksNotify,
4798
- hooksInit,
4799
- hooksIntelligence,
4800
- hooksIntelligenceReset,
4801
- hooksTrajectoryStart,
4802
- hooksTrajectoryStep,
4803
- hooksTrajectoryEnd,
4804
- hooksPatternStore,
4805
- hooksPatternSearch,
4806
- hooksIntelligenceStats,
4807
- hooksIntelligenceLearn,
4808
- hooksIntelligenceAttention,
4809
- // Worker tools
4810
- hooksWorkerList,
4811
- hooksWorkerDispatch,
4812
- hooksWorkerStatus,
4813
- hooksWorkerDetect,
4814
- hooksWorkerCancel,
4815
- // Model routing tools
4816
- hooksModelRoute,
4817
- hooksModelOutcome,
4818
- hooksModelStats,
4819
- hooksModelVerify,
4820
- // Deterministic Tier-1 codemod execution (ADR-143)
4821
- hooksCodemod,
4822
- ];
4823
- export default hooksTools;
4824
- //# sourceMappingURL=hooks-tools.js.map