claude-flow-novice 2.0.3 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/dist/src/cli/commands/guidance.js +487 -668
  2. package/dist/src/cli/commands/index-validate.js +18 -29
  3. package/dist/src/cli/commands/mcp-troubleshoot.js +230 -282
  4. package/dist/src/cli/commands/neural-goal-init.js +92 -125
  5. package/dist/src/cli/commands/swarm-exec.js +317 -393
  6. package/dist/src/cli/commands/swarm.js +1 -1
  7. package/dist/src/cli/commands/validate-framework.js +983 -1100
  8. package/dist/src/cli/commands/validate.js +144 -223
  9. package/dist/src/cli/simple-commands/__tests__/agent.test.js +265 -277
  10. package/dist/src/cli/simple-commands/__tests__/memory.test.js +6 -7
  11. package/dist/src/cli/simple-commands/__tests__/swarm.test.js +373 -356
  12. package/dist/src/cli/simple-commands/__tests__/task.test.js +6 -7
  13. package/dist/src/cli/simple-commands/agent.js +157 -193
  14. package/dist/src/cli/simple-commands/analysis.js +336 -446
  15. package/dist/src/cli/simple-commands/automation-executor.js +1095 -1339
  16. package/dist/src/cli/simple-commands/automation.js +481 -469
  17. package/dist/src/cli/simple-commands/batch-manager.js +261 -313
  18. package/dist/src/cli/simple-commands/claude-telemetry.js +241 -267
  19. package/dist/src/cli/simple-commands/claude-track.js +68 -90
  20. package/dist/src/cli/simple-commands/concurrent-display.js +266 -320
  21. package/dist/src/cli/simple-commands/config.js +245 -290
  22. package/dist/src/cli/simple-commands/coordination.js +182 -234
  23. package/dist/src/cli/simple-commands/enhanced-ui-views.js +812 -615
  24. package/dist/src/cli/simple-commands/enhanced-webui-complete.js +922 -981
  25. package/dist/src/cli/simple-commands/fix-hook-variables.js +274 -294
  26. package/dist/src/cli/simple-commands/github/gh-coordinator.js +378 -457
  27. package/dist/src/cli/simple-commands/github/github-api.js +535 -574
  28. package/dist/src/cli/simple-commands/github/init.js +276 -303
  29. package/dist/src/cli/simple-commands/github.js +222 -247
  30. package/dist/src/cli/simple-commands/goal.js +51 -63
  31. package/dist/src/cli/simple-commands/hive-mind/auto-save-middleware.js +208 -278
  32. package/dist/src/cli/simple-commands/hive-mind/communication.js +601 -696
  33. package/dist/src/cli/simple-commands/hive-mind/core.js +907 -979
  34. package/dist/src/cli/simple-commands/hive-mind/db-optimizer.js +406 -655
  35. package/dist/src/cli/simple-commands/hive-mind/mcp-wrapper.js +1125 -1245
  36. package/dist/src/cli/simple-commands/hive-mind/memory.js +854 -1090
  37. package/dist/src/cli/simple-commands/hive-mind/performance-optimizer.js +459 -574
  38. package/dist/src/cli/simple-commands/hive-mind/performance-test.js +263 -347
  39. package/dist/src/cli/simple-commands/hive-mind/queen.js +727 -768
  40. package/dist/src/cli/simple-commands/hive-mind/session-manager.js +745 -1049
  41. package/dist/src/cli/simple-commands/hive-mind-optimize.js +227 -283
  42. package/dist/src/cli/simple-commands/hive-mind-wizard.js +174 -217
  43. package/dist/src/cli/simple-commands/hive-mind.js +1842 -2283
  44. package/dist/src/cli/simple-commands/hive.js +90 -79
  45. package/dist/src/cli/simple-commands/hook-safety.js +431 -521
  46. package/dist/src/cli/simple-commands/hooks/session-start-soul.js +203 -254
  47. package/dist/src/cli/simple-commands/hooks.js +1064 -1204
  48. package/dist/src/cli/simple-commands/init/agent-copier.js +294 -319
  49. package/dist/src/cli/simple-commands/init/batch-init.js +496 -562
  50. package/dist/src/cli/simple-commands/init/claude-commands/claude-flow-commands.js +13 -19
  51. package/dist/src/cli/simple-commands/init/claude-commands/optimized-claude-flow-commands.js +13 -19
  52. package/dist/src/cli/simple-commands/init/claude-commands/optimized-slash-commands.js +61 -88
  53. package/dist/src/cli/simple-commands/init/claude-commands/optimized-sparc-commands.js +125 -150
  54. package/dist/src/cli/simple-commands/init/claude-commands/slash-commands.js +42 -49
  55. package/dist/src/cli/simple-commands/init/claude-commands/sparc-commands.js +43 -61
  56. package/dist/src/cli/simple-commands/init/copy-revised-templates.js +141 -147
  57. package/dist/src/cli/simple-commands/init/executable-wrapper.js +31 -44
  58. package/dist/src/cli/simple-commands/init/gitignore-updater.js +64 -90
  59. package/dist/src/cli/simple-commands/init/help.js +104 -107
  60. package/dist/src/cli/simple-commands/init/hive-mind-init.js +509 -528
  61. package/dist/src/cli/simple-commands/init/index.js +1510 -1759
  62. package/dist/src/cli/simple-commands/init/performance-monitor.js +234 -317
  63. package/dist/src/cli/simple-commands/init/rollback/backup-manager.js +441 -504
  64. package/dist/src/cli/simple-commands/init/rollback/index.js +289 -364
  65. package/dist/src/cli/simple-commands/init/rollback/recovery-manager.js +652 -728
  66. package/dist/src/cli/simple-commands/init/rollback/rollback-executor.js +416 -481
  67. package/dist/src/cli/simple-commands/init/rollback/state-tracker.js +369 -448
  68. package/dist/src/cli/simple-commands/init/sparc/roo-readme.js +1 -2
  69. package/dist/src/cli/simple-commands/init/sparc/roomodes-config.js +122 -99
  70. package/dist/src/cli/simple-commands/init/sparc/workflows.js +32 -37
  71. package/dist/src/cli/simple-commands/init/sparc-structure.js +55 -62
  72. package/dist/src/cli/simple-commands/init/template-copier.js +421 -533
  73. package/dist/src/cli/simple-commands/init/templates/coordination-md.js +3 -6
  74. package/dist/src/cli/simple-commands/init/templates/enhanced-templates.js +344 -318
  75. package/dist/src/cli/simple-commands/init/templates/github-safe-enhanced.js +173 -218
  76. package/dist/src/cli/simple-commands/init/templates/github-safe.js +65 -75
  77. package/dist/src/cli/simple-commands/init/templates/memory-bank-md.js +3 -6
  78. package/dist/src/cli/simple-commands/init/templates/readme-files.js +2 -4
  79. package/dist/src/cli/simple-commands/init/templates/safe-hook-patterns.js +187 -230
  80. package/dist/src/cli/simple-commands/init/templates/sparc-modes.js +53 -80
  81. package/dist/src/cli/simple-commands/init/templates/verification-claude-md.js +101 -85
  82. package/dist/src/cli/simple-commands/init/validation/config-validator.js +283 -330
  83. package/dist/src/cli/simple-commands/init/validation/health-checker.js +495 -561
  84. package/dist/src/cli/simple-commands/init/validation/index.js +302 -358
  85. package/dist/src/cli/simple-commands/init/validation/mode-validator.js +308 -359
  86. package/dist/src/cli/simple-commands/init/validation/post-init-validator.js +389 -366
  87. package/dist/src/cli/simple-commands/init/validation/pre-init-validator.js +270 -268
  88. package/dist/src/cli/simple-commands/init/validation/test-runner.js +427 -447
  89. package/dist/src/cli/simple-commands/init.js +1 -2
  90. package/dist/src/cli/simple-commands/mcp-health.js +131 -158
  91. package/dist/src/cli/simple-commands/mcp-integration-layer.js +533 -634
  92. package/dist/src/cli/simple-commands/mcp.js +345 -400
  93. package/dist/src/cli/simple-commands/memory-consolidation.js +426 -537
  94. package/dist/src/cli/simple-commands/memory.js +247 -311
  95. package/dist/src/cli/simple-commands/migrate-hooks.js +39 -46
  96. package/dist/src/cli/simple-commands/monitor.js +294 -363
  97. package/dist/src/cli/simple-commands/neural.js +51 -65
  98. package/dist/src/cli/simple-commands/pair-autofix-only.js +538 -662
  99. package/dist/src/cli/simple-commands/pair-basic.js +528 -656
  100. package/dist/src/cli/simple-commands/pair-old.js +430 -543
  101. package/dist/src/cli/simple-commands/pair-working.js +615 -751
  102. package/dist/src/cli/simple-commands/pair.js +615 -751
  103. package/dist/src/cli/simple-commands/performance-hooks.js +83 -111
  104. package/dist/src/cli/simple-commands/performance-metrics.js +348 -433
  105. package/dist/src/cli/simple-commands/process-ui-enhanced.js +708 -787
  106. package/dist/src/cli/simple-commands/process-ui.js +230 -254
  107. package/dist/src/cli/simple-commands/realtime-update-system.js +525 -611
  108. package/dist/src/cli/simple-commands/sparc/architecture.js +1704 -1530
  109. package/dist/src/cli/simple-commands/sparc/commands.js +438 -516
  110. package/dist/src/cli/simple-commands/sparc/completion.js +1224 -1481
  111. package/dist/src/cli/simple-commands/sparc/coordinator.js +913 -978
  112. package/dist/src/cli/simple-commands/sparc/index.js +241 -298
  113. package/dist/src/cli/simple-commands/sparc/phase-base.js +314 -390
  114. package/dist/src/cli/simple-commands/sparc/pseudocode.js +965 -869
  115. package/dist/src/cli/simple-commands/sparc/refinement.js +980 -1273
  116. package/dist/src/cli/simple-commands/sparc/specification.js +559 -645
  117. package/dist/src/cli/simple-commands/sparc-modes/architect.js +1 -1
  118. package/dist/src/cli/simple-commands/sparc-modes/ask.js +1 -1
  119. package/dist/src/cli/simple-commands/sparc-modes/code.js +1 -1
  120. package/dist/src/cli/simple-commands/sparc-modes/debug.js +1 -1
  121. package/dist/src/cli/simple-commands/sparc-modes/devops.js +1 -1
  122. package/dist/src/cli/simple-commands/sparc-modes/docs-writer.js +1 -1
  123. package/dist/src/cli/simple-commands/sparc-modes/generic.js +1 -1
  124. package/dist/src/cli/simple-commands/sparc-modes/index.js +47 -55
  125. package/dist/src/cli/simple-commands/sparc-modes/integration.js +1 -1
  126. package/dist/src/cli/simple-commands/sparc-modes/mcp.js +1 -1
  127. package/dist/src/cli/simple-commands/sparc-modes/monitoring.js +1 -1
  128. package/dist/src/cli/simple-commands/sparc-modes/optimization.js +1 -1
  129. package/dist/src/cli/simple-commands/sparc-modes/security-review.js +1 -1
  130. package/dist/src/cli/simple-commands/sparc-modes/sparc-orchestrator.js +1 -1
  131. package/dist/src/cli/simple-commands/sparc-modes/spec-pseudocode.js +1 -1
  132. package/dist/src/cli/simple-commands/sparc-modes/supabase-admin.js +1 -1
  133. package/dist/src/cli/simple-commands/sparc-modes/swarm.js +101 -87
  134. package/dist/src/cli/simple-commands/sparc-modes/tdd.js +1 -1
  135. package/dist/src/cli/simple-commands/sparc-modes/tutorial.js +1 -1
  136. package/dist/src/cli/simple-commands/sparc.js +465 -493
  137. package/dist/src/cli/simple-commands/start-ui.js +108 -132
  138. package/dist/src/cli/simple-commands/start-wrapper.js +240 -268
  139. package/dist/src/cli/simple-commands/start.js +1 -1
  140. package/dist/src/cli/simple-commands/status.js +254 -275
  141. package/dist/src/cli/simple-commands/stream-chain-clean.js +128 -171
  142. package/dist/src/cli/simple-commands/stream-chain-fixed.js +61 -82
  143. package/dist/src/cli/simple-commands/stream-chain-real.js +267 -331
  144. package/dist/src/cli/simple-commands/stream-chain-working.js +211 -263
  145. package/dist/src/cli/simple-commands/stream-chain.js +260 -318
  146. package/dist/src/cli/simple-commands/stream-processor.js +290 -315
  147. package/dist/src/cli/simple-commands/swarm-executor.js +189 -222
  148. package/dist/src/cli/simple-commands/swarm-metrics-integration.js +208 -300
  149. package/dist/src/cli/simple-commands/swarm-ui.js +623 -703
  150. package/dist/src/cli/simple-commands/swarm-webui-integration.js +258 -286
  151. package/dist/src/cli/simple-commands/swarm.js +887 -1082
  152. package/dist/src/cli/simple-commands/task.js +161 -206
  153. package/dist/src/cli/simple-commands/timestamp-fix.js +59 -89
  154. package/dist/src/cli/simple-commands/token-tracker.js +258 -316
  155. package/dist/src/cli/simple-commands/tool-execution-framework.js +433 -519
  156. package/dist/src/cli/simple-commands/train-and-stream.js +275 -331
  157. package/dist/src/cli/simple-commands/training-pipeline.js +619 -725
  158. package/dist/src/cli/simple-commands/training.js +170 -227
  159. package/dist/src/cli/simple-commands/verification-hooks.js +261 -284
  160. package/dist/src/cli/simple-commands/verification-integration.js +389 -417
  161. package/dist/src/cli/simple-commands/verification-training-integration.js +486 -606
  162. package/dist/src/cli/simple-commands/verification.js +493 -513
  163. package/dist/src/cli/simple-commands/web-server.js +766 -836
  164. package/dist/src/cli/simple-commands/webui-validator.js +106 -124
  165. package/dist/src/coordination/event-bus/demo-wasm-integration.js +212 -251
  166. package/dist/src/coordination/event-bus/qe-event-bus.js +608 -748
  167. package/dist/src/coordination/event-bus/qe-event-bus.test.js +379 -454
  168. package/dist/src/coordination/iteration-tracker.js +363 -454
  169. package/dist/src/enterprise/analytics-manager.js +1135 -0
  170. package/dist/src/enterprise/audit-manager.js +1115 -0
  171. package/dist/src/enterprise/cloud-manager.js +891 -0
  172. package/dist/src/enterprise/deployment-manager.js +966 -0
  173. package/dist/src/enterprise/index.js +6 -0
  174. package/dist/src/enterprise/project-manager.js +584 -0
  175. package/dist/src/enterprise/security-manager.js +991 -0
  176. package/dist/src/index.js +1 -1
  177. package/dist/src/mcp/DEPRECATED.js +46 -60
  178. package/dist/src/mcp/fixes/mcp-error-fixes.js +115 -134
  179. package/dist/src/mcp/implementations/agent-tracker.js +114 -128
  180. package/dist/src/mcp/implementations/daa-tools.js +292 -350
  181. package/dist/src/mcp/implementations/workflow-tools.js +329 -361
  182. package/dist/src/mcp/mcp-config-manager.js +1183 -1331
  183. package/dist/src/mcp/mcp-server-novice-simplified.js +11 -17
  184. package/dist/src/mcp/mcp-server-novice.js +11 -17
  185. package/dist/src/mcp/mcp-server-sdk.js +11 -17
  186. package/dist/src/mcp/mcp-server.js +1620 -1484
  187. package/dist/src/mcp/ruv-swarm-wrapper.js +209 -239
  188. package/dist/src/memory/advanced-serializer.js +609 -589
  189. package/dist/src/memory/enhanced-examples.js +220 -305
  190. package/dist/src/memory/enhanced-memory.js +295 -336
  191. package/dist/src/memory/enhanced-session-serializer.js +408 -492
  192. package/dist/src/memory/fallback-memory-system.js +900 -1021
  193. package/dist/src/memory/fallback-store.js +93 -131
  194. package/dist/src/memory/high-performance-serialization.js +592 -730
  195. package/dist/src/memory/in-memory-store.js +161 -213
  196. package/dist/src/memory/index.js +123 -157
  197. package/dist/src/memory/lock-free-structures.js +578 -764
  198. package/dist/src/memory/memory-mapped-persistence.js +585 -766
  199. package/dist/src/memory/memory-pressure-manager.js +569 -707
  200. package/dist/src/memory/migration.js +358 -445
  201. package/dist/src/memory/shared-memory.js +641 -768
  202. package/dist/src/memory/sqlite-store.js +245 -325
  203. package/dist/src/memory/sqlite-wrapper.js +122 -151
  204. package/dist/src/memory/swarm-memory.js +470 -603
  205. package/dist/src/memory/test-example.js +126 -134
  206. package/dist/src/memory/ultra-fast-memory-store.js +622 -821
  207. package/dist/src/memory/unified-memory-manager.js +356 -437
  208. package/dist/src/migration/index.js +92 -0
  209. package/dist/src/migration/logger.js +121 -0
  210. package/dist/src/migration/migration-analyzer.js +268 -0
  211. package/dist/src/migration/migration-runner.js +522 -0
  212. package/dist/src/migration/migration-validator.js +285 -0
  213. package/dist/src/migration/progress-reporter.js +150 -0
  214. package/dist/src/migration/rollback-manager.js +321 -0
  215. package/dist/src/migration/tests/migration-system.test.js +7 -0
  216. package/dist/src/migration/types.js +3 -0
  217. package/dist/src/swarm/CodeRefactoringSwarm.js +777 -952
  218. package/dist/src/swarm/__tests__/integration.test.js +227 -0
  219. package/dist/src/swarm/__tests__/prompt-copier.test.js +344 -0
  220. package/dist/src/swarm/advanced-orchestrator.js +1095 -0
  221. package/dist/src/swarm/claude-code-interface.js +961 -0
  222. package/dist/src/swarm/claude-flow-executor.js +229 -0
  223. package/dist/src/swarm/consensus-coordinator.js +475 -0
  224. package/dist/src/swarm/coordinator.js +2993 -0
  225. package/dist/src/swarm/direct-executor.js +1180 -0
  226. package/dist/src/swarm/error-recovery/advanced-error-detection.js +691 -0
  227. package/dist/src/swarm/error-recovery/automated-recovery-workflows.js +998 -0
  228. package/dist/src/swarm/error-recovery/error-recovery-coordinator.js +1197 -0
  229. package/dist/src/swarm/error-recovery/recovery-monitoring.js +772 -0
  230. package/dist/src/swarm/error-recovery/resilience-architecture.js +714 -0
  231. package/dist/src/swarm/error-recovery/self-healing-mechanisms.js +1319 -0
  232. package/dist/src/swarm/error-recovery/test-error-recovery-effectiveness.js +808 -0
  233. package/dist/src/swarm/executor-v2.js +322 -0
  234. package/dist/src/swarm/executor.js +815 -0
  235. package/dist/src/swarm/hive-mind-integration.js +703 -0
  236. package/dist/src/swarm/index.js +41 -0
  237. package/dist/src/swarm/json-output-aggregator.js +267 -0
  238. package/dist/src/swarm/large-scale-coordinator.js +542 -0
  239. package/dist/src/swarm/mcp-integration-wrapper.js +628 -0
  240. package/dist/src/swarm/memory.js +1117 -0
  241. package/dist/src/swarm/optimizations/__tests__/optimization.test.js +348 -0
  242. package/dist/src/swarm/optimizations/async-file-manager.js +285 -0
  243. package/dist/src/swarm/optimizations/circular-buffer.js +162 -0
  244. package/dist/src/swarm/optimizations/connection-pool.js +244 -0
  245. package/dist/src/swarm/optimizations/index.js +28 -0
  246. package/dist/src/swarm/optimizations/optimized-executor.js +320 -0
  247. package/dist/src/swarm/optimizations/ttl-map.js +234 -0
  248. package/dist/src/swarm/prompt-cli.js +200 -0
  249. package/dist/src/swarm/prompt-copier-enhanced.js +202 -0
  250. package/dist/src/swarm/prompt-copier.js +381 -0
  251. package/dist/src/swarm/prompt-manager.js +295 -0
  252. package/dist/src/swarm/prompt-utils.js +310 -0
  253. package/dist/src/swarm/result-aggregator.js +718 -0
  254. package/dist/src/swarm/sparc-executor.js +1568 -0
  255. package/dist/src/swarm/strategies/auto.js +758 -0
  256. package/dist/src/swarm/strategies/base.js +128 -0
  257. package/dist/src/swarm/strategies/research.js +914 -0
  258. package/dist/src/swarm/strategies/strategy-metrics-patch.js +2 -0
  259. package/dist/src/swarm/types.js +52 -0
  260. package/dist/src/swarm/workers/copy-worker.js +56 -0
  261. package/dist/src/utils/__tests__/github-cli-safety-wrapper.test.js +332 -400
  262. package/dist/src/utils/github-cli-safe.js +56 -64
  263. package/dist/src/utils/github-cli-safety-wrapper.js +451 -546
  264. package/dist/src/utils/npx-isolated-cache.js +104 -119
  265. package/dist/src/utils/preference-manager.js +622 -652
  266. package/dist/src/utils/timezone-utils.js +86 -105
  267. package/dist/src/validators/epic-config-schema.js +214 -0
  268. package/dist/src/validators/index.js +10 -0
  269. package/dist/src/validators/swarm-init-validator.js +259 -0
  270. package/dist/src/validators/todowrite-batching-validator.js +215 -0
  271. package/dist/src/validators/todowrite-integration.js +187 -0
  272. package/package.json +2 -2
