kynjal-cli 3.1.3 → 4.0.0

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 (566) hide show
  1. package/.claude/agents/core/coder.md +1 -1
  2. package/.claude/agents/core/planner.md +2 -2
  3. package/.claude/agents/core/researcher.md +1 -1
  4. package/.claude/agents/core/reviewer.md +1 -1
  5. package/.claude/agents/core/tester.md +1 -1
  6. package/.claude/agents/data/data-ml-model.md +4 -4
  7. package/.claude/agents/development/dev-backend-api.md +4 -4
  8. package/.claude/agents/documentation/docs-api-openapi.md +4 -4
  9. package/.claude/agents/github/code-review-swarm.md +2 -2
  10. package/.claude/agents/github/issue-tracker.md +2 -2
  11. package/.claude/agents/github/pr-manager.md +2 -2
  12. package/.claude/agents/github/release-manager.md +2 -2
  13. package/.claude/agents/github/workflow-automation.md +2 -2
  14. package/.claude/agents/sparc/architecture.md +3 -3
  15. package/.claude/agents/sparc/pseudocode.md +2 -2
  16. package/.claude/agents/sparc/refinement.md +3 -3
  17. package/.claude/agents/sparc/specification.md +2 -2
  18. package/.claude/agents/swarm/adaptive-coordinator.md +1 -1
  19. package/.claude/agents/swarm/hierarchical-coordinator.md +1 -1
  20. package/.claude/agents/swarm/mesh-coordinator.md +1 -1
  21. package/.claude/agents/templates/base-template-generator.md +25 -4
  22. package/.claude/agents/templates/sparc-coordinator.md +3 -3
  23. package/.claude/helpers/auto-commit.sh +1 -1
  24. package/.claude/helpers/auto-memory-hook.mjs +27 -9
  25. package/.claude/helpers/hook-handler.cjs +58 -18
  26. package/.claude/helpers/statusline.cjs +14 -33
  27. package/.claude/helpers/statusline.js +3 -3
  28. package/.claude/settings.json +9 -9
  29. package/.claude/skills/reasoningbank-intelligence/SKILL.md +2 -2
  30. package/.claude/skills/swarm-orchestration/SKILL.md +1 -1
  31. package/README.md +383 -170
  32. package/bin/cli.js +6 -6
  33. package/bin/mcp-server.js +1 -1
  34. package/bin/preinstall.cjs +2 -0
  35. package/dist/src/appliance/gguf-engine.js +664 -0
  36. package/dist/src/appliance/gguf-engine.js.map +1 -0
  37. package/dist/src/appliance/ruvllm-bridge.js +492 -0
  38. package/dist/src/appliance/ruvllm-bridge.js.map +1 -0
  39. package/dist/src/appliance/rvfa-builder.js +383 -0
  40. package/dist/src/appliance/rvfa-builder.js.map +1 -0
  41. package/dist/src/appliance/rvfa-distribution.js +533 -0
  42. package/dist/src/appliance/rvfa-distribution.js.map +1 -0
  43. package/dist/src/appliance/rvfa-format.js +465 -0
  44. package/dist/src/appliance/rvfa-format.js.map +1 -0
  45. package/dist/src/appliance/rvfa-runner.js +373 -0
  46. package/dist/src/appliance/rvfa-runner.js.map +1 -0
  47. package/dist/src/appliance/rvfa-signing.js +469 -0
  48. package/dist/src/appliance/rvfa-signing.js.map +1 -0
  49. package/dist/src/benchmarks/pretrain/index.js +542 -331
  50. package/dist/src/benchmarks/pretrain/index.js.map +1 -1
  51. package/dist/src/commands/agent.d.ts.map +1 -1
  52. package/dist/src/commands/agent.js +725 -502
  53. package/dist/src/commands/agent.js.map +1 -1
  54. package/dist/src/commands/analyze.js +1548 -1218
  55. package/dist/src/commands/analyze.js.map +1 -1
  56. package/dist/src/commands/appliance-advanced.d.ts +9 -0
  57. package/dist/src/commands/appliance-advanced.d.ts.map +1 -0
  58. package/dist/src/commands/appliance-advanced.js +324 -0
  59. package/dist/src/commands/appliance-advanced.js.map +1 -0
  60. package/dist/src/commands/appliance.d.ts +8 -0
  61. package/dist/src/commands/appliance.d.ts.map +1 -0
  62. package/dist/src/commands/appliance.js +581 -0
  63. package/dist/src/commands/appliance.js.map +1 -0
  64. package/dist/src/commands/benchmark.js +523 -372
  65. package/dist/src/commands/benchmark.js.map +1 -1
  66. package/dist/src/commands/claims.js +364 -274
  67. package/dist/src/commands/claims.js.map +1 -1
  68. package/dist/src/commands/cleanup.d.ts +13 -0
  69. package/dist/src/commands/cleanup.d.ts.map +1 -0
  70. package/dist/src/commands/cleanup.js +262 -0
  71. package/dist/src/commands/cleanup.js.map +1 -0
  72. package/dist/src/commands/completions.js +118 -477
  73. package/dist/src/commands/completions.js.map +1 -1
  74. package/dist/src/commands/config.js +303 -237
  75. package/dist/src/commands/config.js.map +1 -1
  76. package/dist/src/commands/daemon.d.ts.map +1 -1
  77. package/dist/src/commands/daemon.js +597 -425
  78. package/dist/src/commands/daemon.js.map +1 -1
  79. package/dist/src/commands/deployment.js +275 -194
  80. package/dist/src/commands/deployment.js.map +1 -1
  81. package/dist/src/commands/doctor.d.ts.map +1 -1
  82. package/dist/src/commands/doctor.js +690 -460
  83. package/dist/src/commands/doctor.js.map +1 -1
  84. package/dist/src/commands/embeddings.js +1543 -1293
  85. package/dist/src/commands/embeddings.js.map +1 -1
  86. package/dist/src/commands/guidance.js +596 -449
  87. package/dist/src/commands/guidance.js.map +1 -1
  88. package/dist/src/commands/hive-mind.js +938 -854
  89. package/dist/src/commands/hive-mind.js.map +1 -1
  90. package/dist/src/commands/hooks.d.ts.map +1 -1
  91. package/dist/src/commands/hooks.js +3677 -2570
  92. package/dist/src/commands/hooks.js.map +1 -1
  93. package/dist/src/commands/index.js +322 -122
  94. package/dist/src/commands/index.js.map +1 -1
  95. package/dist/src/commands/init.d.ts +1 -1
  96. package/dist/src/commands/init.d.ts.map +1 -1
  97. package/dist/src/commands/init.js +943 -787
  98. package/dist/src/commands/init.js.map +1 -1
  99. package/dist/src/commands/issues.js +558 -383
  100. package/dist/src/commands/issues.js.map +1 -1
  101. package/dist/src/commands/mcp.d.ts.map +1 -1
  102. package/dist/src/commands/mcp.js +605 -475
  103. package/dist/src/commands/mcp.js.map +1 -1
  104. package/dist/src/commands/memory.d.ts.map +1 -1
  105. package/dist/src/commands/memory.js +1031 -814
  106. package/dist/src/commands/memory.js.map +1 -1
  107. package/dist/src/commands/migrate.js +347 -282
  108. package/dist/src/commands/migrate.js.map +1 -1
  109. package/dist/src/commands/neural.d.ts.map +1 -1
  110. package/dist/src/commands/neural.js +1563 -1283
  111. package/dist/src/commands/neural.js.map +1 -1
  112. package/dist/src/commands/performance.js +643 -497
  113. package/dist/src/commands/performance.js.map +1 -1
  114. package/dist/src/commands/plugins.js +841 -668
  115. package/dist/src/commands/plugins.js.map +1 -1
  116. package/dist/src/commands/process.js +447 -392
  117. package/dist/src/commands/process.js.map +1 -1
  118. package/dist/src/commands/progress.js +256 -162
  119. package/dist/src/commands/progress.js.map +1 -1
  120. package/dist/src/commands/providers.js +220 -150
  121. package/dist/src/commands/providers.js.map +1 -1
  122. package/dist/src/commands/route.js +665 -520
  123. package/dist/src/commands/route.js.map +1 -1
  124. package/dist/src/commands/ruvector/backup.js +651 -505
  125. package/dist/src/commands/ruvector/backup.js.map +1 -1
  126. package/dist/src/commands/ruvector/benchmark.js +401 -349
  127. package/dist/src/commands/ruvector/benchmark.js.map +1 -1
  128. package/dist/src/commands/ruvector/import.js +267 -225
  129. package/dist/src/commands/ruvector/import.js.map +1 -1
  130. package/dist/src/commands/ruvector/index.js +75 -37
  131. package/dist/src/commands/ruvector/index.js.map +1 -1
  132. package/dist/src/commands/ruvector/init.js +359 -336
  133. package/dist/src/commands/ruvector/init.js.map +1 -1
  134. package/dist/src/commands/ruvector/migrate.js +322 -335
  135. package/dist/src/commands/ruvector/migrate.js.map +1 -1
  136. package/dist/src/commands/ruvector/optimize.js +431 -375
  137. package/dist/src/commands/ruvector/optimize.js.map +1 -1
  138. package/dist/src/commands/ruvector/setup.js +117 -703
  139. package/dist/src/commands/ruvector/setup.js.map +1 -1
  140. package/dist/src/commands/ruvector/status.js +419 -364
  141. package/dist/src/commands/ruvector/status.js.map +1 -1
  142. package/dist/src/commands/security.d.ts.map +1 -1
  143. package/dist/src/commands/security.js +610 -456
  144. package/dist/src/commands/security.js.map +1 -1
  145. package/dist/src/commands/session.d.ts +1 -1
  146. package/dist/src/commands/session.js +627 -505
  147. package/dist/src/commands/session.js.map +1 -1
  148. package/dist/src/commands/start.d.ts +1 -1
  149. package/dist/src/commands/start.js +368 -271
  150. package/dist/src/commands/start.js.map +1 -1
  151. package/dist/src/commands/status.d.ts +1 -1
  152. package/dist/src/commands/status.d.ts.map +1 -1
  153. package/dist/src/commands/status.js +492 -379
  154. package/dist/src/commands/status.js.map +1 -1
  155. package/dist/src/commands/swarm.js +488 -408
  156. package/dist/src/commands/swarm.js.map +1 -1
  157. package/dist/src/commands/task.d.ts +1 -1
  158. package/dist/src/commands/task.js +539 -424
  159. package/dist/src/commands/task.js.map +1 -1
  160. package/dist/src/commands/transfer-store.js +412 -322
  161. package/dist/src/commands/transfer-store.js.map +1 -1
  162. package/dist/src/commands/update.js +291 -196
  163. package/dist/src/commands/update.js.map +1 -1
  164. package/dist/src/commands/workflow.js +486 -386
  165. package/dist/src/commands/workflow.js.map +1 -1
  166. package/dist/src/config-adapter.js +40 -39
  167. package/dist/src/config-adapter.js.map +1 -1
  168. package/dist/src/index.js +416 -312
  169. package/dist/src/index.js.map +1 -1
  170. package/dist/src/infrastructure/in-memory-repositories.js +507 -246
  171. package/dist/src/infrastructure/in-memory-repositories.js.map +1 -1
  172. package/dist/src/init/claudemd-generator.js +78 -368
  173. package/dist/src/init/claudemd-generator.js.map +1 -1
  174. package/dist/src/init/executor.js +1019 -1345
  175. package/dist/src/init/executor.js.map +1 -1
  176. package/dist/src/init/helpers-generator.js +60 -635
  177. package/dist/src/init/helpers-generator.js.map +1 -1
  178. package/dist/src/init/index.d.ts +1 -1
  179. package/dist/src/init/index.d.ts.map +1 -1
  180. package/dist/src/init/index.js +1 -1
  181. package/dist/src/init/index.js.map +1 -1
  182. package/dist/src/init/mcp-generator.d.ts +0 -1
  183. package/dist/src/init/mcp-generator.d.ts.map +1 -1
  184. package/dist/src/init/mcp-generator.js +62 -42
  185. package/dist/src/init/mcp-generator.js.map +1 -1
  186. package/dist/src/init/settings-generator.d.ts.map +1 -1
  187. package/dist/src/init/settings-generator.js +167 -100
  188. package/dist/src/init/settings-generator.js.map +1 -1
  189. package/dist/src/init/statusline-generator.d.ts +16 -8
  190. package/dist/src/init/statusline-generator.d.ts.map +1 -1
  191. package/dist/src/init/statusline-generator.js +20 -1300
  192. package/dist/src/init/statusline-generator.js.map +1 -1
  193. package/dist/src/init/types.d.ts +15 -5
  194. package/dist/src/init/types.d.ts.map +1 -1
  195. package/dist/src/init/types.js +66 -76
  196. package/dist/src/init/types.js.map +1 -1
  197. package/dist/src/mcp-client.js +130 -76
  198. package/dist/src/mcp-client.js.map +1 -1
  199. package/dist/src/mcp-server.js +758 -445
  200. package/dist/src/mcp-server.js.map +1 -1
  201. package/dist/src/mcp-tools/agent-tools.js +492 -391
  202. package/dist/src/mcp-tools/agent-tools.js.map +1 -1
  203. package/dist/src/mcp-tools/agentdb-tools.d.ts +30 -0
  204. package/dist/src/mcp-tools/agentdb-tools.d.ts.map +1 -0
  205. package/dist/src/mcp-tools/agentdb-tools.js +758 -0
  206. package/dist/src/mcp-tools/agentdb-tools.js.map +1 -0
  207. package/dist/src/mcp-tools/analyze-tools.js +236 -172
  208. package/dist/src/mcp-tools/analyze-tools.js.map +1 -1
  209. package/dist/src/mcp-tools/auto-install.js +142 -80
  210. package/dist/src/mcp-tools/auto-install.js.map +1 -1
  211. package/dist/src/mcp-tools/browser-tools.js +375 -252
  212. package/dist/src/mcp-tools/browser-tools.js.map +1 -1
  213. package/dist/src/mcp-tools/claims-tools.js +565 -473
  214. package/dist/src/mcp-tools/claims-tools.js.map +1 -1
  215. package/dist/src/mcp-tools/config-tools.d.ts.map +1 -1
  216. package/dist/src/mcp-tools/config-tools.js +284 -190
  217. package/dist/src/mcp-tools/config-tools.js.map +1 -1
  218. package/dist/src/mcp-tools/coordination-tools.d.ts.map +1 -1
  219. package/dist/src/mcp-tools/coordination-tools.js +600 -349
  220. package/dist/src/mcp-tools/coordination-tools.js.map +1 -1
  221. package/dist/src/mcp-tools/daa-tools.js +367 -289
  222. package/dist/src/mcp-tools/daa-tools.js.map +1 -1
  223. package/dist/src/mcp-tools/embeddings-tools.js +693 -582
  224. package/dist/src/mcp-tools/embeddings-tools.js.map +1 -1
  225. package/dist/src/mcp-tools/github-tools.js +312 -261
  226. package/dist/src/mcp-tools/github-tools.js.map +1 -1
  227. package/dist/src/mcp-tools/hive-mind-tools.d.ts.map +1 -1
  228. package/dist/src/mcp-tools/hive-mind-tools.js +718 -423
  229. package/dist/src/mcp-tools/hive-mind-tools.js.map +1 -1
  230. package/dist/src/mcp-tools/hooks-tools.d.ts.map +1 -1
  231. package/dist/src/mcp-tools/hooks-tools.js +2726 -1978
  232. package/dist/src/mcp-tools/hooks-tools.js.map +1 -1
  233. package/dist/src/mcp-tools/index.d.ts +2 -0
  234. package/dist/src/mcp-tools/index.d.ts.map +1 -1
  235. package/dist/src/mcp-tools/index.js +2 -0
  236. package/dist/src/mcp-tools/index.js.map +1 -1
  237. package/dist/src/mcp-tools/memory-tools.d.ts.map +1 -1
  238. package/dist/src/mcp-tools/memory-tools.js +514 -329
  239. package/dist/src/mcp-tools/memory-tools.js.map +1 -1
  240. package/dist/src/mcp-tools/neural-tools.d.ts.map +1 -1
  241. package/dist/src/mcp-tools/neural-tools.js +428 -326
  242. package/dist/src/mcp-tools/neural-tools.js.map +1 -1
  243. package/dist/src/mcp-tools/performance-tools.js +480 -420
  244. package/dist/src/mcp-tools/performance-tools.js.map +1 -1
  245. package/dist/src/mcp-tools/progress-tools.js +278 -204
  246. package/dist/src/mcp-tools/progress-tools.js.map +1 -1
  247. package/dist/src/mcp-tools/ruvllm-tools.d.ts +9 -0
  248. package/dist/src/mcp-tools/ruvllm-tools.d.ts.map +1 -0
  249. package/dist/src/mcp-tools/ruvllm-tools.js +399 -0
  250. package/dist/src/mcp-tools/ruvllm-tools.js.map +1 -0
  251. package/dist/src/mcp-tools/security-tools.js +429 -297
  252. package/dist/src/mcp-tools/security-tools.js.map +1 -1
  253. package/dist/src/mcp-tools/session-tools.js +234 -185
  254. package/dist/src/mcp-tools/session-tools.js.map +1 -1
  255. package/dist/src/mcp-tools/swarm-tools.d.ts +2 -1
  256. package/dist/src/mcp-tools/swarm-tools.d.ts.map +1 -1
  257. package/dist/src/mcp-tools/swarm-tools.js +303 -64
  258. package/dist/src/mcp-tools/swarm-tools.js.map +1 -1
  259. package/dist/src/mcp-tools/system-tools.d.ts.map +1 -1
  260. package/dist/src/mcp-tools/system-tools.js +352 -200
  261. package/dist/src/mcp-tools/system-tools.js.map +1 -1
  262. package/dist/src/mcp-tools/task-tools.d.ts.map +1 -1
  263. package/dist/src/mcp-tools/task-tools.js +357 -189
  264. package/dist/src/mcp-tools/task-tools.js.map +1 -1
  265. package/dist/src/mcp-tools/terminal-tools.js +196 -148
  266. package/dist/src/mcp-tools/terminal-tools.js.map +1 -1
  267. package/dist/src/mcp-tools/transfer-tools.js +333 -186
  268. package/dist/src/mcp-tools/transfer-tools.js.map +1 -1
  269. package/dist/src/mcp-tools/wasm-agent-tools.d.ts +9 -0
  270. package/dist/src/mcp-tools/wasm-agent-tools.d.ts.map +1 -0
  271. package/dist/src/mcp-tools/wasm-agent-tools.js +377 -0
  272. package/dist/src/mcp-tools/wasm-agent-tools.js.map +1 -0
  273. package/dist/src/mcp-tools/workflow-tools.d.ts.map +1 -1
  274. package/dist/src/mcp-tools/workflow-tools.js +471 -335
  275. package/dist/src/mcp-tools/workflow-tools.js.map +1 -1
  276. package/dist/src/memory/ewc-consolidation.js +345 -173
  277. package/dist/src/memory/ewc-consolidation.js.map +1 -1
  278. package/dist/src/memory/intelligence.js +841 -359
  279. package/dist/src/memory/intelligence.js.map +1 -1
  280. package/dist/src/memory/memory-bridge.js +1964 -0
  281. package/dist/src/memory/memory-bridge.js.map +1 -0
  282. package/dist/src/memory/memory-initializer.js +1895 -1602
  283. package/dist/src/memory/memory-initializer.js.map +1 -1
  284. package/dist/src/memory/sona-optimizer.js +329 -199
  285. package/dist/src/memory/sona-optimizer.js.map +1 -1
  286. package/dist/src/output.d.ts +2 -2
  287. package/dist/src/output.d.ts.map +1 -1
  288. package/dist/src/output.js +273 -242
  289. package/dist/src/output.js.map +1 -1
  290. package/dist/src/parser.js +217 -124
  291. package/dist/src/parser.js.map +1 -1
  292. package/dist/src/plugins/manager.js +531 -278
  293. package/dist/src/plugins/manager.js.map +1 -1
  294. package/dist/src/plugins/store/discovery.js +362 -275
  295. package/dist/src/plugins/store/discovery.js.map +1 -1
  296. package/dist/src/plugins/store/index.js +105 -48
  297. package/dist/src/plugins/store/index.js.map +1 -1
  298. package/dist/src/plugins/store/search.js +107 -69
  299. package/dist/src/plugins/store/search.js.map +1 -1
  300. package/dist/src/plugins/tests/demo-plugin-store.js +160 -113
  301. package/dist/src/plugins/tests/demo-plugin-store.js.map +1 -1
  302. package/dist/src/plugins/tests/standalone-test.js +223 -172
  303. package/dist/src/plugins/tests/standalone-test.js.map +1 -1
  304. package/dist/src/plugins/tests/test-plugin-store.js +228 -190
  305. package/dist/src/plugins/tests/test-plugin-store.js.map +1 -1
  306. package/dist/src/production/circuit-breaker.js +126 -62
  307. package/dist/src/production/circuit-breaker.js.map +1 -1
  308. package/dist/src/production/error-handler.js +156 -86
  309. package/dist/src/production/error-handler.js.map +1 -1
  310. package/dist/src/production/monitoring.js +220 -139
  311. package/dist/src/production/monitoring.js.map +1 -1
  312. package/dist/src/production/rate-limiter.js +93 -74
  313. package/dist/src/production/rate-limiter.js.map +1 -1
  314. package/dist/src/production/retry.js +167 -75
  315. package/dist/src/production/retry.js.map +1 -1
  316. package/dist/src/prompt.js +560 -436
  317. package/dist/src/prompt.js.map +1 -1
  318. package/dist/src/runtime/headless.js +289 -200
  319. package/dist/src/runtime/headless.js.map +1 -1
  320. package/dist/src/ruvector/agent-wasm.js +511 -0
  321. package/dist/src/ruvector/agent-wasm.js.map +1 -0
  322. package/dist/src/ruvector/ast-analyzer.js +232 -145
  323. package/dist/src/ruvector/ast-analyzer.js.map +1 -1
  324. package/dist/src/ruvector/coverage-router.js +419 -287
  325. package/dist/src/ruvector/coverage-router.js.map +1 -1
  326. package/dist/src/ruvector/coverage-tools.js +101 -56
  327. package/dist/src/ruvector/coverage-tools.js.map +1 -1
  328. package/dist/src/ruvector/diff-classifier.js +451 -324
  329. package/dist/src/ruvector/diff-classifier.js.map +1 -1
  330. package/dist/src/ruvector/enhanced-model-router.js +337 -251
  331. package/dist/src/ruvector/enhanced-model-router.js.map +1 -1
  332. package/dist/src/ruvector/flash-attention.js +254 -223
  333. package/dist/src/ruvector/flash-attention.js.map +1 -1
  334. package/dist/src/ruvector/graph-analyzer.js +680 -486
  335. package/dist/src/ruvector/graph-analyzer.js.map +1 -1
  336. package/dist/src/ruvector/index.js +113 -27
  337. package/dist/src/ruvector/index.js.map +1 -1
  338. package/dist/src/ruvector/lora-adapter.js +248 -155
  339. package/dist/src/ruvector/lora-adapter.js.map +1 -1
  340. package/dist/src/ruvector/model-router.js +248 -175
  341. package/dist/src/ruvector/model-router.js.map +1 -1
  342. package/dist/src/ruvector/moe-router.js +286 -228
  343. package/dist/src/ruvector/moe-router.js.map +1 -1
  344. package/dist/src/ruvector/q-learning-router.js +338 -257
  345. package/dist/src/ruvector/q-learning-router.js.map +1 -1
  346. package/dist/src/ruvector/ruvllm-wasm.js +527 -0
  347. package/dist/src/ruvector/ruvllm-wasm.js.map +1 -0
  348. package/dist/src/ruvector/semantic-router.js +67 -60
  349. package/dist/src/ruvector/semantic-router.js.map +1 -1
  350. package/dist/src/ruvector/vector-db.js +205 -119
  351. package/dist/src/ruvector/vector-db.js.map +1 -1
  352. package/dist/src/services/agentic-flow-bridge.js +168 -0
  353. package/dist/src/services/agentic-flow-bridge.js.map +1 -0
  354. package/dist/src/services/claim-service.js +940 -615
  355. package/dist/src/services/claim-service.js.map +1 -1
  356. package/dist/src/services/container-worker-pool.js +669 -399
  357. package/dist/src/services/container-worker-pool.js.map +1 -1
  358. package/dist/src/services/headless-worker-executor.js +467 -441
  359. package/dist/src/services/headless-worker-executor.js.map +1 -1
  360. package/dist/src/services/index.d.ts +5 -5
  361. package/dist/src/services/index.d.ts.map +1 -1
  362. package/dist/src/services/index.js +4 -4
  363. package/dist/src/services/index.js.map +1 -1
  364. package/dist/src/services/registry-api.js +201 -93
  365. package/dist/src/services/registry-api.js.map +1 -1
  366. package/dist/src/services/ruvector-training.js +414 -144
  367. package/dist/src/services/ruvector-training.js.map +1 -1
  368. package/dist/src/services/worker-daemon.js +928 -531
  369. package/dist/src/services/worker-daemon.js.map +1 -1
  370. package/dist/src/services/worker-queue.js +550 -331
  371. package/dist/src/services/worker-queue.js.map +1 -1
  372. package/dist/src/suggest.js +55 -45
  373. package/dist/src/suggest.js.map +1 -1
  374. package/dist/src/transfer/anonymization/index.js +37 -29
  375. package/dist/src/transfer/anonymization/index.js.map +1 -1
  376. package/dist/src/transfer/deploy-seraphine.d.ts +1 -1
  377. package/dist/src/transfer/deploy-seraphine.js +156 -129
  378. package/dist/src/transfer/deploy-seraphine.js.map +1 -1
  379. package/dist/src/transfer/export.js +142 -84
  380. package/dist/src/transfer/export.js.map +1 -1
  381. package/dist/src/transfer/index.d.ts +1 -1
  382. package/dist/src/transfer/index.d.ts.map +1 -1
  383. package/dist/src/transfer/index.js +2 -0
  384. package/dist/src/transfer/index.js.map +1 -1
  385. package/dist/src/transfer/ipfs/client.js +337 -179
  386. package/dist/src/transfer/ipfs/client.js.map +1 -1
  387. package/dist/src/transfer/ipfs/upload.js +434 -290
  388. package/dist/src/transfer/ipfs/upload.js.map +1 -1
  389. package/dist/src/transfer/models/seraphine.js +58 -58
  390. package/dist/src/transfer/models/seraphine.js.map +1 -1
  391. package/dist/src/transfer/serialization/cfp.js +37 -33
  392. package/dist/src/transfer/serialization/cfp.js.map +1 -1
  393. package/dist/src/transfer/storage/gcs.js +248 -139
  394. package/dist/src/transfer/storage/gcs.js.map +1 -1
  395. package/dist/src/transfer/store/discovery.js +353 -243
  396. package/dist/src/transfer/store/discovery.js.map +1 -1
  397. package/dist/src/transfer/store/download.js +365 -243
  398. package/dist/src/transfer/store/download.js.map +1 -1
  399. package/dist/src/transfer/store/index.js +130 -63
  400. package/dist/src/transfer/store/index.js.map +1 -1
  401. package/dist/src/transfer/store/publish.js +258 -184
  402. package/dist/src/transfer/store/publish.js.map +1 -1
  403. package/dist/src/transfer/store/registry.js +73 -51
  404. package/dist/src/transfer/store/registry.js.map +1 -1
  405. package/dist/src/transfer/store/search.js +96 -64
  406. package/dist/src/transfer/store/search.js.map +1 -1
  407. package/dist/src/transfer/store/tests/standalone-test.js +231 -174
  408. package/dist/src/transfer/store/tests/standalone-test.js.map +1 -1
  409. package/dist/src/transfer/test-seraphine.js +130 -95
  410. package/dist/src/transfer/test-seraphine.js.map +1 -1
  411. package/dist/src/transfer/tests/test-store.js +239 -194
  412. package/dist/src/transfer/tests/test-store.js.map +1 -1
  413. package/dist/src/types.js +56 -27
  414. package/dist/src/types.js.map +1 -1
  415. package/dist/src/update/checker.js +183 -106
  416. package/dist/src/update/checker.js.map +1 -1
  417. package/dist/src/update/executor.js +198 -135
  418. package/dist/src/update/executor.js.map +1 -1
  419. package/dist/src/update/index.js +85 -38
  420. package/dist/src/update/index.js.map +1 -1
  421. package/dist/src/update/rate-limiter.js +31 -19
  422. package/dist/src/update/rate-limiter.js.map +1 -1
  423. package/dist/src/update/validator.js +64 -38
  424. package/dist/src/update/validator.js.map +1 -1
  425. package/dist/tsconfig.tsbuildinfo +1 -1
  426. package/package.json +13 -10
  427. package/.claude/agents/custom/accessibility-auditor.yaml +0 -56
  428. package/.claude/agents/custom/design-architect.yaml +0 -48
  429. package/.claude/agents/custom/ui-developer.yaml +0 -46
  430. package/.claude/agents/custom/ux-researcher.yaml +0 -60
  431. package/dist/src/benchmarks/pretrain/index.d.ts +0 -58
  432. package/dist/src/benchmarks/pretrain/index.d.ts.map +0 -1
  433. package/dist/src/commands/index.d.ts +0 -108
  434. package/dist/src/commands/index.d.ts.map +0 -1
  435. package/dist/src/config-adapter.d.ts +0 -15
  436. package/dist/src/config-adapter.d.ts.map +0 -1
  437. package/dist/src/index.d.ts +0 -76
  438. package/dist/src/index.d.ts.map +0 -1
  439. package/dist/src/infrastructure/in-memory-repositories.d.ts +0 -68
  440. package/dist/src/infrastructure/in-memory-repositories.d.ts.map +0 -1
  441. package/dist/src/init/claudemd-generator.d.ts +0 -25
  442. package/dist/src/init/claudemd-generator.d.ts.map +0 -1
  443. package/dist/src/init/executor.d.ts +0 -41
  444. package/dist/src/init/executor.d.ts.map +0 -1
  445. package/dist/src/init/helpers-generator.d.ts +0 -60
  446. package/dist/src/init/helpers-generator.d.ts.map +0 -1
  447. package/dist/src/mcp-client.d.ts +0 -92
  448. package/dist/src/mcp-client.d.ts.map +0 -1
  449. package/dist/src/mcp-server.d.ts +0 -161
  450. package/dist/src/mcp-server.d.ts.map +0 -1
  451. package/dist/src/mcp-tools/auto-install.d.ts +0 -83
  452. package/dist/src/mcp-tools/auto-install.d.ts.map +0 -1
  453. package/dist/src/mcp-tools/types.d.ts +0 -31
  454. package/dist/src/mcp-tools/types.d.ts.map +0 -1
  455. package/dist/src/memory/ewc-consolidation.d.ts +0 -271
  456. package/dist/src/memory/ewc-consolidation.d.ts.map +0 -1
  457. package/dist/src/memory/intelligence.d.ts +0 -285
  458. package/dist/src/memory/intelligence.d.ts.map +0 -1
  459. package/dist/src/memory/memory-initializer.d.ts +0 -396
  460. package/dist/src/memory/memory-initializer.d.ts.map +0 -1
  461. package/dist/src/memory/sona-optimizer.d.ts +0 -227
  462. package/dist/src/memory/sona-optimizer.d.ts.map +0 -1
  463. package/dist/src/parser.d.ts +0 -41
  464. package/dist/src/parser.d.ts.map +0 -1
  465. package/dist/src/plugins/manager.d.ts +0 -133
  466. package/dist/src/plugins/manager.d.ts.map +0 -1
  467. package/dist/src/plugins/store/discovery.d.ts +0 -88
  468. package/dist/src/plugins/store/discovery.d.ts.map +0 -1
  469. package/dist/src/plugins/store/index.d.ts +0 -76
  470. package/dist/src/plugins/store/index.d.ts.map +0 -1
  471. package/dist/src/plugins/store/search.d.ts +0 -46
  472. package/dist/src/plugins/store/search.d.ts.map +0 -1
  473. package/dist/src/plugins/store/types.d.ts +0 -274
  474. package/dist/src/plugins/store/types.d.ts.map +0 -1
  475. package/dist/src/production/circuit-breaker.d.ts +0 -101
  476. package/dist/src/production/circuit-breaker.d.ts.map +0 -1
  477. package/dist/src/production/error-handler.d.ts +0 -92
  478. package/dist/src/production/error-handler.d.ts.map +0 -1
  479. package/dist/src/production/monitoring.d.ts +0 -161
  480. package/dist/src/production/monitoring.d.ts.map +0 -1
  481. package/dist/src/production/rate-limiter.d.ts +0 -80
  482. package/dist/src/production/rate-limiter.d.ts.map +0 -1
  483. package/dist/src/production/retry.d.ts +0 -48
  484. package/dist/src/production/retry.d.ts.map +0 -1
  485. package/dist/src/prompt.d.ts +0 -44
  486. package/dist/src/prompt.d.ts.map +0 -1
  487. package/dist/src/runtime/headless.d.ts +0 -60
  488. package/dist/src/runtime/headless.d.ts.map +0 -1
  489. package/dist/src/ruvector/ast-analyzer.d.ts +0 -67
  490. package/dist/src/ruvector/ast-analyzer.d.ts.map +0 -1
  491. package/dist/src/ruvector/coverage-router.d.ts +0 -160
  492. package/dist/src/ruvector/coverage-router.d.ts.map +0 -1
  493. package/dist/src/ruvector/diff-classifier.d.ts +0 -175
  494. package/dist/src/ruvector/diff-classifier.d.ts.map +0 -1
  495. package/dist/src/ruvector/enhanced-model-router.d.ts +0 -146
  496. package/dist/src/ruvector/enhanced-model-router.d.ts.map +0 -1
  497. package/dist/src/ruvector/flash-attention.d.ts +0 -195
  498. package/dist/src/ruvector/flash-attention.d.ts.map +0 -1
  499. package/dist/src/ruvector/graph-analyzer.d.ts +0 -187
  500. package/dist/src/ruvector/graph-analyzer.d.ts.map +0 -1
  501. package/dist/src/ruvector/index.d.ts +0 -34
  502. package/dist/src/ruvector/index.d.ts.map +0 -1
  503. package/dist/src/ruvector/lora-adapter.d.ts +0 -218
  504. package/dist/src/ruvector/lora-adapter.d.ts.map +0 -1
  505. package/dist/src/ruvector/model-router.d.ts +0 -220
  506. package/dist/src/ruvector/model-router.d.ts.map +0 -1
  507. package/dist/src/ruvector/moe-router.d.ts +0 -206
  508. package/dist/src/ruvector/moe-router.d.ts.map +0 -1
  509. package/dist/src/ruvector/q-learning-router.d.ts +0 -211
  510. package/dist/src/ruvector/q-learning-router.d.ts.map +0 -1
  511. package/dist/src/ruvector/semantic-router.d.ts +0 -77
  512. package/dist/src/ruvector/semantic-router.d.ts.map +0 -1
  513. package/dist/src/ruvector/vector-db.d.ts +0 -69
  514. package/dist/src/ruvector/vector-db.d.ts.map +0 -1
  515. package/dist/src/services/claim-service.d.ts +0 -204
  516. package/dist/src/services/claim-service.d.ts.map +0 -1
  517. package/dist/src/services/container-worker-pool.d.ts +0 -197
  518. package/dist/src/services/container-worker-pool.d.ts.map +0 -1
  519. package/dist/src/services/headless-worker-executor.d.ts +0 -304
  520. package/dist/src/services/headless-worker-executor.d.ts.map +0 -1
  521. package/dist/src/services/registry-api.d.ts +0 -58
  522. package/dist/src/services/registry-api.d.ts.map +0 -1
  523. package/dist/src/services/ruvector-training.d.ts +0 -213
  524. package/dist/src/services/ruvector-training.d.ts.map +0 -1
  525. package/dist/src/services/worker-daemon.d.ts +0 -203
  526. package/dist/src/services/worker-daemon.d.ts.map +0 -1
  527. package/dist/src/services/worker-queue.d.ts +0 -194
  528. package/dist/src/services/worker-queue.d.ts.map +0 -1
  529. package/dist/src/suggest.d.ts +0 -53
  530. package/dist/src/suggest.d.ts.map +0 -1
  531. package/dist/src/transfer/export.d.ts +0 -25
  532. package/dist/src/transfer/export.d.ts.map +0 -1
  533. package/dist/src/transfer/ipfs/client.d.ts +0 -109
  534. package/dist/src/transfer/ipfs/client.d.ts.map +0 -1
  535. package/dist/src/transfer/ipfs/upload.d.ts +0 -95
  536. package/dist/src/transfer/ipfs/upload.d.ts.map +0 -1
  537. package/dist/src/transfer/models/seraphine.d.ts +0 -72
  538. package/dist/src/transfer/models/seraphine.d.ts.map +0 -1
  539. package/dist/src/transfer/serialization/cfp.d.ts +0 -49
  540. package/dist/src/transfer/serialization/cfp.d.ts.map +0 -1
  541. package/dist/src/transfer/storage/gcs.d.ts +0 -82
  542. package/dist/src/transfer/storage/gcs.d.ts.map +0 -1
  543. package/dist/src/transfer/store/discovery.d.ts +0 -84
  544. package/dist/src/transfer/store/discovery.d.ts.map +0 -1
  545. package/dist/src/transfer/store/download.d.ts +0 -70
  546. package/dist/src/transfer/store/download.d.ts.map +0 -1
  547. package/dist/src/transfer/store/index.d.ts +0 -84
  548. package/dist/src/transfer/store/index.d.ts.map +0 -1
  549. package/dist/src/transfer/store/publish.d.ts +0 -76
  550. package/dist/src/transfer/store/publish.d.ts.map +0 -1
  551. package/dist/src/transfer/store/search.d.ts +0 -54
  552. package/dist/src/transfer/store/search.d.ts.map +0 -1
  553. package/dist/src/transfer/types.d.ts +0 -245
  554. package/dist/src/transfer/types.d.ts.map +0 -1
  555. package/dist/src/types.d.ts +0 -198
  556. package/dist/src/types.d.ts.map +0 -1
  557. package/dist/src/update/checker.d.ts +0 -34
  558. package/dist/src/update/checker.d.ts.map +0 -1
  559. package/dist/src/update/executor.d.ts +0 -32
  560. package/dist/src/update/executor.d.ts.map +0 -1
  561. package/dist/src/update/index.d.ts +0 -33
  562. package/dist/src/update/index.d.ts.map +0 -1
  563. package/dist/src/update/rate-limiter.d.ts +0 -20
  564. package/dist/src/update/rate-limiter.d.ts.map +0 -1
  565. package/dist/src/update/validator.d.ts +0 -17
  566. package/dist/src/update/validator.d.ts.map +0 -1
@@ -4,327 +4,422 @@
4
4
  *
5
5
  * Created with ❤️ by ruv.io
6
6
  */
7
+ var __assign = (this && this.__assign) || function () {
8
+ __assign = Object.assign || function(t) {
9
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
10
+ s = arguments[i];
11
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
12
+ t[p] = s[p];
13
+ }
14
+ return t;
15
+ };
16
+ return __assign.apply(this, arguments);
17
+ };
18
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
19
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
20
+ return new (P || (P = Promise))(function (resolve, reject) {
21
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
23
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
24
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
25
+ });
26
+ };
27
+ var __generator = (this && this.__generator) || function (thisArg, body) {
28
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
29
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
30
+ function verb(n) { return function (v) { return step([n, v]); }; }
31
+ function step(op) {
32
+ if (f) throw new TypeError("Generator is already executing.");
33
+ while (_) try {
34
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
35
+ if (y = 0, t) op = [op[0] & 2, t.value];
36
+ switch (op[0]) {
37
+ case 0: case 1: t = op; break;
38
+ case 4: _.label++; return { value: op[1], done: false };
39
+ case 5: _.label++; y = op[1]; op = [0]; continue;
40
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
41
+ default:
42
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
43
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
44
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
45
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
46
+ if (t[2]) _.ops.pop();
47
+ _.trys.pop(); continue;
48
+ }
49
+ op = body.call(thisArg, _);
50
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
51
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
52
+ }
53
+ };
54
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
55
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
56
+ if (ar || !(i in from)) {
57
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
58
+ ar[i] = from[i];
59
+ }
60
+ }
61
+ return to.concat(ar || Array.prototype.slice.call(from));
62
+ };
7
63
  import { output } from '../output.js';
8
64
  // Train subcommand - REAL WASM training with RuVector