@@ -2,77 +2,60 @@
2
2
  /**
3
3
  * Training Pipeline with Real Task Execution
4
4
  * Executes actual code and learns from real test results
5
- */
6
-
7
- import fs from 'fs/promises';
8
- import path from 'path';
9
- import { execSync, spawn } from 'child_process';
10
- import { promisify } from 'util';
11
- import { exec } from 'child_process';
12
-
5
+ */ import fs from "node:fs/promises";
6
+ import path from "path";
7
+ import { execSync } from "child_process";
8
+ import { promisify } from "util";
9
+ import { exec } from "child_process";
13
10
  const execAsync = promisify(exec);
14
-
15
11
  /**
16
12
  * Training Pipeline that executes real tasks and learns from actual results
17
- */
18
- export class TrainingPipeline {
19
- constructor() {
20
- this.pipelineConfig = '.claude-flow/pipeline-config.json';
21
- this.trainingLog = '.claude-flow/training/pipeline-log.jsonl';
22
- this.improvementMetrics = '.claude-flow/metrics/improvements.json';
23
- this.agentProfiles = '.claude-flow/agents/profiles.json';
24
- this.realTasksDir = '.claude-flow/training/real-tasks';
25
- this.initialized = false;
26
- }
27
-
28
- /**
13
+ */ export class TrainingPipeline {
14
+ /**
29
15
  * Initialize the training pipeline
30
- */
31
- async initialize() {
32
- // Create necessary directories
33
- const dirs = [
34
- '.claude-flow/pipeline',
35
- '.claude-flow/training',
36
- '.claude-flow/training/real-tasks',
37
- '.claude-flow/metrics',
38
- '.claude-flow/agents',
39
- '.claude-flow/validation',
40
- '.claude-flow/benchmarks',
41
- ];
42
-
43
- for (const dir of dirs) {
44
- await fs.mkdir(dir, { recursive: true });
16
+ */ async initialize() {
17
+ // Create necessary directories
18
+ const dirs = [
19
+ '.claude-flow/pipeline',
20
+ '.claude-flow/training',
21
+ '.claude-flow/training/real-tasks',
22
+ '.claude-flow/metrics',
23
+ '.claude-flow/agents',
24
+ '.claude-flow/validation',
25
+ '.claude-flow/benchmarks'
26
+ ];
27
+ for (const dir of dirs){
28
+ await fs.mkdir(dir, {
29
+ recursive: true
30
+ });
31
+ }
32
+ // Load or create pipeline configuration
33
+ await this.loadPipelineConfig();
34
+ console.log('šŸš€ Training Pipeline initialized');
35
+ this.initialized = true;
45
36
  }
46
-
47
- // Load or create pipeline configuration
48
- await this.loadPipelineConfig();
49
-
50
- console.log('šŸš€ Training Pipeline initialized');
51
- this.initialized = true;
52
- }
53
-
54
- /**
37
+ /**
55
38
  * STAGE 1: Generate Training Tasks
56
39
  * Creates actual code files that can be tested
57
- */
58
- async generateTrainingTasks(complexity = 'medium') {
59
- const taskId = Date.now();
60
- const taskDir = path.join(this.realTasksDir, `task-${taskId}`);
61
- await fs.mkdir(taskDir, { recursive: true });
62
-
63
- const tasks = {
64
- easy: [
65
- {
66
- type: 'function',
67
- name: 'validateEmail',
68
- task: 'Create email validation function',
69
- code: `function validateEmail(email) {
40
+ */ async generateTrainingTasks(complexity = 'medium') {
41
+ const taskId = Date.now();
42
+ const taskDir = path.join(this.realTasksDir, `task-${taskId}`);
43
+ await fs.mkdir(taskDir, {
44
+ recursive: true
45
+ });
46
+ const tasks = {
47
+ easy: [
48
+ {
49
+ type: 'function',
50
+ name: 'validateEmail',
51
+ task: 'Create email validation function',
52
+ code: `function validateEmail(email) {
70
53
  const regex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
71
54
  return regex.test(email);
72
55
  }
73
56
 
74
57
  module.exports = { validateEmail };`,
75
- test: `
58
+ test: `
76
59
  const { validateEmail } = require('./index');
77
60
 
78
61
  describe('validateEmail', () => {
@@ -84,15 +67,15 @@ describe('validateEmail', () => {
84
67
  expect(validateEmail('invalid')).toBe(false);
85
68
  });
86
69
  });
87
- `,
88
- },
89
- ],
90
- medium: [
91
- {
92
- type: 'api',
93
- name: 'userApi',
94
- task: 'Build user API endpoint',
95
- code: `
70
+ `
71
+ }
72
+ ],
73
+ medium: [
74
+ {
75
+ type: 'api',
76
+ name: 'userApi',
77
+ task: 'Build user API endpoint',
78
+ code: `
96
79
  const express = require('express');
97
80
  const app = express();
98
81
 
@@ -116,7 +99,7 @@ app.post('/users', (req, res) => {
116
99
 
117
100
  module.exports = app;
118
101
  `,
119
- test: `
102
+ test: `
120
103
  const request = require('supertest');
121
104
  const app = require('./index');
122
105
 
@@ -135,15 +118,15 @@ describe('User API', () => {
135
118
  expect(res.body.name).toBe('Test');
136
119
  });
137
120
  });
138
- `,
139
- },
140
- ],
141
- hard: [
142
- {
143
- type: 'algorithm',
144
- name: 'sortAlgorithm',
145
- task: 'Implement efficient sorting',
146
- code: `
121
+ `
122
+ }
123
+ ],
124
+ hard: [
125
+ {
126
+ type: 'algorithm',
127
+ name: 'sortAlgorithm',
128
+ task: 'Implement efficient sorting',
129
+ code: `
147
130
  function quickSort(arr) {
148
131
  if (arr.length <= 1) return arr;
149
132
 
@@ -178,7 +161,7 @@ function mergeSort(arr) {
178
161
 
179
162
  module.exports = { quickSort, mergeSort };
180
163
  `,
181
- test: `
164
+ test: `
182
165
  const { quickSort, mergeSort } = require('./index');
183
166
 
184
167
  describe('Sorting Algorithms', () => {
@@ -198,677 +181,588 @@ describe('Sorting Algorithms', () => {
198
181
  expect(mergeSort([])).toEqual([]);
199
182
  });
200
183
  });
201
- `,
202
- },
203
- ],
204
- };
205
-
206
- const selectedTasks = tasks[complexity] || tasks.medium;
207
- const realTasks = [];
208
-
209
- // Create real task files
210
- for (const task of selectedTasks) {
211
- const projectDir = path.join(taskDir, task.name);
212
- await fs.mkdir(projectDir, { recursive: true });
213
-
214
- // Write actual code file
215
- await fs.writeFile(path.join(projectDir, 'index.js'), task.code);
216
-
217
- // Write test file
218
- await fs.writeFile(path.join(projectDir, 'index.test.js'), task.test);
219
-
220
- // Create package.json with real dependencies
221
- const packageJson = {
222
- name: task.name,
223
- version: '1.0.0',
224
- scripts: {
225
- test: 'jest --silent',
226
- lint: 'eslint index.js || true',
227
- typecheck: "echo 'No TypeScript' || true",
228
- },
229
- devDependencies: {
230
- jest: '^29.0.0',
231
- eslint: '^8.0.0',
232
- supertest: '^6.0.0',
233
- },
234
- dependencies: {
235
- express: task.type === 'api' ? '^4.18.0' : undefined,
236
- },
237
- };
238
-
239
- await fs.writeFile(
240
- path.join(projectDir, 'package.json'),
241
- JSON.stringify(packageJson, null, 2),
242
- );
243
-
244
- realTasks.push({
245
- ...task,
246
- projectDir,
247
- taskId,
248
- });
184
+ `
185
+ }
186
+ ]
187
+ };
188
+ const selectedTasks = tasks[complexity] || tasks.medium;
189
+ const realTasks = [];
190
+ // Create real task files
191
+ for (const task of selectedTasks){
192
+ const projectDir = path.join(taskDir, task.name);
193
+ await fs.mkdir(projectDir, {
194
+ recursive: true
195
+ });
196
+ // Write actual code file
197
+ await fs.writeFile(path.join(projectDir, 'index.js'), task.code);
198
+ // Write test file
199
+ await fs.writeFile(path.join(projectDir, 'index.test.js'), task.test);
200
+ // Create package.json with real dependencies
201
+ const packageJson = {
202
+ name: task.name,
203
+ version: '1.0.0',
204
+ scripts: {
205
+ test: 'jest --silent',
206
+ lint: 'eslint index.js || true',
207
+ typecheck: "echo 'No TypeScript' || true"
208
+ },
209
+ devDependencies: {
210
+ jest: '^29.0.0',
211
+ eslint: '^8.0.0',
212
+ supertest: '^6.0.0'
213
+ },
214
+ dependencies: {
215
+ express: task.type === 'api' ? '^4.18.0' : undefined
216
+ }
217
+ };
218
+ await fs.writeFile(path.join(projectDir, 'package.json'), JSON.stringify(packageJson, null, 2));
219
+ realTasks.push({
220
+ ...task,
221
+ projectDir,
222
+ taskId
223
+ });
224
+ }
225
+ console.log(`šŸ“ Generated ${realTasks.length} ${complexity} training tasks`);
226
+ return realTasks;
249
227
  }
250
-
251
- console.log(`šŸ“ Generated ${realTasks.length} ${complexity} training tasks`);
252
- return realTasks;
253
- }
254
-
255
- /**
228
+ /**
256
229
  * STAGE 2: Execute Tasks with Different Strategies
257
230
  * Actually runs npm install, tests, and measures real performance
258
- */
259
- async executeTrainingRun(tasks, agentConfig = {}) {
260
- const results = [];
261
-
262
- for (const task of tasks) {
263
- console.log(`\nšŸ”„ Executing task: ${task.task}`);
264
-
265
- // Install dependencies (only once per task)
266
- try {
267
- console.log(` šŸ“¦ Installing dependencies...`);
268
- execSync('npm install --silent', {
269
- cwd: task.projectDir,
270
- stdio: 'pipe',
271
- });
272
- } catch (e) {
273
- console.log(` āš ļø Install warning: ${e.message.slice(0, 50)}`);
274
- }
275
-
276
- // Test different strategies with REAL variations
277
- const strategies = agentConfig.strategies || ['conservative', 'balanced', 'aggressive'];
278
-
279
- for (const strategy of strategies) {
280
- const result = await this.executeTaskWithStrategy(task, strategy);
281
- results.push({
282
- task: task.task,
283
- type: task.type,
284
- strategy,
285
- ...result,
286
- timestamp: new Date().toISOString(),
287
- });
288
- }
231
+ */ async executeTrainingRun(tasks, agentConfig = {}) {
232
+ const results = [];
233
+ for (const task of tasks){
234
+ console.log(`\nšŸ”„ Executing task: ${task.task}`);
235
+ // Install dependencies (only once per task)
236
+ try {
237
+ console.log(` šŸ“¦ Installing dependencies...`);
238
+ execSync('npm install --silent', {
239
+ cwd: task.projectDir,
240
+ stdio: 'pipe'
241
+ });
242
+ } catch (e) {
243
+ console.log(` āš ļø Install warning: ${e.message.slice(0, 50)}`);
244
+ }
245
+ // Test different strategies with REAL variations
246
+ const strategies = agentConfig.strategies || [
247
+ 'conservative',
248
+ 'balanced',
249
+ 'aggressive'
250
+ ];
251
+ for (const strategy of strategies){
252
+ const result = await this.executeTaskWithStrategy(task, strategy);
253
+ results.push({
254
+ task: task.task,
255
+ type: task.type,
256
+ strategy,
257
+ ...result,
258
+ timestamp: new Date().toISOString()
259
+ });
260
+ }
261
+ }
262
+ // Save real results
263
+ const resultsFile = `.claude-flow/training/real-results-${Date.now()}.json`;
264
+ await fs.writeFile(resultsFile, JSON.stringify(results, null, 2));
265
+ return results;
289
266
  }
290
-
291
- // Save real results
292
- const resultsFile = `.claude-flow/training/real-results-${Date.now()}.json`;
293
- await fs.writeFile(resultsFile, JSON.stringify(results, null, 2));
294
-
295
- return results;
296
- }
297
-
298
- /**
267
+ /**
299
268
  * Execute a task with a specific strategy
300
269
  * Strategies affect how we modify and test the code
301
- */
302
- async executeTaskWithStrategy(task, strategy) {
303
- const startTime = Date.now();
304
- const checks = {};
305
-
306
- // Save original code
307
- const originalCode = await fs.readFile(path.join(task.projectDir, 'index.js'), 'utf8');
308
-
309
- // Modify code based on strategy (but more carefully!)
310
- if (strategy === 'aggressive') {
311
- // Aggressive: Skip some validation (but keep valid syntax)
312
- const aggressiveCode = originalCode.replace(/if \(!(\w+)\)/g, 'if (false && !$1)');
313
- await fs.writeFile(path.join(task.projectDir, 'index.js'), aggressiveCode);
314
- } else if (strategy === 'conservative') {
315
- // Conservative: Add validation at the top of functions
316
- const conservativeCode = originalCode.replace(
317
- /function (\w+)\((.*?)\) {/g,
318
- 'function $1($2) {\n // Extra validation for conservative strategy\n if (arguments.length === 0) throw new Error("No arguments provided");',
319
- );
320
- await fs.writeFile(path.join(task.projectDir, 'index.js'), conservativeCode);
321
- }
322
- // Balanced: Keep original code
323
-
324
- // Run REAL tests
325
- try {
326
- const testResult = execSync('npm test', {
327
- cwd: task.projectDir,
328
- encoding: 'utf8',
329
- stdio: 'pipe',
330
- });
331
- checks.test = {
332
- passed: true,
333
- score: 1.0,
334
- output: testResult.slice(0, 100),
335
- };
336
- } catch (e) {
337
- checks.test = {
338
- passed: false,
339
- score: 0.3,
340
- error: e.message.slice(0, 100),
341
- };
342
- }
343
-
344
- // Run REAL lint
345
- try {
346
- const lintResult = execSync('npm run lint', {
347
- cwd: task.projectDir,
348
- encoding: 'utf8',
349
- stdio: 'pipe',
350
- });
351
- const hasErrors = lintResult.includes('error');
352
- checks.lint = {
353
- passed: !hasErrors,
354
- score: hasErrors ? 0.5 : 1.0,
355
- };
356
- } catch (e) {
357
- checks.lint = {
358
- passed: false,
359
- score: 0.3,
360
- };
361
- }
362
-
363
- // Restore original code after testing
364
- await fs.writeFile(path.join(task.projectDir, 'index.js'), originalCode);
365
-
366
- // Calculate REAL performance metrics
367
- const executionTime = Date.now() - startTime;
368
- const successRate =
369
- Object.values(checks).filter((c) => c.passed).length / Object.values(checks).length;
370
-
371
- // Strategy-specific scoring based on REAL results
372
- let strategyBonus = 0;
373
- if (strategy === 'aggressive' && executionTime < 1000) {
374
- strategyBonus = 0.2; // Bonus for fast execution
375
- } else if (strategy === 'conservative' && successRate === 1.0) {
376
- strategyBonus = 0.3; // Bonus for perfect reliability
377
- } else if (strategy === 'balanced' && successRate > 0.5 && executionTime < 2000) {
378
- strategyBonus = 0.25; // Bonus for good balance
270
+ */ async executeTaskWithStrategy(task, strategy) {
271
+ const startTime = Date.now();
272
+ const checks = {};
273
+ // Save original code
274
+ const originalCode = await fs.readFile(path.join(task.projectDir, 'index.js'), 'utf8');
275
+ // Modify code based on strategy (but more carefully!)
276
+ if (strategy === 'aggressive') {
277
+ // Aggressive: Skip some validation (but keep valid syntax)
278
+ const aggressiveCode = originalCode.replace(/if \(!(\w+)\)/g, 'if (false && !$1)');
279
+ await fs.writeFile(path.join(task.projectDir, 'index.js'), aggressiveCode);
280
+ } else if (strategy === 'conservative') {
281
+ // Conservative: Add validation at the top of functions
282
+ const conservativeCode = originalCode.replace(/function (\w+)\((.*?)\) {/g, 'function $1($2) {\n // Extra validation for conservative strategy\n if (arguments.length === 0) throw new Error("No arguments provided");');
283
+ await fs.writeFile(path.join(task.projectDir, 'index.js'), conservativeCode);
284
+ }
285
+ // Balanced: Keep original code
286
+ // Run REAL tests
287
+ try {
288
+ const testResult = execSync('npm test', {
289
+ cwd: task.projectDir,
290
+ encoding: 'utf8',
291
+ stdio: 'pipe'
292
+ });
293
+ checks.test = {
294
+ passed: true,
295
+ score: 1.0,
296
+ output: testResult.slice(0, 100)
297
+ };
298
+ } catch (e) {
299
+ checks.test = {
300
+ passed: false,
301
+ score: 0.3,
302
+ error: e.message.slice(0, 100)
303
+ };
304
+ }
305
+ // Run REAL lint
306
+ try {
307
+ const lintResult = execSync('npm run lint', {
308
+ cwd: task.projectDir,
309
+ encoding: 'utf8',
310
+ stdio: 'pipe'
311
+ });
312
+ const hasErrors = lintResult.includes('error');
313
+ checks.lint = {
314
+ passed: !hasErrors,
315
+ score: hasErrors ? 0.5 : 1.0
316
+ };
317
+ } catch (e) {
318
+ checks.lint = {
319
+ passed: false,
320
+ score: 0.3
321
+ };
322
+ }
323
+ // Restore original code after testing
324
+ await fs.writeFile(path.join(task.projectDir, 'index.js'), originalCode);
325
+ // Calculate REAL performance metrics
326
+ const executionTime = Date.now() - startTime;
327
+ const successRate = Object.values(checks).filter((c)=>c.passed).length / Object.values(checks).length;
328
+ // Strategy-specific scoring based on REAL results
329
+ let strategyBonus = 0;
330
+ if (strategy === 'aggressive' && executionTime < 1000) {
331
+ strategyBonus = 0.2; // Bonus for fast execution
332
+ } else if (strategy === 'conservative' && successRate === 1.0) {
333
+ strategyBonus = 0.3; // Bonus for perfect reliability
334
+ } else if (strategy === 'balanced' && successRate > 0.5 && executionTime < 2000) {
335
+ strategyBonus = 0.25; // Bonus for good balance
336
+ }
337
+ const score = successRate * 60 + Math.max(0, 1 - executionTime / 5000) * 20 + strategyBonus * 20;
338
+ return {
339
+ executionTime,
340
+ successRate,
341
+ checks,
342
+ strategy,
343
+ score,
344
+ real: true
345
+ };
379
346
  }
380
-
381
- const score =
382
- successRate * 60 + Math.max(0, 1 - executionTime / 5000) * 20 + strategyBonus * 20;
383
-
384
- return {
385
- executionTime,
386
- successRate,
387
- checks,
388
- strategy,
389
- score,
390
- real: true, // Mark as real execution
391
- };
392
- }
393
-
394
- /**
347
+ /**
395
348
  * STAGE 3: Learn from Results
396
349
  * Updates profiles based on actual performance
397
- */
398
- async learnFromResults(results) {
399
- console.log('\n🧠 Learning from results...');
400
-
401
- // Load current agent profiles
402
- let profiles = {};
403
- try {
404
- const data = await fs.readFile(this.agentProfiles, 'utf8');
405
- profiles = JSON.parse(data);
406
- } catch {
407
- profiles = this.getDefaultProfiles();
408
- }
409
-
410
- // Analyze REAL results by strategy
411
- const strategyPerformance = {};
412
- for (const result of results) {
413
- if (!strategyPerformance[result.strategy]) {
414
- strategyPerformance[result.strategy] = {
415
- totalScore: 0,
416
- count: 0,
417
- avgExecutionTime: 0,
418
- successRate: 0,
419
- realExecutions: 0,
350
+ */ async learnFromResults(results) {
351
+ console.log('\n🧠 Learning from results...');
352
+ // Load current agent profiles
353
+ let profiles = {};
354
+ try {
355
+ const data = await fs.readFile(this.agentProfiles, 'utf8');
356
+ profiles = JSON.parse(data);
357
+ } catch {
358
+ profiles = this.getDefaultProfiles();
359
+ }
360
+ // Analyze REAL results by strategy
361
+ const strategyPerformance = {};
362
+ for (const result of results){
363
+ if (!strategyPerformance[result.strategy]) {
364
+ strategyPerformance[result.strategy] = {
365
+ totalScore: 0,
366
+ count: 0,
367
+ avgExecutionTime: 0,
368
+ successRate: 0,
369
+ realExecutions: 0
370
+ };
371
+ }
372
+ const perf = strategyPerformance[result.strategy];
373
+ perf.totalScore += result.score;
374
+ perf.count++;
375
+ perf.avgExecutionTime += result.executionTime;
376
+ perf.successRate += result.successRate;
377
+ if (result.real) perf.realExecutions++;
378
+ }
379
+ // Calculate averages and update profiles with REAL data
380
+ for (const [strategy, perf] of Object.entries(strategyPerformance)){
381
+ perf.avgScore = perf.totalScore / perf.count;
382
+ perf.avgExecutionTime = perf.avgExecutionTime / perf.count;
383
+ perf.successRate = perf.successRate / perf.count;
384
+ // Update with stronger learning for real executions
385
+ const learningRate = perf.realExecutions > 0 ? 0.4 : 0.1;
386
+ this.updateAgentProfile(profiles, strategy, perf, learningRate);
387
+ }
388
+ // Save updated profiles
389
+ await fs.writeFile(this.agentProfiles, JSON.stringify(profiles, null, 2));
390
+ // Generate recommendations based on performance
391
+ const recommendations = this.generateRecommendations(strategyPerformance);
392
+ console.log('\nšŸ“Š Learning Results:');
393
+ for (const [strategy, perf] of Object.entries(strategyPerformance)){
394
+ console.log(` ${strategy}: Score ${perf.avgScore.toFixed(2)}, Success ${(perf.successRate * 100).toFixed(1)}%, Time ${perf.avgExecutionTime.toFixed(0)}ms`);
395
+ }
396
+ return {
397
+ profiles,
398
+ recommendations
420
399
  };
421
- }
422
-
423
- const perf = strategyPerformance[result.strategy];
424
- perf.totalScore += result.score;
425
- perf.count++;
426
- perf.avgExecutionTime += result.executionTime;
427
- perf.successRate += result.successRate;
428
- if (result.real) perf.realExecutions++;
429
400
  }
430
-
431
- // Calculate averages and update profiles with REAL data
432
- for (const [strategy, perf] of Object.entries(strategyPerformance)) {
433
- perf.avgScore = perf.totalScore / perf.count;
434
- perf.avgExecutionTime = perf.avgExecutionTime / perf.count;
435
- perf.successRate = perf.successRate / perf.count;
436
-
437
- // Update with stronger learning for real executions
438
- const learningRate = perf.realExecutions > 0 ? 0.4 : 0.1;
439
- this.updateAgentProfile(profiles, strategy, perf, learningRate);
440
- }
441
-
442
- // Save updated profiles
443
- await fs.writeFile(this.agentProfiles, JSON.stringify(profiles, null, 2));
444
-
445
- // Generate recommendations based on performance
446
- const recommendations = this.generateRecommendations(strategyPerformance);
447
-
448
- console.log('\nšŸ“Š Learning Results:');
449
- for (const [strategy, perf] of Object.entries(strategyPerformance)) {
450
- console.log(
451
- ` ${strategy}: Score ${perf.avgScore.toFixed(2)}, Success ${(perf.successRate * 100).toFixed(1)}%, Time ${perf.avgExecutionTime.toFixed(0)}ms`,
452
- );
453
- }
454
-
455
- return { profiles, recommendations };
456
- }
457
-
458
- updateAgentProfile(profiles, strategy, performance, learningRate = 0.3) {
459
- if (!profiles[strategy]) {
460
- profiles[strategy] = {
461
- successRate: 0.5,
462
- avgScore: 50,
463
- avgExecutionTime: 2000,
464
- uses: 0,
465
- realExecutions: 0,
466
- };
467
- }
468
-
469
- const profile = profiles[strategy];
470
-
471
- // Update with exponential moving average
472
- profile.successRate =
473
- profile.successRate * (1 - learningRate) + performance.successRate * learningRate;
474
- profile.avgScore = profile.avgScore * (1 - learningRate) + performance.avgScore * learningRate;
475
- profile.avgExecutionTime =
476
- profile.avgExecutionTime * (1 - learningRate) + performance.avgExecutionTime * learningRate;
477
- profile.uses++;
478
- if (performance.realExecutions) {
479
- profile.realExecutions = (profile.realExecutions || 0) + performance.realExecutions;
480
- }
481
-
482
- // Add performance trend
483
- if (!profile.trend) profile.trend = [];
484
- profile.trend.push({
485
- score: performance.avgScore,
486
- timestamp: new Date().toISOString(),
487
- real: performance.realExecutions > 0,
488
- });
489
- if (profile.trend.length > 20) {
490
- profile.trend = profile.trend.slice(-20);
491
- }
492
-
493
- // Mark improvement
494
- if (profile.trend.length > 1) {
495
- const recent =
496
- profile.trend.slice(-5).reduce((sum, t) => sum + t.score, 0) /
497
- Math.min(5, profile.trend.length);
498
- const older =
499
- profile.trend.slice(0, -5).reduce((sum, t) => sum + t.score, 0) /
500
- Math.max(1, profile.trend.length - 5);
501
- profile.improving = recent > older;
502
- profile.improvementRate = (((recent - older) / older) * 100).toFixed(1);
503
- }
504
- }
505
-
506
- generateRecommendations(strategyPerformance) {
507
- const recommendations = [];
508
-
509
- for (const [strategy, perf] of Object.entries(strategyPerformance)) {
510
- if (perf.successRate < 0.7) {
511
- recommendations.push({
512
- type: 'improve_reliability',
513
- strategy,
514
- action: `${strategy} needs better error handling (${(perf.successRate * 100).toFixed(1)}% success)`,
515
- priority: 'high',
516
- });
517
- }
518
-
519
- if (perf.avgExecutionTime > 3000) {
520
- recommendations.push({
521
- type: 'optimize_speed',
522
- strategy,
523
- action: `${strategy} is too slow (${perf.avgExecutionTime.toFixed(0)}ms avg)`,
524
- priority: 'medium',
525
- });
526
- }
527
-
528
- if (perf.avgScore > 75) {
529
- recommendations.push({
530
- type: 'good_performance',
531
- strategy,
532
- action: `${strategy} performing well (${perf.avgScore.toFixed(1)} score)`,
533
- priority: 'info',
401
+ updateAgentProfile(profiles, strategy, performance, learningRate = 0.3) {
402
+ if (!profiles[strategy]) {
403
+ profiles[strategy] = {
404
+ successRate: 0.5,
405
+ avgScore: 50,
406
+ avgExecutionTime: 2000,
407
+ uses: 0,
408
+ realExecutions: 0
409
+ };
410
+ }
411
+ const profile = profiles[strategy];
412
+ // Update with exponential moving average
413
+ profile.successRate = profile.successRate * (1 - learningRate) + performance.successRate * learningRate;
414
+ profile.avgScore = profile.avgScore * (1 - learningRate) + performance.avgScore * learningRate;
415
+ profile.avgExecutionTime = profile.avgExecutionTime * (1 - learningRate) + performance.avgExecutionTime * learningRate;
416
+ profile.uses++;
417
+ if (performance.realExecutions) {
418
+ profile.realExecutions = (profile.realExecutions || 0) + performance.realExecutions;
419
+ }
420
+ // Add performance trend
421
+ if (!profile.trend) profile.trend = [];
422
+ profile.trend.push({
423
+ score: performance.avgScore,
424
+ timestamp: new Date().toISOString(),
425
+ real: performance.realExecutions > 0
534
426
  });
535
- }
427
+ if (profile.trend.length > 20) {
428
+ profile.trend = profile.trend.slice(-20);
429
+ }
430
+ // Mark improvement
431
+ if (profile.trend.length > 1) {
432
+ const recent = profile.trend.slice(-5).reduce((sum, t)=>sum + t.score, 0) / Math.min(5, profile.trend.length);
433
+ const older = profile.trend.slice(0, -5).reduce((sum, t)=>sum + t.score, 0) / Math.max(1, profile.trend.length - 5);
434
+ profile.improving = recent > older;
435
+ profile.improvementRate = ((recent - older) / older * 100).toFixed(1);
436
+ }
536
437
  }
537
-
538
- return recommendations;
539
- }
540
-
541
- /**
438
+ generateRecommendations(strategyPerformance) {
439
+ const recommendations = [];
440
+ for (const [strategy, perf] of Object.entries(strategyPerformance)){
441
+ if (perf.successRate < 0.7) {
442
+ recommendations.push({
443
+ type: 'improve_reliability',
444
+ strategy,
445
+ action: `${strategy} needs better error handling (${(perf.successRate * 100).toFixed(1)}% success)`,
446
+ priority: 'high'
447
+ });
448
+ }
449
+ if (perf.avgExecutionTime > 3000) {
450
+ recommendations.push({
451
+ type: 'optimize_speed',
452
+ strategy,
453
+ action: `${strategy} is too slow (${perf.avgExecutionTime.toFixed(0)}ms avg)`,
454
+ priority: 'medium'
455
+ });
456
+ }
457
+ if (perf.avgScore > 75) {
458
+ recommendations.push({
459
+ type: 'good_performance',
460
+ strategy,
461
+ action: `${strategy} performing well (${perf.avgScore.toFixed(1)} score)`,
462
+ priority: 'info'
463
+ });
464
+ }
465
+ }
466
+ return recommendations;
467
+ }
468
+ /**
542
469
  * Full Training Pipeline Execution
543
- */
544
- async runFullPipeline(options = {}) {
545
- const { complexity = 'medium', iterations = 3, validate = true } = options;
546
-
547
- console.log('šŸŽÆ Starting Training Pipeline');
548
- console.log('━'.repeat(50));
549
-
550
- await this.initialize();
551
-
552
- // Capture baseline metrics
553
- const baselineMetrics = await this.captureMetrics();
554
-
555
- let cumulativeResults = [];
556
-
557
- for (let i = 1; i <= iterations; i++) {
558
- console.log(`\nšŸ“ Iteration ${i}/${iterations}`);
559
- console.log('─'.repeat(40));
560
-
561
- // Stage 1: Generate tasks
562
- const tasks = await this.generateTrainingTasks(complexity);
563
-
564
- // Stage 2: Execute with real code
565
- const results = await this.executeTrainingRun(tasks);
566
- cumulativeResults = [...cumulativeResults, ...results];
567
-
568
- // Stage 3: Learn from results
569
- const { profiles, recommendations } = await this.learnFromResults(results);
570
-
571
- // Show recommendations
572
- if (recommendations.length > 0) {
573
- console.log('\nšŸ’” Recommendations:');
574
- for (const rec of recommendations.slice(0, 3)) {
575
- console.log(` • ${rec.action}`);
470
+ */ async runFullPipeline(options = {}) {
471
+ const { complexity = 'medium', iterations = 3, validate = true } = options;
472
+ console.log('šŸŽÆ Starting Training Pipeline');
473
+ console.log('━'.repeat(50));
474
+ await this.initialize();
475
+ // Capture baseline metrics
476
+ const baselineMetrics = await this.captureMetrics();
477
+ let cumulativeResults = [];
478
+ for(let i = 1; i <= iterations; i++){
479
+ console.log(`\nšŸ“ Iteration ${i}/${iterations}`);
480
+ console.log('─'.repeat(40));
481
+ // Stage 1: Generate tasks
482
+ const tasks = await this.generateTrainingTasks(complexity);
483
+ // Stage 2: Execute with real code
484
+ const results = await this.executeTrainingRun(tasks);
485
+ cumulativeResults = [
486
+ ...cumulativeResults,
487
+ ...results
488
+ ];
489
+ // Stage 3: Learn from results
490
+ const { profiles, recommendations } = await this.learnFromResults(results);
491
+ // Show recommendations
492
+ if (recommendations.length > 0) {
493
+ console.log('\nšŸ’” Recommendations:');
494
+ for (const rec of recommendations.slice(0, 3)){
495
+ console.log(` • ${rec.action}`);
496
+ }
497
+ }
498
+ // Stage 4: Validate if enabled
499
+ if (validate && i === iterations) {
500
+ const currentMetrics = await this.captureMetrics();
501
+ const validation = await this.validateImprovements(baselineMetrics, currentMetrics);
502
+ if (validation.summary.overallImprovement) {
503
+ console.log('āœ… Improvement detected!');
504
+ } else {
505
+ console.log('āš ļø More training needed for significant improvement');
506
+ }
507
+ }
576
508
  }
577
- }
578
-
579
- // Stage 4: Validate if enabled
580
- if (validate && i === iterations) {
581
- const currentMetrics = await this.captureMetrics();
582
- const validation = await this.validateImprovements(baselineMetrics, currentMetrics);
583
-
584
- if (validation.summary.overallImprovement) {
585
- console.log('āœ… Improvement detected!');
586
- } else {
587
- console.log('āš ļø More training needed for significant improvement');
509
+ // Generate final report
510
+ const report = await this.generateFinalReport(cumulativeResults);
511
+ console.log('\n' + report);
512
+ return {
513
+ success: true,
514
+ totalTasks: cumulativeResults.length,
515
+ realExecutions: cumulativeResults.filter((r)=>r.real).length,
516
+ improvements: await this.calculateOverallImprovement(baselineMetrics)
517
+ };
518
+ }
519
+ // Reuse helper methods from original
520
+ async captureMetrics() {
521
+ try {
522
+ const data = await fs.readFile(this.agentProfiles, 'utf8');
523
+ const profiles = JSON.parse(data);
524
+ // Calculate weighted average from all strategies
525
+ let totalScore = 0;
526
+ let totalSuccess = 0;
527
+ let totalTime = 0;
528
+ let count = 0;
529
+ for (const profile of Object.values(profiles)){
530
+ if (profile.uses > 0) {
531
+ totalScore += profile.avgScore;
532
+ totalSuccess += profile.successRate;
533
+ totalTime += profile.avgExecutionTime;
534
+ count++;
535
+ }
536
+ }
537
+ return {
538
+ successRate: count > 0 ? totalSuccess / count : 0,
539
+ executionTime: count > 0 ? totalTime / count : 0,
540
+ score: count > 0 ? totalScore / count : 0
541
+ };
542
+ } catch {
543
+ return {
544
+ successRate: 0,
545
+ executionTime: 0,
546
+ score: 0
547
+ };
588
548
  }
589
- }
590
549
  }
591
-
592
- // Generate final report
593
- const report = await this.generateFinalReport(cumulativeResults);
594
- console.log('\n' + report);
595
-
596
- return {
597
- success: true,
598
- totalTasks: cumulativeResults.length,
599
- realExecutions: cumulativeResults.filter((r) => r.real).length,
600
- improvements: await this.calculateOverallImprovement(baselineMetrics),
601
- };
602
- }
603
-
604
- // Reuse helper methods from original
605
- async captureMetrics() {
606
- try {
607
- const data = await fs.readFile(this.agentProfiles, 'utf8');
608
- const profiles = JSON.parse(data);
609
-
610
- // Calculate weighted average from all strategies
611
- let totalScore = 0;
612
- let totalSuccess = 0;
613
- let totalTime = 0;
614
- let count = 0;
615
-
616
- for (const profile of Object.values(profiles)) {
617
- if (profile.uses > 0) {
618
- totalScore += profile.avgScore;
619
- totalSuccess += profile.successRate;
620
- totalTime += profile.avgExecutionTime;
621
- count++;
550
+ async validateImprovements(beforeMetrics, afterMetrics) {
551
+ const validation = {
552
+ improved: [],
553
+ declined: [],
554
+ unchanged: [],
555
+ summary: {}
556
+ };
557
+ const metrics = [
558
+ 'successRate',
559
+ 'executionTime',
560
+ 'score'
561
+ ];
562
+ for (const metric of metrics){
563
+ const before = beforeMetrics[metric] || 0.01; // Avoid division by zero
564
+ const after = afterMetrics[metric] || 0;
565
+ const change = after - before;
566
+ const percentChange = change / before * 100;
567
+ if (percentChange > 5) {
568
+ validation.improved.push({
569
+ metric,
570
+ change: percentChange
571
+ });
572
+ } else if (percentChange < -5) {
573
+ validation.declined.push({
574
+ metric,
575
+ change: percentChange
576
+ });
577
+ } else {
578
+ validation.unchanged.push({
579
+ metric,
580
+ change: percentChange
581
+ });
582
+ }
622
583
  }
623
- }
624
-
625
- return {
626
- successRate: count > 0 ? totalSuccess / count : 0,
627
- executionTime: count > 0 ? totalTime / count : 0,
628
- score: count > 0 ? totalScore / count : 0,
629
- };
630
- } catch {
631
- return {
632
- successRate: 0,
633
- executionTime: 0,
634
- score: 0,
635
- };
584
+ validation.summary = {
585
+ overallImprovement: validation.improved.length > validation.declined.length,
586
+ improvementScore: validation.improved.length - validation.declined.length,
587
+ timestamp: new Date().toISOString()
588
+ };
589
+ console.log(`\nāœ… Validating improvements...`);
590
+ console.log(` Improved: ${validation.improved.length} metrics`);
591
+ console.log(` Declined: ${validation.declined.length} metrics`);
592
+ console.log(` Unchanged: ${validation.unchanged.length} metrics`);
593
+ return validation;
636
594
  }
637
- }
638
-
639
- async validateImprovements(beforeMetrics, afterMetrics) {
640
- const validation = {
641
- improved: [],
642
- declined: [],
643
- unchanged: [],
644
- summary: {},
645
- };
646
-
647
- const metrics = ['successRate', 'executionTime', 'score'];
648
-
649
- for (const metric of metrics) {
650
- const before = beforeMetrics[metric] || 0.01; // Avoid division by zero
651
- const after = afterMetrics[metric] || 0;
652
- const change = after - before;
653
- const percentChange = (change / before) * 100;
654
-
655
- if (percentChange > 5) {
656
- validation.improved.push({ metric, change: percentChange });
657
- } else if (percentChange < -5) {
658
- validation.declined.push({ metric, change: percentChange });
659
- } else {
660
- validation.unchanged.push({ metric, change: percentChange });
661
- }
595
+ async calculateOverallImprovement(baselineMetrics) {
596
+ const currentMetrics = await this.captureMetrics();
597
+ const base = {
598
+ successRate: baselineMetrics.successRate || 0.01,
599
+ executionTime: baselineMetrics.executionTime || 1,
600
+ score: baselineMetrics.score || 0.01
601
+ };
602
+ return {
603
+ successRate: (currentMetrics.successRate - base.successRate) / base.successRate * 100,
604
+ executionTime: (base.executionTime - currentMetrics.executionTime) / base.executionTime * 100,
605
+ score: (currentMetrics.score - base.score) / base.score * 100
606
+ };
662
607
  }
663
-
664
- validation.summary = {
665
- overallImprovement: validation.improved.length > validation.declined.length,
666
- improvementScore: validation.improved.length - validation.declined.length,
667
- timestamp: new Date().toISOString(),
668
- };
669
-
670
- console.log(`\nāœ… Validating improvements...`);
671
- console.log(` Improved: ${validation.improved.length} metrics`);
672
- console.log(` Declined: ${validation.declined.length} metrics`);
673
- console.log(` Unchanged: ${validation.unchanged.length} metrics`);
674
-
675
- return validation;
676
- }
677
-
678
- async calculateOverallImprovement(baselineMetrics) {
679
- const currentMetrics = await this.captureMetrics();
680
-
681
- const base = {
682
- successRate: baselineMetrics.successRate || 0.01,
683
- executionTime: baselineMetrics.executionTime || 1,
684
- score: baselineMetrics.score || 0.01,
685
- };
686
-
687
- return {
688
- successRate: ((currentMetrics.successRate - base.successRate) / base.successRate) * 100,
689
- executionTime:
690
- ((base.executionTime - currentMetrics.executionTime) / base.executionTime) * 100,
691
- score: ((currentMetrics.score - base.score) / base.score) * 100,
692
- };
693
- }
694
-
695
- async generateFinalReport(results) {
696
- const realResults = results.filter((r) => r.real);
697
- const successRates = {};
698
- const scores = {};
699
- const times = {};
700
-
701
- for (const result of realResults) {
702
- if (!successRates[result.strategy]) {
703
- successRates[result.strategy] = [];
704
- scores[result.strategy] = [];
705
- times[result.strategy] = [];
706
- }
707
- successRates[result.strategy].push(result.successRate);
708
- scores[result.strategy].push(result.score);
709
- times[result.strategy].push(result.executionTime);
608
+ async generateFinalReport(results) {
609
+ const realResults = results.filter((r)=>r.real);
610
+ const successRates = {};
611
+ const scores = {};
612
+ const times = {};
613
+ for (const result of realResults){
614
+ if (!successRates[result.strategy]) {
615
+ successRates[result.strategy] = [];
616
+ scores[result.strategy] = [];
617
+ times[result.strategy] = [];
618
+ }
619
+ successRates[result.strategy].push(result.successRate);
620
+ scores[result.strategy].push(result.score);
621
+ times[result.strategy].push(result.executionTime);
622
+ }
623
+ let report = 'šŸ“Š Training Pipeline Report\n';
624
+ report += '━'.repeat(50) + '\n\n';
625
+ for (const strategy of Object.keys(successRates)){
626
+ const avgSuccess = successRates[strategy].reduce((a, b)=>a + b, 0) / successRates[strategy].length;
627
+ const avgScore = scores[strategy].reduce((a, b)=>a + b, 0) / scores[strategy].length;
628
+ const avgTime = times[strategy].reduce((a, b)=>a + b, 0) / times[strategy].length;
629
+ report += `Strategy: ${strategy}\n`;
630
+ report += ` Average Success Rate: ${(avgSuccess * 100).toFixed(1)}%\n`;
631
+ report += ` Average Score: ${avgScore.toFixed(2)}\n`;
632
+ report += ` Average Time: ${avgTime.toFixed(0)}ms\n`;
633
+ report += ` Real Executions: ${successRates[strategy].length}\n`;
634
+ report += '\n';
635
+ }
636
+ return report;
710
637
  }
711
-
712
- let report = 'šŸ“Š Training Pipeline Report\n';
713
- report += '━'.repeat(50) + '\n\n';
714
-
715
- for (const strategy of Object.keys(successRates)) {
716
- const avgSuccess =
717
- successRates[strategy].reduce((a, b) => a + b, 0) / successRates[strategy].length;
718
- const avgScore = scores[strategy].reduce((a, b) => a + b, 0) / scores[strategy].length;
719
- const avgTime = times[strategy].reduce((a, b) => a + b, 0) / times[strategy].length;
720
-
721
- report += `Strategy: ${strategy}\n`;
722
- report += ` Average Success Rate: ${(avgSuccess * 100).toFixed(1)}%\n`;
723
- report += ` Average Score: ${avgScore.toFixed(2)}\n`;
724
- report += ` Average Time: ${avgTime.toFixed(0)}ms\n`;
725
- report += ` Real Executions: ${successRates[strategy].length}\n`;
726
- report += '\n';
638
+ getDefaultProfiles() {
639
+ return {
640
+ conservative: {
641
+ successRate: 0.5,
642
+ avgScore: 50,
643
+ avgExecutionTime: 3000,
644
+ uses: 0,
645
+ realExecutions: 0
646
+ },
647
+ balanced: {
648
+ successRate: 0.5,
649
+ avgScore: 50,
650
+ avgExecutionTime: 2000,
651
+ uses: 0,
652
+ realExecutions: 0
653
+ },
654
+ aggressive: {
655
+ successRate: 0.5,
656
+ avgScore: 50,
657
+ avgExecutionTime: 1000,
658
+ uses: 0,
659
+ realExecutions: 0
660
+ }
661
+ };
727
662
  }
728
-
729
- return report;
730
- }
731
-
732
- getDefaultProfiles() {
733
- return {
734
- conservative: {
735
- successRate: 0.5,
736
- avgScore: 50,
737
- avgExecutionTime: 3000,
738
- uses: 0,
739
- realExecutions: 0,
740
- },
741
- balanced: {
742
- successRate: 0.5,
743
- avgScore: 50,
744
- avgExecutionTime: 2000,
745
- uses: 0,
746
- realExecutions: 0,
747
- },
748
- aggressive: {
749
- successRate: 0.5,
750
- avgScore: 50,
751
- avgExecutionTime: 1000,
752
- uses: 0,
753
- realExecutions: 0,
754
- },
755
- };
756
- }
757
-
758
- async loadPipelineConfig() {
759
- try {
760
- const data = await fs.readFile(this.pipelineConfig, 'utf8');
761
- return JSON.parse(data);
762
- } catch {
763
- const defaultConfig = {
764
- version: '2.0.0',
765
- strategies: ['conservative', 'balanced', 'aggressive'],
766
- learningRate: 0.4,
767
- minSamplesForUpdate: 3,
768
- useRealExecution: true,
769
- created: new Date().toISOString(),
770
- };
771
-
772
- await fs.writeFile(this.pipelineConfig, JSON.stringify(defaultConfig, null, 2));
773
- return defaultConfig;
663
+ async loadPipelineConfig() {
664
+ try {
665
+ const data = await fs.readFile(this.pipelineConfig, 'utf8');
666
+ return JSON.parse(data);
667
+ } catch {
668
+ const defaultConfig = {
669
+ version: '2.0.0',
670
+ strategies: [
671
+ 'conservative',
672
+ 'balanced',
673
+ 'aggressive'
674
+ ],
675
+ learningRate: 0.4,
676
+ minSamplesForUpdate: 3,
677
+ useRealExecution: true,
678
+ created: new Date().toISOString()
679
+ };
680
+ await fs.writeFile(this.pipelineConfig, JSON.stringify(defaultConfig, null, 2));
681
+ return defaultConfig;
682
+ }
683
+ }
684
+ constructor(){
685
+ this.pipelineConfig = '.claude-flow/pipeline-config.json';
686
+ this.trainingLog = '.claude-flow/training/pipeline-log.jsonl';
687
+ this.improvementMetrics = '.claude-flow/metrics/improvements.json';
688
+ this.agentProfiles = '.claude-flow/agents/profiles.json';
689
+ this.realTasksDir = '.claude-flow/training/real-tasks';
690
+ this.initialized = false;
774
691
  }
775
- }
776
692
  }
777
-
778
693
  /**
779
694
  * CLI Command Handler
780
- */
781
- export async function trainingPipelineCommand(args, flags) {
782
- const pipeline = new TrainingPipeline();
783
- const subcommand = args[0] || 'run';
784
-
785
- switch (subcommand) {
786
- case 'run':
787
- // Run real pipeline
788
- const options = {
789
- complexity: flags.complexity || 'medium',
790
- iterations: parseInt(flags.iterations) || 3,
791
- validate: flags.validate !== false,
792
- };
793
-
794
- console.log('šŸš€ Starting Training Pipeline');
795
- console.log(` Complexity: ${options.complexity}`);
796
- console.log(` Iterations: ${options.iterations}`);
797
- console.log(` Validation: ${options.validate ? 'Enabled' : 'Disabled'}`);
798
-
799
- const result = await pipeline.runFullPipeline(options);
800
-
801
- if (result.success) {
802
- console.log('\nāœ… Training Pipeline completed');
803
- console.log(` Total tasks: ${result.totalTasks}`);
804
- console.log(` Real executions: ${result.realExecutions}`);
805
-
806
- if (result.improvements) {
807
- console.log('\nšŸ“ˆ Improvements:');
808
- console.log(
809
- ` Success Rate: ${result.improvements.successRate > 0 ? '+' : ''}${result.improvements.successRate.toFixed(1)}%`,
810
- );
811
- console.log(
812
- ` Execution Time: ${result.improvements.executionTime > 0 ? '+' : ''}${result.improvements.executionTime.toFixed(1)}%`,
813
- );
814
- console.log(
815
- ` Score: ${result.improvements.score > 0 ? '+' : ''}${result.improvements.score.toFixed(1)}%`,
816
- );
817
- }
818
- }
819
- break;
820
-
821
- case 'status':
822
- // Show real pipeline status
823
- await pipeline.initialize();
824
-
825
- let profiles = {};
826
- try {
827
- const data = await fs.readFile(pipeline.agentProfiles, 'utf8');
828
- profiles = JSON.parse(data);
829
- } catch {
830
- profiles = pipeline.getDefaultProfiles();
831
- }
832
-
833
- console.log('\nšŸ“Š Training Pipeline Status');
834
- console.log('━'.repeat(50));
835
-
836
- console.log('\nšŸ¤– Strategy Profiles:');
837
- for (const [strategy, profile] of Object.entries(profiles)) {
838
- console.log(` ${strategy}:`);
839
- console.log(` Success Rate: ${(profile.successRate * 100).toFixed(1)}%`);
840
- console.log(` Average Score: ${profile.avgScore.toFixed(2)}`);
841
- console.log(` Execution Time: ${profile.avgExecutionTime.toFixed(0)}ms`);
842
- console.log(` Total Uses: ${profile.uses}`);
843
- console.log(` Real Executions: ${profile.realExecutions || 0}`);
844
- if (profile.improving !== undefined) {
845
- console.log(
846
- ` Trend: ${profile.improving ? 'šŸ“ˆ Improving' : 'šŸ“‰ Declining'} (${profile.improvementRate}%)`,
847
- );
848
- }
849
- }
850
- break;
851
-
852
- case 'validate':
853
- // Validate current performance
854
- await pipeline.initialize();
855
- const metrics = await pipeline.captureMetrics();
856
- console.log('\nšŸ“Š Current Performance:');
857
- console.log(` Success Rate: ${(metrics.successRate * 100).toFixed(1)}%`);
858
- console.log(` Avg Execution Time: ${metrics.executionTime.toFixed(0)}ms`);
859
- console.log(` Average Score: ${metrics.score.toFixed(2)}`);
860
- break;
861
-
862
- default:
863
- console.log('Usage: train-pipeline <command> [options]');
864
- console.log('\nCommands:');
865
- console.log(' run - Run training pipeline with real code');
866
- console.log(' status - Show pipeline status');
867
- console.log(' validate - Check current performance');
868
- console.log('\nOptions:');
869
- console.log(' --complexity <level> - easy/medium/hard');
870
- console.log(' --iterations <n> - Training cycles');
871
- }
695
+ */ export async function trainingPipelineCommand(args, flags) {
696
+ const pipeline = new TrainingPipeline();
697
+ const subcommand = args[0] || 'run';
698
+ switch(subcommand){
699
+ case 'run':
700
+ // Run real pipeline
701
+ const options = {
702
+ complexity: flags.complexity || 'medium',
703
+ iterations: parseInt(flags.iterations) || 3,
704
+ validate: flags.validate !== false
705
+ };
706
+ console.log('šŸš€ Starting Training Pipeline');
707
+ console.log(` Complexity: ${options.complexity}`);
708
+ console.log(` Iterations: ${options.iterations}`);
709
+ console.log(` Validation: ${options.validate ? 'Enabled' : 'Disabled'}`);
710
+ const result = await pipeline.runFullPipeline(options);
711
+ if (result.success) {
712
+ console.log('\nāœ… Training Pipeline completed');
713
+ console.log(` Total tasks: ${result.totalTasks}`);
714
+ console.log(` Real executions: ${result.realExecutions}`);
715
+ if (result.improvements) {
716
+ console.log('\nšŸ“ˆ Improvements:');
717
+ console.log(` Success Rate: ${result.improvements.successRate > 0 ? '+' : ''}${result.improvements.successRate.toFixed(1)}%`);
718
+ console.log(` Execution Time: ${result.improvements.executionTime > 0 ? '+' : ''}${result.improvements.executionTime.toFixed(1)}%`);
719
+ console.log(` Score: ${result.improvements.score > 0 ? '+' : ''}${result.improvements.score.toFixed(1)}%`);
720
+ }
721
+ }
722
+ break;
723
+ case 'status':
724
+ // Show real pipeline status
725
+ await pipeline.initialize();
726
+ let profiles = {};
727
+ try {
728
+ const data = await fs.readFile(pipeline.agentProfiles, 'utf8');
729
+ profiles = JSON.parse(data);
730
+ } catch {
731
+ profiles = pipeline.getDefaultProfiles();
732
+ }
733
+ console.log('\nšŸ“Š Training Pipeline Status');
734
+ console.log('━'.repeat(50));
735
+ console.log('\nšŸ¤– Strategy Profiles:');
736
+ for (const [strategy, profile] of Object.entries(profiles)){
737
+ console.log(` ${strategy}:`);
738
+ console.log(` Success Rate: ${(profile.successRate * 100).toFixed(1)}%`);
739
+ console.log(` Average Score: ${profile.avgScore.toFixed(2)}`);
740
+ console.log(` Execution Time: ${profile.avgExecutionTime.toFixed(0)}ms`);
741
+ console.log(` Total Uses: ${profile.uses}`);
742
+ console.log(` Real Executions: ${profile.realExecutions || 0}`);
743
+ if (profile.improving !== undefined) {
744
+ console.log(` Trend: ${profile.improving ? 'šŸ“ˆ Improving' : 'šŸ“‰ Declining'} (${profile.improvementRate}%)`);
745
+ }
746
+ }
747
+ break;
748
+ case 'validate':
749
+ // Validate current performance
750
+ await pipeline.initialize();
751
+ const metrics = await pipeline.captureMetrics();
752
+ console.log('\nšŸ“Š Current Performance:');
753
+ console.log(` Success Rate: ${(metrics.successRate * 100).toFixed(1)}%`);
754
+ console.log(` Avg Execution Time: ${metrics.executionTime.toFixed(0)}ms`);
755
+ console.log(` Average Score: ${metrics.score.toFixed(2)}`);
756
+ break;
757
+ default:
758
+ console.log('Usage: train-pipeline <command> [options]');
759
+ console.log('\nCommands:');
760
+ console.log(' run - Run training pipeline with real code');
761
+ console.log(' status - Show pipeline status');
762
+ console.log(' validate - Check current performance');
763
+ console.log('\nOptions:');
764
+ console.log(' --complexity <level> - easy/medium/hard');
765
+ console.log(' --iterations <n> - Training cycles');
766
+ }
872
767
  }
873
-
874
768
  export default TrainingPipeline;