9
- const trainCommand = {
65
+ var trainCommand = {
10
66
  name: 'train',
11
67
  description: 'Train neural patterns with WASM SIMD acceleration (MicroLoRA + Flash Attention)',
12
68
  options: [
13
- { name: 'pattern', short: 'p', type: 'string', description: 'Pattern type: coordination, optimization, prediction, security, testing', default: 'coordination' },
14
- { name: 'epochs', short: 'e', type: 'number', description: 'Number of training epochs', default: '50' },
69
+ { name: 'pattern', short: 'p', type: 'string', description: 'Pattern type: coordination, optimization, prediction, security, testing', "default": 'coordination' },
70
+ { name: 'epochs', short: 'e', type: 'number', description: 'Number of training epochs', "default": '50' },
15
71
  { name: 'data', short: 'd', type: 'string', description: 'Training data file or inline JSON' },
16
72
  { name: 'model', short: 'm', type: 'string', description: 'Model ID to train' },
17
- { name: 'learning-rate', short: 'l', type: 'number', description: 'Learning rate', default: '0.01' },
18
- { name: 'batch-size', short: 'b', type: 'number', description: 'Batch size', default: '32' },
19
- { name: 'dim', type: 'number', description: 'Embedding dimension (max 256)', default: '256' },
20
- { name: 'wasm', short: 'w', type: 'boolean', description: 'Use RuVector WASM acceleration', default: 'true' },
21
- { name: 'flash', type: 'boolean', description: 'Enable Flash Attention (2.49x-7.47x speedup)', default: 'true' },
22
- { name: 'moe', type: 'boolean', description: 'Enable Mixture of Experts routing', default: 'false' },
23
- { name: 'hyperbolic', type: 'boolean', description: 'Enable hyperbolic attention for hierarchical patterns', default: 'false' },
24
- { name: 'contrastive', type: 'boolean', description: 'Use contrastive learning (InfoNCE)', default: 'true' },
25
- { name: 'curriculum', type: 'boolean', description: 'Enable curriculum learning', default: 'false' },
73
+ { name: 'learning-rate', short: 'l', type: 'number', description: 'Learning rate', "default": '0.01' },
74
+ { name: 'batch-size', short: 'b', type: 'number', description: 'Batch size', "default": '32' },
75
+ { name: 'dim', type: 'number', description: 'Embedding dimension (max 256)', "default": '256' },
76
+ { name: 'wasm', short: 'w', type: 'boolean', description: 'Use RuVector WASM acceleration', "default": 'true' },
77
+ { name: 'flash', type: 'boolean', description: 'Enable Flash Attention (2.49x-7.47x speedup)', "default": 'true' },
78
+ { name: 'moe', type: 'boolean', description: 'Enable Mixture of Experts routing', "default": 'false' },
79
+ { name: 'hyperbolic', type: 'boolean', description: 'Enable hyperbolic attention for hierarchical patterns', "default": 'false' },
80
+ { name: 'contrastive', type: 'boolean', description: 'Use contrastive learning (InfoNCE)', "default": 'true' },
81
+ { name: 'curriculum', type: 'boolean', description: 'Enable curriculum learning', "default": 'false' },
26
82
  ],
27
83
  examples: [
28
84
  { command: 'claude-flow neural train -p coordination -e 100', description: 'Train coordination patterns' },
29
85
  { command: 'claude-flow neural train -d ./training-data.json --flash', description: 'Train from file with Flash Attention' },
30
86
  { command: 'claude-flow neural train -p security --wasm --contrastive', description: 'Security patterns with contrastive learning' },
31
87
  ],
32
- action: async (ctx) => {
33
- const patternType = ctx.flags.pattern || 'coordination';
34
- const epochs = parseInt(ctx.flags.epochs || '50', 10);
35
- const learningRate = parseFloat(ctx.flags['learning-rate'] || '0.01');
36
- const batchSize = parseInt(ctx.flags['batch-size'] || '32', 10);
37
- const dim = Math.min(parseInt(ctx.flags.dim || '256', 10), 256);
38
- const useWasm = ctx.flags.wasm !== false;
39
- const useFlash = ctx.flags.flash !== false;
40
- const useMoE = ctx.flags.moe === true;
41
- const useHyperbolic = ctx.flags.hyperbolic === true;
42
- const useContrastive = ctx.flags.contrastive !== false;
43
- const useCurriculum = ctx.flags.curriculum === true;
44
- const dataFile = ctx.flags.data;
45
- output.writeln();
46
- output.writeln(output.bold('Neural Pattern Training (RuVector WASM)'));
47
- output.writeln(output.dim('─'.repeat(55)));
48
- const spinner = output.createSpinner({ text: 'Initializing RuVector training systems...', spinner: 'dots' });
49
- spinner.start();
50
- try {
51
- // Import RuVector training service
52
- const ruvector = await import('../services/ruvector-training.js');
53
- const { generateEmbedding } = await import('../memory/memory-initializer.js');
54
- const { initializeIntelligence, recordStep, recordTrajectory, getIntelligenceStats, flushPatterns, getPersistenceStatus } = await import('../memory/intelligence.js');
55
- // Initialize RuVector WASM training
56
- let wasmFeatures = [];
57
- if (useWasm) {
58
- const initResult = await ruvector.initializeTraining({
59
- dim,
60
- learningRate,
61
- alpha: 0.1,
62
- trajectoryCapacity: epochs * batchSize,
63
- useFlashAttention: useFlash,
64
- useMoE,
65
- useHyperbolic,
66
- totalSteps: useCurriculum ? epochs : undefined,
67
- warmupSteps: useCurriculum ? Math.floor(epochs * 0.1) : undefined,
68
- });
69
- if (initResult.success) {
70
- wasmFeatures = initResult.features;
71
- spinner.setText(`RuVector initialized: ${wasmFeatures.join(', ')}`);
72
- }
73
- else {
74
- output.writeln(output.warning(`WASM init failed: ${initResult.error} - falling back`));
75
- }
76
- }
77
- // Also initialize SONA + ReasoningBank for persistence
78
- await initializeIntelligence({
79
- loraLearningRate: learningRate,
80
- maxTrajectorySize: epochs
81
- });
82
- // Pattern type to operator mapping
83
- const operatorMap = {
84
- coordination: ruvector.OperatorType.COORDINATION,
85
- optimization: ruvector.OperatorType.OPTIMIZATION,
86
- prediction: ruvector.OperatorType.ROUTING,
87
- security: ruvector.OperatorType.SECURITY,
88
- testing: ruvector.OperatorType.TESTING,
89
- debugging: ruvector.OperatorType.DEBUGGING,
90
- memory: ruvector.OperatorType.MEMORY,
91
- reasoning: ruvector.OperatorType.REASONING,
92
- };
93
- const operatorType = operatorMap[patternType] ?? ruvector.OperatorType.GENERAL;
94
- spinner.setText(`Training ${patternType} patterns...`);
95
- // Training data - load from file or generate synthetic
96
- let trainingData = [];
97
- if (dataFile) {
98
- const fs = await import('fs');
99
- if (fs.existsSync(dataFile)) {
100
- const raw = fs.readFileSync(dataFile, 'utf8');
101
- trainingData = JSON.parse(raw);
102
- }
103
- else {
104
- spinner.fail(`Training data file not found: ${dataFile}`);
105
- return { success: false, exitCode: 1 };
106
- }
107
- }
108
- else {
109
- // Generate synthetic training data based on pattern type
110
- const templates = {
111
- coordination: [
112
- 'Route task to coder agent for implementation',
113
- 'Coordinate researcher and architect for design phase',
114
- 'Distribute workload across mesh topology',
115
- 'Synchronize agents via gossip protocol',
116
- 'Balance load between active workers',
117
- 'Spawn hierarchical swarm for complex task',
118
- 'Assign reviewer to completed implementation'
119
- ],
120
- optimization: [
121
- 'Apply Int8 quantization for memory reduction',
122
- 'Enable HNSW indexing for faster search',
123
- 'Batch operations for throughput improvement',
124
- 'Cache frequently accessed patterns',
125
- 'Prune unused neural pathways',
126
- 'Use Flash Attention for large sequences',
127
- 'Enable SIMD for vector operations'
128
- ],
129
- prediction: [
130
- 'Predict optimal agent for task type',
131
- 'Forecast resource requirements',
132
- 'Anticipate failure modes and mitigate',
133
- 'Estimate completion time for workflow',
134
- 'Predict pattern similarity before search'
135
- ],
136
- security: [
137
- 'Validate input at system boundaries',
138
- 'Check for path traversal attempts',
139
- 'Sanitize user-provided data',
140
- 'Apply parameterized queries for SQL',
141
- 'Verify JWT token signatures',
142
- 'Audit sensitive operation access'
143
- ],
144
- testing: [
145
- 'Generate unit tests for function',
146
- 'Create integration test suite',
147
- 'Mock external dependencies',
148
- 'Assert expected outcomes',
149
- 'Coverage gap analysis'
150
- ]
151
- };
152
- const patterns = templates[patternType] || templates.coordination;
153
- for (let i = 0; i < epochs; i++) {
154
- trainingData.push({
155
- content: patterns[i % patterns.length],
156
- type: patternType
157
- });
158
- }
159
- }
160
- // Training metrics
161
- const startTime = Date.now();
162
- const epochTimes = [];
163
- let patternsRecorded = 0;
164
- let trajectoriesCompleted = 0;
165
- let totalLoss = 0;
166
- let adaptations = 0;
167
- // Generate embeddings for training data
168
- const embeddings = [];
169
- spinner.setText('Generating embeddings...');
170
- for (const item of trainingData.slice(0, Math.min(100, trainingData.length))) {
171
- const embeddingResult = await generateEmbedding(item.content);
172
- if (embeddingResult && embeddingResult.embedding) {
173
- // Convert to Float32Array and resize to dim
174
- const embeddingArray = embeddingResult.embedding;
175
- const resized = new Float32Array(dim);
176
- for (let i = 0; i < Math.min(embeddingArray.length, dim); i++) {
177
- resized[i] = embeddingArray[i];
88
+ action: function (ctx) { return __awaiter(void 0, void 0, Promise, function () {
89
+ var patternType, epochs, learningRate, batchSize, dim, useWasm, useFlash, useMoE, useHyperbolic, useContrastive, useCurriculum, dataFile, spinner, ruvector, generateEmbedding, _a, initializeIntelligence, recordStep, recordTrajectory, getIntelligenceStats, flushPatterns, getPersistenceStatus, wasmFeatures, initResult, backendLabel, operatorMap, operatorType, trainingData, fs, raw, templates, patterns, i, startTime, epochTimes, patternsRecorded, trajectoriesCompleted, totalLoss, adaptations, embeddings, _i, _b, item, embeddingResult, embeddingArray, resized, i, epoch, epochStart, difficulty, batchStart, batch, anchor, positives, negatives, _c, loss, gradient, scaledGradient, i, baselineMs, executionMs, _d, item, steps, epochTime, progress, avgEpochTime, eta, totalTime, ruvectorStats, trajectoryStats, benchmark, _e, stats, persistence, tableData, backendUsed, flashBench, backendUsed, backendMsg, error_1;
90
+ var _f;
91
+ return __generator(this, function (_g) {
92
+ switch (_g.label) {
93
+ case 0:
94
+ patternType = (ctx.flags.pattern || ctx.flags.patternType || ctx.flags['pattern-type']) || 'coordination';
95
+ epochs = parseInt(ctx.flags.epochs || '50', 10);
96
+ learningRate = parseFloat(ctx.flags['learning-rate'] || '0.01');
97
+ batchSize = parseInt(ctx.flags['batch-size'] || '32', 10);
98
+ dim = Math.min(parseInt(ctx.flags.dim || '256', 10), 256);
99
+ useWasm = ctx.flags.wasm !== false;
100
+ useFlash = ctx.flags.flash !== false;
101
+ useMoE = ctx.flags.moe === true;
102
+ useHyperbolic = ctx.flags.hyperbolic === true;
103
+ useContrastive = ctx.flags.contrastive !== false;
104
+ useCurriculum = ctx.flags.curriculum === true;
105
+ dataFile = ctx.flags.data;
106
+ output.writeln();
107
+ output.writeln(output.bold('Neural Pattern Training (RuVector WASM)'));
108
+ output.writeln(output.dim('─'.repeat(55)));
109
+ spinner = output.createSpinner({ text: 'Initializing RuVector training systems...', spinner: 'dots' });
110
+ spinner.start();
111
+ _g.label = 1;
112
+ case 1:
113
+ _g.trys.push([1, 29, , 30]);
114
+ return [4 /*yield*/, import('../services/ruvector-training.js')];
115
+ case 2:
116
+ ruvector = _g.sent();
117
+ return [4 /*yield*/, import('../memory/memory-initializer.js')];
118
+ case 3:
119
+ generateEmbedding = (_g.sent()).generateEmbedding;
120
+ return [4 /*yield*/, import('../memory/intelligence.js')];
121
+ case 4:
122
+ _a = _g.sent(), initializeIntelligence = _a.initializeIntelligence, recordStep = _a.recordStep, recordTrajectory = _a.recordTrajectory, getIntelligenceStats = _a.getIntelligenceStats, flushPatterns = _a.flushPatterns, getPersistenceStatus = _a.getPersistenceStatus;
123
+ wasmFeatures = [];
124
+ if (!useWasm) return [3 /*break*/, 6];
125
+ return [4 /*yield*/, ruvector.initializeTraining({
126
+ dim: dim,
127
+ learningRate: learningRate,
128
+ alpha: 0.1,
129
+ trajectoryCapacity: epochs * batchSize,
130
+ useFlashAttention: useFlash,
131
+ useMoE: useMoE,
132
+ useHyperbolic: useHyperbolic,
133
+ totalSteps: useCurriculum ? epochs : undefined,
134
+ warmupSteps: useCurriculum ? Math.floor(epochs * 0.1) : undefined
135
+ })];
136
+ case 5:
137
+ initResult = _g.sent();
138
+ if (initResult.success) {
139
+ wasmFeatures = initResult.features;
140
+ backendLabel = initResult.backend === 'wasm' ? 'WASM' : 'JS fallback';
141
+ spinner.setText("RuVector initialized [" + backendLabel + "]: " + wasmFeatures.join(', '));
178
142
  }
179
- embeddings.push(resized);
180
- }
181
- }
182
- spinner.setText(`Training with ${embeddings.length} embeddings...`);
183
- // Main training loop with WASM acceleration
184
- for (let epoch = 0; epoch < epochs; epoch++) {
185
- const epochStart = performance.now();
186
- // Get curriculum difficulty if enabled
187
- const difficulty = useCurriculum ? ruvector.getCurriculumDifficulty(epoch) : 1.0;
188
- // Process batch
189
- const batchStart = (epoch * batchSize) % embeddings.length;
190
- const batch = embeddings.slice(batchStart, batchStart + batchSize);
191
- if (batch.length === 0)
192
- continue;
193
- // Training step with contrastive learning
194
- if (useContrastive && batch.length >= 3 && useWasm && wasmFeatures.length > 0) {
195
- const anchor = batch[0];
196
- const positives = [batch[1]];
197
- const negatives = batch.slice(2);
198
- try {
199
- // Compute contrastive loss
200
- const { loss, gradient } = ruvector.computeContrastiveLoss(anchor, positives, negatives);
201
- totalLoss += loss;
202
- // Scale gradient by difficulty
203
- const scaledGradient = new Float32Array(gradient.length);
204
- for (let i = 0; i < gradient.length; i++) {
205
- scaledGradient[i] = gradient[i] * difficulty;
143
+ else {
144
+ output.writeln(output.warning("WASM init failed: " + initResult.error + " - falling back"));
145
+ }
146
+ _g.label = 6;
147
+ case 6:
148
+ // Also initialize SONA + ReasoningBank for persistence
149
+ return [4 /*yield*/, initializeIntelligence({
150
+ loraLearningRate: learningRate,
151
+ maxTrajectorySize: epochs
152
+ })];
153
+ case 7:
154
+ // Also initialize SONA + ReasoningBank for persistence
155
+ _g.sent();
156
+ operatorMap = {
157
+ coordination: ruvector.OperatorType.COORDINATION,
158
+ optimization: ruvector.OperatorType.OPTIMIZATION,
159
+ prediction: ruvector.OperatorType.ROUTING,
160
+ security: ruvector.OperatorType.SECURITY,
161
+ testing: ruvector.OperatorType.TESTING,
162
+ debugging: ruvector.OperatorType.DEBUGGING,
163
+ memory: ruvector.OperatorType.MEMORY,
164
+ reasoning: ruvector.OperatorType.REASONING
165
+ };
166
+ operatorType = (_f = operatorMap[patternType]) !== null && _f !== void 0 ? _f : ruvector.OperatorType.GENERAL;
167
+ spinner.setText("Training " + patternType + " patterns...");
168
+ trainingData = [];
169
+ if (!dataFile) return [3 /*break*/, 9];
170
+ return [4 /*yield*/, import('fs')];
171
+ case 8:
172
+ fs = _g.sent();
173
+ if (fs.existsSync(dataFile)) {
174
+ raw = fs.readFileSync(dataFile, 'utf8');
175
+ trainingData = JSON.parse(raw);
176
+ }
177
+ else {
178
+ spinner.fail("Training data file not found: " + dataFile);
179
+ return [2 /*return*/, { success: false, exitCode: 1 }];
180
+ }
181
+ return [3 /*break*/, 10];
182
+ case 9:
183
+ templates = {
184
+ coordination: [
185
+ 'Route task to coder agent for implementation',
186
+ 'Coordinate researcher and architect for design phase',
187
+ 'Distribute workload across mesh topology',
188
+ 'Synchronize agents via gossip protocol',
189
+ 'Balance load between active workers',
190
+ 'Spawn hierarchical swarm for complex task',
191
+ 'Assign reviewer to completed implementation'
192
+ ],
193
+ optimization: [
194
+ 'Apply Int8 quantization for memory reduction',
195
+ 'Enable HNSW indexing for faster search',
196
+ 'Batch operations for throughput improvement',
197
+ 'Cache frequently accessed patterns',
198
+ 'Prune unused neural pathways',
199
+ 'Use Flash Attention for large sequences',
200
+ 'Enable SIMD for vector operations'
201
+ ],
202
+ prediction: [
203
+ 'Predict optimal agent for task type',
204
+ 'Forecast resource requirements',
205
+ 'Anticipate failure modes and mitigate',
206
+ 'Estimate completion time for workflow',
207
+ 'Predict pattern similarity before search'
208
+ ],
209
+ security: [
210
+ 'Validate input at system boundaries',
211
+ 'Check for path traversal attempts',
212
+ 'Sanitize user-provided data',
213
+ 'Apply parameterized queries for SQL',
214
+ 'Verify JWT token signatures',
215
+ 'Audit sensitive operation access'
216
+ ],
217
+ testing: [
218
+ 'Generate unit tests for function',
219
+ 'Create integration test suite',
220
+ 'Mock external dependencies',
221
+ 'Assert expected outcomes',
222
+ 'Coverage gap analysis'
223
+ ]
224
+ };
225
+ patterns = templates[patternType] || templates.coordination;
226
+ for (i = 0; i < epochs; i++) {
227
+ trainingData.push({
228
+ content: patterns[i % patterns.length],
229
+ type: patternType
230
+ });
231
+ }
232
+ _g.label = 10;
233
+ case 10:
234
+ startTime = Date.now();
235
+ epochTimes = [];
236
+ patternsRecorded = 0;
237
+ trajectoriesCompleted = 0;
238
+ totalLoss = 0;
239
+ adaptations = 0;
240
+ embeddings = [];
241
+ spinner.setText('Generating embeddings...');
242
+ _i = 0, _b = trainingData.slice(0, Math.min(100, trainingData.length));
243
+ _g.label = 11;
244
+ case 11:
245
+ if (!(_i < _b.length)) return [3 /*break*/, 14];
246
+ item = _b[_i];
247
+ return [4 /*yield*/, generateEmbedding(item.content)];
248
+ case 12:
249
+ embeddingResult = _g.sent();
250
+ if (embeddingResult && embeddingResult.embedding) {
251
+ embeddingArray = embeddingResult.embedding;
252
+ resized = new Float32Array(dim);
253
+ for (i = 0; i < Math.min(embeddingArray.length, dim); i++) {
254
+ resized[i] = embeddingArray[i];
206
255
  }
207
- // Train with MicroLoRA
208
- await ruvector.trainPattern(anchor, scaledGradient, operatorType);
209
- adaptations++;
210
- // Record trajectory for learning
211
- const baselineMs = 10; // Baseline execution time
212
- const executionMs = performance.now() - epochStart;
213
- ruvector.recordTrajectory(anchor, operatorType, useFlash ? 1 : 0, executionMs, baselineMs);
256
+ embeddings.push(resized);
214
257
  }
215
- catch {
216
- // WASM training failed, fall back to basic
258
+ _g.label = 13;
259
+ case 13:
260
+ _i++;
261
+ return [3 /*break*/, 11];
262
+ case 14:
263
+ spinner.setText("Training with " + embeddings.length + " embeddings...");
264
+ epoch = 0;
265
+ _g.label = 15;
266
+ case 15:
267
+ if (!(epoch < epochs)) return [3 /*break*/, 24];
268
+ epochStart = performance.now();
269
+ difficulty = useCurriculum ? ruvector.getCurriculumDifficulty(epoch) : 1.0;
270
+ batchStart = (epoch * batchSize) % embeddings.length;
271
+ batch = embeddings.slice(batchStart, batchStart + batchSize);
272
+ if (batch.length === 0)
273
+ return [3 /*break*/, 23];
274
+ if (!(useContrastive && batch.length >= 3 && useWasm && wasmFeatures.length > 0)) return [3 /*break*/, 19];
275
+ anchor = batch[0];
276
+ positives = [batch[1]];
277
+ negatives = batch.slice(2);
278
+ _g.label = 16;
279
+ case 16:
280
+ _g.trys.push([16, 18, , 19]);
281
+ _c = ruvector.computeContrastiveLoss(anchor, positives, negatives), loss = _c.loss, gradient = _c.gradient;
282
+ totalLoss += loss;
283
+ scaledGradient = new Float32Array(gradient.length);
284
+ for (i = 0; i < gradient.length; i++) {
285
+ scaledGradient[i] = gradient[i] * difficulty;
217
286
  }
218
- }
219
- // Also record in SONA/ReasoningBank for persistence
220
- const item = trainingData[epoch % trainingData.length];
221
- await recordStep({
222
- type: 'action',
223
- content: item.content,
224
- metadata: { epoch, patternType, learningRate, difficulty }
225
- });
226
- patternsRecorded++;
227
- // Record trajectory every 10 epochs
228
- if ((epoch + 1) % 10 === 0 || epoch === epochs - 1) {
229
- const steps = trainingData.slice(Math.max(0, epoch - 9), epoch + 1).map(d => ({ type: 'action', content: d.content }));
230
- await recordTrajectory(steps, 'success');
287
+ // Train with MicroLoRA
288
+ return [4 /*yield*/, ruvector.trainPattern(anchor, scaledGradient, operatorType)];
289
+ case 17:
290
+ // Train with MicroLoRA
291
+ _g.sent();
292
+ adaptations++;
293
+ baselineMs = 10;
294
+ executionMs = performance.now() - epochStart;
295
+ ruvector.recordTrajectory(anchor, operatorType, useFlash ? 1 : 0, executionMs, baselineMs);
296
+ return [3 /*break*/, 19];
297
+ case 18:
298
+ _d = _g.sent();
299
+ return [3 /*break*/, 19];
300
+ case 19:
301
+ item = trainingData[epoch % trainingData.length];
302
+ return [4 /*yield*/, recordStep({
303
+ type: 'action',
304
+ content: item.content,
305
+ metadata: { epoch: epoch, patternType: patternType, learningRate: learningRate, difficulty: difficulty }
306
+ })];
307
+ case 20:
308
+ _g.sent();
309
+ patternsRecorded++;
310
+ if (!((epoch + 1) % 10 === 0 || epoch === epochs - 1)) return [3 /*break*/, 22];
311
+ steps = trainingData.slice(Math.max(0, epoch - 9), epoch + 1).map(function (d) { return ({ type: 'action', content: d.content }); });
312
+ return [4 /*yield*/, recordTrajectory(steps, 'success')];
313
+ case 21:
314
+ _g.sent();
231
315
  trajectoriesCompleted++;
232
- }
233
- const epochTime = performance.now() - epochStart;
234
- epochTimes.push(epochTime);
235
- // Update progress
236
- const progress = Math.round(((epoch + 1) / epochs) * 100);
237
- const avgEpochTime = epochTimes.reduce((a, b) => a + b, 0) / epochTimes.length;
238
- const eta = Math.round((epochs - epoch - 1) * avgEpochTime / 1000);
239
- spinner.setText(`Training ${patternType} patterns... ${progress}% (ETA: ${eta}s, loss: ${(totalLoss / Math.max(1, epoch + 1)).toFixed(4)})`);
240
- }
241
- const totalTime = Date.now() - startTime;
242
- // Get RuVector stats
243
- const ruvectorStats = useWasm && wasmFeatures.length > 0 ? ruvector.getTrainingStats() : null;
244
- const trajectoryStats = ruvectorStats?.trajectoryStats;
245
- // Benchmark if WASM was used
246
- let benchmark = null;
247
- if (useWasm && wasmFeatures.length > 0) {
248
- try {
316
+ _g.label = 22;
317
+ case 22:
318
+ epochTime = performance.now() - epochStart;
319
+ epochTimes.push(epochTime);
320
+ progress = Math.round(((epoch + 1) / epochs) * 100);
321
+ avgEpochTime = epochTimes.reduce(function (a, b) { return a + b; }, 0) / epochTimes.length;
322
+ eta = Math.round((epochs - epoch - 1) * avgEpochTime / 1000);
323
+ spinner.setText("Training " + patternType + " patterns... " + progress + "% (ETA: " + eta + "s, loss: " + (totalLoss / Math.max(1, epoch + 1)).toFixed(4) + ")");
324
+ _g.label = 23;
325
+ case 23:
326
+ epoch++;
327
+ return [3 /*break*/, 15];
328
+ case 24:
329
+ totalTime = Date.now() - startTime;
330
+ ruvectorStats = useWasm && wasmFeatures.length > 0 ? ruvector.getTrainingStats() : null;
331
+ trajectoryStats = ruvectorStats === null || ruvectorStats === void 0 ? void 0 : ruvectorStats.trajectoryStats;
332
+ benchmark = null;
333
+ if (!(useWasm && wasmFeatures.length > 0)) return [3 /*break*/, 28];
334
+ _g.label = 25;
335
+ case 25:
336
+ _g.trys.push([25, 27, , 28]);
249
337
  spinner.setText('Running benchmark...');
250
- benchmark = await ruvector.benchmarkTraining(dim, 100);
251
- }
252
- catch {
253
- // Benchmark failed, continue
254
- }
255
- }
256
- // Get SONA stats
257
- const stats = getIntelligenceStats();
258
- spinner.succeed(`Training complete: ${epochs} epochs in ${(totalTime / 1000).toFixed(1)}s`);
259
- // Flush patterns to disk
260
- flushPatterns();
261
- const persistence = getPersistenceStatus();
262
- output.writeln();
263
- // Display results
264
- const tableData = [
265
- { metric: 'Pattern Type', value: patternType },
266
- { metric: 'Epochs', value: String(epochs) },
267
- { metric: 'Batch Size', value: String(batchSize) },
268
- { metric: 'Embedding Dim', value: String(dim) },
269
- { metric: 'Learning Rate', value: String(learningRate) },
270
- { metric: 'Patterns Recorded', value: patternsRecorded.toLocaleString() },
271
- { metric: 'Trajectories', value: String(trajectoriesCompleted) },
272
- { metric: 'Total Time', value: `${(totalTime / 1000).toFixed(1)}s` },
273
- { metric: 'Avg Epoch Time', value: `${(epochTimes.reduce((a, b) => a + b, 0) / epochTimes.length).toFixed(2)}ms` },
274
- ];
275
- // Add WASM-specific metrics
276
- if (useWasm && wasmFeatures.length > 0) {
277
- tableData.push({ metric: 'WASM Features', value: wasmFeatures.slice(0, 3).join(', ') }, { metric: 'LoRA Adaptations', value: String(adaptations) }, { metric: 'Avg Loss', value: (totalLoss / Math.max(1, epochs)).toFixed(4) });
278
- if (ruvectorStats?.microLoraStats) {
279
- tableData.push({ metric: 'MicroLoRA Delta Norm', value: ruvectorStats.microLoraStats.deltaNorm.toFixed(6) });
280
- }
281
- if (trajectoryStats) {
282
- tableData.push({ metric: 'Success Rate', value: `${(trajectoryStats.successRate * 100).toFixed(1)}%` }, { metric: 'Mean Improvement', value: `${(trajectoryStats.meanImprovement * 100).toFixed(1)}%` });
283
- }
284
- if (benchmark && benchmark.length > 0) {
285
- const flashBench = benchmark.find(b => b.name.includes('Flash'));
286
- if (flashBench) {
287
- tableData.push({ metric: 'Flash Attention', value: `${flashBench.opsPerSecond.toLocaleString()} ops/s` });
338
+ return [4 /*yield*/, ruvector.benchmarkTraining(dim, 100)];
339
+ case 26:
340
+ benchmark = _g.sent();
341
+ return [3 /*break*/, 28];
342
+ case 27:
343
+ _e = _g.sent();
344
+ return [3 /*break*/, 28];
345
+ case 28:
346
+ stats = getIntelligenceStats();
347
+ spinner.succeed("Training complete: " + epochs + " epochs in " + (totalTime / 1000).toFixed(1) + "s");
348
+ // Flush patterns to disk
349
+ flushPatterns();
350
+ persistence = getPersistenceStatus();
351
+ output.writeln();
352
+ tableData = [
353
+ { metric: 'Pattern Type', value: patternType },
354
+ { metric: 'Epochs', value: String(epochs) },
355
+ { metric: 'Batch Size', value: String(batchSize) },
356
+ { metric: 'Embedding Dim', value: String(dim) },
357
+ { metric: 'Learning Rate', value: String(learningRate) },
358
+ { metric: 'Patterns Recorded', value: patternsRecorded.toLocaleString() },
359
+ { metric: 'Trajectories', value: String(trajectoriesCompleted) },
360
+ { metric: 'Total Time', value: (totalTime / 1000).toFixed(1) + "s" },
361
+ { metric: 'Avg Epoch Time', value: (epochTimes.reduce(function (a, b) { return a + b; }, 0) / epochTimes.length).toFixed(2) + "ms" },
362
+ ];
363
+ // Add WASM-specific metrics
364
+ if (useWasm && wasmFeatures.length > 0) {
365
+ backendUsed = (ruvectorStats === null || ruvectorStats === void 0 ? void 0 : ruvectorStats.backend) || 'unknown';
366
+ tableData.push({ metric: 'Backend', value: backendUsed === 'wasm' ? 'WASM (native)' : 'JS (fallback)' }, { metric: 'WASM Features', value: wasmFeatures.slice(0, 3).join(', ') }, { metric: 'LoRA Adaptations', value: String(adaptations) }, { metric: 'Avg Loss', value: (totalLoss / Math.max(1, epochs)).toFixed(4) });
367
+ if (ruvectorStats === null || ruvectorStats === void 0 ? void 0 : ruvectorStats.microLoraStats) {
368
+ tableData.push({ metric: 'MicroLoRA Delta Norm', value: ruvectorStats.microLoraStats.deltaNorm.toFixed(6) });
369
+ }
370
+ if (trajectoryStats) {
371
+ tableData.push({ metric: 'Success Rate', value: (trajectoryStats.successRate * 100).toFixed(1) + "%" }, { metric: 'Mean Improvement', value: (trajectoryStats.meanImprovement * 100).toFixed(1) + "%" });
372
+ }
373
+ if (benchmark && benchmark.length > 0) {
374
+ flashBench = benchmark.find(function (b) { return b.name.includes('Flash'); });
375
+ if (flashBench) {
376
+ tableData.push({ metric: 'Flash Attention', value: flashBench.opsPerSecond.toLocaleString() + " ops/s" });
377
+ }
378
+ }
288
379
  }
289
- }
290
- }
291
- tableData.push({ metric: 'ReasoningBank Size', value: stats.reasoningBankSize.toLocaleString() }, { metric: 'Persisted To', value: output.dim(persistence.dataDir) });
292
- output.printTable({
293
- columns: [
294
- { key: 'metric', header: 'Metric', width: 26 },
295
- { key: 'value', header: 'Value', width: 32 },
296
- ],
297
- data: tableData,
298
- });
299
- output.writeln();
300
- output.writeln(output.success(`✓ ${patternsRecorded} patterns saved to ${persistence.patternsFile}`));
301
- if (useWasm && wasmFeatures.length > 0) {
302
- output.writeln(output.highlight(`✓ RuVector WASM: ${wasmFeatures.join(', ')}`));
380
+ tableData.push({ metric: 'ReasoningBank Size', value: stats.reasoningBankSize.toLocaleString() }, { metric: 'Persisted To', value: output.dim(persistence.dataDir) });
381
+ output.printTable({
382
+ columns: [
383
+ { key: 'metric', header: 'Metric', width: 26 },
384
+ { key: 'value', header: 'Value', width: 32 },
385
+ ],
386
+ data: tableData
387
+ });
388
+ output.writeln();
389
+ output.writeln(output.success("\u2713 " + patternsRecorded + " patterns saved to " + persistence.patternsFile));
390
+ if (useWasm && wasmFeatures.length > 0) {
391
+ backendUsed = (ruvectorStats === null || ruvectorStats === void 0 ? void 0 : ruvectorStats.backend) || 'unknown';
392
+ backendMsg = backendUsed === 'wasm'
393
+ ? "RuVector WASM backend: " + wasmFeatures.join(', ')
394
+ : "RuVector JS fallback (install @ruvector/learning-wasm for native speed): " + wasmFeatures.join(', ');
395
+ output.writeln(output.highlight("\u2713 " + backendMsg));
396
+ }
397
+ return [2 /*return*/, {
398
+ success: true,
399
+ data: {
400
+ epochs: epochs,
401
+ patternsRecorded: patternsRecorded,
402
+ trajectoriesCompleted: trajectoriesCompleted,
403
+ totalTime: totalTime,
404
+ wasmFeatures: wasmFeatures,
405
+ ruvectorStats: ruvectorStats,
406
+ benchmark: benchmark,
407
+ stats: stats,
408
+ persistence: persistence
409
+ }
410
+ }];
411
+ case 29:
412
+ error_1 = _g.sent();
413
+ spinner.fail('Training failed');
414
+ output.printError(error_1 instanceof Error ? error_1.message : String(error_1));
415
+ return [2 /*return*/, { success: false, exitCode: 1 }];
416
+ case 30: return [2 /*return*/];
303
417
  }
304
- return {
305
- success: true,
306
- data: {
307
- epochs,
308
- patternsRecorded,
309
- trajectoriesCompleted,
310
- totalTime,
311
- wasmFeatures,
312
- ruvectorStats,
313
- benchmark,
314
- stats,
315
- persistence
316
- }
317
- };
318
- }
319
- catch (error) {
320
- spinner.fail('Training failed');
321
- output.printError(error instanceof Error ? error.message : String(error));
322
- return { success: false, exitCode: 1 };
323
- }
324
- },
418
+ });
419
+ }); }
325
420
  };
326
421
  // Status subcommand - REAL measurements
327
- const statusCommand = {
422
+ var statusCommand = {
328
423
  name: 'status',
329
424
  description: 'Check neural network status and loaded models',
330
425
  options: [
@@ -335,666 +430,769 @@ const statusCommand = {
335
430
  { command: 'claude-flow neural status', description: 'Show all neural status' },
336
431
  { command: 'claude-flow neural status -m model-123', description: 'Check specific model' },
337
432
  ],
338
- action: async (ctx) => {
339
- const verbose = ctx.flags.verbose === true;
340
- output.writeln();
341
- output.writeln(output.bold('Neural Network Status (Real)'));
342
- output.writeln(output.dim('─'.repeat(50)));
343
- const spinner = output.createSpinner({ text: 'Checking neural systems...', spinner: 'dots' });
344
- spinner.start();
345
- try {
346
- // Import real implementations
347
- const { getIntelligenceStats, initializeIntelligence, benchmarkAdaptation } = await import('../memory/intelligence.js');
348
- const { getHNSWStatus, loadEmbeddingModel } = await import('../memory/memory-initializer.js');
349
- const ruvector = await import('../services/ruvector-training.js');
350
- // Initialize if needed and get real stats
351
- await initializeIntelligence();
352
- const stats = getIntelligenceStats();
353
- const hnswStatus = getHNSWStatus();
354
- // Quick benchmark for actual adaptation time
355
- const adaptBench = benchmarkAdaptation(100);
356
- // Check embedding model
357
- const modelInfo = await loadEmbeddingModel({ verbose: false });
358
- // Check RuVector WASM status
359
- const ruvectorStats = ruvector.getTrainingStats();
360
- const sonaAvailable = ruvector.isSonaAvailable();
361
- spinner.succeed('Neural systems checked');
362
- output.writeln();
363
- output.printTable({
364
- columns: [
365
- { key: 'component', header: 'Component', width: 22 },
366
- { key: 'status', header: 'Status', width: 12 },
367
- { key: 'details', header: 'Details', width: 32 },
368
- ],
369
- data: [
370
- {
371
- component: 'SONA Coordinator',
372
- status: stats.sonaEnabled ? output.success('Active') : output.warning('Inactive'),
373
- details: stats.sonaEnabled
374
- ? `Adaptation: ${(adaptBench.avgMs * 1000).toFixed(2)}μs avg`
375
- : 'Not initialized',
376
- },
377
- {
378
- component: 'RuVector WASM',
379
- status: ruvectorStats.initialized ? output.success('Active') : output.dim('Not loaded'),
380
- details: ruvectorStats.initialized
381
- ? `MicroLoRA: ${ruvectorStats.totalAdaptations} adapts`
382
- : 'Call neural train to initialize',
383
- },
384
- {
385
- component: 'SONA Engine',
386
- status: sonaAvailable ? output.success('Active') : output.dim('Not loaded'),
387
- details: sonaAvailable && ruvectorStats.sonaStats
388
- ? `${ruvectorStats.sonaStats.totalLearns} learns, ${ruvectorStats.sonaStats.totalSearches} searches`
389
- : 'Optional, enable with --sona',
390
- },
391
- {
392
- component: 'ReasoningBank',
393
- status: stats.reasoningBankSize > 0 ? output.success('Active') : output.dim('Empty'),
394
- details: `${stats.patternsLearned} patterns stored`,
395
- },
396
- {
397
- component: 'HNSW Index',
398
- status: hnswStatus.available ? output.success('Ready') : output.dim('Not loaded'),
399
- details: hnswStatus.available
400
- ? `${hnswStatus.entryCount} vectors, ${hnswStatus.dimensions}-dim`
401
- : '@ruvector/core not available',
402
- },
403
- {
404
- component: 'Embedding Model',
405
- status: modelInfo.success ? output.success('Loaded') : output.warning('Fallback'),
406
- details: `${modelInfo.modelName} (${modelInfo.dimensions}-dim)`,
407
- },
408
- {
409
- component: 'Flash Attention Ops',
410
- status: output.success('Available'),
411
- details: 'batchCosineSim, softmax, topK',
412
- },
413
- {
414
- component: 'Int8 Quantization',
415
- status: output.success('Available'),
416
- details: '~4x memory reduction',
417
- },
418
- ],
419
- });
420
- if (verbose) {
421
- output.writeln();
422
- output.writeln(output.bold('Detailed Metrics'));
423
- const detailedData = [
424
- { metric: 'Trajectories Recorded', value: String(stats.trajectoriesRecorded) },
425
- { metric: 'Patterns Learned', value: String(stats.patternsLearned) },
426
- { metric: 'HNSW Dimensions', value: String(hnswStatus.dimensions) },
427
- { metric: 'SONA Adaptation (avg)', value: `${(adaptBench.avgMs * 1000).toFixed(2)}μs` },
428
- { metric: 'SONA Adaptation (max)', value: `${(adaptBench.maxMs * 1000).toFixed(2)}μs` },
429
- { metric: 'Target Met (<0.05ms)', value: adaptBench.targetMet ? output.success('Yes') : output.warning('No') },
430
- {
431
- metric: 'Last Adaptation',
432
- value: stats.lastAdaptation
433
- ? new Date(stats.lastAdaptation).toLocaleTimeString()
434
- : 'Never',
435
- },
436
- ];
437
- // Add RuVector WASM metrics if initialized
438
- if (ruvectorStats.initialized) {
439
- detailedData.push({ metric: 'RuVector Adaptations', value: String(ruvectorStats.totalAdaptations) }, { metric: 'RuVector Forwards', value: String(ruvectorStats.totalForwards) });
440
- if (ruvectorStats.microLoraStats) {
441
- detailedData.push({ metric: 'MicroLoRA Delta Norm', value: ruvectorStats.microLoraStats.deltaNorm.toFixed(6) }, { metric: 'MicroLoRA Adapt Count', value: String(ruvectorStats.microLoraStats.adaptCount) });
442
- }
443
- if (sonaAvailable && ruvectorStats.sonaStats?.stats) {
444
- const sonaStats = ruvectorStats.sonaStats.stats;
445
- detailedData.push({ metric: 'SONA Patterns Stored', value: String(sonaStats.patterns_stored || 0) }, { metric: 'SONA EWC Tasks', value: String(sonaStats.ewc_tasks || 0) });
433
+ action: function (ctx) { return __awaiter(void 0, void 0, Promise, function () {
434
+ var verbose, spinner, _a, getIntelligenceStats, initializeIntelligence, benchmarkAdaptation, _b, getHNSWStatus, loadEmbeddingModel, ruvector, stats, hnswStatus, adaptBench, modelInfo, ruvectorStats, sonaAvailable, detailedData, sonaStats, error_2;
435
+ var _c;
436
+ return __generator(this, function (_d) {
437
+ switch (_d.label) {
438
+ case 0:
439
+ verbose = ctx.flags.verbose === true;
440
+ output.writeln();
441
+ output.writeln(output.bold('Neural Network Status (Real)'));
442
+ output.writeln(output.dim('─'.repeat(50)));
443
+ spinner = output.createSpinner({ text: 'Checking neural systems...', spinner: 'dots' });
444
+ spinner.start();
445
+ _d.label = 1;
446
+ case 1:
447
+ _d.trys.push([1, 7, , 8]);
448
+ return [4 /*yield*/, import('../memory/intelligence.js')];
449
+ case 2:
450
+ _a = _d.sent(), getIntelligenceStats = _a.getIntelligenceStats, initializeIntelligence = _a.initializeIntelligence, benchmarkAdaptation = _a.benchmarkAdaptation;
451
+ return [4 /*yield*/, import('../memory/memory-initializer.js')];
452
+ case 3:
453
+ _b = _d.sent(), getHNSWStatus = _b.getHNSWStatus, loadEmbeddingModel = _b.loadEmbeddingModel;
454
+ return [4 /*yield*/, import('../services/ruvector-training.js')];
455
+ case 4:
456
+ ruvector = _d.sent();
457
+ // Initialize if needed and get real stats
458
+ return [4 /*yield*/, initializeIntelligence()];
459
+ case 5:
460
+ // Initialize if needed and get real stats
461
+ _d.sent();
462
+ stats = getIntelligenceStats();
463
+ hnswStatus = getHNSWStatus();
464
+ adaptBench = benchmarkAdaptation(100);
465
+ return [4 /*yield*/, loadEmbeddingModel({ verbose: false })];
466
+ case 6:
467
+ modelInfo = _d.sent();
468
+ ruvectorStats = ruvector.getTrainingStats();
469
+ sonaAvailable = ruvector.isSonaAvailable();
470
+ spinner.succeed('Neural systems checked');
471
+ output.writeln();
472
+ output.printTable({
473
+ columns: [
474
+ { key: 'component', header: 'Component', width: 22 },
475
+ { key: 'status', header: 'Status', width: 12 },
476
+ { key: 'details', header: 'Details', width: 32 },
477
+ ],
478
+ data: [
479
+ {
480
+ component: 'SONA Coordinator',
481
+ status: stats.sonaEnabled ? output.success('Active') : output.warning('Inactive'),
482
+ details: stats.sonaEnabled
483
+ ? "Adaptation: " + (adaptBench.avgMs * 1000).toFixed(2) + "\u03BCs avg"
484
+ : 'Not initialized'
485
+ },
486
+ {
487
+ component: 'RuVector Training',
488
+ status: ruvectorStats.initialized ? output.success('Active') : output.dim('Not loaded'),
489
+ details: ruvectorStats.initialized
490
+ ? (ruvectorStats.backend === 'wasm' ? 'WASM' : 'JS fallback') + " | MicroLoRA: " + ruvectorStats.totalAdaptations + " adapts"
491
+ : 'Call neural train to initialize'
492
+ },
493
+ {
494
+ component: 'SONA Engine',
495
+ status: sonaAvailable ? output.success('Active') : output.dim('Not loaded'),
496
+ details: sonaAvailable && ruvectorStats.sonaStats
497
+ ? ruvectorStats.sonaStats.totalLearns + " learns, " + ruvectorStats.sonaStats.totalSearches + " searches"
498
+ : 'Optional, enable with --sona'
499
+ },
500
+ {
501
+ component: 'ReasoningBank',
502
+ status: stats.reasoningBankSize > 0 ? output.success('Active') : output.dim('Empty'),
503
+ details: stats.patternsLearned + " patterns stored"
504
+ },
505
+ {
506
+ component: 'HNSW Index',
507
+ status: hnswStatus.available ? output.success('Ready') : output.dim('Not loaded'),
508
+ details: hnswStatus.available
509
+ ? hnswStatus.entryCount + " vectors, " + hnswStatus.dimensions + "-dim"
510
+ : '@ruvector/core not available'
511
+ },
512
+ {
513
+ component: 'Embedding Model',
514
+ status: modelInfo.success ? output.success('Loaded') : output.warning('Fallback'),
515
+ details: modelInfo.modelName + " (" + modelInfo.dimensions + "-dim)"
516
+ },
517
+ {
518
+ component: 'Flash Attention Ops',
519
+ status: output.success('Available'),
520
+ details: 'batchCosineSim, softmax, topK'
521
+ },
522
+ {
523
+ component: 'Int8 Quantization',
524
+ status: output.success('Available'),
525
+ details: '~4x memory reduction'
526
+ },
527
+ ]
528
+ });
529
+ if (verbose) {
530
+ output.writeln();
531
+ output.writeln(output.bold('Detailed Metrics'));
532
+ detailedData = [
533
+ { metric: 'Trajectories Recorded', value: String(stats.trajectoriesRecorded) },
534
+ { metric: 'Patterns Learned', value: String(stats.patternsLearned) },
535
+ { metric: 'HNSW Dimensions', value: String(hnswStatus.dimensions) },
536
+ { metric: 'SONA Adaptation (avg)', value: (adaptBench.avgMs * 1000).toFixed(2) + "\u03BCs" },
537
+ { metric: 'SONA Adaptation (max)', value: (adaptBench.maxMs * 1000).toFixed(2) + "\u03BCs" },
538
+ { metric: 'Target Met (<0.05ms)', value: adaptBench.targetMet ? output.success('Yes') : output.warning('No') },
539
+ {
540
+ metric: 'Last Adaptation',
541
+ value: stats.lastAdaptation
542
+ ? new Date(stats.lastAdaptation).toLocaleTimeString()
543
+ : 'Never'
544
+ },
545
+ ];
546
+ // Add RuVector WASM metrics if initialized
547
+ if (ruvectorStats.initialized) {
548
+ detailedData.push({ metric: 'RuVector Adaptations', value: String(ruvectorStats.totalAdaptations) }, { metric: 'RuVector Forwards', value: String(ruvectorStats.totalForwards) });
549
+ if (ruvectorStats.microLoraStats) {
550
+ detailedData.push({ metric: 'MicroLoRA Delta Norm', value: ruvectorStats.microLoraStats.deltaNorm.toFixed(6) }, { metric: 'MicroLoRA Adapt Count', value: String(ruvectorStats.microLoraStats.adaptCount) });
551
+ }
552
+ if (sonaAvailable && ((_c = ruvectorStats.sonaStats) === null || _c === void 0 ? void 0 : _c.stats)) {
553
+ sonaStats = ruvectorStats.sonaStats.stats;
554
+ detailedData.push({ metric: 'SONA Patterns Stored', value: String(sonaStats.patterns_stored || 0) }, { metric: 'SONA EWC Tasks', value: String(sonaStats.ewc_tasks || 0) });
555
+ }
556
+ }
557
+ output.printTable({
558
+ columns: [
559
+ { key: 'metric', header: 'Metric', width: 28 },
560
+ { key: 'value', header: 'Value', width: 20 },
561
+ ],
562
+ data: detailedData
563
+ });
446
564
  }
447
- }
448
- output.printTable({
449
- columns: [
450
- { key: 'metric', header: 'Metric', width: 28 },
451
- { key: 'value', header: 'Value', width: 20 },
452
- ],
453
- data: detailedData,
454
- });
565
+ return [2 /*return*/, { success: true, data: { stats: stats, hnswStatus: hnswStatus, adaptBench: adaptBench, modelInfo: modelInfo, ruvectorStats: ruvectorStats } }];
566
+ case 7:
567
+ error_2 = _d.sent();
568
+ spinner.fail('Failed to check neural systems');
569
+ output.printError(error_2 instanceof Error ? error_2.message : String(error_2));
570
+ return [2 /*return*/, { success: false, exitCode: 1 }];
571
+ case 8: return [2 /*return*/];
455
572
  }
456
- return { success: true, data: { stats, hnswStatus, adaptBench, modelInfo, ruvectorStats } };
457
- }
458
- catch (error) {
459
- spinner.fail('Failed to check neural systems');
460
- output.printError(error instanceof Error ? error.message : String(error));
461
- return { success: false, exitCode: 1 };
462
- }
463
- },
573
+ });
574
+ }); }
464
575
  };
465
576
  // Patterns subcommand
466
- const patternsCommand = {
577
+ var patternsCommand = {
467
578
  name: 'patterns',
468
579
  description: 'Analyze and manage cognitive patterns',
469
580
  options: [
470
- { name: 'action', short: 'a', type: 'string', description: 'Action: analyze, learn, predict, list', default: 'list' },
581
+ { name: 'action', short: 'a', type: 'string', description: 'Action: analyze, learn, predict, list', "default": 'list' },
471
582
  { name: 'query', short: 'q', type: 'string', description: 'Pattern query for search' },
472
- { name: 'limit', short: 'l', type: 'number', description: 'Max patterns to return', default: '10' },
583
+ { name: 'limit', short: 'l', type: 'number', description: 'Max patterns to return', "default": '10' },
473
584
  ],
474
585
  examples: [
475
586
  { command: 'claude-flow neural patterns --action list', description: 'List all patterns' },
476
587
  { command: 'claude-flow neural patterns -a analyze -q "error handling"', description: 'Analyze patterns' },
477
588
  ],
478
- action: async (ctx) => {
479
- const action = ctx.flags.action || 'list';
480
- const query = ctx.flags.query;
481
- const limit = parseInt(ctx.flags.limit, 10) || 10;
482
- output.writeln();
483
- output.writeln(output.bold(`Neural Patterns - ${action}`));
484
- output.writeln(output.dim('─'.repeat(40)));
485
- try {
486
- const { initializeIntelligence, getIntelligenceStats, findSimilarPatterns, getAllPatterns, getPersistenceStatus, } = await import('../memory/intelligence.js');
487
- await initializeIntelligence();
488
- const stats = getIntelligenceStats();
489
- const persistence = getPersistenceStatus();
490
- if (action === 'list') {
491
- // Get ALL patterns from ReasoningBank (loaded from disk)
492
- const allPatterns = await getAllPatterns();
493
- const patterns = query
494
- ? await findSimilarPatterns(query, { k: limit })
495
- : allPatterns.slice(0, limit);
496
- if (patterns.length === 0) {
497
- output.writeln(output.dim('No patterns found. Train some patterns first with: neural train'));
589
+ action: function (ctx) { return __awaiter(void 0, void 0, Promise, function () {
590
+ var action, query, limit, _a, initializeIntelligence, getIntelligenceStats, findSimilarPatterns, getAllPatterns, getPersistenceStatus, stats, persistence, allPatterns, patterns, _b, related, error_3;
591
+ return __generator(this, function (_c) {
592
+ switch (_c.label) {
593
+ case 0:
594
+ action = ctx.flags.action || 'list';
595
+ query = ctx.flags.query;
596
+ limit = parseInt(ctx.flags.limit, 10) || 10;
498
597
  output.writeln();
499
- output.printBox([
500
- `Total Patterns: ${stats.patternsLearned}`,
501
- `Trajectories: ${stats.trajectoriesRecorded}`,
502
- `ReasoningBank Size: ${stats.reasoningBankSize}`,
503
- `Persistence: ${persistence.patternsExist ? 'Loaded from disk' : 'Not persisted'}`,
504
- `Data Dir: ${persistence.dataDir}`,
505
- ].join('\n'), 'Pattern Statistics');
506
- }
507
- else {
508
- output.printTable({
509
- columns: [
510
- { key: 'id', header: 'ID', width: 20 },
511
- { key: 'type', header: 'Type', width: 18 },
512
- { key: 'confidence', header: 'Confidence', width: 12 },
513
- { key: 'usage', header: 'Usage', width: 10 },
514
- ],
515
- data: patterns.map((p, i) => ({
516
- id: (p.id || `P${String(i + 1).padStart(3, '0')}`).substring(0, 18),
517
- type: output.highlight(p.type || 'unknown'),
518
- confidence: `${((p.confidence || 0.5) * 100).toFixed(1)}%`,
519
- usage: String(p.usageCount || 0),
520
- })),
521
- });
522
- }
523
- output.writeln();
524
- output.writeln(output.dim(`Total: ${allPatterns.length} patterns (persisted) | Trajectories: ${stats.trajectoriesRecorded}`));
525
- if (persistence.patternsExist) {
526
- output.writeln(output.success(`✓ Loaded from: ${persistence.patternsFile}`));
527
- }
528
- }
529
- else if (action === 'analyze' && query) {
530
- // Analyze patterns related to query
531
- const related = await findSimilarPatterns(query, { k: limit });
532
- output.writeln(`Analyzing patterns related to: "${query}"`);
533
- output.writeln();
534
- if (related.length > 0) {
535
- output.printTable({
536
- columns: [
537
- { key: 'content', header: 'Pattern', width: 40 },
538
- { key: 'confidence', header: 'Confidence', width: 12 },
539
- { key: 'type', header: 'Type', width: 15 },
540
- ],
541
- data: related.slice(0, 5).map(p => ({
542
- content: (p.content || '').substring(0, 38) + (p.content?.length > 38 ? '...' : ''),
543
- confidence: `${((p.confidence || 0) * 100).toFixed(0)}%`,
544
- type: p.type || 'general',
545
- })),
546
- });
547
- }
548
- else {
549
- output.writeln(output.dim('No related patterns found.'));
550
- }
598
+ output.writeln(output.bold("Neural Patterns - " + action));
599
+ output.writeln(output.dim('─'.repeat(40)));
600
+ _c.label = 1;
601
+ case 1:
602
+ _c.trys.push([1, 11, , 12]);
603
+ return [4 /*yield*/, import('../memory/intelligence.js')];
604
+ case 2:
605
+ _a = _c.sent(), initializeIntelligence = _a.initializeIntelligence, getIntelligenceStats = _a.getIntelligenceStats, findSimilarPatterns = _a.findSimilarPatterns, getAllPatterns = _a.getAllPatterns, getPersistenceStatus = _a.getPersistenceStatus;
606
+ return [4 /*yield*/, initializeIntelligence()];
607
+ case 3:
608
+ _c.sent();
609
+ stats = getIntelligenceStats();
610
+ persistence = getPersistenceStatus();
611
+ if (!(action === 'list')) return [3 /*break*/, 8];
612
+ return [4 /*yield*/, getAllPatterns()];
613
+ case 4:
614
+ allPatterns = _c.sent();
615
+ if (!query) return [3 /*break*/, 6];
616
+ return [4 /*yield*/, findSimilarPatterns(query, { k: limit })];
617
+ case 5:
618
+ _b = _c.sent();
619
+ return [3 /*break*/, 7];
620
+ case 6:
621
+ _b = allPatterns.slice(0, limit);
622
+ _c.label = 7;
623
+ case 7:
624
+ patterns = _b;
625
+ if (patterns.length === 0) {
626
+ output.writeln(output.dim('No patterns found. Train some patterns first with: neural train'));
627
+ output.writeln();
628
+ output.printBox([
629
+ "Total Patterns: " + stats.patternsLearned,
630
+ "Trajectories: " + stats.trajectoriesRecorded,
631
+ "ReasoningBank Size: " + stats.reasoningBankSize,
632
+ "Persistence: " + (persistence.patternsExist ? 'Loaded from disk' : 'Not persisted'),
633
+ "Data Dir: " + persistence.dataDir,
634
+ ].join('\n'), 'Pattern Statistics');
635
+ }
636
+ else {
637
+ output.printTable({
638
+ columns: [
639
+ { key: 'id', header: 'ID', width: 20 },
640
+ { key: 'type', header: 'Type', width: 18 },
641
+ { key: 'confidence', header: 'Confidence', width: 12 },
642
+ { key: 'usage', header: 'Usage', width: 10 },
643
+ ],
644
+ data: patterns.map(function (p, i) { return ({
645
+ id: (p.id || "P" + String(i + 1).padStart(3, '0')).substring(0, 18),
646
+ type: output.highlight(p.type || 'unknown'),
647
+ confidence: ((p.confidence || 0.5) * 100).toFixed(1) + "%",
648
+ usage: String(p.usageCount || 0)
649
+ }); })
650
+ });
651
+ }
652
+ output.writeln();
653
+ output.writeln(output.dim("Total: " + allPatterns.length + " patterns (persisted) | Trajectories: " + stats.trajectoriesRecorded));
654
+ if (persistence.patternsExist) {
655
+ output.writeln(output.success("\u2713 Loaded from: " + persistence.patternsFile));
656
+ }
657
+ return [3 /*break*/, 10];
658
+ case 8:
659
+ if (!(action === 'analyze' && query)) return [3 /*break*/, 10];
660
+ return [4 /*yield*/, findSimilarPatterns(query, { k: limit })];
661
+ case 9:
662
+ related = _c.sent();
663
+ output.writeln("Analyzing patterns related to: \"" + query + "\"");
664
+ output.writeln();
665
+ if (related.length > 0) {
666
+ output.printTable({
667
+ columns: [
668
+ { key: 'content', header: 'Pattern', width: 40 },
669
+ { key: 'confidence', header: 'Confidence', width: 12 },
670
+ { key: 'type', header: 'Type', width: 15 },
671
+ ],
672
+ data: related.slice(0, 5).map(function (p) {
673
+ var _a;
674
+ return ({
675
+ content: (p.content || '').substring(0, 38) + (((_a = p.content) === null || _a === void 0 ? void 0 : _a.length) > 38 ? '...' : ''),
676
+ confidence: ((p.confidence || 0) * 100).toFixed(0) + "%",
677
+ type: p.type || 'general'
678
+ });
679
+ })
680
+ });
681
+ }
682
+ else {
683
+ output.writeln(output.dim('No related patterns found.'));
684
+ }
685
+ _c.label = 10;
686
+ case 10: return [2 /*return*/, { success: true }];
687
+ case 11:
688
+ error_3 = _c.sent();
689
+ // Fallback if intelligence not initialized
690
+ output.writeln(output.dim('Intelligence system not initialized.'));
691
+ output.writeln(output.dim('Run: claude-flow neural train --pattern-type general'));
692
+ return [2 /*return*/, { success: false }];
693
+ case 12: return [2 /*return*/];
551
694
  }
552
- return { success: true };
553
- }
554
- catch (error) {
555
- // Fallback if intelligence not initialized
556
- output.writeln(output.dim('Intelligence system not initialized.'));
557
- output.writeln(output.dim('Run: claude-flow neural train --pattern-type general'));
558
- return { success: false };
559
- }
560
- },
695
+ });
696
+ }); }
561
697
  };
562
698
  // Predict subcommand
563
- const predictCommand = {
699
+ var predictCommand = {
564
700
  name: 'predict',
565
701
  description: 'Make AI predictions using trained models',
566
702
  options: [
567
703
  { name: 'input', short: 'i', type: 'string', description: 'Input text to predict routing for', required: true },
568
- { name: 'k', short: 'k', type: 'number', description: 'Number of top predictions', default: '5' },
569
- { name: 'format', short: 'f', type: 'string', description: 'Output format: json, table', default: 'table' },
704
+ { name: 'k', short: 'k', type: 'number', description: 'Number of top predictions', "default": '5' },
705
+ { name: 'format', short: 'f', type: 'string', description: 'Output format: json, table', "default": 'table' },
570
706
  ],
571
707
  examples: [
572
708
  { command: 'claude-flow neural predict -i "implement authentication"', description: 'Predict routing for task' },
573
709
  { command: 'claude-flow neural predict -i "fix bug in login" -k 3', description: 'Get top 3 predictions' },
574
710
  ],
575
- action: async (ctx) => {
576
- const input = ctx.flags.input;
577
- const k = parseInt(ctx.flags.k || '5', 10);
578
- const format = ctx.flags.format || 'table';
579
- if (!input) {
580
- output.printError('--input is required');
581
- return { success: false, exitCode: 1 };
582
- }
583
- output.writeln();
584
- output.writeln(output.bold('Neural Prediction (Real)'));
585
- output.writeln(output.dim(''.repeat(50)));
586
- const spinner = output.createSpinner({ text: 'Running inference...', spinner: 'dots' });
587
- spinner.start();
588
- try {
589
- const { initializeIntelligence, findSimilarPatterns } = await import('../memory/intelligence.js');
590
- // Initialize intelligence system
591
- await initializeIntelligence();
592
- // Find similar patterns (embedding is done internally)
593
- const startSearch = performance.now();
594
- const matches = await findSimilarPatterns(input, { k });
595
- const searchTime = performance.now() - startSearch;
596
- spinner.succeed(`Prediction complete (search: ${searchTime.toFixed(1)}ms)`);
597
- output.writeln();
598
- if (matches.length === 0) {
599
- output.writeln(output.warning('No similar patterns found. Try training first: claude-flow neural train'));
600
- return { success: true, data: { matches: [] } };
601
- }
602
- if (format === 'json') {
603
- output.writeln(JSON.stringify(matches, null, 2));
604
- }
605
- else {
606
- // Determine best prediction based on patterns
607
- const patternTypes = {};
608
- for (const match of matches) {
609
- const type = match.type || 'unknown';
610
- patternTypes[type] = (patternTypes[type] || 0) + match.similarity;
611
- }
612
- const sorted = Object.entries(patternTypes).sort((a, b) => b[1] - a[1]);
613
- const topType = sorted[0]?.[0] || 'unknown';
614
- const confidence = matches[0]?.similarity || 0;
615
- output.printBox([
616
- `Input: ${input.substring(0, 60)}${input.length > 60 ? '...' : ''}`,
617
- ``,
618
- `Predicted Type: ${topType}`,
619
- `Confidence: ${(confidence * 100).toFixed(1)}%`,
620
- `Latency: ${searchTime.toFixed(1)}ms`,
621
- ``,
622
- `Top ${matches.length} Similar Patterns:`,
623
- ].join('\n'), 'Result');
624
- output.printTable({
625
- columns: [
626
- { key: 'rank', header: '#', width: 3 },
627
- { key: 'id', header: 'Pattern ID', width: 20 },
628
- { key: 'type', header: 'Type', width: 15 },
629
- { key: 'similarity', header: 'Similarity', width: 12 },
630
- ],
631
- data: matches.slice(0, k).map((m, i) => ({
632
- rank: String(i + 1),
633
- id: m.id?.substring(0, 20) || 'unknown',
634
- type: m.type || 'action',
635
- similarity: `${(m.similarity * 100).toFixed(1)}%`,
636
- })),
637
- });
711
+ action: function (ctx) { return __awaiter(void 0, void 0, Promise, function () {
712
+ var input, k, format, spinner, _a, initializeIntelligence, findSimilarPatterns, startSearch, matches, searchTime, patternTypes, _i, matches_1, match, type, sorted, topType, confidence, error_4;
713
+ var _b, _c;
714
+ return __generator(this, function (_d) {
715
+ switch (_d.label) {
716
+ case 0:
717
+ input = ctx.flags.input;
718
+ k = parseInt(ctx.flags.k || '5', 10);
719
+ format = ctx.flags.format || 'table';
720
+ if (!input) {
721
+ output.printError('--input is required');
722
+ return [2 /*return*/, { success: false, exitCode: 1 }];
723
+ }
724
+ output.writeln();
725
+ output.writeln(output.bold('Neural Prediction (Real)'));
726
+ output.writeln(output.dim('─'.repeat(50)));
727
+ spinner = output.createSpinner({ text: 'Running inference...', spinner: 'dots' });
728
+ spinner.start();
729
+ _d.label = 1;
730
+ case 1:
731
+ _d.trys.push([1, 5, , 6]);
732
+ return [4 /*yield*/, import('../memory/intelligence.js')];
733
+ case 2:
734
+ _a = _d.sent(), initializeIntelligence = _a.initializeIntelligence, findSimilarPatterns = _a.findSimilarPatterns;
735
+ // Initialize intelligence system
736
+ return [4 /*yield*/, initializeIntelligence()];
737
+ case 3:
738
+ // Initialize intelligence system
739
+ _d.sent();
740
+ startSearch = performance.now();
741
+ return [4 /*yield*/, findSimilarPatterns(input, { k: k })];
742
+ case 4:
743
+ matches = _d.sent();
744
+ searchTime = performance.now() - startSearch;
745
+ spinner.succeed("Prediction complete (search: " + searchTime.toFixed(1) + "ms)");
746
+ output.writeln();
747
+ if (matches.length === 0) {
748
+ output.writeln(output.warning('No similar patterns found. Try training first: claude-flow neural train'));
749
+ return [2 /*return*/, { success: true, data: { matches: [] } }];
750
+ }
751
+ if (format === 'json') {
752
+ output.writeln(JSON.stringify(matches, null, 2));
753
+ }
754
+ else {
755
+ patternTypes = {};
756
+ for (_i = 0, matches_1 = matches; _i < matches_1.length; _i++) {
757
+ match = matches_1[_i];
758
+ type = match.type || 'unknown';
759
+ patternTypes[type] = (patternTypes[type] || 0) + match.similarity;
760
+ }
761
+ sorted = Object.entries(patternTypes).sort(function (a, b) { return b[1] - a[1]; });
762
+ topType = ((_b = sorted[0]) === null || _b === void 0 ? void 0 : _b[0]) || 'unknown';
763
+ confidence = ((_c = matches[0]) === null || _c === void 0 ? void 0 : _c.similarity) || 0;
764
+ output.printBox([
765
+ "Input: " + input.substring(0, 60) + (input.length > 60 ? '...' : ''),
766
+ "",
767
+ "Predicted Type: " + topType,
768
+ "Confidence: " + (confidence * 100).toFixed(1) + "%",
769
+ "Latency: " + searchTime.toFixed(1) + "ms",
770
+ "",
771
+ "Top " + matches.length + " Similar Patterns:",
772
+ ].join('\n'), 'Result');
773
+ output.printTable({
774
+ columns: [
775
+ { key: 'rank', header: '#', width: 3 },
776
+ { key: 'id', header: 'Pattern ID', width: 20 },
777
+ { key: 'type', header: 'Type', width: 15 },
778
+ { key: 'similarity', header: 'Similarity', width: 12 },
779
+ ],
780
+ data: matches.slice(0, k).map(function (m, i) {
781
+ var _a;
782
+ return ({
783
+ rank: String(i + 1),
784
+ id: ((_a = m.id) === null || _a === void 0 ? void 0 : _a.substring(0, 20)) || 'unknown',
785
+ type: m.type || 'action',
786
+ similarity: (m.similarity * 100).toFixed(1) + "%"
787
+ });
788
+ })
789
+ });
790
+ }
791
+ return [2 /*return*/, { success: true, data: { matches: matches, searchTime: searchTime } }];
792
+ case 5:
793
+ error_4 = _d.sent();
794
+ spinner.fail('Prediction failed');
795
+ output.printError(error_4 instanceof Error ? error_4.message : String(error_4));
796
+ return [2 /*return*/, { success: false, exitCode: 1 }];
797
+ case 6: return [2 /*return*/];
638
798
  }
639
- return { success: true, data: { matches, searchTime } };
640
- }
641
- catch (error) {
642
- spinner.fail('Prediction failed');
643
- output.printError(error instanceof Error ? error.message : String(error));
644
- return { success: false, exitCode: 1 };
645
- }
646
- },
799
+ });
800
+ }); }
647
801
  };
648
802
  // Optimize subcommand - Real Int8 quantization and pattern optimization
649
- const optimizeCommand = {
803
+ var optimizeCommand = {
650
804
  name: 'optimize',
651
805
  description: 'Optimize neural patterns (Int8 quantization, memory compression)',
652
806
  options: [
653
- { name: 'method', type: 'string', description: 'Method: quantize, analyze, compact', default: 'quantize' },
807
+ { name: 'method', type: 'string', description: 'Method: quantize, analyze, compact', "default": 'quantize' },
654
808
  { name: 'verbose', short: 'v', type: 'boolean', description: 'Show detailed metrics' },
655
809
  ],
656
810
  examples: [
657
811
  { command: 'claude-flow neural optimize --method quantize', description: 'Quantize patterns to Int8' },
658
812
  { command: 'claude-flow neural optimize --method analyze -v', description: 'Analyze memory usage' },
659
813
  ],
660
- action: async (ctx) => {
661
- const method = ctx.flags.method || 'quantize';
662
- const verbose = ctx.flags.verbose === true;
663
- output.writeln();
664
- output.writeln(output.bold('Pattern Optimization (Real)'));
665
- output.writeln(output.dim(''.repeat(50)));
666
- const spinner = output.createSpinner({ text: `Running ${method} optimization...`, spinner: 'dots' });
667
- spinner.start();
668
- try {
669
- const { initializeIntelligence, getIntelligenceStats, getAllPatterns, flushPatterns, compactPatterns } = await import('../memory/intelligence.js');
670
- const fs = await import('fs');
671
- const path = await import('path');
672
- await initializeIntelligence();
673
- const patterns = await getAllPatterns();
674
- const stats = getIntelligenceStats();
675
- // Get actual pattern storage size
676
- const patternDir = path.join(process.cwd(), '.claude-flow', 'neural');
677
- let beforeSize = 0;
678
- try {
679
- const patternFile = path.join(patternDir, 'patterns.json');
680
- if (fs.existsSync(patternFile)) {
681
- beforeSize = fs.statSync(patternFile).size;
682
- }
683
- }
684
- catch { /* ignore */ }
685
- if (method === 'quantize') {
686
- // Perform real Int8 quantization on pattern embeddings
687
- spinner.setText('Quantizing pattern embeddings to Int8...');
688
- let quantizedCount = 0;
689
- let memoryReduction = 0;
690
- for (const pattern of patterns) {
691
- if (pattern.embedding && pattern.embedding.length > 0) {
692
- // Float32 (4 bytes) -> Int8 (1 byte) = 4x reduction
693
- const beforeBytes = pattern.embedding.length * 4;
694
- const afterBytes = pattern.embedding.length; // Int8
695
- memoryReduction += beforeBytes - afterBytes;
696
- quantizedCount++;
697
- }
698
- }
699
- // Save optimized patterns
700
- await flushPatterns();
701
- // Get after size
702
- let afterSize = beforeSize;
703
- try {
704
- const patternFile = path.join(patternDir, 'patterns.json');
705
- if (fs.existsSync(patternFile)) {
706
- afterSize = fs.statSync(patternFile).size;
707
- }
708
- }
709
- catch { /* ignore */ }
710
- spinner.succeed(`Quantized ${quantizedCount} patterns`);
711
- output.writeln();
712
- output.printTable({
713
- columns: [
714
- { key: 'metric', header: 'Metric', width: 25 },
715
- { key: 'before', header: 'Before', width: 18 },
716
- { key: 'after', header: 'After', width: 18 },
717
- ],
718
- data: [
719
- { metric: 'Pattern Count', before: String(patterns.length), after: String(patterns.length) },
720
- { metric: 'Storage Size', before: `${(beforeSize / 1024).toFixed(1)} KB`, after: `${(afterSize / 1024).toFixed(1)} KB` },
721
- { metric: 'Embedding Memory', before: `${((memoryReduction * 4) / 1024).toFixed(1)} KB`, after: `${(memoryReduction / 1024).toFixed(1)} KB` },
722
- { metric: 'Memory Reduction', before: '-', after: `~${(3.92).toFixed(2)}x (Int8)` },
723
- { metric: 'Precision', before: 'Float32', after: 'Int8 (±0.5%)' },
724
- ],
725
- });
726
- }
727
- else if (method === 'analyze') {
728
- spinner.succeed('Analysis complete');
729
- output.writeln();
730
- output.writeln(output.bold('Pattern Memory Analysis'));
731
- const embeddingBytes = patterns.reduce((sum, p) => sum + (p.embedding?.length || 0) * 4, 0);
732
- const metadataEstimate = patterns.length * 100; // ~100 bytes per pattern metadata
733
- output.printTable({
734
- columns: [
735
- { key: 'component', header: 'Component', width: 25 },
736
- { key: 'size', header: 'Size', width: 18 },
737
- { key: 'count', header: 'Count', width: 12 },
738
- ],
739
- data: [
740
- { component: 'Pattern Embeddings (F32)', size: `${(embeddingBytes / 1024).toFixed(1)} KB`, count: String(patterns.length) },
741
- { component: 'Pattern Metadata', size: `${(metadataEstimate / 1024).toFixed(1)} KB`, count: '-' },
742
- { component: 'Total In-Memory', size: `${((embeddingBytes + metadataEstimate) / 1024).toFixed(1)} KB`, count: '-' },
743
- { component: 'Storage (patterns.json)', size: `${(beforeSize / 1024).toFixed(1)} KB`, count: '-' },
744
- { component: 'Trajectories', size: '-', count: String(stats.trajectoriesRecorded) },
745
- ],
746
- });
747
- if (verbose) {
814
+ action: function (ctx) { return __awaiter(void 0, void 0, Promise, function () {
815
+ var method, verbose, spinner, _a, initializeIntelligence, getIntelligenceStats, getAllPatterns, flushPatterns, compactPatterns, fs, path, patterns, stats, patternDir, beforeSize, patternFile, quantizedCount, memoryReduction, _i, patterns_1, pattern, beforeBytes, afterBytes, afterSize, patternFile, embeddingBytes, metadataEstimate, recommendations, compacted, error_5;
816
+ return __generator(this, function (_b) {
817
+ switch (_b.label) {
818
+ case 0:
819
+ method = ctx.flags.method || 'quantize';
820
+ verbose = ctx.flags.verbose === true;
748
821
  output.writeln();
749
- output.writeln(output.bold('Optimization Recommendations'));
750
- const recommendations = [];
751
- if (patterns.length > 1000) {
752
- recommendations.push('- Consider pruning low-usage patterns');
822
+ output.writeln(output.bold('Pattern Optimization (Real)'));
823
+ output.writeln(output.dim('─'.repeat(50)));
824
+ spinner = output.createSpinner({ text: "Running " + method + " optimization...", spinner: 'dots' });
825
+ spinner.start();
826
+ _b.label = 1;
827
+ case 1:
828
+ _b.trys.push([1, 12, , 13]);
829
+ return [4 /*yield*/, import('../memory/intelligence.js')];
830
+ case 2:
831
+ _a = _b.sent(), initializeIntelligence = _a.initializeIntelligence, getIntelligenceStats = _a.getIntelligenceStats, getAllPatterns = _a.getAllPatterns, flushPatterns = _a.flushPatterns, compactPatterns = _a.compactPatterns;
832
+ return [4 /*yield*/, import('fs')];
833
+ case 3:
834
+ fs = _b.sent();
835
+ return [4 /*yield*/, import('path')];
836
+ case 4:
837
+ path = _b.sent();
838
+ return [4 /*yield*/, initializeIntelligence()];
839
+ case 5:
840
+ _b.sent();
841
+ return [4 /*yield*/, getAllPatterns()];
842
+ case 6:
843
+ patterns = _b.sent();
844
+ stats = getIntelligenceStats();
845
+ patternDir = path.join(process.cwd(), '.claude-flow', 'neural');
846
+ beforeSize = 0;
847
+ try {
848
+ patternFile = path.join(patternDir, 'patterns.json');
849
+ if (fs.existsSync(patternFile)) {
850
+ beforeSize = fs.statSync(patternFile).size;
851
+ }
753
852
  }
754
- if (embeddingBytes > 1024 * 1024) {
755
- recommendations.push('- Int8 quantization would reduce memory by ~75%');
853
+ catch ( /* ignore */_c) { /* ignore */ }
854
+ if (!(method === 'quantize')) return [3 /*break*/, 8];
855
+ // Perform real Int8 quantization on pattern embeddings
856
+ spinner.setText('Quantizing pattern embeddings to Int8...');
857
+ quantizedCount = 0;
858
+ memoryReduction = 0;
859
+ for (_i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) {
860
+ pattern = patterns_1[_i];
861
+ if (pattern.embedding && pattern.embedding.length > 0) {
862
+ beforeBytes = pattern.embedding.length * 4;
863
+ afterBytes = pattern.embedding.length;
864
+ memoryReduction += beforeBytes - afterBytes;
865
+ quantizedCount++;
866
+ }
756
867
  }
757
- if (stats.trajectoriesRecorded > 100) {
758
- recommendations.push('- Trajectory consolidation available');
868
+ // Save optimized patterns
869
+ return [4 /*yield*/, flushPatterns()];
870
+ case 7:
871
+ // Save optimized patterns
872
+ _b.sent();
873
+ afterSize = beforeSize;
874
+ try {
875
+ patternFile = path.join(patternDir, 'patterns.json');
876
+ if (fs.existsSync(patternFile)) {
877
+ afterSize = fs.statSync(patternFile).size;
878
+ }
759
879
  }
760
- if (recommendations.length === 0) {
761
- recommendations.push('- Patterns are already well optimized');
880
+ catch ( /* ignore */_d) { /* ignore */ }
881
+ spinner.succeed("Quantized " + quantizedCount + " patterns");
882
+ output.writeln();
883
+ output.printTable({
884
+ columns: [
885
+ { key: 'metric', header: 'Metric', width: 25 },
886
+ { key: 'before', header: 'Before', width: 18 },
887
+ { key: 'after', header: 'After', width: 18 },
888
+ ],
889
+ data: [
890
+ { metric: 'Pattern Count', before: String(patterns.length), after: String(patterns.length) },
891
+ { metric: 'Storage Size', before: (beforeSize / 1024).toFixed(1) + " KB", after: (afterSize / 1024).toFixed(1) + " KB" },
892
+ { metric: 'Embedding Memory', before: ((memoryReduction * 4) / 1024).toFixed(1) + " KB", after: (memoryReduction / 1024).toFixed(1) + " KB" },
893
+ { metric: 'Memory Reduction', before: '-', after: "~" + (3.92).toFixed(2) + "x (Int8)" },
894
+ { metric: 'Precision', before: 'Float32', after: 'Int8 (±0.5%)' },
895
+ ]
896
+ });
897
+ return [3 /*break*/, 11];
898
+ case 8:
899
+ if (!(method === 'analyze')) return [3 /*break*/, 9];
900
+ spinner.succeed('Analysis complete');
901
+ output.writeln();
902
+ output.writeln(output.bold('Pattern Memory Analysis'));
903
+ embeddingBytes = patterns.reduce(function (sum, p) { var _a; return sum + (((_a = p.embedding) === null || _a === void 0 ? void 0 : _a.length) || 0) * 4; }, 0);
904
+ metadataEstimate = patterns.length * 100;
905
+ output.printTable({
906
+ columns: [
907
+ { key: 'component', header: 'Component', width: 25 },
908
+ { key: 'size', header: 'Size', width: 18 },
909
+ { key: 'count', header: 'Count', width: 12 },
910
+ ],
911
+ data: [
912
+ { component: 'Pattern Embeddings (F32)', size: (embeddingBytes / 1024).toFixed(1) + " KB", count: String(patterns.length) },
913
+ { component: 'Pattern Metadata', size: (metadataEstimate / 1024).toFixed(1) + " KB", count: '-' },
914
+ { component: 'Total In-Memory', size: ((embeddingBytes + metadataEstimate) / 1024).toFixed(1) + " KB", count: '-' },
915
+ { component: 'Storage (patterns.json)', size: (beforeSize / 1024).toFixed(1) + " KB", count: '-' },
916
+ { component: 'Trajectories', size: '-', count: String(stats.trajectoriesRecorded) },
917
+ ]
918
+ });
919
+ if (verbose) {
920
+ output.writeln();
921
+ output.writeln(output.bold('Optimization Recommendations'));
922
+ recommendations = [];
923
+ if (patterns.length > 1000) {
924
+ recommendations.push('- Consider pruning low-usage patterns');
925
+ }
926
+ if (embeddingBytes > 1024 * 1024) {
927
+ recommendations.push('- Int8 quantization would reduce memory by ~75%');
928
+ }
929
+ if (stats.trajectoriesRecorded > 100) {
930
+ recommendations.push('- Trajectory consolidation available');
931
+ }
932
+ if (recommendations.length === 0) {
933
+ recommendations.push('- Patterns are already well optimized');
934
+ }
935
+ recommendations.forEach(function (r) { return output.writeln(r); });
762
936
  }
763
- recommendations.forEach(r => output.writeln(r));
764
- }
765
- }
766
- else if (method === 'compact') {
767
- spinner.setText('Compacting pattern storage...');
768
- // Remove duplicate or very similar patterns
769
- const compacted = await compactPatterns(0.95); // Remove patterns with >95% similarity
770
- spinner.succeed(`Compacted ${compacted.removed} patterns`);
771
- output.writeln();
772
- output.printTable({
773
- columns: [
774
- { key: 'metric', header: 'Metric', width: 20 },
775
- { key: 'value', header: 'Value', width: 15 },
776
- ],
777
- data: [
778
- { metric: 'Patterns Before', value: String(compacted.before) },
779
- { metric: 'Patterns After', value: String(compacted.after) },
780
- { metric: 'Removed', value: String(compacted.removed) },
781
- { metric: 'Similarity Threshold', value: '95%' },
782
- ],
783
- });
937
+ return [3 /*break*/, 11];
938
+ case 9:
939
+ if (!(method === 'compact')) return [3 /*break*/, 11];
940
+ spinner.setText('Compacting pattern storage...');
941
+ return [4 /*yield*/, compactPatterns(0.95)];
942
+ case 10:
943
+ compacted = _b.sent();
944
+ spinner.succeed("Compacted " + compacted.removed + " patterns");
945
+ output.writeln();
946
+ output.printTable({
947
+ columns: [
948
+ { key: 'metric', header: 'Metric', width: 20 },
949
+ { key: 'value', header: 'Value', width: 15 },
950
+ ],
951
+ data: [
952
+ { metric: 'Patterns Before', value: String(compacted.before) },
953
+ { metric: 'Patterns After', value: String(compacted.after) },
954
+ { metric: 'Removed', value: String(compacted.removed) },
955
+ { metric: 'Similarity Threshold', value: '95%' },
956
+ ]
957
+ });
958
+ _b.label = 11;
959
+ case 11: return [2 /*return*/, { success: true }];
960
+ case 12:
961
+ error_5 = _b.sent();
962
+ spinner.fail('Optimization failed');
963
+ output.printError(error_5 instanceof Error ? error_5.message : String(error_5));
964
+ return [2 /*return*/, { success: false, exitCode: 1 }];
965
+ case 13: return [2 /*return*/];
784
966
  }
785
- return { success: true };
786
- }
787
- catch (error) {
788
- spinner.fail('Optimization failed');
789
- output.printError(error instanceof Error ? error.message : String(error));
790
- return { success: false, exitCode: 1 };
791
- }
792
- },
967
+ });
968
+ }); }
793
969
  };
794
970
  // Export subcommand - Securely export trained models to IPFS
795
- const exportCommand = {
971
+ var exportCommand = {
796
972
  name: 'export',
797
973
  description: 'Export trained models to IPFS for sharing (Ed25519 signed)',
798
974
  options: [
799
975
  { name: 'model', short: 'm', type: 'string', description: 'Model ID or category to export' },
800
976
  { name: 'output', short: 'o', type: 'string', description: 'Output file path (optional)' },
801
977
  { name: 'ipfs', short: 'i', type: 'boolean', description: 'Pin to IPFS (requires Pinata credentials)' },
802
- { name: 'sign', short: 's', type: 'boolean', description: 'Sign with Ed25519 key', default: 'true' },
803
- { name: 'strip-pii', type: 'boolean', description: 'Strip potential PII from export', default: 'true' },
978
+ { name: 'sign', short: 's', type: 'boolean', description: 'Sign with Ed25519 key', "default": 'true' },
979
+ { name: 'strip-pii', type: 'boolean', description: 'Strip potential PII from export', "default": 'true' },
804
980
  { name: 'name', short: 'n', type: 'string', description: 'Custom name for exported model' },
805
981
  ],
806
982
  examples: [
807
983
  { command: 'claude-flow neural export -m security-patterns --ipfs', description: 'Export and pin to IPFS' },
808
984
  { command: 'claude-flow neural export -m code-review -o ./export.json', description: 'Export to file' },
809
985
  ],
810
- action: async (ctx) => {
811
- const modelId = ctx.flags.model || 'all';
812
- const outputFile = ctx.flags.output;
813
- const pinToIpfs = ctx.flags.ipfs;
814
- const signExport = ctx.flags.sign !== false;
815
- const stripPii = ctx.flags['strip-pii'] !== false;
816
- const customName = ctx.flags.name;
817
- output.writeln();
818
- output.writeln(output.bold('Secure Model Export'));
819
- output.writeln(output.dim(''.repeat(50)));
820
- const spinner = output.createSpinner({ text: 'Preparing export...', spinner: 'dots' });
821
- spinner.start();
822
- try {
823
- const fs = await import('fs');
824
- const path = await import('path');
825
- const crypto = await import('crypto');
826
- // Collect trained patterns from memory
827
- spinner.setText('Collecting trained patterns...');
828
- const { getIntelligenceStats, flushPatterns } = await import('../memory/intelligence.js');
829
- await flushPatterns(); // Ensure all patterns are persisted
830
- const stats = await getIntelligenceStats();
831
- // SECURITY: Build export data - NEVER include secrets
832
- // - API keys read from env but NEVER included in export
833
- // - Uses ephemeral signing keys (generated per-export, not stored)
834
- // - PII stripping enabled by default
835
- // - Suspicious pattern content blocked
836
- const exportData = {
837
- type: 'learning-pattern',
838
- version: '1.0.0',
839
- name: customName || `claude-flow-model-${Date.now()}`,
840
- exportedAt: new Date().toISOString(),
841
- modelId,
842
- patterns: [],
843
- metadata: {
844
- sourceVersion: '3.0.0-alpha',
845
- piiStripped: stripPii,
846
- signed: signExport,
847
- accuracy: 0,
848
- totalUsage: 0,
849
- },
850
- };
851
- // Load patterns from local storage
852
- const memoryDir = path.join(process.cwd(), '.claude-flow', 'memory');
853
- const patternsFile = path.join(memoryDir, 'patterns.json');
854
- if (fs.existsSync(patternsFile)) {
855
- const patterns = JSON.parse(fs.readFileSync(patternsFile, 'utf8'));
856
- for (const pattern of patterns) {
857
- // Security: Strip potential PII
858
- if (stripPii) {
859
- // Remove any paths, usernames, or sensitive data
860
- if (pattern.content) {
861
- pattern.content = pattern.content
862
- .replace(/\/Users\/[^\/]+/g, '/Users/[REDACTED]')
863
- .replace(/\/home\/[^\/]+/g, '/home/[REDACTED]')
864
- .replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, '[EMAIL_REDACTED]')
865
- .replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g, '[IP_REDACTED]');
986
+ action: function (ctx) { return __awaiter(void 0, void 0, Promise, function () {
987
+ var modelId, outputFile, pinToIpfs, signExport, stripPii, customName, spinner, fs, path, crypto, _a, getIntelligenceStats, flushPatterns, stats, exportData, memoryDir, patternsFile, patterns, _i, patterns_2, pattern, signature, publicKey, webcrypto, keyPair, exportBytes, signatureBytes, publicKeyBytes, exportPackage, exportStr, secretPatterns, _b, secretPatterns_1, pattern, pinataKey, pinataSecret, response, error, result, error_6;
988
+ return __generator(this, function (_c) {
989
+ switch (_c.label) {
990
+ case 0:
991
+ modelId = ctx.flags.model || 'all';
992
+ outputFile = ctx.flags.output;
993
+ pinToIpfs = ctx.flags.ipfs;
994
+ signExport = ctx.flags.sign !== false;
995
+ stripPii = ctx.flags['strip-pii'] !== false;
996
+ customName = ctx.flags.name;
997
+ output.writeln();
998
+ output.writeln(output.bold('Secure Model Export'));
999
+ output.writeln(output.dim(''.repeat(50)));
1000
+ spinner = output.createSpinner({ text: 'Preparing export...', spinner: 'dots' });
1001
+ spinner.start();
1002
+ _c.label = 1;
1003
+ case 1:
1004
+ _c.trys.push([1, 17, , 18]);
1005
+ return [4 /*yield*/, import('fs')];
1006
+ case 2:
1007
+ fs = _c.sent();
1008
+ return [4 /*yield*/, import('path')];
1009
+ case 3:
1010
+ path = _c.sent();
1011
+ return [4 /*yield*/, import('crypto')];
1012
+ case 4:
1013
+ crypto = _c.sent();
1014
+ // Collect trained patterns from memory
1015
+ spinner.setText('Collecting trained patterns...');
1016
+ return [4 /*yield*/, import('../memory/intelligence.js')];
1017
+ case 5:
1018
+ _a = _c.sent(), getIntelligenceStats = _a.getIntelligenceStats, flushPatterns = _a.flushPatterns;
1019
+ return [4 /*yield*/, flushPatterns()];
1020
+ case 6:
1021
+ _c.sent(); // Ensure all patterns are persisted
1022
+ return [4 /*yield*/, getIntelligenceStats()];
1023
+ case 7:
1024
+ stats = _c.sent();
1025
+ exportData = {
1026
+ type: 'learning-pattern',
1027
+ version: '1.0.0',
1028
+ name: customName || "claude-flow-model-" + Date.now(),
1029
+ exportedAt: new Date().toISOString(),
1030
+ modelId: modelId,
1031
+ patterns: [],
1032
+ metadata: {
1033
+ sourceVersion: '3.0.0-alpha',
1034
+ piiStripped: stripPii,
1035
+ signed: signExport,
1036
+ accuracy: 0,
1037
+ totalUsage: 0
1038
+ }
1039
+ };
1040
+ memoryDir = path.join(process.cwd(), '.claude-flow', 'memory');
1041
+ patternsFile = path.join(memoryDir, 'patterns.json');
1042
+ if (fs.existsSync(patternsFile)) {
1043
+ patterns = JSON.parse(fs.readFileSync(patternsFile, 'utf8'));
1044
+ for (_i = 0, patterns_2 = patterns; _i < patterns_2.length; _i++) {
1045
+ pattern = patterns_2[_i];
1046
+ // Security: Strip potential PII
1047
+ if (stripPii) {
1048
+ // Remove any paths, usernames, or sensitive data
1049
+ if (pattern.content) {
1050
+ pattern.content = pattern.content
1051
+ .replace(/\/Users\/[^\/]+/g, '/Users/[REDACTED]')
1052
+ .replace(/\/home\/[^\/]+/g, '/home/[REDACTED]')
1053
+ .replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, '[EMAIL_REDACTED]')
1054
+ .replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g, '[IP_REDACTED]');
1055
+ }
1056
+ }
1057
+ exportData.patterns.push({
1058
+ id: pattern.id || crypto.randomBytes(8).toString('hex'),
1059
+ trigger: pattern.trigger || pattern.type || 'general',
1060
+ action: pattern.action || pattern.recommendation || 'apply-pattern',
1061
+ confidence: pattern.confidence || 0.85,
1062
+ usageCount: pattern.usageCount || 1
1063
+ });
1064
+ }
1065
+ }
1066
+ // Add stats metadata
1067
+ exportData.metadata.accuracy = stats.retrievalPrecision || 0.85;
1068
+ exportData.metadata.totalUsage = exportData.patterns.reduce(function (sum, p) { return sum + p.usageCount; }, 0);
1069
+ spinner.setText('Generating secure signature...');
1070
+ signature = null;
1071
+ publicKey = null;
1072
+ if (!signExport) return [3 /*break*/, 11];
1073
+ webcrypto = crypto.webcrypto;
1074
+ return [4 /*yield*/, webcrypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']
1075
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1076
+ )];
1077
+ case 8:
1078
+ keyPair = _c.sent();
1079
+ exportBytes = new TextEncoder().encode(JSON.stringify(exportData));
1080
+ return [4 /*yield*/, webcrypto.subtle.sign('Ed25519', keyPair.privateKey, exportBytes)];
1081
+ case 9:
1082
+ signatureBytes = _c.sent();
1083
+ signature = Buffer.from(signatureBytes).toString('hex');
1084
+ return [4 /*yield*/, webcrypto.subtle.exportKey('raw', keyPair.publicKey)];
1085
+ case 10:
1086
+ publicKeyBytes = _c.sent();
1087
+ publicKey = Buffer.from(publicKeyBytes).toString('hex');
1088
+ _c.label = 11;
1089
+ case 11:
1090
+ exportPackage = {
1091
+ pinataContent: exportData,
1092
+ pinataMetadata: {
1093
+ name: exportData.name,
1094
+ keyvalues: {
1095
+ type: 'learning-pattern',
1096
+ version: '1.0.0',
1097
+ signed: signExport ? 'true' : 'false'
1098
+ }
1099
+ },
1100
+ signature: signature,
1101
+ publicKey: publicKey ? "ed25519:" + publicKey : null
1102
+ };
1103
+ exportStr = JSON.stringify(exportPackage);
1104
+ secretPatterns = [
1105
+ /sk-ant-[a-zA-Z0-9-]+/,
1106
+ /sk-[a-zA-Z0-9]{48}/,
1107
+ /AIza[a-zA-Z0-9-_]{35}/,
1108
+ /pinata_[a-zA-Z0-9]+/,
1109
+ /-----BEGIN.*KEY-----/, // PEM keys
1110
+ ];
1111
+ for (_b = 0, secretPatterns_1 = secretPatterns; _b < secretPatterns_1.length; _b++) {
1112
+ pattern = secretPatterns_1[_b];
1113
+ if (pattern.test(exportStr)) {
1114
+ spinner.fail('SECURITY: Export contains potential API keys - aborting');
1115
+ return [2 /*return*/, { success: false, exitCode: 1 }];
866
1116
  }
867
1117
  }
868
- exportData.patterns.push({
869
- id: pattern.id || crypto.randomBytes(8).toString('hex'),
870
- trigger: pattern.trigger || pattern.type || 'general',
871
- action: pattern.action || pattern.recommendation || 'apply-pattern',
872
- confidence: pattern.confidence || 0.85,
873
- usageCount: pattern.usageCount || 1,
1118
+ // Output handling
1119
+ if (outputFile) {
1120
+ fs.writeFileSync(outputFile, JSON.stringify(exportPackage, null, 2));
1121
+ spinner.succeed("Exported to: " + outputFile);
1122
+ }
1123
+ if (!pinToIpfs) return [3 /*break*/, 16];
1124
+ spinner.setText('Pinning to IPFS...');
1125
+ pinataKey = process.env.PINATA_API_KEY;
1126
+ pinataSecret = process.env.PINATA_API_SECRET;
1127
+ if (!pinataKey || !pinataSecret) {
1128
+ spinner.fail('PINATA_API_KEY and PINATA_API_SECRET required for IPFS export');
1129
+ output.writeln(output.dim('Set these in your environment or .env file'));
1130
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1131
+ }
1132
+ return [4 /*yield*/, fetch('https://api.pinata.cloud/pinning/pinJSONToIPFS', {
1133
+ method: 'POST',
1134
+ headers: {
1135
+ 'Content-Type': 'application/json',
1136
+ 'pinata_api_key': pinataKey,
1137
+ 'pinata_secret_api_key': pinataSecret
1138
+ },
1139
+ body: JSON.stringify(exportPackage)
1140
+ })];
1141
+ case 12:
1142
+ response = _c.sent();
1143
+ if (!!response.ok) return [3 /*break*/, 14];
1144
+ return [4 /*yield*/, response.text()];
1145
+ case 13:
1146
+ error = _c.sent();
1147
+ spinner.fail("IPFS pin failed: " + error);
1148
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1149
+ case 14: return [4 /*yield*/, response.json()];
1150
+ case 15:
1151
+ result = _c.sent();
1152
+ spinner.succeed('Successfully exported to IPFS');
1153
+ output.writeln();
1154
+ output.table({
1155
+ columns: [
1156
+ { key: 'property', header: 'Property', width: 20 },
1157
+ { key: 'value', header: 'Value', width: 50 },
1158
+ ],
1159
+ data: [
1160
+ { property: 'CID', value: result.IpfsHash },
1161
+ { property: 'Size', value: result.PinSize + " bytes" },
1162
+ { property: 'Gateway URL', value: "https://gateway.pinata.cloud/ipfs/" + result.IpfsHash },
1163
+ { property: 'Patterns', value: String(exportData.patterns.length) },
1164
+ { property: 'Signed', value: signExport ? 'Yes (Ed25519)' : 'No' },
1165
+ { property: 'PII Stripped', value: stripPii ? 'Yes' : 'No' },
1166
+ ]
874
1167
  });
875
- }
876
- }
877
- // Add stats metadata
878
- exportData.metadata.accuracy = stats.retrievalPrecision || 0.85;
879
- exportData.metadata.totalUsage = exportData.patterns.reduce((sum, p) => sum + p.usageCount, 0);
880
- spinner.setText('Generating secure signature...');
881
- // Sign with Ed25519 if requested
882
- let signature = null;
883
- let publicKey = null;
884
- if (signExport) {
885
- // Generate ephemeral key pair for signing
886
- // Use Node.js webcrypto for Ed25519 signing
887
- const { webcrypto } = crypto;
888
- const keyPair = await webcrypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']
889
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
890
- );
891
- const exportBytes = new TextEncoder().encode(JSON.stringify(exportData));
892
- const signatureBytes = await webcrypto.subtle.sign('Ed25519', keyPair.privateKey, exportBytes);
893
- signature = Buffer.from(signatureBytes).toString('hex');
894
- const publicKeyBytes = await webcrypto.subtle.exportKey('raw', keyPair.publicKey);
895
- publicKey = Buffer.from(publicKeyBytes).toString('hex');
896
- }
897
- // SECURITY: Final export package - verify no secrets leaked
898
- const exportPackage = {
899
- pinataContent: exportData,
900
- pinataMetadata: {
901
- name: exportData.name,
902
- keyvalues: {
903
- type: 'learning-pattern',
904
- version: '1.0.0',
905
- signed: signExport ? 'true' : 'false',
906
- },
907
- },
908
- signature,
909
- publicKey: publicKey ? `ed25519:${publicKey}` : null,
910
- // Note: Private key is ephemeral and NEVER stored or exported
911
- };
912
- // SECURITY AUDIT: Ensure no secrets in export
913
- const exportStr = JSON.stringify(exportPackage);
914
- const secretPatterns = [
915
- /sk-ant-[a-zA-Z0-9-]+/, // Anthropic keys
916
- /sk-[a-zA-Z0-9]{48}/, // OpenAI keys
917
- /AIza[a-zA-Z0-9-_]{35}/, // Google keys
918
- /pinata_[a-zA-Z0-9]+/, // Pinata JWT
919
- /-----BEGIN.*KEY-----/, // PEM keys
920
- ];
921
- for (const pattern of secretPatterns) {
922
- if (pattern.test(exportStr)) {
923
- spinner.fail('SECURITY: Export contains potential API keys - aborting');
924
- return { success: false, exitCode: 1 };
925
- }
926
- }
927
- // Output handling
928
- if (outputFile) {
929
- fs.writeFileSync(outputFile, JSON.stringify(exportPackage, null, 2));
930
- spinner.succeed(`Exported to: ${outputFile}`);
931
- }
932
- if (pinToIpfs) {
933
- spinner.setText('Pinning to IPFS...');
934
- // Check for Pinata credentials
935
- const pinataKey = process.env.PINATA_API_KEY;
936
- const pinataSecret = process.env.PINATA_API_SECRET;
937
- if (!pinataKey || !pinataSecret) {
938
- spinner.fail('PINATA_API_KEY and PINATA_API_SECRET required for IPFS export');
939
- output.writeln(output.dim('Set these in your environment or .env file'));
940
- return { success: false, exitCode: 1 };
941
- }
942
- const response = await fetch('https://api.pinata.cloud/pinning/pinJSONToIPFS', {
943
- method: 'POST',
944
- headers: {
945
- 'Content-Type': 'application/json',
946
- 'pinata_api_key': pinataKey,
947
- 'pinata_secret_api_key': pinataSecret,
948
- },
949
- body: JSON.stringify(exportPackage),
950
- });
951
- if (!response.ok) {
952
- const error = await response.text();
953
- spinner.fail(`IPFS pin failed: ${error}`);
954
- return { success: false, exitCode: 1 };
955
- }
956
- const result = await response.json();
957
- spinner.succeed('Successfully exported to IPFS');
958
- output.writeln();
959
- output.table({
960
- columns: [
961
- { key: 'property', header: 'Property', width: 20 },
962
- { key: 'value', header: 'Value', width: 50 },
963
- ],
964
- data: [
965
- { property: 'CID', value: result.IpfsHash },
966
- { property: 'Size', value: `${result.PinSize} bytes` },
967
- { property: 'Gateway URL', value: `https://gateway.pinata.cloud/ipfs/${result.IpfsHash}` },
968
- { property: 'Patterns', value: String(exportData.patterns.length) },
969
- { property: 'Signed', value: signExport ? 'Yes (Ed25519)' : 'No' },
970
- { property: 'PII Stripped', value: stripPii ? 'Yes' : 'No' },
971
- ],
972
- });
973
- output.writeln();
974
- output.writeln(output.success('Share this CID for others to import your trained patterns'));
975
- output.writeln(output.dim(`Import command: claude-flow neural import --cid ${result.IpfsHash}`));
976
- }
977
- if (!outputFile && !pinToIpfs) {
978
- // Just display the export
979
- spinner.succeed('Export prepared');
980
- output.writeln();
981
- output.writeln(JSON.stringify(exportPackage, null, 2));
1168
+ output.writeln();
1169
+ output.writeln(output.success('Share this CID for others to import your trained patterns'));
1170
+ output.writeln(output.dim("Import command: claude-flow neural import --cid " + result.IpfsHash));
1171
+ _c.label = 16;
1172
+ case 16:
1173
+ if (!outputFile && !pinToIpfs) {
1174
+ // Just display the export
1175
+ spinner.succeed('Export prepared');
1176
+ output.writeln();
1177
+ output.writeln(JSON.stringify(exportPackage, null, 2));
1178
+ }
1179
+ return [2 /*return*/, { success: true }];
1180
+ case 17:
1181
+ error_6 = _c.sent();
1182
+ spinner.fail("Export failed: " + (error_6 instanceof Error ? error_6.message : String(error_6)));
1183
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1184
+ case 18: return [2 /*return*/];
982
1185
  }
983
- return { success: true };
984
- }
985
- catch (error) {
986
- spinner.fail(`Export failed: ${error instanceof Error ? error.message : String(error)}`);
987
- return { success: false, exitCode: 1 };
988
- }
989
- },
1186
+ });
1187
+ }); }
990
1188
  };
991
1189
  // List subcommand - List available pre-trained models
992
- const listCommand = {
1190
+ var listCommand = {
993
1191
  name: 'list',
994
1192
  description: 'List available pre-trained models from the official registry',
995
1193
  options: [
996
1194
  { name: 'category', type: 'string', description: 'Filter by category (security, quality, performance, etc.)' },
997
- { name: 'format', short: 'f', type: 'string', description: 'Output format: table, json, simple', default: 'table' },
1195
+ { name: 'format', short: 'f', type: 'string', description: 'Output format: table, json, simple', "default": 'table' },
998
1196
  { name: 'cid', type: 'string', description: 'Custom registry CID (default: official registry)' },
999
1197
  ],
1000
1198
  examples: [
@@ -1002,116 +1200,137 @@ const listCommand = {
1002
1200
  { command: 'claude-flow neural list --category security', description: 'List only security models' },
1003
1201
  { command: 'claude-flow neural list -f json', description: 'Output as JSON' },
1004
1202
  ],
1005
- action: async (ctx) => {
1006
- const category = ctx.flags.category;
1007
- const format = ctx.flags.format || 'table';
1008
- const customCid = ctx.flags.cid;
1009
- // Official model registry CID
1010
- const registryCid = customCid || 'QmNr1yYMKi7YBaL8JSztQyuB5ZUaTdRMLxJC1pBpGbjsTc';
1011
- output.writeln();
1012
- output.writeln(output.bold('Pre-trained Model Registry'));
1013
- output.writeln(output.dim(''.repeat(60)));
1014
- const spinner = output.createSpinner({ text: 'Fetching model registry...', spinner: 'dots' });
1015
- spinner.start();
1016
- try {
1017
- const gateways = [
1018
- 'https://gateway.pinata.cloud',
1019
- 'https://ipfs.io',
1020
- 'https://dweb.link',
1021
- ];
1022
- let registry = null;
1023
- for (const gateway of gateways) {
1024
- try {
1025
- const response = await fetch(`${gateway}/ipfs/${registryCid}`, {
1026
- signal: AbortSignal.timeout(15000),
1027
- headers: { 'Accept': 'application/json' },
1028
- });
1029
- if (response.ok) {
1030
- registry = await response.json();
1031
- break;
1203
+ action: function (ctx) { return __awaiter(void 0, void 0, Promise, function () {
1204
+ var category, format, customCid, registryCid, spinner, gateways, registry, _i, gateways_1, gateway, response, _a, registryData, models, _b, models_1, model, error_7;
1205
+ return __generator(this, function (_c) {
1206
+ switch (_c.label) {
1207
+ case 0:
1208
+ category = ctx.flags.category;
1209
+ format = ctx.flags.format || 'table';
1210
+ customCid = ctx.flags.cid;
1211
+ registryCid = customCid || 'QmNr1yYMKi7YBaL8JSztQyuB5ZUaTdRMLxJC1pBpGbjsTc';
1212
+ output.writeln();
1213
+ output.writeln(output.bold('Pre-trained Model Registry'));
1214
+ output.writeln(output.dim('─'.repeat(60)));
1215
+ spinner = output.createSpinner({ text: 'Fetching model registry...', spinner: 'dots' });
1216
+ spinner.start();
1217
+ _c.label = 1;
1218
+ case 1:
1219
+ _c.trys.push([1, 10, , 11]);
1220
+ gateways = [
1221
+ 'https://gateway.pinata.cloud',
1222
+ 'https://ipfs.io',
1223
+ 'https://dweb.link',
1224
+ ];
1225
+ registry = null;
1226
+ _i = 0, gateways_1 = gateways;
1227
+ _c.label = 2;
1228
+ case 2:
1229
+ if (!(_i < gateways_1.length)) return [3 /*break*/, 9];
1230
+ gateway = gateways_1[_i];
1231
+ _c.label = 3;
1232
+ case 3:
1233
+ _c.trys.push([3, 7, , 8]);
1234
+ return [4 /*yield*/, fetch(gateway + "/ipfs/" + registryCid, {
1235
+ signal: AbortSignal.timeout(15000),
1236
+ headers: { 'Accept': 'application/json' }
1237
+ })];
1238
+ case 4:
1239
+ response = _c.sent();
1240
+ if (!response.ok) return [3 /*break*/, 6];
1241
+ return [4 /*yield*/, response.json()];
1242
+ case 5:
1243
+ registry = (_c.sent());
1244
+ return [3 /*break*/, 9];
1245
+ case 6: return [3 /*break*/, 8];
1246
+ case 7:
1247
+ _a = _c.sent();
1248
+ return [3 /*break*/, 8];
1249
+ case 8:
1250
+ _i++;
1251
+ return [3 /*break*/, 2];
1252
+ case 9:
1253
+ if (!registry || !registry.models) {
1254
+ spinner.fail('Could not fetch model registry');
1255
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1032
1256
  }
1033
- }
1034
- catch {
1035
- continue;
1036
- }
1037
- }
1038
- if (!registry || !registry.models) {
1039
- spinner.fail('Could not fetch model registry');
1040
- return { success: false, exitCode: 1 };
1041
- }
1042
- const registryData = registry;
1043
- // Filter by category if specified
1044
- let models = registryData.models;
1045
- if (category) {
1046
- models = models.filter(m => m.category === category ||
1047
- m.id.includes(category) ||
1048
- m.name.toLowerCase().includes(category.toLowerCase()));
1049
- spinner.succeed(`Found ${models.length} models matching "${category}"`);
1050
- }
1051
- else {
1052
- spinner.succeed(`Found ${registryData.models.length} models`);
1053
- }
1054
- if (models.length === 0) {
1055
- output.writeln(output.warning(`No models found for category: ${category}`));
1056
- output.writeln(output.dim('Available categories: security, quality, performance, testing, api, debugging, refactoring, documentation'));
1057
- return { success: false, exitCode: 1 };
1058
- }
1059
- output.writeln();
1060
- if (format === 'json') {
1061
- output.writeln(JSON.stringify(models, null, 2));
1062
- }
1063
- else if (format === 'simple') {
1064
- for (const model of models) {
1065
- output.writeln(`${model.id} (${model.category}) - ${model.patterns.length} patterns, ${(model.metadata.accuracy * 100).toFixed(0)}% accuracy`);
1066
- }
1067
- }
1068
- else {
1069
- // Table format
1070
- output.printTable({
1071
- columns: [
1072
- { key: 'id', header: 'Model ID', width: 35 },
1073
- { key: 'category', header: 'Category', width: 14 },
1074
- { key: 'patterns', header: 'Patterns', width: 10 },
1075
- { key: 'accuracy', header: 'Accuracy', width: 10 },
1076
- { key: 'usage', header: 'Usage', width: 10 },
1077
- ],
1078
- data: models.map(m => ({
1079
- id: m.id,
1080
- category: m.category,
1081
- patterns: String(m.patterns.length),
1082
- accuracy: `${(m.metadata.accuracy * 100).toFixed(0)}%`,
1083
- usage: m.metadata.totalUsage.toLocaleString(),
1084
- })),
1085
- });
1086
- output.writeln();
1087
- output.writeln(output.dim('Registry CID: ' + registryCid));
1088
- output.writeln();
1089
- output.writeln(output.bold('Import Commands:'));
1090
- output.writeln(output.dim(' All models: ') + `claude-flow neural import --cid ${registryCid}`);
1091
- if (category) {
1092
- output.writeln(output.dim(` ${category} only: `) + `claude-flow neural import --cid ${registryCid} --category ${category}`);
1093
- }
1094
- else {
1095
- output.writeln(output.dim(' By category: ') + `claude-flow neural import --cid ${registryCid} --category <category>`);
1096
- }
1257
+ registryData = registry;
1258
+ models = registryData.models;
1259
+ if (category) {
1260
+ models = models.filter(function (m) {
1261
+ return m.category === category ||
1262
+ m.id.includes(category) ||
1263
+ m.name.toLowerCase().includes(category.toLowerCase());
1264
+ });
1265
+ spinner.succeed("Found " + models.length + " models matching \"" + category + "\"");
1266
+ }
1267
+ else {
1268
+ spinner.succeed("Found " + registryData.models.length + " models");
1269
+ }
1270
+ if (models.length === 0) {
1271
+ output.writeln(output.warning("No models found for category: " + category));
1272
+ output.writeln(output.dim('Available categories: security, quality, performance, testing, api, debugging, refactoring, documentation'));
1273
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1274
+ }
1275
+ output.writeln();
1276
+ if (format === 'json') {
1277
+ output.writeln(JSON.stringify(models, null, 2));
1278
+ }
1279
+ else if (format === 'simple') {
1280
+ for (_b = 0, models_1 = models; _b < models_1.length; _b++) {
1281
+ model = models_1[_b];
1282
+ output.writeln(model.id + " (" + model.category + ") - " + model.patterns.length + " patterns, " + (model.metadata.accuracy * 100).toFixed(0) + "% accuracy");
1283
+ }
1284
+ }
1285
+ else {
1286
+ // Table format
1287
+ output.printTable({
1288
+ columns: [
1289
+ { key: 'id', header: 'Model ID', width: 35 },
1290
+ { key: 'category', header: 'Category', width: 14 },
1291
+ { key: 'patterns', header: 'Patterns', width: 10 },
1292
+ { key: 'accuracy', header: 'Accuracy', width: 10 },
1293
+ { key: 'usage', header: 'Usage', width: 10 },
1294
+ ],
1295
+ data: models.map(function (m) { return ({
1296
+ id: m.id,
1297
+ category: m.category,
1298
+ patterns: String(m.patterns.length),
1299
+ accuracy: (m.metadata.accuracy * 100).toFixed(0) + "%",
1300
+ usage: m.metadata.totalUsage.toLocaleString()
1301
+ }); })
1302
+ });
1303
+ output.writeln();
1304
+ output.writeln(output.dim('Registry CID: ' + registryCid));
1305
+ output.writeln();
1306
+ output.writeln(output.bold('Import Commands:'));
1307
+ output.writeln(output.dim(' All models: ') + ("claude-flow neural import --cid " + registryCid));
1308
+ if (category) {
1309
+ output.writeln(output.dim(" " + category + " only: ") + ("claude-flow neural import --cid " + registryCid + " --category " + category));
1310
+ }
1311
+ else {
1312
+ output.writeln(output.dim(' By category: ') + ("claude-flow neural import --cid " + registryCid + " --category <category>"));
1313
+ }
1314
+ }
1315
+ return [2 /*return*/, { success: true }];
1316
+ case 10:
1317
+ error_7 = _c.sent();
1318
+ spinner.fail("Failed to list models: " + (error_7 instanceof Error ? error_7.message : String(error_7)));
1319
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1320
+ case 11: return [2 /*return*/];
1097
1321
  }
1098
- return { success: true };
1099
- }
1100
- catch (error) {
1101
- spinner.fail(`Failed to list models: ${error instanceof Error ? error.message : String(error)}`);
1102
- return { success: false, exitCode: 1 };
1103
- }
1104
- },
1322
+ });
1323
+ }); }
1105
1324
  };
1106
1325
  // Import subcommand - Securely import models from IPFS
1107
- const importCommand = {
1326
+ var importCommand = {
1108
1327
  name: 'import',
1109
1328
  description: 'Import trained models from IPFS with signature verification',
1110
1329
  options: [
1111
1330
  { name: 'cid', short: 'c', type: 'string', description: 'IPFS CID to import from' },
1112
1331
  { name: 'file', short: 'f', type: 'string', description: 'Local file to import' },
1113
- { name: 'verify', short: 'v', type: 'boolean', description: 'Verify Ed25519 signature', default: 'true' },
1114
- { name: 'merge', type: 'boolean', description: 'Merge with existing patterns (vs replace)', default: 'true' },
1332
+ { name: 'verify', short: 'v', type: 'boolean', description: 'Verify Ed25519 signature', "default": 'true' },
1333
+ { name: 'merge', type: 'boolean', description: 'Merge with existing patterns (vs replace)', "default": 'true' },
1115
1334
  { name: 'category', type: 'string', description: 'Only import patterns from specific category' },
1116
1335
  ],
1117
1336
  examples: [
@@ -1119,312 +1338,371 @@ const importCommand = {
1119
1338
  { command: 'claude-flow neural import -f ./patterns.json --verify', description: 'Import from file' },
1120
1339
  { command: 'claude-flow neural import --cid QmNr1yYMK... --category security', description: 'Import only security patterns' },
1121
1340
  ],
1122
- action: async (ctx) => {
1123
- const cid = ctx.flags.cid;
1124
- const file = ctx.flags.file;
1125
- const verifySignature = ctx.flags.verify !== false;
1126
- const merge = ctx.flags.merge !== false;
1127
- const categoryFilter = ctx.flags.category;
1128
- if (!cid && !file) {
1129
- output.writeln(output.error('Either --cid or --file is required'));
1130
- return { success: false, exitCode: 1 };
1131
- }
1132
- output.writeln();
1133
- output.writeln(output.bold('Secure Model Import'));
1134
- output.writeln(output.dim('─'.repeat(50)));
1135
- const spinner = output.createSpinner({ text: 'Fetching model...', spinner: 'dots' });
1136
- spinner.start();
1137
- try {
1138
- const fs = await import('fs');
1139
- const path = await import('path');
1140
- const crypto = await import('crypto');
1141
- let importData = null;
1142
- // Fetch from IPFS or file
1143
- if (cid) {
1144
- const gateways = [
1145
- 'https://gateway.pinata.cloud',
1146
- 'https://ipfs.io',
1147
- 'https://dweb.link',
1148
- ];
1149
- for (const gateway of gateways) {
1150
- try {
1151
- spinner.setText(`Fetching from ${gateway}...`);
1152
- const response = await fetch(`${gateway}/ipfs/${cid}`, {
1341
+ action: function (ctx) { return __awaiter(void 0, void 0, Promise, function () {
1342
+ var cid, file, verifySignature, merge, categoryFilter, spinner, fs, path, crypto, importData, gateways, _i, gateways_2, gateway, response, _a, webcrypto, publicKeyHex, publicKeyBytes, signatureBytes, publicKey, dataBytes, valid, err_1, content, patterns, registry, _b, _c, model, _d, _e, pattern, validPatterns, memoryDir, patternsFile, existingPatterns, existingIds_1, newPatterns, finalPatterns, error_8;
1343
+ return __generator(this, function (_f) {
1344
+ switch (_f.label) {
1345
+ case 0:
1346
+ cid = ctx.flags.cid;
1347
+ file = ctx.flags.file;
1348
+ verifySignature = ctx.flags.verify !== false;
1349
+ merge = ctx.flags.merge !== false;
1350
+ categoryFilter = ctx.flags.category;
1351
+ if (!cid && !file) {
1352
+ output.writeln(output.error('Either --cid or --file is required'));
1353
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1354
+ }
1355
+ output.writeln();
1356
+ output.writeln(output.bold('Secure Model Import'));
1357
+ output.writeln(output.dim(''.repeat(50)));
1358
+ spinner = output.createSpinner({ text: 'Fetching model...', spinner: 'dots' });
1359
+ spinner.start();
1360
+ _f.label = 1;
1361
+ case 1:
1362
+ _f.trys.push([1, 20, , 21]);
1363
+ return [4 /*yield*/, import('fs')];
1364
+ case 2:
1365
+ fs = _f.sent();
1366
+ return [4 /*yield*/, import('path')];
1367
+ case 3:
1368
+ path = _f.sent();
1369
+ return [4 /*yield*/, import('crypto')];
1370
+ case 4:
1371
+ crypto = _f.sent();
1372
+ importData = null;
1373
+ if (!cid) return [3 /*break*/, 13];
1374
+ gateways = [
1375
+ 'https://gateway.pinata.cloud',
1376
+ 'https://ipfs.io',
1377
+ 'https://dweb.link',
1378
+ ];
1379
+ _i = 0, gateways_2 = gateways;
1380
+ _f.label = 5;
1381
+ case 5:
1382
+ if (!(_i < gateways_2.length)) return [3 /*break*/, 12];
1383
+ gateway = gateways_2[_i];
1384
+ _f.label = 6;
1385
+ case 6:
1386
+ _f.trys.push([6, 10, , 11]);
1387
+ spinner.setText("Fetching from " + gateway + "...");
1388
+ return [4 /*yield*/, fetch(gateway + "/ipfs/" + cid, {
1153
1389
  signal: AbortSignal.timeout(30000),
1154
- headers: { 'Accept': 'application/json' },
1155
- });
1156
- if (response.ok) {
1157
- importData = await response.json();
1158
- break;
1159
- }
1390
+ headers: { 'Accept': 'application/json' }
1391
+ })];
1392
+ case 7:
1393
+ response = _f.sent();
1394
+ if (!response.ok) return [3 /*break*/, 9];
1395
+ return [4 /*yield*/, response.json()];
1396
+ case 8:
1397
+ importData = (_f.sent());
1398
+ return [3 /*break*/, 12];
1399
+ case 9: return [3 /*break*/, 11];
1400
+ case 10:
1401
+ _a = _f.sent();
1402
+ return [3 /*break*/, 11];
1403
+ case 11:
1404
+ _i++;
1405
+ return [3 /*break*/, 5];
1406
+ case 12:
1407
+ if (!importData) {
1408
+ spinner.fail('Could not fetch from any IPFS gateway');
1409
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1160
1410
  }
1161
- catch {
1162
- continue;
1411
+ return [3 /*break*/, 14];
1412
+ case 13:
1413
+ if (!fs.existsSync(file)) {
1414
+ spinner.fail("File not found: " + file);
1415
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1163
1416
  }
1164
- }
1165
- if (!importData) {
1166
- spinner.fail('Could not fetch from any IPFS gateway');
1167
- return { success: false, exitCode: 1 };
1168
- }
1169
- }
1170
- else {
1171
- if (!fs.existsSync(file)) {
1172
- spinner.fail(`File not found: ${file}`);
1173
- return { success: false, exitCode: 1 };
1174
- }
1175
- importData = JSON.parse(fs.readFileSync(file, 'utf8'));
1176
- }
1177
- if (!importData) {
1178
- spinner.fail('No import data available');
1179
- return { success: false, exitCode: 1 };
1180
- }
1181
- // Verify signature if present and requested
1182
- if (verifySignature && importData.signature && importData.publicKey) {
1183
- spinner.setText('Verifying Ed25519 signature...');
1184
- try {
1185
- const { webcrypto } = crypto;
1186
- const publicKeyHex = importData.publicKey.replace('ed25519:', '');
1187
- const publicKeyBytes = Buffer.from(publicKeyHex, 'hex');
1188
- const signatureBytes = Buffer.from(importData.signature, 'hex');
1189
- const publicKey = await webcrypto.subtle.importKey('raw', publicKeyBytes, { name: 'Ed25519' }, false, ['verify']);
1190
- const dataBytes = new TextEncoder().encode(JSON.stringify(importData.pinataContent));
1191
- const valid = await webcrypto.subtle.verify('Ed25519', publicKey, signatureBytes, dataBytes);
1417
+ importData = JSON.parse(fs.readFileSync(file, 'utf8'));
1418
+ _f.label = 14;
1419
+ case 14:
1420
+ if (!importData) {
1421
+ spinner.fail('No import data available');
1422
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1423
+ }
1424
+ if (!(verifySignature && importData.signature && importData.publicKey)) return [3 /*break*/, 19];
1425
+ spinner.setText('Verifying Ed25519 signature...');
1426
+ _f.label = 15;
1427
+ case 15:
1428
+ _f.trys.push([15, 18, , 19]);
1429
+ webcrypto = crypto.webcrypto;
1430
+ publicKeyHex = importData.publicKey.replace('ed25519:', '');
1431
+ publicKeyBytes = Buffer.from(publicKeyHex, 'hex');
1432
+ signatureBytes = Buffer.from(importData.signature, 'hex');
1433
+ return [4 /*yield*/, webcrypto.subtle.importKey('raw', publicKeyBytes, { name: 'Ed25519' }, false, ['verify'])];
1434
+ case 16:
1435
+ publicKey = _f.sent();
1436
+ dataBytes = new TextEncoder().encode(JSON.stringify(importData.pinataContent));
1437
+ return [4 /*yield*/, webcrypto.subtle.verify('Ed25519', publicKey, signatureBytes, dataBytes)];
1438
+ case 17:
1439
+ valid = _f.sent();
1192
1440
  if (!valid) {
1193
1441
  spinner.fail('Signature verification FAILED - data may be tampered');
1194
- return { success: false, exitCode: 1 };
1442
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1195
1443
  }
1196
1444
  output.writeln(output.success('Signature verified'));
1197
- }
1198
- catch (err) {
1199
- output.writeln(output.warning(`Signature verification skipped: ${err instanceof Error ? err.message : String(err)}`));
1200
- }
1201
- }
1202
- // Extract patterns - handle both single model and model registry formats
1203
- spinner.setText('Importing patterns...');
1204
- const content = importData.pinataContent || importData;
1205
- let patterns = [];
1206
- // Check if this is a model registry (has models array)
1207
- const registry = content;
1208
- if (registry.models && Array.isArray(registry.models)) {
1209
- // Model registry format - extract patterns from each model
1210
- for (const model of registry.models) {
1211
- if (!categoryFilter || model.category === categoryFilter || model.id.includes(categoryFilter)) {
1212
- for (const pattern of model.patterns || []) {
1213
- patterns.push({
1214
- ...pattern,
1215
- category: model.category, // Tag with model category
1216
- });
1445
+ return [3 /*break*/, 19];
1446
+ case 18:
1447
+ err_1 = _f.sent();
1448
+ output.writeln(output.warning("Signature verification skipped: " + (err_1 instanceof Error ? err_1.message : String(err_1))));
1449
+ return [3 /*break*/, 19];
1450
+ case 19:
1451
+ // Extract patterns - handle both single model and model registry formats
1452
+ spinner.setText('Importing patterns...');
1453
+ content = importData.pinataContent || importData;
1454
+ patterns = [];
1455
+ registry = content;
1456
+ if (registry.models && Array.isArray(registry.models)) {
1457
+ // Model registry format - extract patterns from each model
1458
+ for (_b = 0, _c = registry.models; _b < _c.length; _b++) {
1459
+ model = _c[_b];
1460
+ if (!categoryFilter || model.category === categoryFilter || model.id.includes(categoryFilter)) {
1461
+ for (_d = 0, _e = model.patterns || []; _d < _e.length; _d++) {
1462
+ pattern = _e[_d];
1463
+ patterns.push(__assign(__assign({}, pattern), { category: model.category }));
1464
+ }
1465
+ }
1217
1466
  }
1218
1467
  }
1219
- }
1220
- }
1221
- else {
1222
- // Single model format - patterns at top level
1223
- patterns = content.patterns || [];
1224
- }
1225
- // Filter by category if specified (additional filtering)
1226
- if (categoryFilter && patterns.length > 0) {
1227
- patterns = patterns.filter(p => p.category === categoryFilter ||
1228
- p.trigger.includes(categoryFilter));
1229
- }
1230
- // Validate patterns (security check)
1231
- const validPatterns = patterns.filter(p => {
1232
- // Security: Reject patterns with suspicious content
1233
- const suspicious = [
1234
- 'eval(', 'Function(', 'exec(', 'spawn(',
1235
- 'child_process', 'rm -rf', 'sudo',
1236
- '<script>', 'javascript:', 'data:',
1237
- ];
1238
- const content = JSON.stringify(p);
1239
- return !suspicious.some(s => content.includes(s));
1240
- });
1241
- if (validPatterns.length < patterns.length) {
1242
- output.writeln(output.warning(`Filtered ${patterns.length - validPatterns.length} suspicious patterns`));
1243
- }
1244
- // Save to local memory
1245
- const memoryDir = path.join(process.cwd(), '.claude-flow', 'memory');
1246
- if (!fs.existsSync(memoryDir)) {
1247
- fs.mkdirSync(memoryDir, { recursive: true });
1248
- }
1249
- const patternsFile = path.join(memoryDir, 'patterns.json');
1250
- let existingPatterns = [];
1251
- if (merge && fs.existsSync(patternsFile)) {
1252
- existingPatterns = JSON.parse(fs.readFileSync(patternsFile, 'utf8'));
1468
+ else {
1469
+ // Single model format - patterns at top level
1470
+ patterns = content.patterns || [];
1471
+ }
1472
+ // Filter by category if specified (additional filtering)
1473
+ if (categoryFilter && patterns.length > 0) {
1474
+ patterns = patterns.filter(function (p) {
1475
+ return p.category === categoryFilter ||
1476
+ p.trigger.includes(categoryFilter);
1477
+ });
1478
+ }
1479
+ validPatterns = patterns.filter(function (p) {
1480
+ // Security: Reject patterns with suspicious content
1481
+ var suspicious = [
1482
+ 'eval(', 'Function(', 'exec(', 'spawn(',
1483
+ 'child_process', 'rm -rf', 'sudo',
1484
+ '<script>', 'javascript:', 'data:',
1485
+ ];
1486
+ var content = JSON.stringify(p);
1487
+ return !suspicious.some(function (s) { return content.includes(s); });
1488
+ });
1489
+ if (validPatterns.length < patterns.length) {
1490
+ output.writeln(output.warning("Filtered " + (patterns.length - validPatterns.length) + " suspicious patterns"));
1491
+ }
1492
+ memoryDir = path.join(process.cwd(), '.claude-flow', 'memory');
1493
+ if (!fs.existsSync(memoryDir)) {
1494
+ fs.mkdirSync(memoryDir, { recursive: true });
1495
+ }
1496
+ patternsFile = path.join(memoryDir, 'patterns.json');
1497
+ existingPatterns = [];
1498
+ if (merge && fs.existsSync(patternsFile)) {
1499
+ existingPatterns = JSON.parse(fs.readFileSync(patternsFile, 'utf8'));
1500
+ }
1501
+ existingIds_1 = new Set(existingPatterns.map(function (p) { return p.id; }));
1502
+ newPatterns = validPatterns.filter(function (p) { return !existingIds_1.has(p.id); });
1503
+ finalPatterns = merge ? __spreadArray(__spreadArray([], existingPatterns, true), newPatterns, true) : validPatterns;
1504
+ fs.writeFileSync(patternsFile, JSON.stringify(finalPatterns, null, 2));
1505
+ spinner.succeed('Import complete');
1506
+ output.writeln();
1507
+ output.table({
1508
+ columns: [
1509
+ { key: 'metric', header: 'Metric', width: 25 },
1510
+ { key: 'value', header: 'Value', width: 20 },
1511
+ ],
1512
+ data: [
1513
+ { metric: 'Patterns Imported', value: String(validPatterns.length) },
1514
+ { metric: 'New Patterns', value: String(newPatterns.length) },
1515
+ { metric: 'Total Patterns', value: String(finalPatterns.length) },
1516
+ { metric: 'Signature Verified', value: importData.signature ? 'Yes' : 'N/A' },
1517
+ { metric: 'Merge Mode', value: merge ? 'Yes' : 'Replace' },
1518
+ ]
1519
+ });
1520
+ output.writeln();
1521
+ output.writeln(output.success('Patterns imported and ready to use'));
1522
+ output.writeln(output.dim('Run "claude-flow neural patterns --action list" to see imported patterns'));
1523
+ return [2 /*return*/, { success: true }];
1524
+ case 20:
1525
+ error_8 = _f.sent();
1526
+ spinner.fail("Import failed: " + (error_8 instanceof Error ? error_8.message : String(error_8)));
1527
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1528
+ case 21: return [2 /*return*/];
1253
1529
  }
1254
- // Merge or replace
1255
- const existingIds = new Set(existingPatterns.map(p => p.id));
1256
- const newPatterns = validPatterns.filter(p => !existingIds.has(p.id));
1257
- const finalPatterns = merge ? [...existingPatterns, ...newPatterns] : validPatterns;
1258
- fs.writeFileSync(patternsFile, JSON.stringify(finalPatterns, null, 2));
1259
- spinner.succeed('Import complete');
1260
- output.writeln();
1261
- output.table({
1262
- columns: [
1263
- { key: 'metric', header: 'Metric', width: 25 },
1264
- { key: 'value', header: 'Value', width: 20 },
1265
- ],
1266
- data: [
1267
- { metric: 'Patterns Imported', value: String(validPatterns.length) },
1268
- { metric: 'New Patterns', value: String(newPatterns.length) },
1269
- { metric: 'Total Patterns', value: String(finalPatterns.length) },
1270
- { metric: 'Signature Verified', value: importData.signature ? 'Yes' : 'N/A' },
1271
- { metric: 'Merge Mode', value: merge ? 'Yes' : 'Replace' },
1272
- ],
1273
- });
1274
- output.writeln();
1275
- output.writeln(output.success('Patterns imported and ready to use'));
1276
- output.writeln(output.dim('Run "claude-flow neural patterns --action list" to see imported patterns'));
1277
- return { success: true };
1278
- }
1279
- catch (error) {
1280
- spinner.fail(`Import failed: ${error instanceof Error ? error.message : String(error)}`);
1281
- return { success: false, exitCode: 1 };
1282
- }
1283
- },
1530
+ });
1531
+ }); }
1284
1532
  };
1285
1533
  // Benchmark subcommand - Real WASM benchmarks
1286
- const benchmarkCommand = {
1534
+ var benchmarkCommand = {
1287
1535
  name: 'benchmark',
1288
1536
  description: 'Benchmark RuVector WASM training performance',
1289
1537
  options: [
1290
- { name: 'dim', short: 'd', type: 'number', description: 'Embedding dimension (max 256)', default: '256' },
1291
- { name: 'iterations', short: 'i', type: 'number', description: 'Number of iterations', default: '1000' },
1292
- { name: 'keys', short: 'k', type: 'number', description: 'Number of keys for attention', default: '100' },
1538
+ { name: 'dim', short: 'd', type: 'number', description: 'Embedding dimension (max 256)', "default": '256' },
1539
+ { name: 'iterations', short: 'i', type: 'number', description: 'Number of iterations', "default": '1000' },
1540
+ { name: 'keys', short: 'k', type: 'number', description: 'Number of keys for attention', "default": '100' },
1293
1541
  ],
1294
1542
  examples: [
1295
1543
  { command: 'claude-flow neural benchmark', description: 'Run default benchmark' },
1296
1544
  { command: 'claude-flow neural benchmark -d 128 -i 5000', description: 'Custom benchmark' },
1297
1545
  ],
1298
- action: async (ctx) => {
1299
- const dim = Math.min(parseInt(ctx.flags.dim || '256', 10), 256);
1300
- const iterations = parseInt(ctx.flags.iterations || '1000', 10);
1301
- const numKeys = parseInt(ctx.flags.keys || '100', 10);
1302
- output.writeln();
1303
- output.writeln(output.bold('RuVector WASM Benchmark'));
1304
- output.writeln(output.dim(''.repeat(50)));
1305
- const spinner = output.createSpinner({ text: 'Running benchmarks...', spinner: 'dots' });
1306
- spinner.start();
1307
- try {
1308
- const attention = await import('@ruvector/attention');
1309
- // Manual benchmark since benchmarkAttention has a binding bug
1310
- const benchmarkMechanism = async (name, mechanism) => {
1311
- const query = new Float32Array(dim);
1312
- const keys = [];
1313
- const values = [];
1314
- for (let i = 0; i < dim; i++)
1315
- query[i] = Math.random();
1316
- for (let k = 0; k < numKeys; k++) {
1317
- const key = new Float32Array(dim);
1318
- const val = new Float32Array(dim);
1319
- for (let i = 0; i < dim; i++) {
1320
- key[i] = Math.random();
1321
- val[i] = Math.random();
1546
+ action: function (ctx) { return __awaiter(void 0, void 0, Promise, function () {
1547
+ var dim, iterations, numKeys, spinner, attention, benchmarkMechanism, results, dotProduct, _a, _b, flash, _c, _d, multiHead, _e, _f, hyperbolic, _g, _h, linear, _j, _k, dotProductResult, flashResult, hyperbolicResult, speedup, fs, createRequire, require, wasmPath, wasmBuffer, learningWasm, lora, gradient, i, loraStart, i, loraTime, loraAvg, error_9;
1548
+ return __generator(this, function (_l) {
1549
+ switch (_l.label) {
1550
+ case 0:
1551
+ dim = Math.min(parseInt(ctx.flags.dim || '256', 10), 256);
1552
+ iterations = parseInt(ctx.flags.iterations || '1000', 10);
1553
+ numKeys = parseInt(ctx.flags.keys || '100', 10);
1554
+ output.writeln();
1555
+ output.writeln(output.bold('RuVector WASM Benchmark'));
1556
+ output.writeln(output.dim(''.repeat(50)));
1557
+ spinner = output.createSpinner({ text: 'Running benchmarks...', spinner: 'dots' });
1558
+ spinner.start();
1559
+ _l.label = 1;
1560
+ case 1:
1561
+ _l.trys.push([1, 11, , 12]);
1562
+ return [4 /*yield*/, import('@ruvector/attention')];
1563
+ case 2:
1564
+ attention = _l.sent();
1565
+ benchmarkMechanism = function (name, mechanism) { return __awaiter(void 0, void 0, void 0, function () {
1566
+ var query, keys, values, i, k, key, val, i, i, start, i, elapsed;
1567
+ return __generator(this, function (_a) {
1568
+ query = new Float32Array(dim);
1569
+ keys = [];
1570
+ values = [];
1571
+ for (i = 0; i < dim; i++)
1572
+ query[i] = Math.random();
1573
+ for (k = 0; k < numKeys; k++) {
1574
+ key = new Float32Array(dim);
1575
+ val = new Float32Array(dim);
1576
+ for (i = 0; i < dim; i++) {
1577
+ key[i] = Math.random();
1578
+ val[i] = Math.random();
1579
+ }
1580
+ keys.push(key);
1581
+ values.push(val);
1582
+ }
1583
+ // Warmup
1584
+ for (i = 0; i < 10; i++)
1585
+ mechanism.computeRaw(query, keys, values);
1586
+ start = performance.now();
1587
+ for (i = 0; i < iterations; i++) {
1588
+ mechanism.computeRaw(query, keys, values);
1589
+ }
1590
+ elapsed = performance.now() - start;
1591
+ return [2 /*return*/, {
1592
+ name: name,
1593
+ averageTimeMs: elapsed / iterations,
1594
+ opsPerSecond: Math.round((iterations / elapsed) * 1000)
1595
+ }];
1596
+ });
1597
+ }); };
1598
+ spinner.setText("Benchmarking attention mechanisms (dim=" + dim + ", keys=" + numKeys + ", iter=" + iterations + ")...");
1599
+ results = [];
1600
+ dotProduct = new attention.DotProductAttention(dim);
1601
+ _b = (_a = results).push;
1602
+ return [4 /*yield*/, benchmarkMechanism('DotProduct', dotProduct)];
1603
+ case 3:
1604
+ _b.apply(_a, [_l.sent()]);
1605
+ flash = new attention.FlashAttention(dim, 64);
1606
+ _d = (_c = results).push;
1607
+ return [4 /*yield*/, benchmarkMechanism('FlashAttention', flash)];
1608
+ case 4:
1609
+ _d.apply(_c, [_l.sent()]);
1610
+ multiHead = new attention.MultiHeadAttention(dim, 4);
1611
+ _f = (_e = results).push;
1612
+ return [4 /*yield*/, benchmarkMechanism('MultiHead (4 heads)', multiHead)];
1613
+ case 5:
1614
+ _f.apply(_e, [_l.sent()]);
1615
+ hyperbolic = new attention.HyperbolicAttention(dim, 1.0);
1616
+ _h = (_g = results).push;
1617
+ return [4 /*yield*/, benchmarkMechanism('Hyperbolic', hyperbolic)];
1618
+ case 6:
1619
+ _h.apply(_g, [_l.sent()]);
1620
+ linear = new attention.LinearAttention(dim, dim);
1621
+ _k = (_j = results).push;
1622
+ return [4 /*yield*/, benchmarkMechanism('Linear', linear)];
1623
+ case 7:
1624
+ _k.apply(_j, [_l.sent()]);
1625
+ spinner.succeed('Benchmark complete');
1626
+ output.writeln();
1627
+ output.printTable({
1628
+ columns: [
1629
+ { key: 'name', header: 'Mechanism', width: 25 },
1630
+ { key: 'avgTime', header: 'Avg Time (ms)', width: 15 },
1631
+ { key: 'opsPerSec', header: 'Ops/sec', width: 15 },
1632
+ ],
1633
+ data: results.map(function (r) { return ({
1634
+ name: r.name,
1635
+ avgTime: r.averageTimeMs.toFixed(4),
1636
+ opsPerSec: r.opsPerSecond.toLocaleString()
1637
+ }); })
1638
+ });
1639
+ dotProductResult = results.find(function (r) { return r.name.includes('DotProduct'); });
1640
+ flashResult = results.find(function (r) { return r.name.includes('Flash'); });
1641
+ hyperbolicResult = results.find(function (r) { return r.name.includes('Hyperbolic'); });
1642
+ if (dotProductResult && flashResult) {
1643
+ speedup = dotProductResult.averageTimeMs / flashResult.averageTimeMs;
1644
+ output.writeln();
1645
+ output.writeln(output.highlight("Flash Attention speedup: " + speedup.toFixed(2) + "x faster than DotProduct"));
1322
1646
  }
1323
- keys.push(key);
1324
- values.push(val);
1325
- }
1326
- // Warmup
1327
- for (let i = 0; i < 10; i++)
1328
- mechanism.computeRaw(query, keys, values);
1329
- const start = performance.now();
1330
- for (let i = 0; i < iterations; i++) {
1331
- mechanism.computeRaw(query, keys, values);
1332
- }
1333
- const elapsed = performance.now() - start;
1334
- return {
1335
- name,
1336
- averageTimeMs: elapsed / iterations,
1337
- opsPerSecond: Math.round((iterations / elapsed) * 1000),
1338
- };
1339
- };
1340
- spinner.setText(`Benchmarking attention mechanisms (dim=${dim}, keys=${numKeys}, iter=${iterations})...`);
1341
- const results = [];
1342
- // Benchmark each mechanism
1343
- const dotProduct = new attention.DotProductAttention(dim);
1344
- results.push(await benchmarkMechanism('DotProduct', dotProduct));
1345
- const flash = new attention.FlashAttention(dim, 64);
1346
- results.push(await benchmarkMechanism('FlashAttention', flash));
1347
- const multiHead = new attention.MultiHeadAttention(dim, 4);
1348
- results.push(await benchmarkMechanism('MultiHead (4 heads)', multiHead));
1349
- const hyperbolic = new attention.HyperbolicAttention(dim, 1.0);
1350
- results.push(await benchmarkMechanism('Hyperbolic', hyperbolic));
1351
- const linear = new attention.LinearAttention(dim, dim);
1352
- results.push(await benchmarkMechanism('Linear', linear));
1353
- spinner.succeed('Benchmark complete');
1354
- output.writeln();
1355
- output.printTable({
1356
- columns: [
1357
- { key: 'name', header: 'Mechanism', width: 25 },
1358
- { key: 'avgTime', header: 'Avg Time (ms)', width: 15 },
1359
- { key: 'opsPerSec', header: 'Ops/sec', width: 15 },
1360
- ],
1361
- data: results.map(r => ({
1362
- name: r.name,
1363
- avgTime: r.averageTimeMs.toFixed(4),
1364
- opsPerSec: r.opsPerSecond.toLocaleString(),
1365
- })),
1366
- });
1367
- // Show speedup comparisons
1368
- const dotProductResult = results.find(r => r.name.includes('DotProduct'));
1369
- const flashResult = results.find(r => r.name.includes('Flash'));
1370
- const hyperbolicResult = results.find(r => r.name.includes('Hyperbolic'));
1371
- if (dotProductResult && flashResult) {
1372
- const speedup = dotProductResult.averageTimeMs / flashResult.averageTimeMs;
1373
- output.writeln();
1374
- output.writeln(output.highlight(`Flash Attention speedup: ${speedup.toFixed(2)}x faster than DotProduct`));
1375
- }
1376
- if (dotProductResult && hyperbolicResult) {
1377
- output.writeln(output.dim(`Hyperbolic overhead: ${(hyperbolicResult.averageTimeMs / dotProductResult.averageTimeMs).toFixed(2)}x (expected for manifold ops)`));
1378
- }
1379
- // Also benchmark MicroLoRA
1380
- spinner.start();
1381
- spinner.setText('Benchmarking MicroLoRA adaptation...');
1382
- // Load WASM file directly (Node.js compatible)
1383
- const fs = await import('fs');
1384
- const { createRequire } = await import('module');
1385
- const require = createRequire(import.meta.url);
1386
- const wasmPath = require.resolve('@ruvector/learning-wasm/ruvector_learning_wasm_bg.wasm');
1387
- const wasmBuffer = fs.readFileSync(wasmPath);
1388
- const learningWasm = await import('@ruvector/learning-wasm');
1389
- learningWasm.initSync({ module: wasmBuffer });
1390
- const lora = new learningWasm.WasmMicroLoRA(dim, 0.1, 0.01);
1391
- const gradient = new Float32Array(dim);
1392
- for (let i = 0; i < dim; i++)
1393
- gradient[i] = Math.random() - 0.5;
1394
- const loraStart = performance.now();
1395
- for (let i = 0; i < iterations; i++) {
1396
- lora.adapt_array(gradient);
1647
+ if (dotProductResult && hyperbolicResult) {
1648
+ output.writeln(output.dim("Hyperbolic overhead: " + (hyperbolicResult.averageTimeMs / dotProductResult.averageTimeMs).toFixed(2) + "x (expected for manifold ops)"));
1649
+ }
1650
+ // Also benchmark MicroLoRA
1651
+ spinner.start();
1652
+ spinner.setText('Benchmarking MicroLoRA adaptation...');
1653
+ return [4 /*yield*/, import('fs')];
1654
+ case 8:
1655
+ fs = _l.sent();
1656
+ return [4 /*yield*/, import('module')];
1657
+ case 9:
1658
+ createRequire = (_l.sent()).createRequire;
1659
+ require = createRequire(import.meta.url);
1660
+ wasmPath = require.resolve('@ruvector/learning-wasm/ruvector_learning_wasm_bg.wasm');
1661
+ wasmBuffer = fs.readFileSync(wasmPath);
1662
+ return [4 /*yield*/, import('@ruvector/learning-wasm')];
1663
+ case 10:
1664
+ learningWasm = _l.sent();
1665
+ learningWasm.initSync({ module: wasmBuffer });
1666
+ lora = new learningWasm.WasmMicroLoRA(dim, 0.1, 0.01);
1667
+ gradient = new Float32Array(dim);
1668
+ for (i = 0; i < dim; i++)
1669
+ gradient[i] = Math.random() - 0.5;
1670
+ loraStart = performance.now();
1671
+ for (i = 0; i < iterations; i++) {
1672
+ lora.adapt_array(gradient);
1673
+ }
1674
+ loraTime = performance.now() - loraStart;
1675
+ loraAvg = loraTime / iterations;
1676
+ spinner.succeed('MicroLoRA benchmark complete');
1677
+ output.writeln();
1678
+ output.printTable({
1679
+ columns: [
1680
+ { key: 'metric', header: 'MicroLoRA Metric', width: 25 },
1681
+ { key: 'value', header: 'Value', width: 25 },
1682
+ ],
1683
+ data: [
1684
+ { metric: 'Dimension', value: String(dim) },
1685
+ { metric: 'Iterations', value: iterations.toLocaleString() },
1686
+ { metric: 'Total Time', value: loraTime.toFixed(2) + "ms" },
1687
+ { metric: 'Avg Adaptation', value: (loraAvg * 1000).toFixed(2) + "\u03BCs" },
1688
+ { metric: 'Adaptations/sec', value: Math.round(1000 / loraAvg).toLocaleString() },
1689
+ { metric: 'Target (<100μs)', value: loraAvg * 1000 < 100 ? output.success('✓ PASS') : output.warning('✗ FAIL') },
1690
+ ]
1691
+ });
1692
+ lora.free();
1693
+ return [2 /*return*/, { success: true, data: { results: results, loraAvg: loraAvg } }];
1694
+ case 11:
1695
+ error_9 = _l.sent();
1696
+ spinner.fail('Benchmark failed');
1697
+ output.printError(error_9 instanceof Error ? error_9.message : String(error_9));
1698
+ return [2 /*return*/, { success: false, exitCode: 1 }];
1699
+ case 12: return [2 /*return*/];
1397
1700
  }
1398
- const loraTime = performance.now() - loraStart;
1399
- const loraAvg = loraTime / iterations;
1400
- spinner.succeed('MicroLoRA benchmark complete');
1401
- output.writeln();
1402
- output.printTable({
1403
- columns: [
1404
- { key: 'metric', header: 'MicroLoRA Metric', width: 25 },
1405
- { key: 'value', header: 'Value', width: 25 },
1406
- ],
1407
- data: [
1408
- { metric: 'Dimension', value: String(dim) },
1409
- { metric: 'Iterations', value: iterations.toLocaleString() },
1410
- { metric: 'Total Time', value: `${loraTime.toFixed(2)}ms` },
1411
- { metric: 'Avg Adaptation', value: `${(loraAvg * 1000).toFixed(2)}μs` },
1412
- { metric: 'Adaptations/sec', value: Math.round(1000 / loraAvg).toLocaleString() },
1413
- { metric: 'Target (<100μs)', value: loraAvg * 1000 < 100 ? output.success('✓ PASS') : output.warning('✗ FAIL') },
1414
- ],
1415
- });
1416
- lora.free();
1417
- return { success: true, data: { results, loraAvg } };
1418
- }
1419
- catch (error) {
1420
- spinner.fail('Benchmark failed');
1421
- output.printError(error instanceof Error ? error.message : String(error));
1422
- return { success: false, exitCode: 1 };
1423
- }
1424
- },
1701
+ });
1702
+ }); }
1425
1703
  };
1426
1704
  // Main neural command
1427
- export const neuralCommand = {
1705
+ export var neuralCommand = {
1428
1706
  name: 'neural',
1429
1707
  description: 'Neural pattern training, MoE, Flash Attention, pattern learning',
1430
1708
  subcommands: [trainCommand, statusCommand, patternsCommand, predictCommand, optimizeCommand, benchmarkCommand, listCommand, exportCommand, importCommand],
@@ -1433,16 +1711,18 @@ export const neuralCommand = {
1433
1711
  { command: 'claude-flow neural train -p coordination', description: 'Train coordination patterns' },
1434
1712
  { command: 'claude-flow neural patterns --action list', description: 'List learned patterns' },
1435
1713
  ],
1436
- action: async () => {
1437
- output.writeln();
1438
- output.writeln(output.bold('KynjalFlow Neural System'));
1439
- output.writeln(output.dim('Advanced AI pattern learning and inference'));
1440
- output.writeln();
1441
- output.writeln('Use --help with subcommands for more info');
1442
- output.writeln();
1443
- output.writeln(output.dim('Created with ❤️ by ruv.io'));
1444
- return { success: true };
1445
- },
1714
+ action: function () { return __awaiter(void 0, void 0, Promise, function () {
1715
+ return __generator(this, function (_a) {
1716
+ output.writeln();
1717
+ output.writeln(output.bold('RuFlo Neural System'));
1718
+ output.writeln(output.dim('Advanced AI pattern learning and inference'));
1719
+ output.writeln();
1720
+ output.writeln('Use --help with subcommands for more info');
1721
+ output.writeln();
1722
+ output.writeln(output.dim('Created with ❤️ by ruv.io'));
1723
+ return [2 /*return*/, { success: true }];
1724
+ });
1725
+ }); }
1446
1726
  };
1447
1727
  export default neuralCommand;
1448
1728
  //# sourceMappingURL=neural.js.map