Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

πŸ”– Task: full implement all real benchmarks and optmization in swarm-benchmark cli commands in benchmark/src/...

rUv3271ef483ab6
diff --git a/.claude-flow/metrics/system-metrics.json b/.claude-flow/metrics/system-metrics.json
index b0e424b62a..bdc513d96f 100644
--- a/.claude-flow/metrics/system-metrics.json
+++ b/.claude-flow/metrics/system-metrics.json
@@ -1822,5 +1822,473 @@
"cpuLoad": 0.02875,
"platform": "linux",
"uptime": 14556.69
+ },
+ {
+ "timestamp": 1754446518084,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7785693184,
+ "memoryFree": 59641851904,
+ "memoryUsagePercent": 11.546754629489856,
+ "memoryEfficiency": 88.45324537051015,
+ "cpuCount": 16,
+ "cpuLoad": 0.08,
+ "platform": "linux",
+ "uptime": 14586.7
+ },
+ {
+ "timestamp": 1754446548114,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7788032000,
+ "memoryFree": 59639513088,
+ "memoryUsagePercent": 11.550223265337339,
+ "memoryEfficiency": 88.44977673466266,
+ "cpuCount": 16,
+ "cpuLoad": 0.0925,
+ "platform": "linux",
+ "uptime": 14616.73
+ },
+ {
+ "timestamp": 1754446578128,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7637868544,
+ "memoryFree": 59789676544,
+ "memoryUsagePercent": 11.327519834856485,
+ "memoryEfficiency": 88.67248016514351,
+ "cpuCount": 16,
+ "cpuLoad": 0.063125,
+ "platform": "linux",
+ "uptime": 14646.75
+ },
+ {
+ "timestamp": 1754446608159,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7756529664,
+ "memoryFree": 59671015424,
+ "memoryUsagePercent": 11.503502988099177,
+ "memoryEfficiency": 88.49649701190083,
+ "cpuCount": 16,
+ "cpuLoad": 0.056875,
+ "platform": "linux",
+ "uptime": 14676.78
+ },
+ {
+ "timestamp": 1754446638185,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7825842176,
+ "memoryFree": 59601702912,
+ "memoryUsagePercent": 11.606298532426855,
+ "memoryEfficiency": 88.39370146757315,
+ "cpuCount": 16,
+ "cpuLoad": 0.059375,
+ "platform": "linux",
+ "uptime": 14706.8
+ },
+ {
+ "timestamp": 1754446668188,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7807348736,
+ "memoryFree": 59620196352,
+ "memoryUsagePercent": 11.578871403089929,
+ "memoryEfficiency": 88.42112859691007,
+ "cpuCount": 16,
+ "cpuLoad": 0.076875,
+ "platform": "linux",
+ "uptime": 14736.81
+ },
+ {
+ "timestamp": 1754446698190,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7797444608,
+ "memoryFree": 59630100480,
+ "memoryUsagePercent": 11.564182854089555,
+ "memoryEfficiency": 88.43581714591045,
+ "cpuCount": 16,
+ "cpuLoad": 0.07125,
+ "platform": "linux",
+ "uptime": 14766.81
+ },
+ {
+ "timestamp": 1754446728221,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7728590848,
+ "memoryFree": 59698954240,
+ "memoryUsagePercent": 11.462067672660158,
+ "memoryEfficiency": 88.53793232733985,
+ "cpuCount": 16,
+ "cpuLoad": 0.053125,
+ "platform": "linux",
+ "uptime": 14796.84
+ },
+ {
+ "timestamp": 1754446758251,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7762096128,
+ "memoryFree": 59665448960,
+ "memoryUsagePercent": 11.51175846290956,
+ "memoryEfficiency": 88.48824153709045,
+ "cpuCount": 16,
+ "cpuLoad": 0.045625,
+ "platform": "linux",
+ "uptime": 14826.87
+ },
+ {
+ "timestamp": 1754446788281,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7705227264,
+ "memoryFree": 59722317824,
+ "memoryUsagePercent": 11.427417762197738,
+ "memoryEfficiency": 88.57258223780227,
+ "cpuCount": 16,
+ "cpuLoad": 0.041875,
+ "platform": "linux",
+ "uptime": 14856.9
+ },
+ {
+ "timestamp": 1754446818310,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7714119680,
+ "memoryFree": 59713425408,
+ "memoryUsagePercent": 11.440605868020654,
+ "memoryEfficiency": 88.55939413197935,
+ "cpuCount": 16,
+ "cpuLoad": 0.061875,
+ "platform": "linux",
+ "uptime": 14886.93
+ },
+ {
+ "timestamp": 1754446848329,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7785394176,
+ "memoryFree": 59642150912,
+ "memoryUsagePercent": 11.546311178672227,
+ "memoryEfficiency": 88.45368882132777,
+ "cpuCount": 16,
+ "cpuLoad": 0.04875,
+ "platform": "linux",
+ "uptime": 14916.95
+ },
+ {
+ "timestamp": 1754446878332,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7736954880,
+ "memoryFree": 59690590208,
+ "memoryUsagePercent": 11.474472146216305,
+ "memoryEfficiency": 88.5255278537837,
+ "cpuCount": 16,
+ "cpuLoad": 0.041875,
+ "platform": "linux",
+ "uptime": 14946.95
+ },
+ {
+ "timestamp": 1754446908363,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7902740480,
+ "memoryFree": 59524804608,
+ "memoryUsagePercent": 11.720344363251096,
+ "memoryEfficiency": 88.2796556367489,
+ "cpuCount": 16,
+ "cpuLoad": 0.06,
+ "platform": "linux",
+ "uptime": 14976.98
+ },
+ {
+ "timestamp": 1754446938368,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7939031040,
+ "memoryFree": 59488514048,
+ "memoryUsagePercent": 11.77416592824006,
+ "memoryEfficiency": 88.22583407175993,
+ "cpuCount": 16,
+ "cpuLoad": 0.100625,
+ "platform": "linux",
+ "uptime": 15006.99
+ },
+ {
+ "timestamp": 1754446968381,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8411983872,
+ "memoryFree": 59015561216,
+ "memoryUsagePercent": 12.475589703023417,
+ "memoryEfficiency": 87.52441029697658,
+ "cpuCount": 16,
+ "cpuLoad": 0.17,
+ "platform": "linux",
+ "uptime": 15037
+ },
+ {
+ "timestamp": 1754446998412,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8439586816,
+ "memoryFree": 58987958272,
+ "memoryUsagePercent": 12.516526895626196,
+ "memoryEfficiency": 87.4834731043738,
+ "cpuCount": 16,
+ "cpuLoad": 0.223125,
+ "platform": "linux",
+ "uptime": 15067.03
+ },
+ {
+ "timestamp": 1754447028441,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8977084416,
+ "memoryFree": 58450460672,
+ "memoryUsagePercent": 13.313675300330102,
+ "memoryEfficiency": 86.6863246996699,
+ "cpuCount": 16,
+ "cpuLoad": 0.223125,
+ "platform": "linux",
+ "uptime": 15097.06
+ },
+ {
+ "timestamp": 1754447058470,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8599498752,
+ "memoryFree": 58828046336,
+ "memoryUsagePercent": 12.753688037695508,
+ "memoryEfficiency": 87.24631196230449,
+ "cpuCount": 16,
+ "cpuLoad": 0.258125,
+ "platform": "linux",
+ "uptime": 15127.09
+ },
+ {
+ "timestamp": 1754447088500,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8968142848,
+ "memoryFree": 58459402240,
+ "memoryUsagePercent": 13.300414298482371,
+ "memoryEfficiency": 86.69958570151763,
+ "cpuCount": 16,
+ "cpuLoad": 0.28625,
+ "platform": "linux",
+ "uptime": 15157.12
+ },
+ {
+ "timestamp": 1754447118504,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8536969216,
+ "memoryFree": 58890575872,
+ "memoryUsagePercent": 12.660952144792404,
+ "memoryEfficiency": 87.3390478552076,
+ "cpuCount": 16,
+ "cpuLoad": 0.2725,
+ "platform": "linux",
+ "uptime": 15187.12
+ },
+ {
+ "timestamp": 1754447148533,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8592052224,
+ "memoryFree": 58835492864,
+ "memoryUsagePercent": 12.74264428993592,
+ "memoryEfficiency": 87.25735571006408,
+ "cpuCount": 16,
+ "cpuLoad": 0.299375,
+ "platform": "linux",
+ "uptime": 15217.15
+ },
+ {
+ "timestamp": 1754447178545,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8411684864,
+ "memoryFree": 59015860224,
+ "memoryUsagePercent": 12.475146252205787,
+ "memoryEfficiency": 87.52485374779421,
+ "cpuCount": 16,
+ "cpuLoad": 0.26625,
+ "platform": "linux",
+ "uptime": 15247.16
+ },
+ {
+ "timestamp": 1754447208558,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8092315648,
+ "memoryFree": 59335229440,
+ "memoryUsagePercent": 12.001498256296713,
+ "memoryEfficiency": 87.99850174370329,
+ "cpuCount": 16,
+ "cpuLoad": 0.24375,
+ "platform": "linux",
+ "uptime": 15277.18
+ },
+ {
+ "timestamp": 1754447238589,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8033267712,
+ "memoryFree": 59394277376,
+ "memoryUsagePercent": 11.913925831818057,
+ "memoryEfficiency": 88.08607416818194,
+ "cpuCount": 16,
+ "cpuLoad": 0.229375,
+ "platform": "linux",
+ "uptime": 15307.21
+ },
+ {
+ "timestamp": 1754447268590,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8090943488,
+ "memoryFree": 59336601600,
+ "memoryUsagePercent": 11.999463242270608,
+ "memoryEfficiency": 88.00053675772939,
+ "cpuCount": 16,
+ "cpuLoad": 0.183125,
+ "platform": "linux",
+ "uptime": 15337.21
+ },
+ {
+ "timestamp": 1754447298593,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7889969152,
+ "memoryFree": 59537575936,
+ "memoryUsagePercent": 11.701403546136472,
+ "memoryEfficiency": 88.29859645386352,
+ "cpuCount": 16,
+ "cpuLoad": 0.135625,
+ "platform": "linux",
+ "uptime": 15367.21
+ },
+ {
+ "timestamp": 1754447328623,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 7916969984,
+ "memoryFree": 59510575104,
+ "memoryUsagePercent": 11.741447762435257,
+ "memoryEfficiency": 88.25855223756474,
+ "cpuCount": 16,
+ "cpuLoad": 0.099375,
+ "platform": "linux",
+ "uptime": 15397.24
+ },
+ {
+ "timestamp": 1754447358654,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8058675200,
+ "memoryFree": 59368869888,
+ "memoryUsagePercent": 11.951607001979065,
+ "memoryEfficiency": 88.04839299802093,
+ "cpuCount": 16,
+ "cpuLoad": 0.0975,
+ "platform": "linux",
+ "uptime": 15427.27
+ },
+ {
+ "timestamp": 1754447388683,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8109285376,
+ "memoryFree": 59318259712,
+ "memoryUsagePercent": 12.02666560886435,
+ "memoryEfficiency": 87.97333439113565,
+ "cpuCount": 16,
+ "cpuLoad": 0.1225,
+ "platform": "linux",
+ "uptime": 15457.3
+ },
+ {
+ "timestamp": 1754447418713,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8225681408,
+ "memoryFree": 59201863680,
+ "memoryUsagePercent": 12.199289470296783,
+ "memoryEfficiency": 87.80071052970322,
+ "cpuCount": 16,
+ "cpuLoad": 0.108125,
+ "platform": "linux",
+ "uptime": 15487.33
+ },
+ {
+ "timestamp": 1754447448728,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8210259968,
+ "memoryFree": 59217285120,
+ "memoryUsagePercent": 12.176418342510843,
+ "memoryEfficiency": 87.82358165748916,
+ "cpuCount": 16,
+ "cpuLoad": 0.163125,
+ "platform": "linux",
+ "uptime": 15517.35
+ },
+ {
+ "timestamp": 1754447478758,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8181493760,
+ "memoryFree": 59246051328,
+ "memoryUsagePercent": 12.133755943987424,
+ "memoryEfficiency": 87.86624405601258,
+ "cpuCount": 16,
+ "cpuLoad": 0.139375,
+ "platform": "linux",
+ "uptime": 15547.38
+ },
+ {
+ "timestamp": 1754447508761,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8202301440,
+ "memoryFree": 59225243648,
+ "memoryUsagePercent": 12.164615261159424,
+ "memoryEfficiency": 87.83538473884057,
+ "cpuCount": 16,
+ "cpuLoad": 0.144375,
+ "platform": "linux",
+ "uptime": 15577.38
+ },
+ {
+ "timestamp": 1754447538791,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8081051648,
+ "memoryFree": 59346493440,
+ "memoryUsagePercent": 11.984792917276437,
+ "memoryEfficiency": 88.01520708272356,
+ "cpuCount": 16,
+ "cpuLoad": 0.129375,
+ "platform": "linux",
+ "uptime": 15607.41
+ },
+ {
+ "timestamp": 1754447568820,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8180891648,
+ "memoryFree": 59246653440,
+ "memoryUsagePercent": 12.13286296768343,
+ "memoryEfficiency": 87.86713703231658,
+ "cpuCount": 16,
+ "cpuLoad": 0.135,
+ "platform": "linux",
+ "uptime": 15637.44
+ },
+ {
+ "timestamp": 1754447598850,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8314695680,
+ "memoryFree": 59112849408,
+ "memoryUsagePercent": 12.331304171238108,
+ "memoryEfficiency": 87.6686958287619,
+ "cpuCount": 16,
+ "cpuLoad": 0.143125,
+ "platform": "linux",
+ "uptime": 15667.47
+ },
+ {
+ "timestamp": 1754447628880,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8325357568,
+ "memoryFree": 59102187520,
+ "memoryUsagePercent": 12.347116533954392,
+ "memoryEfficiency": 87.65288346604561,
+ "cpuCount": 16,
+ "cpuLoad": 0.120625,
+ "platform": "linux",
+ "uptime": 15697.5
+ },
+ {
+ "timestamp": 1754447658893,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8269135872,
+ "memoryFree": 59158409216,
+ "memoryUsagePercent": 12.263735630902643,
+ "memoryEfficiency": 87.73626436909736,
+ "cpuCount": 16,
+ "cpuLoad": 0.105,
+ "platform": "linux",
+ "uptime": 15727.51
}
]
\ No newline at end of file
diff --git a/benchmark/.claude-flow/metrics/performance.json b/benchmark/.claude-flow/metrics/performance.json
index 50a4ecf34d..919151bb87 100644
--- a/benchmark/.claude-flow/metrics/performance.json
+++ b/benchmark/.claude-flow/metrics/performance.json
@@ -1,5 +1,5 @@
{
- "startTime": 1754446200982,
+ "startTime": 1754447658902,
"totalTasks": 1,
"successfulTasks": 1,
"failedTasks": 0,
diff --git a/benchmark/.claude-flow/metrics/system-metrics.json b/benchmark/.claude-flow/metrics/system-metrics.json
index bd7b27b52f..167a5877f9 100644
--- a/benchmark/.claude-flow/metrics/system-metrics.json
+++ b/benchmark/.claude-flow/metrics/system-metrics.json
@@ -1,14 +1,38 @@
[
{
- "timestamp": 1754445232155,
+ "timestamp": 1754447117321,
"memoryTotal": 67427545088,
- "memoryUsed": 7993483264,
- "memoryFree": 59434061824,
- "memoryUsagePercent": 11.854922574398442,
- "memoryEfficiency": 88.14507742560156,
+ "memoryUsed": 8473821184,
+ "memoryFree": 58953723904,
+ "memoryUsagePercent": 12.567298976910365,
+ "memoryEfficiency": 87.43270102308963,
"cpuCount": 16,
- "cpuLoad": 0.153125,
+ "cpuLoad": 0.2725,
"platform": "linux",
- "uptime": 13300.77
+ "uptime": 15185.94
+ },
+ {
+ "timestamp": 1754447147351,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8559190016,
+ "memoryFree": 58868355072,
+ "memoryUsagePercent": 12.693907222677856,
+ "memoryEfficiency": 87.30609277732215,
+ "cpuCount": 16,
+ "cpuLoad": 0.299375,
+ "platform": "linux",
+ "uptime": 15215.97
+ },
+ {
+ "timestamp": 1754447177381,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 8363446272,
+ "memoryFree": 59064098816,
+ "memoryUsagePercent": 12.403604878517864,
+ "memoryEfficiency": 87.59639512148213,
+ "cpuCount": 16,
+ "cpuLoad": 0.26625,
+ "platform": "linux",
+ "uptime": 15246
}
]
\ No newline at end of file
diff --git a/benchmark/.claude-flow/metrics/task-metrics.json b/benchmark/.claude-flow/metrics/task-metrics.json
index a0c3f8dcdc..d2aa9ad03e 100644
--- a/benchmark/.claude-flow/metrics/task-metrics.json
+++ b/benchmark/.claude-flow/metrics/task-metrics.json
@@ -1,10 +1,10 @@
[
{
- "id": "cmd-hooks-1754446201092",
+ "id": "cmd-hooks-1754447659008",
"type": "hooks",
"success": true,
- "duration": 32.59213199999999,
- "timestamp": 1754446201125,
+ "duration": 11.502896000000021,
+ "timestamp": 1754447659020,
"metadata": {}
}
]
\ No newline at end of file
diff --git a/benchmark/.claude/checkpoints/1754447514.json b/benchmark/.claude/checkpoints/1754447514.json
new file mode 100644
index 0000000000..ca9394b39a
--- /dev/null
+++ b/benchmark/.claude/checkpoints/1754447514.json
@@ -0,0 +1 @@
+{"branch": "checkpoint/pre-edit-20250806-023154", "file": "/workspaces/claude-code-flow/benchmark/README.md", "timestamp": "2025-08-06T02:31:54Z", "type": "pre-edit", "original_branch": "alpha-88"}
diff --git a/benchmark/.claude/checkpoints/1754447516.json b/benchmark/.claude/checkpoints/1754447516.json
new file mode 100644
index 0000000000..9fef8df984
--- /dev/null
+++ b/benchmark/.claude/checkpoints/1754447516.json
@@ -0,0 +1 @@
+{"tag": "checkpoint-20250806-023156", "file": "/workspaces/claude-code-flow/benchmark/README.md", "timestamp": "2025-08-06T02:31:56Z", "type": "post-edit", "branch": "alpha-88", "diff_summary": " .claude-flow/metrics/system-metrics.json | 408 +++++++++ benchmark/.claude-flow/metrics/performance.json | 2 +- benchmark/.claude-flow/metrics/system-metrics.json | 38 +- benchmark/.claude-flow/metrics/task-metrics.json | 6 +- benchmark/.claude/checkpoints/1754447479.json | 1 + benchmark/.claude/checkpoints/1754447481.json | 1 + benchmark/README.md | 136 +-- benchmark/__pycache__/hello_world.cpython-312.pyc | Bin 710 -> 2656 bytes .../old-reports}/AGENT2_IMPORT_FIXES_REPORT.md | 0 .../{ => archive/old-reports}/CLEANUP_REPORT.md | 0 .../old-reports}/GITHUB_ISSUE_599_COMPLETION.md | 0 .../old-reports}/GITHUB_ISSUE_599_UPDATE.md | 0 benchmark/archive/old-reports/README.md | 149 ++++ .../old-reports}/README_HELLO_WORLD.md | 0 .../old-reports}/REAL_BENCHMARKS_README.md | 0 .../REAL_BENCHMARK_COMPLETION_REPORT.md | 0 .../REAL_CLAUDE_FLOW_INTEGRATION_REPORT.md | 0 .../old-reports}/REORGANIZATION_REPORT.md | 0 .../{ => archive/old-reports}/VALIDATION_REPORT.md | 0 .../api_development_accuracy_claude.md | 0 .../old-reports}/api_development_speed_claude.md | 0 .../old-reports}/api_development_tokens_claude.md | 0 .../old-reports}/github_issue_599_comment.md | 0 .../old-reports}/ml_pipeline_claude.md | 0 .../performance_optimization_claude.md | 0 .../old-reports}/testing_automation_claude.md | 0 benchmark/ci_performance_integration.py | 754 ----------------- benchmark/compare_optimizations.py | 172 ---- benchmark/continuous_performance_monitor.py | 673 --------------- benchmark/demo_comprehensive.py | 233 ----- benchmark/demo_mle_star.py | 152 ---- benchmark/demo_real_benchmark.py | 219 ----- benchmark/example_usage.py | 249 ------ .../examples/.claude-flow/metrics/performance.json | 2 +- .../.claude-flow/metrics/task-metrics.json | 6 +- benchmark/examples/real_hive_mind_benchmark.py | 0 benchmark/examples/real_sparc_benchmark.py | 0 benchmark/examples/real_swarm_benchmark.py | 0 benchmark/hello_world.py | 76 +- benchmark/hive-mind-load-test.py | 902 -------------------- benchmark/hive-mind-stress-test.py | 935 --------------------- benchmark/mle_star_benchmark_example.py | 229 ----- benchmark/performance_dashboard.py | 769 ----------------- benchmark/quick_test_integration.py | 44 - benchmark/run-load-tests.py | 479 ----------- benchmark/run_performance_tests.py | 550 ------------ benchmark/run_real_benchmarks.py | 0 benchmark/simple-load-test.py | 322 ------- .../__pycache__/benchmark_engine.cpython-312.pyc | Bin 7620 -> 13461 bytes benchmark/swarm_performance_suite.py | 840 ------------------ benchmark/test_claude_optimizer.py | 235 ------ benchmark/test_hello_world.py | 99 ++- benchmark/test_integration.py | 274 ------ benchmark/test_mle_star_integration.py | 225 ----- benchmark/test_real_benchmark_engine.py | 317 ------- benchmark/test_real_benchmarks.py | 0 benchmark/test_real_claude_flow.py | 218 ----- benchmark/test_real_metrics.py | 128 --- benchmark/test_real_simple.py | 104 --- benchmark/test_simple_run.py | 35 - .../conftest.cpython-312-pytest-8.4.0.pyc | Bin 22406 -> 22448 bytes ...e_flow_integration.cpython-312-pytest-8.4.0.pyc | Bin 41481 -> 41556 bytes .../tests/integration/quick_test_integration.py | 2 +- .../tests/integration/test_claude_optimizer.py | 2 +- benchmark/tests/integration/test_integration.py | 2 +- .../tests/integration/test_mle_star_integration.py | 4 +- .../integration/test_real_benchmark_engine.py | 4 +- .../tests/integration/test_real_claude_flow.py | 2 +- benchmark/tests/integration/test_real_metrics.py | 2 +- benchmark/tests/integration/test_simple_run.py | 2 +- claude-flow-wiki | 0 71 files changed, 768 insertions(+), 9234 deletions(-) "}
diff --git a/benchmark/AGENT2_IMPORT_FIXES_REPORT.md b/benchmark/AGENT2_IMPORT_FIXES_REPORT.md
deleted file mode 100644
index 0265ddc3bc..0000000000
--- a/benchmark/AGENT2_IMPORT_FIXES_REPORT.md
+++ /dev/null
@@ -1,47 +0,0 @@
-## Agent 2: Import Fixer - COMPLETION REPORT
-
-### Summary
-βœ… **MISSION ACCOMPLISHED** - All Python import issues have been successfully fixed after file reorganization.
-
-### Fixed Import Issues:
-
-#### Root Directory Files:
-- test_mle_star_integration.py: Fixed os.path.join() β†’ Path(__file__).parent/"src"
-- demo_mle_star.py: Fixed os.path.join() β†’ Path(__file__).parent/"src"
-- mle_star_benchmark_example.py: Fixed os.path.join() β†’ Path(__file__).parent/"src"
-- test_simple_run.py: Added missing sys.path.insert
-- demo_comprehensive.py: Added missing sys.path.insert
-- examples/parallel_benchmark_demo.py: Added missing sys.path.insert
-
-#### Examples Directory:
-- All files now use: str(Path(__file__).parent.parent / "src")
-- real_benchmark_examples.py: Removed incorrect SystemMonitor import
-- All examples/* files tested and working correctly
-
-#### Tests Directory:
-- tests/integration/*: Fixed all paths to use parent.parent.parent / "src"
-- tests/conftest.py: Fixed path to parent.parent / "src"
-- Removed all incorrect SystemMonitor imports
-- Added missing Path imports where needed
-
-#### Import Pattern Fixes:
-- OLD: sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
-- NEW: sys.path.insert(0, str(Path(__file__).parent / "src"))
-
-- OLD: sys.path.insert(0, str(Path(__file__).parent / "src")) [in tests/]
-- NEW: sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
-
-### Verification Results:
-βœ… swarm_benchmark core imports working
-βœ… swarm_benchmark.mle_star imports working
-βœ… swarm_benchmark.claude_optimizer imports working
-βœ… examples/ directory scripts working
-βœ… tests/integration/ scripts working
-βœ… tests/conftest.py working
-
-### Files Successfully Fixed: 15+
-### Import Errors Resolved: 100%
-### Status: READY FOR PRODUCTION
-
-Agent 2 has successfully completed the import reorganization task.
-All Python imports now work correctly with the new src/swarm_benchmark/ structure.
diff --git a/benchmark/CLEANUP_REPORT.md b/benchmark/CLEANUP_REPORT.md
deleted file mode 100644
index 7bc6cbf62e..0000000000
--- a/benchmark/CLEANUP_REPORT.md
+++ /dev/null
@@ -1,165 +0,0 @@
-# Python Code Cleanup Report
-## Agent 4: Cleanup Specialist
-
-**Date:** August 6, 2025
-**Task:** Clean up redundant files and finalize Python code structure
-**Status:** βœ… COMPLETED
-
-## Summary of Changes
-
-### 🧹 Files Cleaned and Organized
-
-#### 1. Cache and Temporary Files Removed
-- βœ… Removed all `__pycache__` directories (12 locations)
-- βœ… Removed all `.pyc` files (48+ files)
-- βœ… No temporary files found (.tmp, .temp, .DS_Store, etc.)
-
-#### 2. Test Files Organization
-- βœ… All test files properly organized in `tests/` directory structure
-- βœ… No duplicate test files found in root directory
-- βœ… Unit tests: 9 files in `tests/unit/`
-- βœ… Integration tests: 3 files in `tests/integration/`
-- βœ… Performance tests: 1 file in `tests/performance/`
-
-#### 3. Demo and Example Files
-- βœ… All demo files moved to `examples/` directory:
- - `demo_comprehensive.py`
- - `demo_mle_star.py`
- - `demo_real_benchmark.py`
- - `parallel_benchmark_demo.py`
- - `real_metrics_demo.py`
-- βœ… Load test examples moved to `examples/`:
- - `hive-mind-load-test.py`
- - `hive-mind-stress-test.py`
- - `simple-load-test.py`
- - `swarm_performance_suite.py`
-
-#### 4. Script Files Organization
-- βœ… All utility scripts properly organized in `scripts/`:
- - `continuous_performance_monitor.py`
- - `run-load-tests.py`
- - `run_performance_tests.py`
- - `hive-mind-load-test.py`
- - `hive-mind-stress-test.py`
- - `simple-load-test.py`
- - `swarm_performance_suite.py`
-
-#### 5. Tool Files Organization
-- βœ… Tools properly organized in `tools/`:
- - `ci_performance_integration.py`
- - `compare_optimizations.py`
- - `performance_dashboard.py`
- - `__init__.py` (created for proper package structure)
-
-#### 6. Archive Organization
-- βœ… Old reports moved to `archive/`:
- - `demo_reports/` (22 JSON files)
- - `test_output/` directory
- - `optimization_results/` directory
- - Historical result files: `real_benchmark_results.json`, `simple_load_test_results.json`
-
-### πŸ“ Final Directory Structure
-
-```
-benchmark/
-β”œβ”€β”€ src/swarm_benchmark/ # βœ… Main package (properly organized)
-β”‚ β”œβ”€β”€ __init__.py
-β”‚ β”œβ”€β”€ __main__.py
-β”‚ β”œβ”€β”€ advanced_metrics/ # Advanced metrics and analysis
-β”‚ β”œβ”€β”€ automation/ # Automation pipeline components
-β”‚ β”œβ”€β”€ claude_optimizer/ # Claude-specific optimizations
-β”‚ β”œβ”€β”€ cli/ # Command-line interface
-β”‚ β”œβ”€β”€ collective/ # Collective intelligence
-β”‚ β”œβ”€β”€ config/ # Configuration management
-β”‚ β”œβ”€β”€ core/ # Core benchmark engines
-β”‚ β”œβ”€β”€ metrics/ # Performance metrics
-β”‚ β”œβ”€β”€ mle_star/ # MLE-STAR implementation
-β”‚ β”œβ”€β”€ modes/ # Coordination modes
-β”‚ β”œβ”€β”€ output/ # Output formatters
-β”‚ └── strategies/ # Benchmark strategies
-β”œβ”€β”€ scripts/ # βœ… Executable scripts (8 files)
-β”œβ”€β”€ examples/ # βœ… Examples and demos (9 files)
-β”œβ”€β”€ tools/ # βœ… Utility tools (4 files)
-β”œβ”€β”€ tests/ # βœ… Test suite (organized structure)
-β”‚ β”œβ”€β”€ unit/ # Unit tests (9 files)
-β”‚ β”œβ”€β”€ integration/ # Integration tests (3 files)
-β”‚ β”œβ”€β”€ performance/ # Performance tests (1 file)
-β”‚ └── fixtures/ # Test fixtures and data
-β”œβ”€β”€ archive/ # βœ… Old reports and deprecated files
-β”‚ β”œβ”€β”€ demo_reports/ # Historical demo results
-β”‚ β”œβ”€β”€ test_output/ # Old test outputs
-β”‚ β”œβ”€β”€ optimization_results/ # Historical optimization data
-β”‚ β”œβ”€β”€ reports/ # Agent completion reports
-β”‚ └── agent-reports/ # Detailed agent summaries
-β”œβ”€β”€ docs/ # βœ… Documentation (13 MD files)
-β”œβ”€β”€ analysis/ # βœ… Performance analysis reports
-β”œβ”€β”€ reports/ # βœ… Current benchmark reports
-β”œβ”€β”€ plans/ # βœ… Architecture and planning docs
-β”œβ”€β”€ hive-mind-benchmarks/ # βœ… Specialized hive-mind tests
-β”œβ”€β”€ setup.py # βœ… Package setup (properly configured)
-β”œβ”€β”€ requirements.txt # βœ… Dependencies
-β”œβ”€β”€ requirements-dev.txt # βœ… Development dependencies
-└── README.md # βœ… Main documentation
-```
-
-### πŸ“Š Cleanup Statistics
-
-| Category | Before | After | Removed/Organized |
-|----------|---------|--------|-------------------|
-| Root Python files | 22 | 1 | 21 files organized |
-| `__pycache__` dirs | 12+ | 0 | 12+ directories removed |
-| `.pyc` files | 48+ | 0 | 48+ files removed |
-| Test files in root | 8 | 0 | 8 files moved to tests/ |
-| Demo files in root | 3 | 0 | 3 files moved to examples/ |
-| Utility scripts | 7 | 0 | 7 files moved to scripts/tools/ |
-| Archived items | 0 | 26+ | Historical data preserved |
-
-## βœ… Quality Assurance
-
-### Package Structure Validation
-- βœ… `setup.py` correctly configured with `src/` layout
-- βœ… All modules have proper `__init__.py` files
-- βœ… Entry points configured for CLI usage
-- βœ… Dependencies properly listed in requirements files
-
-### File Organization Standards
-- βœ… No duplicate files
-- βœ… Consistent naming conventions
-- βœ… Proper directory structure
-- βœ… Clean root directory (only setup.py and config files)
-
-### Archive Preservation
-- βœ… Historical data preserved in `archive/`
-- βœ… No data loss during reorganization
-- βœ… Reports and results accessible for reference
-
-## 🎯 Impact and Benefits
-
-1. **Cleaner Structure**: Root directory contains only essential files
-2. **Better Organization**: Files grouped by purpose and functionality
-3. **Easier Navigation**: Clear separation between source, tests, examples, and tools
-4. **Improved Maintainability**: Consistent structure follows Python best practices
-5. **Development Efficiency**: Developers can quickly locate relevant files
-6. **CI/CD Ready**: Proper test structure supports automated testing
-7. **Package Distribution**: Clean structure ready for PyPI distribution
-
-## πŸ”„ Next Steps
-
-The Python code reorganization is complete. The structure now follows Python packaging best practices and is ready for:
-
-1. **Development**: Clear separation of concerns
-2. **Testing**: Comprehensive test organization
-3. **Distribution**: Proper package structure for PyPI
-4. **Documentation**: Well-organized docs and examples
-5. **Maintenance**: Easy navigation and updates
-
-## πŸ“ Notes
-
-- All original functionality preserved
-- No breaking changes introduced
-- Historical data safely archived
-- Structure follows PEP standards
-- Ready for GitHub issue #599 update
-
----
-**Agent 4 Cleanup Specialist - Task Complete** βœ…
\ No newline at end of file
diff --git a/benchmark/GITHUB_ISSUE_599_COMPLETION.md b/benchmark/GITHUB_ISSUE_599_COMPLETION.md
deleted file mode 100644
index c83337ee73..0000000000
--- a/benchmark/GITHUB_ISSUE_599_COMPLETION.md
+++ /dev/null
@@ -1,94 +0,0 @@
-# GitHub Issue #599 - Python Package Reorganization Complete
-
-## Status: βœ… COMPLETED
-
-### Summary
-Agent 1 (Structure Analyst) has successfully reorganized all Python files in the benchmark directory from a flat structure to a traditional package layout.
-
-### Key Achievements
-
-#### 1. File Organization (31 files reorganized)
-- **7 scripts** moved to `benchmark/scripts/`
-- **5 demos/examples** moved to `benchmark/examples/`
-- **3 tools** moved to `benchmark/tools/`
-- **12 test files** moved to `benchmark/tests/integration/`
-- **4 package modules** created with proper `__init__.py` files
-
-#### 2. Directory Structure Created
-```
-benchmark/
-β”œβ”€β”€ src/swarm_benchmark/ # Main package (preserved)
-β”œβ”€β”€ scripts/ # Executable scripts βœ… NEW
-β”‚ β”œβ”€β”€ run_performance_tests.py
-β”‚ β”œβ”€β”€ hive-mind-load-test.py
-β”‚ └── 5 other scripts
-β”œβ”€β”€ examples/ # Demo files (enhanced) βœ… ENHANCED
-β”‚ β”œβ”€β”€ demo_comprehensive.py
-β”‚ β”œβ”€β”€ example_usage.py
-β”‚ └── 7 other examples
-β”œβ”€β”€ tools/ # Utility tools βœ… NEW
-β”‚ β”œβ”€β”€ performance_dashboard.py
-β”‚ β”œβ”€β”€ ci_performance_integration.py
-β”‚ └── compare_optimizations.py
-β”œβ”€β”€ tests/ # All tests (organized) βœ… ORGANIZED
-└── setup.py # Package setup (root only)
-```
-
-#### 3. Backward Compatibility Maintained
-- βœ… All imports working correctly
-- βœ… Package structure follows PEP guidelines
-- βœ… Entry points preserved in setup.py
-- βœ… No breaking changes
-
-#### 4. Quality Validation
-- βœ… Main package imports successfully
-- βœ… New module directories import correctly
-- βœ… Root directory clean (only setup.py remains)
-- βœ… Professional Python package structure
-
-### Files Successfully Reorganized
-
-**Scripts (7 files):**
-- `run_performance_tests.py`
-- `run-load-tests.py`
-- `continuous_performance_monitor.py`
-- `hive-mind-load-test.py`
-- `hive-mind-stress-test.py`
-- `simple-load-test.py`
-- `swarm_performance_suite.py`
-
-**Examples (5 files):**
-- `demo_comprehensive.py`
-- `demo_real_benchmark.py`
-- `demo_mle_star.py`
-- `example_usage.py`
-- `mle_star_benchmark_example.py`
-
-**Tools (3 files):**
-- `compare_optimizations.py`
-- `performance_dashboard.py`
-- `ci_performance_integration.py`
-
-**Tests (12 files):**
-- All `test_*.py` files moved to proper test directory structure
-
-### Benefits Achieved
-1. **Clean Organization** - Clear separation of executable scripts, examples, tools, and tests
-2. **Professional Structure** - Follows Python packaging standards and best practices
-3. **Better Maintainability** - Logical grouping makes development easier
-4. **Improved Navigation** - Intuitive directory layout for developers
-5. **Enhanced Tooling** - Better IDE support and development experience
-
-### Next Steps for Other Agents
-The reorganized structure is now ready for:
-- Enhanced documentation (Agent 2)
-- Performance optimization work (Agent 3)
-- Integration testing (Agent 4)
-- Any additional development tasks
-
----
-
-**Completed by:** Agent 1 - Structure Analyst
-**Date:** 2025-08-06
-**Working Directory:** `/workspaces/claude-code-flow/benchmark/`
-**Report:** Full details in `REORGANIZATION_REPORT.md`
\ No newline at end of file
diff --git a/benchmark/GITHUB_ISSUE_599_UPDATE.md b/benchmark/GITHUB_ISSUE_599_UPDATE.md
deleted file mode 100644
index 74609d91a1..0000000000
--- a/benchmark/GITHUB_ISSUE_599_UPDATE.md
+++ /dev/null
@@ -1,166 +0,0 @@
-# GitHub Issue #599 - Python Code Reorganization: COMPLETED βœ…
-
-## Issue Status: **RESOLVED**
-**Completion Date:** August 6, 2025
-**Agent:** Agent 4 - Cleanup Specialist
-**Task:** Clean up redundant files and finalize Python code structure
-
-## 🎯 Original Objectives - ALL COMPLETED
-
-βœ… **Clean up redundant files and finalize the structure**
-βœ… **Remove duplicate test files (test_*.py in root if moved to tests/)**
-βœ… **Clean up any __pycache__ directories**
-βœ… **Remove duplicate demo files**
-βœ… **Update setup.py with correct package structure**
-βœ… **Create a final structure report**
-
-## πŸ“Š Cleanup Summary
-
-### Files Processed and Organized
-| Category | Action Taken | Count | Result |
-|----------|--------------|-------|---------|
-| `__pycache__` directories | Removed | 12+ | βœ… All cleaned |
-| `.pyc` files | Removed | 48+ | βœ… All cleaned |
-| Root test files | Organized | 0 | βœ… Already in tests/ |
-| Root demo files | Organized | 0 | βœ… Already in examples/ |
-| Utility scripts | Organized | 8 | βœ… Moved to scripts/ |
-| Tool files | Organized | 4 | βœ… Organized in tools/ |
-| Archive items | Preserved | 26+ | βœ… Moved to archive/ |
-| Total Python files | Maintained | 121 | βœ… All preserved |
-
-### πŸ—οΈ Final Structure Achieved
-
-```
-benchmark/
-β”œβ”€β”€ src/swarm_benchmark/ # βœ… Main package (proper src layout)
-β”œβ”€β”€ scripts/ # βœ… Executable scripts (8 files)
-β”œβ”€β”€ examples/ # βœ… Examples and demos (10 files)
-β”œβ”€β”€ tools/ # βœ… Utility tools (4 files)
-β”œβ”€β”€ tests/ # βœ… Comprehensive test suite
-β”‚ β”œβ”€β”€ unit/ # 9 unit tests
-β”‚ β”œβ”€β”€ integration/ # 3 integration tests
-β”‚ β”œβ”€β”€ performance/ # 1 performance test
-β”‚ └── fixtures/ # Test data and fixtures
-β”œβ”€β”€ archive/ # βœ… Historical data preserved
-β”œβ”€β”€ docs/ # βœ… Documentation (15 files)
-β”œβ”€β”€ reports/ # βœ… Current benchmark reports
-β”œβ”€β”€ analysis/ # βœ… Performance analysis
-β”œβ”€β”€ plans/ # βœ… Architecture documentation
-β”œβ”€β”€ hive-mind-benchmarks/ # βœ… Specialized benchmarks
-β”œβ”€β”€ setup.py # βœ… Properly configured
-β”œβ”€β”€ requirements.txt # βœ… Dependencies
-β”œβ”€β”€ requirements-dev.txt # βœ… Dev dependencies
-└── README.md # βœ… Main documentation
-```
-
-## ✨ Quality Achievements
-
-### Code Organization Excellence
-- βœ… **Zero duplicate files** - All redundancy eliminated
-- βœ… **Clean root directory** - Only essential config files remain
-- βœ… **Proper Python package structure** - Follows PEP standards
-- βœ… **No cache pollution** - All `__pycache__` and `.pyc` files removed
-- βœ… **Logical file grouping** - Scripts, tools, examples properly separated
-
-### Package Quality Standards
-- βœ… **setup.py validation** - Correct src layout, proper dependencies
-- βœ… **Entry points configured** - CLI tools properly registered
-- βœ… **Test structure compliance** - pytest-compatible organization
-- βœ… **Documentation completeness** - 15 comprehensive docs
-- βœ… **Archive preservation** - Historical data safely stored
-
-## πŸ”§ Technical Implementation Details
-
-### Cleanup Operations Performed
-1. **Cache Cleanup**: Removed all Python cache files and directories
-2. **File Organization**: Moved utilities to appropriate directories
-3. **Archive Management**: Preserved historical data in structured archive
-4. **Structure Validation**: Ensured proper Python package compliance
-5. **Quality Assurance**: Verified no functionality loss during reorganization
-
-### Files Relocated
-```bash
-# Scripts organized (8 files)
-continuous_performance_monitor.py β†’ scripts/
-run-load-tests.py β†’ scripts/
-run_performance_tests.py β†’ scripts/
-hive-mind-load-test.py β†’ scripts/
-hive-mind-stress-test.py β†’ scripts/
-simple-load-test.py β†’ scripts/
-swarm_performance_suite.py β†’ scripts/
-
-# Tools organized (4 files)
-ci_performance_integration.py β†’ tools/
-compare_optimizations.py β†’ tools/
-performance_dashboard.py β†’ tools/
-
-# Archives preserved (26+ items)
-demo_reports/ β†’ archive/
-test_output/ β†’ archive/
-optimization_results/ β†’ archive/
-*.json results β†’ archive/
-```
-
-## πŸ“ˆ Impact and Benefits
-
-### Development Benefits
-- **πŸš€ Faster Navigation**: Developers can quickly locate relevant files
-- **🧹 Cleaner Codebase**: No clutter or duplicate files
-- **πŸ“¦ Distribution Ready**: Proper structure for PyPI packaging
-- **πŸ§ͺ Testing Efficiency**: Well-organized test structure
-- **πŸ”§ Tool Access**: Utilities properly categorized and accessible
-
-### Maintenance Improvements
-- **πŸ“ Documentation**: Comprehensive structure documentation
-- **πŸ” Searchability**: Logical file organization improves discoverability
-- **⚑ CI/CD Ready**: Clean structure supports automated workflows
-- **πŸ—οΈ Scalability**: Structure supports future growth and additions
-- **πŸ›‘οΈ Quality Assurance**: No technical debt from file duplication
-
-## πŸŽ‰ Success Metrics
-
-| Metric | Before | After | Improvement |
-|--------|---------|--------|-------------|
-| Root Python files | 22 | 1 (setup.py) | 95% reduction |
-| Cache directories | 12+ | 0 | 100% cleaned |
-| Duplicate files | Multiple | 0 | 100% eliminated |
-| Organization score | 3/10 | 10/10 | Perfect structure |
-| Maintainability | Poor | Excellent | Major improvement |
-
-## πŸ“‹ Deliverables Completed
-
-βœ… **CLEANUP_REPORT.md** - Comprehensive cleanup documentation
-βœ… **Structure validation** - All directories properly organized
-βœ… **Archive preservation** - Historical data safely stored
-βœ… **Setup.py verification** - Package structure validated
-βœ… **Quality assurance** - Zero functionality loss confirmed
-βœ… **Documentation update** - Complete structure documentation
-
-## πŸ† Final Status
-
-**ISSUE #599: FULLY RESOLVED** βœ…
-
-The Python code reorganization task has been completed successfully with:
-- **Zero data loss** - All files preserved appropriately
-- **Perfect organization** - Files logically grouped by purpose
-- **Clean structure** - Follows Python packaging best practices
-- **Quality assurance** - Comprehensive validation completed
-- **Future-ready** - Structure supports continued development
-
-## πŸ”„ Recommended Follow-up Actions
-
-1. **βœ… COMPLETED**: Code structure cleanup and organization
-2. **βœ… COMPLETED**: Archive historical data preservation
-3. **βœ… COMPLETED**: Setup.py and package configuration
-4. **Ready for**: Development team to begin using clean structure
-5. **Ready for**: CI/CD pipeline integration with organized tests
-6. **Ready for**: Package distribution preparation
-
----
-
-**Agent 4 - Cleanup Specialist**
-**Task Status**: βœ… COMPLETED
-**Issue Status**: βœ… RESOLVED
-**Next Phase**: Ready for development team handoff
-
-*All Python code reorganization objectives have been achieved with zero functionality loss and maximum maintainability improvement.*
\ No newline at end of file
diff --git a/benchmark/README_HELLO_WORLD.md b/benchmark/README_HELLO_WORLD.md
deleted file mode 100644
index 9f58b2a5b7..0000000000
--- a/benchmark/README_HELLO_WORLD.md
+++ /dev/null
@@ -1,105 +0,0 @@
-# Hello World Function Implementation
-
-A simple yet comprehensive hello world function implementation with parameter support, multiple styles, and thorough testing.
-
-## Features
-
-- βœ… Basic hello world functionality
-- βœ… Parameter support with default values
-- βœ… Input validation and sanitization
-- βœ… Multiple greeting styles (formal, casual, enthusiastic, etc.)
-- βœ… Comprehensive test coverage
-- βœ… Both JavaScript and Python implementations
-
-## JavaScript Usage
-
-```javascript
-const { helloWorld, helloWorldAdvanced } = require('./hello_world');
-
-// Basic usage
-console.log(helloWorld()); // "Hello, World!"
-console.log(helloWorld('Alice')); // "Hello, Alice!"
-
-// Advanced usage with styles
-console.log(helloWorldAdvanced('Bob', 'formal')); // "Greetings, Bob."
-console.log(helloWorldAdvanced('Eve', 'casual')); // "Hey Eve!"
-```
-
-### Running JavaScript Tests
-
-```bash
-node hello_world.test.js
-```
-
-## Python Usage
-
-```python
-from hello_world import hello_world, hello_world_advanced
-
-# Basic usage
-print(hello_world()) # "Hello, World!"
-print(hello_world('Alice')) # "Hello, Alice!"
-
-# Advanced usage with styles
-print(hello_world_advanced('Bob', 'formal')) # "Greetings, Bob."
-print(hello_world_advanced('Eve', 'casual')) # "Hey Eve!"
-```
-
-### Running Python Tests
-
-```bash
-python test_hello_world.py
-```
-
-## Available Greeting Styles
-
-- `default` - Standard greeting: "Hello, Name!"
-- `formal` - Formal greeting: "Greetings, Name."
-- `casual` - Casual greeting: "Hey Name!"
-- `enthusiastic` - Enthusiastic greeting: "Hello, Name! πŸŽ‰"
-- `morning` - Morning greeting: "Good morning, Name!"
-- `evening` - Evening greeting: "Good evening, Name!"
-
-## Implementation Details
-
-### Input Validation
-- Automatically converts non-string inputs to strings
-- Trims whitespace from input names
-- Falls back to 'World' for empty or invalid inputs
-
-### Error Handling
-- Gracefully handles null, undefined, and empty values
-- Unknown styles fall back to default greeting
-- Type coercion for non-string parameters
-
-## Test Coverage
-
-Both implementations include comprehensive test suites covering:
-- Default behavior
-- Custom name parameters
-- Edge cases (empty strings, whitespace, null values)
-- Type conversion (numbers, booleans)
-- All greeting styles
-- Fallback behaviors
-
-## Files Structure
-
-```
-benchmark/
-β”œβ”€β”€ hello_world.js # JavaScript implementation
-β”œβ”€β”€ hello_world.test.js # JavaScript tests
-β”œβ”€β”€ hello_world.py # Python implementation
-β”œβ”€β”€ test_hello_world.py # Python tests
-└── README_HELLO_WORLD.md # This documentation
-```
-
-## Development Notes
-
-This implementation was created by a coordinated swarm of AI agents:
-- **TechLead**: Overall coordination and planning
-- **SystemArchitect**: Function design and API structure
-- **MainDeveloper**: Core implementation
-- **QAEngineer**: Test suite development
-- **TechWriter**: Documentation creation
-
-The swarm worked in parallel to deliver a production-ready hello world function with enterprise-level features.
\ No newline at end of file
diff --git a/benchmark/REAL_BENCHMARKS_README.md b/benchmark/REAL_BENCHMARKS_README.md
deleted file mode 100644
index 240fc78b76..0000000000
--- a/benchmark/REAL_BENCHMARKS_README.md
+++ /dev/null
@@ -1,404 +0,0 @@
-# Real Claude Flow Benchmarks
-
-**CRITICAL**: These are REAL benchmarks that execute actual `./claude-flow` commands. NO simulations.
-
-## 🎯 Overview
-
-This benchmark suite implements real-world performance testing for Claude Flow by:
-
-1. **Executing Real Commands**: Uses actual `./claude-flow` subprocess calls
-2. **Measuring Actual Performance**: Tracks real execution time, token usage, memory consumption
-3. **Parsing Real Responses**: Extracts metrics from actual JSON streaming responses
-4. **Tracking Real Resources**: Monitors CPU, memory, and I/O during execution
-
-## πŸ“ Structure
-
-```
-benchmark/
-β”œβ”€β”€ src/swarm_benchmark/scenarios/
-β”‚ β”œβ”€β”€ __init__.py
-β”‚ └── real_benchmarks.py # Core real benchmark implementations
-β”œβ”€β”€ examples/
-β”‚ β”œβ”€β”€ real_swarm_benchmark.py # Real swarm execution examples
-β”‚ β”œβ”€β”€ real_hive_mind_benchmark.py # Real hive-mind execution examples
-β”‚ └── real_sparc_benchmark.py # Real SPARC mode execution examples
-β”œβ”€β”€ test_real_benchmarks.py # Validation tests for real benchmarks
-β”œβ”€β”€ run_real_benchmarks.py # Comprehensive benchmark runner
-└── REAL_BENCHMARKS_README.md # This file
-```
-
-## πŸš€ Quick Start
-
-### 1. Test Installation
-
-```bash
-# Validate Claude Flow is available and benchmarks work
-python test_real_benchmarks.py --quick
-```
-
-### 2. Run Individual Benchmarks
-
-```bash
-# Real swarm benchmark
-python examples/real_swarm_benchmark.py "Create a REST API for user management"
-
-# Real hive-mind benchmark
-python examples/real_hive_mind_benchmark.py "Design distributed system architecture"
-
-# Real SPARC mode benchmark
-python examples/real_sparc_benchmark.py coder "Implement OAuth2 authentication"
-```
-
-### 3. Run Comprehensive Suite
-
-```bash
-# Run all benchmark types
-python run_real_benchmarks.py --mode comprehensive
-
-# Run specific benchmark type
-python run_real_benchmarks.py --mode swarm
-python run_real_benchmarks.py --mode hive-mind
-python run_real_benchmarks.py --mode sparc
-```
-
-## πŸ”¬ Core Components
-
-### RealBenchmarkResult
-
-Captures comprehensive metrics from real executions:
-
-```python
-@dataclass
-class RealBenchmarkResult:
- benchmark_name: str # Benchmark identifier
- success: bool # Execution success
- execution_time: float # Real execution time (seconds)
- tokens_used: int # Actual tokens consumed by Claude
- agents_spawned: int # Real agent count from output
- memory_usage_mb: float # Actual memory consumption
- cpu_usage_percent: float # Real CPU usage during execution
- output_size_bytes: int # Size of actual output
- error_count: int # Number of errors in stderr
- warning_count: int # Number of warnings
- command_executed: List[str] # Actual command executed
- stdout_excerpt: str # First 500 chars of stdout
- stderr_excerpt: str # First 500 chars of stderr
- metrics_raw: Dict[str, Any] # Raw metrics from JSON parsing
- timestamp: str # ISO timestamp
-```
-
-### ClaudeFlowRealExecutor
-
-Executes real Claude Flow commands with comprehensive monitoring:
-
-```python
-executor = ClaudeFlowRealExecutor()
-
-# Execute real swarm
-result = executor.execute_swarm(
- objective="Create a REST API",
- strategy="development",
- mode="hierarchical",
- max_agents=5,
- non_interactive=True
-)
-
-# Execute real hive-mind
-result = executor.execute_hive_mind(
- task="Solve optimization problem",
- collective_mode="consensus",
- agent_count=8,
- timeout=15
-)
-
-# Execute real SPARC mode
-result = executor.execute_sparc_mode(
- mode="coder",
- task="Implement authentication system",
- timeout=10
-)
-```
-
-## πŸ“Š Benchmark Scenarios
-
-### Swarm Benchmarks
-
-- **Development Swarm**: `development` strategy with `centralized` mode
-- **Research Swarm**: `research` strategy with `distributed` mode
-- **Optimization Swarm**: `optimization` strategy with `hybrid` mode
-- **Analysis Swarm**: `analysis` strategy with `mesh` mode
-
-### Hive-Mind Benchmarks
-
-- **Consensus Mode**: Democratic decision-making with 6-8 agents
-- **Collective Intelligence**: Advanced problem-solving with 10-12 agents
-- **Memory Shared**: Persistent knowledge sharing with 6 agents
-
-### SPARC Mode Benchmarks
-
-- **Coder**: Implementation tasks
-- **TDD**: Test-driven development
-- **Architect**: System design
-- **Optimizer**: Performance optimization
-- **Researcher**: Information gathering
-- **Reviewer**: Code review
-- **Analyzer**: System analysis
-
-## 🎯 Usage Examples
-
-### Simple Swarm Benchmark
-
-```python
-from swarm_benchmark.scenarios.real_benchmarks import RealSwarmBenchmark
-
-benchmark = RealSwarmBenchmark()
-result = benchmark.benchmark_swarm_task("Create a simple API endpoint")
-
-print(f"Success: {result.success}")
-print(f"Time: {result.execution_time:.2f}s")
-print(f"Tokens: {result.tokens_used}")
-print(f"Agents: {result.agents_spawned}")
-```
-
-### Multi-Scenario Benchmark
-
-```python
-from swarm_benchmark.scenarios.real_benchmarks import RealBenchmarkSuite
-
-suite = RealBenchmarkSuite(output_dir="./results")
-results = suite.run_comprehensive_benchmark()
-
-# Results contain actual metrics from real executions
-for category, benchmarks in results.items():
- for benchmark in benchmarks:
- print(f"{benchmark.benchmark_name}: {benchmark.execution_time:.2f}s")
-```
-
-### Custom Real Executor
-
-```python
-from swarm_benchmark.scenarios.real_benchmarks import ClaudeFlowRealExecutor
-
-executor = ClaudeFlowRealExecutor(
- claude_flow_path="/path/to/claude-flow",
- working_dir="/workspace"
-)
-
-# Real execution with resource monitoring
-result = executor.execute_swarm(
- objective="Build microservices architecture",
- strategy="development",
- mode="hierarchical",
- max_agents=6,
- timeout=20
-)
-
-# Actual metrics from real execution
-print(f"Real execution time: {result.execution_time:.2f}s")
-print(f"Actual tokens used: {result.tokens_used}")
-print(f"Real memory usage: {result.memory_usage_mb:.2f} MB")
-```
-
-## πŸ“ˆ Performance Monitoring
-
-### Real-Time Resource Monitoring
-
-The `ResourceMonitor` class tracks actual system resources during benchmark execution:
-
-```python
-class ResourceMonitor:
- def start_monitoring(self, interval: float = 1.0)
- def stop_monitoring(self) -> List[SystemMetrics]
-
- # Tracks:
- # - CPU usage percentage
- # - Memory consumption (MB)
- # - Disk I/O (read/write MB)
- # - Network bytes sent/received
-```
-
-### Metrics Extraction
-
-Real output parsing extracts actual metrics:
-
-```python
-# Extract token usage from real Claude Flow output
-tokens = executor._extract_token_usage(stdout)
-
-# Extract actual agent count from output
-agents = executor._extract_agent_count(stdout)
-
-# Parse JSON metrics from streaming responses
-metrics = executor._parse_json_metrics(stdout)
-```
-
-## πŸ”§ Configuration
-
-### Environment Setup
-
-Required environment for real benchmarks:
-
-```bash
-# Ensure claude-flow is available
-export PATH="/path/to/claude-flow/bin:$PATH"
-
-# Set working directory
-export CLAUDE_WORKING_DIR="/workspace"
-
-# Optional: Custom claude-flow path
-export CLAUDE_FLOW_PATH="/custom/path/claude-flow"
-```
-
-### Benchmark Configuration
-
-```python
-# Swarm configuration
-config = SwarmConfig(
- objective="Task description",
- strategy=ExecutionStrategy.DEVELOPMENT,
- mode=CoordinationMode.HIERARCHICAL,
- max_agents=5,
- timeout=15, # minutes
- output_dir="./results"
-)
-
-# SPARC configuration
-config = SparcConfig(
- prompt="Task description",
- mode=SparcMode.CODER,
- timeout=10, # minutes
- parallel=False,
- monitor=True
-)
-```
-
-## πŸ“Š Output Format
-
-Real benchmark results are saved as JSON:
-
-```json
-{
- "benchmark_name": "swarm_development_hierarchical",
- "success": true,
- "execution_time": 45.67,
- "tokens_used": 2456,
- "agents_spawned": 5,
- "memory_usage_mb": 128.5,
- "cpu_usage_percent": 23.8,
- "output_size_bytes": 15420,
- "error_count": 0,
- "warning_count": 1,
- "command_executed": ["./claude-flow", "swarm", "..."],
- "stdout_excerpt": "Starting swarm execution...",
- "stderr_excerpt": "",
- "metrics_raw": {"performance": 0.95},
- "timestamp": "2025-08-06T10:30:45.123456"
-}
-```
-
-## πŸ§ͺ Testing
-
-### Validation Tests
-
-```bash
-# Quick validation (no real execution)
-python test_real_benchmarks.py --quick
-
-# Full validation with real executions
-python test_real_benchmarks.py
-
-# Structure validation only
-python test_real_benchmarks.py --validate-only
-```
-
-### Example Execution Tests
-
-```bash
-# Test individual examples
-python examples/real_swarm_benchmark.py --multiple
-python examples/real_hive_mind_benchmark.py --suite
-python examples/real_sparc_benchmark.py --workflow
-```
-
-## 🚨 Important Notes
-
-### Real Execution Requirements
-
-1. **Claude Flow Installation**: Must have working `./claude-flow` executable
-2. **Network Access**: Real benchmarks may require internet connectivity
-3. **API Limits**: Respect Claude API rate limits and token usage
-4. **Execution Time**: Real benchmarks take actual time to complete
-5. **Resource Usage**: Real benchmarks consume actual system resources
-
-### Safety Considerations
-
-1. **Non-Interactive Mode**: Always use `--non-interactive` flag
-2. **Timeout Limits**: Set reasonable timeouts to prevent hanging
-3. **Resource Monitoring**: Monitor CPU/memory usage during execution
-4. **Error Handling**: Benchmarks gracefully handle execution failures
-5. **Result Validation**: Verify benchmark results are sane
-
-### Performance Guidelines
-
-1. **Concurrent Execution**: Avoid running multiple benchmarks simultaneously
-2. **Resource Allocation**: Ensure sufficient system resources
-3. **Timeout Configuration**: Set appropriate timeouts for task complexity
-4. **Output Management**: Clean up large output files regularly
-5. **Monitoring Overhead**: Resource monitoring adds minimal overhead
-
-## πŸ“š Advanced Usage
-
-### Custom Benchmark Creation
-
-```python
-class CustomRealBenchmark:
- def __init__(self):
- self.executor = ClaudeFlowRealExecutor()
-
- def benchmark_custom_workflow(self, task: str) -> RealBenchmarkResult:
- # Execute real custom command
- command = [
- self.executor.executor.claude_flow_path,
- "custom-command",
- task,
- "--mode", "custom",
- "--non-interactive"
- ]
-
- # Monitor and execute
- self.executor.resource_monitor.start_monitoring()
-
- result = subprocess.run(
- command,
- capture_output=True,
- text=True,
- timeout=600
- )
-
- metrics = self.executor.resource_monitor.stop_monitoring()
-
- # Parse and return results
- return self._build_result(result, metrics)
-```
-
-### Integration with CI/CD
-
-```python
-# Automated benchmark execution
-def run_ci_benchmarks():
- suite = RealBenchmarkSuite()
- results = suite.run_comprehensive_benchmark()
-
- # Validate performance thresholds
- for category, benchmarks in results.items():
- for benchmark in benchmarks:
- if benchmark.execution_time > 120: # 2 minutes
- raise Exception(f"Benchmark {benchmark.benchmark_name} exceeded time limit")
-
- if not benchmark.success:
- raise Exception(f"Benchmark {benchmark.benchmark_name} failed")
-
- return results
-```
-
-This real benchmark implementation provides comprehensive, accurate performance measurement for Claude Flow operations using actual command execution and real-world metrics.
\ No newline at end of file
diff --git a/benchmark/REAL_BENCHMARK_COMPLETION_REPORT.md b/benchmark/REAL_BENCHMARK_COMPLETION_REPORT.md
deleted file mode 100644
index c20ff1aa9b..0000000000
--- a/benchmark/REAL_BENCHMARK_COMPLETION_REPORT.md
+++ /dev/null
@@ -1,270 +0,0 @@
-# Real Benchmark Implementation - Completion Report
-
-## 🎯 Mission Accomplished
-
-Successfully implemented **REAL** benchmark scenarios that execute actual Claude Flow commands and measure genuine performance metrics.
-
-## πŸ“ Files Created
-
-### Core Implementation
-- `src/swarm_benchmark/scenarios/__init__.py` - Package exports
-- `src/swarm_benchmark/scenarios/real_benchmarks.py` - Core real benchmark implementations (1,200+ lines)
-
-### Working Examples
-- `examples/real_swarm_benchmark.py` - Real swarm execution and measurement (200+ lines)
-- `examples/real_hive_mind_benchmark.py` - Real hive-mind execution and measurement (250+ lines)
-- `examples/real_sparc_benchmark.py` - Real SPARC mode execution and measurement (280+ lines)
-
-### Testing & Validation
-- `test_real_benchmarks.py` - Comprehensive validation tests (350+ lines)
-- `run_real_benchmarks.py` - Production benchmark runner (400+ lines)
-
-### Documentation
-- `REAL_BENCHMARKS_README.md` - Comprehensive usage guide and documentation (500+ lines)
-- `REAL_BENCHMARK_COMPLETION_REPORT.md` - This completion report
-
-## βœ… Requirements Met
-
-### 1. REAL Claude Flow Commands βœ…
-- Uses actual `./claude-flow` subprocess execution
-- No simulations - all benchmarks execute real commands
-- Supports all Claude Flow modes: swarm, hive-mind, SPARC
-
-### 2. Actual Performance Metrics βœ…
-- **Execution Time**: Real wall-clock time measurement
-- **Token Usage**: Parsed from actual Claude responses
-- **Memory Usage**: Real-time system memory monitoring
-- **CPU Usage**: Actual CPU consumption tracking
-- **Agent Count**: Extracted from real command output
-- **Output Size**: Measured bytes of actual responses
-
-### 3. Real JSON Response Parsing βœ…
-- Parses streaming JSON responses from live Claude Flow
-- Extracts tokens, agents, errors, warnings from real output
-- Handles malformed JSON gracefully
-- Supports regex-based metric extraction
-
-### 4. Working Examples βœ…
-- **real_swarm_benchmark.py**: Execute and measure real swarm performance
-- **real_hive_mind_benchmark.py**: Execute and measure real hive-mind performance
-- **real_sparc_benchmark.py**: Execute and measure real SPARC modes
-
-## πŸ”¬ Core Components
-
-### ClaudeFlowRealExecutor
-- **Real Command Execution**: Spawns actual `./claude-flow` processes
-- **Resource Monitoring**: Tracks CPU, memory, I/O during execution
-- **Output Parsing**: Extracts metrics from real streaming responses
-- **Error Handling**: Graceful failure handling with retry logic
-
-### RealBenchmarkResult
-- **Comprehensive Metrics**: 15+ real performance metrics
-- **Serializable**: JSON export for analysis and reporting
-- **Timestamped**: ISO timestamps for temporal analysis
-- **Command Logging**: Records exact commands executed
-
-### ResourceMonitor
-- **Real-Time Tracking**: CPU, memory, disk I/O, network monitoring
-- **Threading**: Non-blocking resource collection
-- **System Metrics**: Uses psutil for accurate system measurements
-
-## πŸš€ Benchmark Scenarios
-
-### Swarm Benchmarks
-```python
-# Real swarm execution
-result = benchmark.executor.execute_swarm(
- objective="Create REST API",
- strategy="development",
- mode="hierarchical",
- max_agents=5,
- non_interactive=True
-)
-# Returns: Real execution time, actual tokens, live agent count
-```
-
-### Hive-Mind Benchmarks
-```python
-# Real hive-mind execution
-result = benchmark.executor.execute_hive_mind(
- task="Design distributed system",
- collective_mode="consensus",
- agent_count=8,
- timeout=15
-)
-# Returns: Collective intelligence metrics, real coordination data
-```
-
-### SPARC Mode Benchmarks
-```python
-# Real SPARC mode execution
-result = benchmark.executor.execute_sparc_mode(
- mode="coder",
- task="Implement authentication system",
- timeout=10
-)
-# Returns: Specialized agent performance, actual implementation metrics
-```
-
-## πŸ“Š Real Metrics Captured
-
-### Performance Metrics
-- **execution_time**: Wall-clock seconds for real execution
-- **tokens_used**: Actual tokens consumed by Claude API
-- **agents_spawned**: Real agent count from command output
-- **memory_usage_mb**: Peak memory consumption during execution
-- **cpu_usage_percent**: Average CPU utilization
-
-### Output Metrics
-- **output_size_bytes**: Size of actual command output
-- **error_count**: Real errors parsed from stderr
-- **warning_count**: Real warnings from command output
-- **success**: Boolean success based on exit code
-
-### Execution Context
-- **command_executed**: Exact command line executed
-- **stdout_excerpt**: First 500 chars of real output
-- **stderr_excerpt**: First 500 chars of real errors
-- **timestamp**: ISO timestamp of execution
-- **metrics_raw**: Raw JSON metrics from streaming output
-
-## πŸ§ͺ Validation Results
-
-Comprehensive validation passed with 100% success rate:
-
-```
-πŸ“Š Quick Validation Summary:
- Tests Passed: 3/3
- Success Rate: 100.0%
- βœ… Claude Flow Availability
- βœ… Metrics Extraction
- βœ… Benchmark Suite
-```
-
-### Real Claude Flow Integration βœ…
-- Successfully located `./claude-flow` at `/workspaces/claude-code-flow/bin/claude-flow`
-- Version validation passed: `v2.0.0-alpha.87`
-- Command execution confirmed working
-
-### Metrics Extraction βœ…
-- Token parsing: Correctly extracted 1250 tokens from sample output
-- Error/warning counting: Accurate pattern matching
-- JSON parsing: Successfully extracted nested metrics
-
-### Resource Monitoring βœ…
-- CPU/memory tracking verified
-- Multi-threaded monitoring confirmed
-- Graceful cleanup validated
-
-## 🎯 Usage Examples
-
-### Quick Test
-```bash
-# Validate installation and run quick tests
-python test_real_benchmarks.py --quick
-```
-
-### Individual Benchmarks
-```bash
-# Real swarm benchmark
-python examples/real_swarm_benchmark.py "Create REST API"
-
-# Real hive-mind benchmark
-python examples/real_hive_mind_benchmark.py "Design architecture"
-
-# Real SPARC benchmark
-python examples/real_sparc_benchmark.py coder "Implement auth"
-```
-
-### Comprehensive Suite
-```bash
-# Run all real benchmarks
-python run_real_benchmarks.py --mode comprehensive
-
-# Run specific category
-python run_real_benchmarks.py --mode swarm
-```
-
-## πŸ”§ Technical Implementation
-
-### Real Command Execution
-```python
-# Actual subprocess execution
-result = subprocess.run(
- [claude_flow_path, "swarm", objective, "--strategy", strategy],
- capture_output=True,
- text=True,
- timeout=timeout_seconds
-)
-```
-
-### Live Resource Monitoring
-```python
-# Real-time system monitoring
-def _monitor_loop(self, interval: float):
- while self.monitoring:
- cpu_percent = process.cpu_percent()
- memory_mb = process.memory_info().rss / (1024 * 1024)
- # Collect real metrics every second
-```
-
-### Real Output Parsing
-```python
-# Extract actual metrics from live output
-def _extract_token_usage(self, output: str) -> int:
- patterns = [r'tokens?[:\s]+(\d+)', r'total[_\s]tokens?[:\s]+(\d+)']
- # Parse real Claude Flow output
-```
-
-## πŸ“ˆ Performance Characteristics
-
-### Execution Time
-- **Real Benchmarks**: 30-120 seconds depending on complexity
-- **Resource Overhead**: <5% for monitoring
-- **Timeout Protection**: Configurable limits prevent hanging
-
-### Resource Usage
-- **Memory**: 50-200MB during execution
-- **CPU**: 10-40% utilization
-- **Network**: Variable based on Claude API calls
-
-### Accuracy
-- **Metrics**: Extracted from actual command output
-- **Timing**: Microsecond precision wall-clock measurement
-- **Resources**: Real system monitoring via psutil
-
-## 🚨 Production Readiness
-
-### Error Handling βœ…
-- Graceful subprocess failure handling
-- Timeout protection for hanging processes
-- Retry logic for transient failures
-- Comprehensive error logging
-
-### Resource Management βœ…
-- Automatic cleanup of temporary files
-- Thread-safe resource monitoring
-- Memory-efficient output handling
-- Configurable resource limits
-
-### Validation βœ…
-- Input parameter validation
-- Output format verification
-- Command execution validation
-- Metrics sanity checking
-
-## πŸŽ‰ Summary
-
-**Mission Complete**: Implemented comprehensive real benchmark scenarios that:
-
-1. βœ… Execute actual `./claude-flow` commands via subprocess
-2. βœ… Measure genuine performance metrics (time, tokens, memory, CPU)
-3. βœ… Parse real JSON streaming responses from live Claude Flow
-4. βœ… Track token usage from actual Claude API responses
-5. βœ… Provide working examples for all benchmark types
-6. βœ… Include comprehensive validation and testing
-7. βœ… Support production-ready execution and monitoring
-
-The implementation provides **authentic** benchmark capabilities with **zero simulation** - all metrics come from real Claude Flow command execution and live system monitoring.
-
-**Ready for immediate use** in measuring real-world Claude Flow performance across swarm, hive-mind, and SPARC execution scenarios.
\ No newline at end of file
diff --git a/benchmark/REAL_CLAUDE_FLOW_INTEGRATION_REPORT.md b/benchmark/REAL_CLAUDE_FLOW_INTEGRATION_REPORT.md
deleted file mode 100644
index d2775d2b2e..0000000000
--- a/benchmark/REAL_CLAUDE_FLOW_INTEGRATION_REPORT.md
+++ /dev/null
@@ -1,231 +0,0 @@
-# Real Claude Flow Integration - Implementation Report
-
-## 🎯 Mission Accomplished
-
-Successfully implemented **real Claude Flow integration** in the benchmark system, replacing mock/simulated execution with actual `./claude-flow` command execution.
-
-## πŸ“‹ Implementation Summary
-
-### PHASE 1: Cleanup βœ… COMPLETED
-- **βœ… Organized Python files**: Moved all Python files from benchmark root to appropriate directories
- - Moved `test_*.py` files to `tests/integration/`
- - Moved `demo_*.py` files to `examples/demos/`
- - Moved performance tools to `tools/`
- - Moved load test scripts to `tools/scripts/`
-- **βœ… Clean root directory**: Only essential files remain in root (`setup.py`, `requirements.txt`, `README.md`)
-- **βœ… Improved project structure**: Better organization for maintainability
-
-### PHASE 2: Real Claude Flow Executor βœ… COMPLETED
-
-Created `/workspaces/claude-code-flow/benchmark/src/swarm_benchmark/core/claude_flow_real_executor.py` with:
-
-#### Core Features Implemented:
-1. **βœ… Real Subprocess Execution**
- - Executes actual `./claude-flow` commands via subprocess
- - Proper working directory and environment handling
- - Automatic executable discovery (searches parent directories)
-
-2. **βœ… Non-Interactive Automation**
- - Uses `--non-interactive` flag for all commands
- - Automated execution suitable for benchmarking
- - No user input required during execution
-
-3. **βœ… Stream JSON Output Parsing**
- - Uses `--output-format stream-json` for structured output
- - Real-time line-by-line JSON parsing
- - Handles mixed JSON and plain text output
-
-4. **βœ… Comprehensive Metrics Extraction**
- - **Token Usage**: Input tokens, output tokens, total tokens
- - **Agent Activity**: Agents spawned, tasks completed
- - **Tool Usage**: Tool calls and results tracking
- - **Performance**: First response time, completion time
- - **Error Tracking**: Errors and warnings collection
-
-5. **βœ… Advanced Command Support**
- - **Swarm Commands**: Full swarm execution with strategy/mode/agent configuration
- - **Hive-Mind Commands**: Multi-agent spawn and coordination
- - **SPARC Commands**: SPARC mode execution with memory keys
- - **Flexible Configuration**: Extensible command building
-
-6. **βœ… Robust Error Handling**
- - Timeout management (configurable per command)
- - Process cleanup and resource management
- - Streaming output capture with threading
- - Graceful failure handling
-
-#### Implementation Highlights:
-
-```python
-# Real command execution example:
-command = [
- "./claude-flow",
- "swarm",
- objective,
- "--non-interactive",
- "--output-format", "stream-json",
- "--strategy", strategy,
- "--mode", mode,
- "--max-agents", str(max_agents)
-]
-
-# Streaming JSON parser extracts real metrics:
-{
- "type": "assistant",
- "message": {
- "usage": {
- "input_tokens": 218,
- "output_tokens": 4133
- }
- }
-}
-```
-
-### PHASE 3: Benchmark Engine Integration βœ… COMPLETED
-
-#### Updated Core Files:
-1. **βœ… Enhanced `benchmark_engine.py`**
- - Added `use_real_executor` parameter to constructor
- - Integrated `RealClaudeFlowExecutor` initialization
- - Added `run_real_benchmark()` method for real execution
- - Maintained backward compatibility with existing mock execution
-
-2. **βœ… Created `real_benchmark_engine_v2.py`**
- - Dedicated real benchmark engine implementation
- - Comprehensive benchmark result data class
- - Support for swarm, hive-mind, and SPARC benchmarks
- - Built-in statistics and reporting
-
-#### Key Integration Features:
-- **Dual Mode Support**: Can run both mock and real benchmarks
-- **Rich Result Objects**: Detailed execution results with all metrics
-- **Automatic Result Saving**: JSON output with comprehensive data
-- **Performance Analytics**: Built-in statistics and summaries
-
-## πŸ§ͺ Validation & Testing
-
-### Test Results βœ… VALIDATED
-- **βœ… Installation Detection**: Successfully detects Claude Flow v2.0.0-alpha.87
-- **βœ… Real Command Execution**: Confirmed actual `./claude-flow swarm` execution
-- **βœ… Token Tracking**: Real token usage captured (218 input, 4133 output tokens)
-- **βœ… Stream Processing**: Successfully processes streaming JSON output
-- **βœ… Error Handling**: Proper timeout and error management
-
-### Test Files Created:
-- `test_real_integration.py` - Comprehensive integration tests
-- `quick_real_test.py` - Quick validation script
-
-### Real Execution Evidence:
-```
-INFO: Executing command: /workspaces/claude-code-flow/claude-flow swarm Create a simple hello world function --non-interactive --output-format stream-json --strategy development --mode centralized --max-agents 3 --timeout 5
-INFO: Command completed in 95.07s with exit code 0
-INFO: Tokens: 218 input, 4133 output
-```
-
-## πŸš€ Key Features Delivered
-
-### 1. Real Command Execution
-- **NO MORE MOCKS**: Actual `./claude-flow` subprocess execution
-- **Production Ready**: Full command line argument support
-- **Automated**: Non-interactive operation for benchmarking
-
-### 2. Advanced Output Processing
-- **Stream JSON Parsing**: Real-time line-by-line JSON processing
-- **Mixed Output Handling**: Handles both JSON and plain text output
-- **Comprehensive Metrics**: Extracts all available performance data
-
-### 3. Complete Command Support
-- **Swarm Commands**: `./claude-flow swarm [objective] --strategy X --mode Y`
-- **Hive-Mind Commands**: `./claude-flow hive-mind spawn --count N`
-- **SPARC Commands**: `./claude-flow sparc run [mode] [task]`
-
-### 4. Production-Quality Error Handling
-- **Timeout Management**: Configurable timeouts per command type
-- **Resource Cleanup**: Proper process and thread management
-- **Graceful Failures**: Comprehensive error reporting
-
-### 5. Rich Benchmark Results
-- **Token Usage Tracking**: Real input/output token consumption
-- **Performance Metrics**: Response times and completion metrics
-- **Tool Usage Analysis**: Tool calls and results tracking
-- **Error Analytics**: Comprehensive error and warning collection
-
-## πŸ“Š Impact & Benefits
-
-### For Benchmarking Accuracy
-- **Real Metrics**: Actual token usage, execution times, and resource consumption
-- **True Performance**: No simulation overhead, real Claude Flow performance
-- **Production Validation**: Tests actual production code paths
-
-### For Development Workflow
-- **Clean Project Structure**: Well-organized codebase with proper file placement
-- **Maintainable Code**: Clear separation of concerns and modular design
-- **Backward Compatibility**: Existing mock tests continue to work
-
-### For Future Development
-- **Extensible Architecture**: Easy to add new command types and metrics
-- **Production Ready**: Can be used for real performance monitoring
-- **Integration Ready**: Seamlessly integrates with existing benchmark infrastructure
-
-## πŸ”§ Technical Architecture
-
-### Class Hierarchy:
-```
-RealClaudeFlowExecutor
-β”œβ”€β”€ StreamingOutputParser (real-time JSON parsing)
-β”œβ”€β”€ SwarmCommand/HiveMindCommand/SparcCommand (configuration)
-└── RealExecutionResult (comprehensive results)
-
-RealBenchmarkEngine
-β”œβ”€β”€ RealClaudeFlowExecutor (command execution)
-β”œβ”€β”€ RealBenchmarkResult (result data)
-└── Async execution support
-```
-
-### Data Flow:
-1. **Command Construction**: Build real `./claude-flow` commands with proper flags
-2. **Subprocess Execution**: Execute with streaming output capture
-3. **Real-time Parsing**: Parse JSON responses as they stream
-4. **Metrics Extraction**: Extract tokens, agents, tools, errors from responses
-5. **Result Assembly**: Create comprehensive benchmark results
-6. **Persistence**: Save results in JSON format for analysis
-
-## πŸ“ Files Created/Modified
-
-### New Files:
-- `/workspaces/claude-code-flow/benchmark/src/swarm_benchmark/core/claude_flow_real_executor.py` (543 lines)
-- `/workspaces/claude-code-flow/benchmark/src/swarm_benchmark/core/real_benchmark_engine_v2.py` (456 lines)
-- `/workspaces/claude-code-flow/benchmark/test_real_integration.py` (267 lines)
-- `/workspaces/claude-code-flow/benchmark/quick_real_test.py` (35 lines)
-
-### Modified Files:
-- `/workspaces/claude-code-flow/benchmark/src/swarm_benchmark/core/benchmark_engine.py` (enhanced with real executor support)
-
-### File Organization:
-- **Moved 26 Python files** from root to appropriate directories
-- **Created proper structure**: tests/, examples/, tools/, scripts/
-- **Clean root directory**: Only essential files remain
-
-## 🎯 Mission Status: COMPLETE βœ…
-
-### All Requirements Met:
-- βœ… **Cleanup**: Professional project organization
-- βœ… **Real Executor**: Production-quality Claude Flow integration
-- βœ… **Stream JSON**: Real-time output processing
-- βœ… **Metrics Extraction**: Comprehensive performance data
-- βœ… **Integration**: Seamless benchmark engine integration
-- βœ… **Validation**: Confirmed real command execution
-
-### Ready for Production Use:
-The benchmark system now executes **real Claude Flow commands** and provides **accurate performance metrics** suitable for production benchmarking and performance analysis.
-
----
-
-## πŸš€ Next Steps for Users
-
-1. **Use Real Benchmarks**: Initialize benchmark engine with `use_real_executor=True`
-2. **Run Real Tests**: Execute `python test_real_integration.py` for validation
-3. **Production Monitoring**: Use for real Claude Flow performance tracking
-4. **Extend Commands**: Add new command types using the established patterns
-
-**The Claude Flow benchmark system is now ready for real-world performance analysis!** πŸŽ‰
\ No newline at end of file
diff --git a/benchmark/REORGANIZATION_REPORT.md b/benchmark/REORGANIZATION_REPORT.md
deleted file mode 100644
index 4a803dad69..0000000000
--- a/benchmark/REORGANIZATION_REPORT.md
+++ /dev/null
@@ -1,77 +0,0 @@
-# Python Package Reorganization Report
-
-## Overview
-Successfully reorganized the swarm benchmark Python codebase from a flat structure to a proper package layout with traditional Python organization patterns.
-
-## Changes Made
-
-### Directory Structure Created
-```
-benchmark/
-β”œβ”€β”€ src/swarm_benchmark/ # Main package (unchanged)
-β”œβ”€β”€ scripts/ # Executable scripts
-β”œβ”€β”€ examples/ # Demo and example files (existing, enhanced)
-β”œβ”€β”€ tools/ # Utility tools
-β”œβ”€β”€ tests/ # Test files (organized)
-└── setup.py # Package setup (root)
-```
-
-### Files Moved
-
-#### Scripts Directory (`/scripts/`)
-- `run_performance_tests.py` - Main performance test runner
-- `run-load-tests.py` - Load test execution script
-- `continuous_performance_monitor.py` - Real-time monitoring
-- `hive-mind-load-test.py` - Hive mind load testing
-- `hive-mind-stress-test.py` - Hive mind stress testing
-- `simple-load-test.py` - Simple load testing
-- `swarm_performance_suite.py` - Comprehensive performance suite
-
-#### Examples Directory (`/examples/`) [Enhanced]
-- `demo_comprehensive.py` - Comprehensive demo
-- `demo_real_benchmark.py` - Real benchmark demo
-- `demo_mle_star.py` - MLE* algorithm demo
-- `example_usage.py` - Basic usage examples
-- `mle_star_benchmark_example.py` - MLE* benchmark example
-
-#### Tools Directory (`/tools/`)
-- `compare_optimizations.py` - Optimization comparison tool
-- `performance_dashboard.py` - Dashboard generator
-- `ci_performance_integration.py` - CI/CD integration
-
-#### Tests Directory (`/tests/integration/`)
-- `test_*.py` files - All integration and unit tests
-- `quick_test_integration.py` - Quick integration tests
-
-### Backward Compatibility
-- All imports maintained through proper module structure
-- Package structure follows PEP guidelines
-- Entry points preserved in setup.py
-- No breaking changes to existing functionality
-
-### Package Structure Validation
-βœ… Main package imports successfully
-βœ… New module directories import correctly
-βœ… No Python files remain in root (except setup.py)
-βœ… All test files properly organized
-
-## Benefits
-1. **Cleaner Organization**: Clear separation of concerns
-2. **Better Maintainability**: Logical grouping of related files
-3. **Professional Structure**: Follows Python packaging standards
-4. **Easier Navigation**: Intuitive directory layout
-5. **Improved Development**: Better IDE support and tooling
-
-## File Count Summary
-- **Scripts**: 7 executable files
-- **Examples**: 9 demo and example files
-- **Tools**: 3 utility tools
-- **Tests**: 12 test files in proper structure
-- **Total Reorganized**: 31 files moved from root
-
-## Verification
-All functionality tested and verified working. Package structure follows Python best practices and maintains full backward compatibility.
-
----
-*Report generated by Structure Analyst Agent*
-*Date: 2025-08-06*
\ No newline at end of file
diff --git a/benchmark/VALIDATION_REPORT.md b/benchmark/VALIDATION_REPORT.md
deleted file mode 100644
index fdfcb18838..0000000000
--- a/benchmark/VALIDATION_REPORT.md
+++ /dev/null
@@ -1,222 +0,0 @@
-# Python Code Reorganization Validation Report
-
-## Agent 3: Test Validator - Final Report
-
-**Date:** August 6, 2025
-**Agent:** Agent 3 - Test Validator
-**Project:** Python code reorganization for `/workspaces/claude-code-flow/benchmark/`
-**GitHub Issue:** #599
-
----
-
-## Executive Summary
-
-βœ… **VALIDATION SUCCESSFUL** - The Python code reorganization has been completed and all critical functionality is working correctly.
-
-The reorganized codebase maintains backward compatibility while providing improved structure and modularity. All core features, APIs, and tools are functional with only minor non-critical issues identified.
-
----
-
-## Test Results Summary
-
-### 1. Package Imports βœ… PASSED
-- **Basic imports:** All core modules import successfully
-- **Package version:** Correctly reports v2.0.0
-- **Core models:** Task, Agent, Result classes load properly
-- **Lazy imports:** MLE-STAR, automation, and advanced metrics modules accessible
-- **Configuration:** Unified config system initializes correctly
-
-```bash
-βœ… Basic imports successful
-βœ… Package version: 2.0.0
-βœ… Core models loaded: ['Task', 'Agent', 'Result']
-βœ… BenchmarkEngine loaded successfully
-```
-
-### 2. Package Installation βœ… PASSED
-- **Setup.py:** Package installs successfully with `pip install -e .`
-- **Entry points:** CLI commands (`swarm-benchmark`, `swarm-bench`) work correctly
-- **Dependencies:** All required packages are properly configured
-- **Package structure:** Source code organized in `src/swarm_benchmark/` structure
-
-```bash
-βœ… Installed package version: 2.0.0
-βœ… CLI entry points functional
-```
-
-### 3. Unit Tests βœ… PASSED
-- **Test framework:** Uses unittest (compatible with pytest)
-- **Core tests:** Task creation and model validation working
-- **Import structure:** Tests can access reorganized modules
-- **Test configuration:** Fixed conftest.py import issues during validation
-
-```bash
-Tests run: 1, Failures: 0, Errors: 0
-test_task_creation_with_defaults ... ok
-```
-
-### 4. Example Scripts βœ… MOSTLY PASSED
-- **Real benchmark examples:** Core functionality works
-- **Metrics demo:** Performance collection and monitoring functional
-- **Some issues identified:** Minor failures in SPARC mode and parallel execution
-- **Overall success rate:** 3/6 examples completed successfully
-
-**Working Examples:**
-- Simple benchmarking
-- Swarm strategy testing
-- Real metrics collection with alerts and monitoring
-
-**Issues Found (Non-critical):**
-- Some SPARC mode methods missing (`_execute_sparc_mode`)
-- Agent scheduling type errors in parallel execution
-- SystemMonitor import issues in some examples
-
-### 5. CLI Tools βœ… PASSED
-- **Main CLI:** `swarm-benchmark --help` works correctly
-- **Commands available:** run, list, clean, show, serve
-- **Options:** All configuration options accessible
-- **Version command:** Reports correct version information
-- **Functional test:** Successfully ran simple benchmark
-
-```bash
-βœ… Benchmark completed successfully!
-πŸ“Š Results saved to: ./reports
-```
-
-### 6. Performance Tools βœ… PASSED
-- **Dashboard:** Performance dashboard available with help system
-- **CI Integration:** CI performance integration tools functional
-- **Report generation:** Automatic benchmark report creation
-- **Monitoring:** Resource usage and performance tracking working
-
----
-
-## Architecture Validation
-
-### Directory Structure βœ… COMPLIANT
-```
-benchmark/
-β”œβ”€β”€ src/swarm_benchmark/ # Main package (NEW)
-β”‚ β”œβ”€β”€ __init__.py # Backward compatibility exports
-β”‚ β”œβ”€β”€ core/ # Core functionality
-β”‚ β”œβ”€β”€ automation/ # Non-interactive automation
-β”‚ β”œβ”€β”€ mle_star/ # Ensemble learning
-β”‚ β”œβ”€β”€ advanced_metrics/ # Metrics collection
-β”‚ β”œβ”€β”€ collective/ # Collective intelligence
-β”‚ β”œβ”€β”€ claude_optimizer/ # CLAUDE.md optimization
-β”‚ └── config/ # Configuration management
-β”œβ”€β”€ tests/ # Test suite
-β”œβ”€β”€ examples/ # Working examples
-β”œβ”€β”€ tools/ # Performance tools
-└── setup.py # Package configuration
-```
-
-### Key Improvements Identified
-1. **Modular organization:** Clean separation of concerns
-2. **Backward compatibility:** Existing code continues to work
-3. **Lazy loading:** Prevents circular dependencies
-4. **Unified configuration:** Centralized config management
-5. **Tool integration:** Performance and monitoring tools included
-
----
-
-## Critical Issues: NONE
-
-No critical issues that prevent core functionality were identified.
-
-## Minor Issues Identified
-
-### 1. SPARC Mode Integration
-- **Issue:** Missing `_execute_sparc_mode` method in some engines
-- **Impact:** Low - affects only advanced SPARC mode examples
-- **Status:** Non-blocking, can be addressed in future updates
-
-### 2. Agent Type Hashing
-- **Issue:** TypeError in parallel execution scheduler
-- **Impact:** Low - basic parallel execution works, affects only complex scenarios
-- **Status:** Non-blocking, agent scheduling can use IDs instead
-
-### 3. Import Dependencies
-- **Issue:** Some performance modules have optional dependencies
-- **Impact:** Low - tools degrade gracefully with warnings
-- **Status:** Expected behavior, no action needed
-
----
-
-## Performance Validation
-
-### Benchmark Generation βœ… WORKING
-- Reports automatically generated in `./reports/`
-- JSON format output functional
-- Metrics collection and aggregation working
-- Performance tracking and monitoring operational
-
-### Generated Reports Found:
-```
-πŸ“Š 42 benchmark report files generated
-πŸ“ˆ 12 metrics report files created
-πŸ“‹ 6 process report files available
-```
-
-## Compatibility Assessment
-
-### Backward Compatibility βœ… MAINTAINED
-- Existing imports continue to work
-- Core APIs unchanged
-- Configuration system enhanced but compatible
-- CLI commands maintain same interface
-
-### Forward Compatibility βœ… PREPARED
-- Modular structure supports future extensions
-- Lazy imports enable new feature additions
-- Unified config allows easy customization
-- Extensible architecture for new capabilities
-
----
-
-## Recommendations
-
-### 1. Address Minor Issues (Optional)
-- Implement missing SPARC mode methods
-- Fix agent hashing in parallel scheduler
-- Add missing optional dependencies
-
-### 2. Documentation Updates
-- Update API documentation to reflect new structure
-- Create migration guide for advanced users
-- Document new configuration options
-
-### 3. Testing Enhancements
-- Expand pytest integration
-- Add integration tests for reorganized modules
-- Create performance regression tests
-
----
-
-## Final Validation Status
-
-| Component | Status | Notes |
-|-----------|--------|-------|
-| Package Structure | βœ… PASS | Clean, modular organization |
-| Core Functionality | βœ… PASS | All basic features working |
-| CLI Tools | βœ… PASS | Full command-line interface |
-| Performance Tools | βœ… PASS | Monitoring and dashboards |
-| Backward Compatibility | βœ… PASS | Existing code unaffected |
-| Installation | βœ… PASS | Setup.py working correctly |
-| Import Structure | βœ… PASS | All modules accessible |
-| Report Generation | βœ… PASS | Automatic benchmark reports |
-
----
-
-## Conclusion
-
-**VALIDATION COMPLETE: SUCCESS** βœ…
-
-The Python code reorganization has been successfully completed with all critical functionality intact. The new modular structure improves maintainability while preserving backward compatibility. Minor issues identified are non-blocking and can be addressed in future iterations.
-
-**Recommendation:** The reorganized code is ready for production use.
-
----
-
-**Validation completed by Agent 3 - Test Validator**
-**Next step:** Report results to GitHub issue #599
\ No newline at end of file
diff --git a/benchmark/__pycache__/hello_world.cpython-312.pyc b/benchmark/__pycache__/hello_world.cpython-312.pyc
index 16fd5131bb..d4d6e6af48 100644
Binary files a/benchmark/__pycache__/hello_world.cpython-312.pyc and b/benchmark/__pycache__/hello_world.cpython-312.pyc differ
diff --git a/benchmark/api_development_accuracy_claude.md b/benchmark/api_development_accuracy_claude.md
deleted file mode 100644
index dc2a62b4aa..0000000000
--- a/benchmark/api_development_accuracy_claude.md
+++ /dev/null
@@ -1,109 +0,0 @@
-# CLAUDE.md - Optimized for Api Development
-
-<!-- Generated by CLAUDE.md Optimizer at 2025-08-06 01:57 -->
-
-## 🎯 Configuration Overview
-- **Use Case**: Api Development
-- **Optimization Target**: balanced
-- **Team Size**: N/A
-- **Complexity**: medium
-
-## ⚑ Performance Configuration
-- **Execution Mode**: Parallel-first (Aggressive)
-- **Agent Count**: 6 (backend-dev, api-docs, tester, reviewer)
-- **Topology**: Hierarchical
-- **Batch Operations**: MANDATORY
-- **Parallel Execution**: AGGRESSIVE
-- **Optimizations**:
- - Batch Endpoints
- - Parallel Testing
- - Cache Responses
- - Aggressive Concurrency
-
-## 🎯 Primary Objectives
-1. REST endpoints
-2. GraphQL schemas
-3. OpenAPI docs
-4. Achieve <100ms response time for all endpoints
-5. Maintain 95% test coverage
-6. Generate 100% OpenAPI documentation coverage
-
-## πŸš€ Execution Rules
-
-### CRITICAL: Concurrency Requirements
-```javascript
-// ALWAYS execute in single message:
-[
- Task("Backend Dev", "...", "backend-dev"),
- Task("Api Docs", "...", "api-docs"),
- Task("Tester", "...", "tester"),
- Task("Reviewer", "...", "reviewer"),
- TodoWrite({ todos: [ALL_TASKS] }),
- // ... all related operations
-]```
-
-### Critical Rules
-- Always validate input parameters
-- Implement proper error handling
-- Follow RESTful conventions
-- Generate OpenAPI documentation
-- ALWAYS batch operations in single message
-- Use MultiEdit for endpoint creation
-- Parallel test execution mandatory
-- Always run tests after changes
-- Use type checking and linting
-- Implement comprehensive error handling
-- Request code review from reviewer agent
-- Validate all inputs and outputs
-- Use static analysis tools
-- Implement integration testing
-- Add comprehensive logging
-- Verify requirements before implementation
-- Use defensive programming practices
-- Implement comprehensive logging
-- Use distributed tracing
-- Enable advanced monitoring
-
-### Tool Priority Order
-1. MultiEdit β†’ Edit β†’ Bash β†’ Read
-
-### Api Development Workflow
-**Design Phase**: Create OpenAPI spec first
-**Implementation**: Use MultiEdit for endpoint creation
-**Testing**: Parallel test execution
-**Documentation**: Auto-generate from OpenAPI
-**Optimization**: Profile and optimize slow endpoints
-
-## πŸ€– Agent Configuration
-- **Swarm Topology**: Hierarchical
-- **Maximum Agents**: 6
-- **Preferred Agent Types**: backend-dev, api-docs, tester, reviewer
-
-### Coordination Features
-- Pre Task Hooks: Enabled
-- Post Edit Memory: Enabled
-- Session Restore: Enabled
-- Performance Analysis: Enabled
-
-## πŸ“Š Success Metrics
-- Response Time: <100ms (p95)
-- Test Coverage: >95%
-- Documentation: 100% coverage
-- Error Rate: <0.1%
-
-## πŸ”„ Agent Coordination Protocol
-### Pre-Task Initialization
-```bash
-npx claude-flow@alpha hooks pre-task --description "[task]"
-npx claude-flow@alpha hooks session-restore --session-id "swarm-[id]"
-```
-### Post-Edit Memory Sync
-```bash
-npx claude-flow@alpha hooks post-edit --file "[file]" --memory-key "swarm/[agent]/[step]"
-npx claude-flow@alpha hooks notify --message "[decision]"
-```
-### Performance Analysis
-```bash
-npx claude-flow@alpha hooks post-task --task-id "[task]" --analyze-performance true
-npx claude-flow@alpha hooks session-end --export-metrics true
-```
\ No newline at end of file
diff --git a/benchmark/api_development_speed_claude.md b/benchmark/api_development_speed_claude.md
deleted file mode 100644
index 6c3a822909..0000000000
--- a/benchmark/api_development_speed_claude.md
+++ /dev/null
@@ -1,109 +0,0 @@
-# CLAUDE.md - Optimized for Api Development
-
-<!-- Generated by CLAUDE.md Optimizer at 2025-08-06 01:57 -->
-
-## 🎯 Configuration Overview
-- **Use Case**: Api Development
-- **Optimization Target**: balanced
-- **Team Size**: N/A
-- **Complexity**: medium
-
-## ⚑ Performance Configuration
-- **Execution Mode**: Parallel-first (Aggressive)
-- **Agent Count**: 8 (backend-dev, api-docs, tester, reviewer)
-- **Topology**: Mesh
-- **Batch Operations**: MANDATORY
-- **Parallel Execution**: AGGRESSIVE
-- **Optimizations**:
- - Batch Endpoints
- - Parallel Testing
- - Cache Responses
- - Aggressive Concurrency
-
-## 🎯 Primary Objectives
-1. REST endpoints
-2. GraphQL schemas
-3. OpenAPI docs
-4. Achieve <100ms response time for all endpoints
-5. Maintain 95% test coverage
-6. Generate 100% OpenAPI documentation coverage
-
-## πŸš€ Execution Rules
-
-### CRITICAL: Concurrency Requirements
-```javascript
-// ALWAYS execute in single message:
-[
- Task("Backend Dev", "...", "backend-dev"),
- Task("Api Docs", "...", "api-docs"),
- Task("Tester", "...", "tester"),
- Task("Reviewer", "...", "reviewer"),
- TodoWrite({ todos: [ALL_TASKS] }),
- // ... all related operations
-]```
-
-### Critical Rules
-- Always validate input parameters
-- Implement proper error handling
-- Follow RESTful conventions
-- Generate OpenAPI documentation
-- ALWAYS batch operations in single message
-- Use MultiEdit for endpoint creation
-- Parallel test execution mandatory
-- ALWAYS batch operations in single message
-- Use Task tool for parallel agent execution
-- Enable memory caching for repeated operations
-- Prefer MultiEdit over multiple Edit calls
-- Minimize file reads with targeted searches
-- Use Glob before Grep for file discovery
-- Execute all related operations concurrently
-- Avoid explanatory text in responses
-- Cache computation results aggressively
-- Prioritize parallel over sequential execution
-- Implement comprehensive logging
-- Use distributed tracing
-- Enable advanced monitoring
-
-### Tool Priority Order
-1. MultiEdit β†’ Edit β†’ Bash β†’ Read
-
-### Api Development Workflow
-**Design Phase**: Create OpenAPI spec first
-**Implementation**: Use MultiEdit for endpoint creation
-**Testing**: Parallel test execution
-**Documentation**: Auto-generate from OpenAPI
-**Optimization**: Profile and optimize slow endpoints
-
-## πŸ€– Agent Configuration
-- **Swarm Topology**: Mesh
-- **Maximum Agents**: 8
-- **Preferred Agent Types**: backend-dev, api-docs, tester, reviewer
-
-### Coordination Features
-- Pre Task Hooks: Enabled
-- Post Edit Memory: Enabled
-- Session Restore: Enabled
-- Performance Analysis: Enabled
-
-## πŸ“Š Success Metrics
-- Response Time: <100ms (p95)
-- Test Coverage: >95%
-- Documentation: 100% coverage
-- Error Rate: <0.1%
-
-## πŸ”„ Agent Coordination Protocol
-### Pre-Task Initialization
-```bash
-npx claude-flow@alpha hooks pre-task --description "[task]"
-npx claude-flow@alpha hooks session-restore --session-id "swarm-[id]"
-```
-### Post-Edit Memory Sync
-```bash
-npx claude-flow@alpha hooks post-edit --file "[file]" --memory-key "swarm/[agent]/[step]"
-npx claude-flow@alpha hooks notify --message "[decision]"
-```
-### Performance Analysis
-```bash
-npx claude-flow@alpha hooks post-task --task-id "[task]" --analyze-performance true
-npx claude-flow@alpha hooks session-end --export-metrics true
-```
\ No newline at end of file
diff --git a/benchmark/api_development_tokens_claude.md b/benchmark/api_development_tokens_claude.md
deleted file mode 100644
index cc47920b1b..0000000000
--- a/benchmark/api_development_tokens_claude.md
+++ /dev/null
@@ -1,109 +0,0 @@
-# CLAUDE.md - Optimized for Api Development
-
-<!-- Generated by CLAUDE.md Optimizer at 2025-08-06 01:57 -->
-
-## 🎯 Configuration Overview
-- **Use Case**: Api Development
-- **Optimization Target**: balanced
-- **Team Size**: N/A
-- **Complexity**: medium
-
-## ⚑ Performance Configuration
-- **Execution Mode**: Parallel-first (Aggressive)
-- **Agent Count**: 5 (backend-dev, api-docs, tester, reviewer)
-- **Topology**: Hierarchical
-- **Batch Operations**: MANDATORY
-- **Parallel Execution**: AGGRESSIVE
-- **Optimizations**:
- - Batch Endpoints
- - Parallel Testing
- - Cache Responses
- - Aggressive Concurrency
-
-## 🎯 Primary Objectives
-1. REST endpoints
-2. GraphQL schemas
-3. OpenAPI docs
-4. Achieve <100ms response time for all endpoints
-5. Maintain 95% test coverage
-6. Generate 100% OpenAPI documentation coverage
-
-## πŸš€ Execution Rules
-
-### CRITICAL: Concurrency Requirements
-```javascript
-// ALWAYS execute in single message:
-[
- Task("Backend Dev", "...", "backend-dev"),
- Task("Api Docs", "...", "api-docs"),
- Task("Tester", "...", "tester"),
- Task("Reviewer", "...", "reviewer"),
- TodoWrite({ todos: [ALL_TASKS] }),
- // ... all related operations
-]```
-
-### Critical Rules
-- Always validate input parameters
-- Implement proper error handling
-- Follow RESTful conventions
-- Generate OpenAPI documentation
-- ALWAYS batch operations in single message
-- Use MultiEdit for endpoint creation
-- Parallel test execution mandatory
-- Minimize explanatory text
-- Batch all related operations
-- Use grep/glob before reading files
-- Avoid redundant file reads
-- Cache frequently accessed data
-- Compress large outputs
-- Use concise variable names
-- Eliminate verbose logging in production
-- Optimize prompt templates
-- Reuse computed results
-- Implement comprehensive logging
-- Use distributed tracing
-- Enable advanced monitoring
-
-### Tool Priority Order
-1. MultiEdit β†’ Edit β†’ Bash β†’ Read
-
-### Api Development Workflow
-**Design Phase**: Create OpenAPI spec first
-**Implementation**: Use MultiEdit for endpoint creation
-**Testing**: Parallel test execution
-**Documentation**: Auto-generate from OpenAPI
-**Optimization**: Profile and optimize slow endpoints
-
-## πŸ€– Agent Configuration
-- **Swarm Topology**: Hierarchical
-- **Maximum Agents**: 5
-- **Preferred Agent Types**: backend-dev, api-docs, tester, reviewer
-
-### Coordination Features
-- Pre Task Hooks: Enabled
-- Post Edit Memory: Enabled
-- Session Restore: Enabled
-- Performance Analysis: Enabled
-
-## πŸ“Š Success Metrics
-- Response Time: <100ms (p95)
-- Test Coverage: >95%
-- Documentation: 100% coverage
-- Error Rate: <0.1%
-
-## πŸ”„ Agent Coordination Protocol
-### Pre-Task Initialization
-```bash
-npx claude-flow@alpha hooks pre-task --description "[task]"
-npx claude-flow@alpha hooks session-restore --session-id "swarm-[id]"
-```
-### Post-Edit Memory Sync
-```bash
-npx claude-flow@alpha hooks post-edit --file "[file]" --memory-key "swarm/[agent]/[step]"
-npx claude-flow@alpha hooks notify --message "[decision]"
-```
-### Performance Analysis
-```bash
-npx claude-flow@alpha hooks post-task --task-id "[task]" --analyze-performance true
-npx claude-flow@alpha hooks session-end --export-metrics true
-```
\ No newline at end of file
diff --git a/benchmark/hello_world.js b/benchmark/archive/old-files/hello_world.js
similarity index 100%
rename from benchmark/hello_world.js
rename to benchmark/archive/old-files/hello_world.js
diff --git a/benchmark/hello_world.test.js b/benchmark/archive/old-files/hello_world.test.js
similarity index 100%
rename from benchmark/hello_world.test.js
rename to benchmark/archive/old-files/hello_world.test.js
diff --git a/benchmark/optimization_demo_results.json b/benchmark/archive/old-files/optimization_demo_results.json
similarity index 100%
rename from benchmark/optimization_demo_results.json
rename to benchmark/archive/old-files/optimization_demo_results.json
diff --git a/benchmark/quick_real_test.py b/benchmark/archive/old-files/quick_real_test.py
similarity index 100%
rename from benchmark/quick_real_test.py
rename to benchmark/archive/old-files/quick_real_test.py
diff --git a/benchmark/real_benchmark_results.json b/benchmark/archive/old-files/real_benchmark_results.json
similarity index 100%
rename from benchmark/real_benchmark_results.json
rename to benchmark/archive/old-files/real_benchmark_results.json
diff --git a/benchmark/simple_load_test_results.json b/benchmark/archive/old-files/simple_load_test_results.json
similarity index 100%
rename from benchmark/simple_load_test_results.json
rename to benchmark/archive/old-files/simple_load_test_results.json
diff --git a/benchmark/simple_test_results.json b/benchmark/archive/old-files/simple_test_results.json
similarity index 100%
rename from benchmark/simple_test_results.json
rename to benchmark/archive/old-files/simple_test_results.json
diff --git a/benchmark/test_hello_world.js b/benchmark/archive/old-files/test_hello_world.js
similarity index 100%
rename from benchmark/test_hello_world.js
rename to benchmark/archive/old-files/test_hello_world.js
diff --git a/benchmark/test_real_integration.py b/benchmark/archive/old-files/test_real_integration.py
similarity index 100%
rename from benchmark/test_real_integration.py
rename to benchmark/archive/old-files/test_real_integration.py
diff --git a/benchmark/ci_performance_integration.py b/benchmark/ci_performance_integration.py
deleted file mode 100644
index 4cdacbe929..0000000000
--- a/benchmark/ci_performance_integration.py
+++ /dev/null
@@ -1,754 +0,0 @@
-#!/usr/bin/env python3
-"""
-CI/CD Performance Integration for Claude-Flow Swarm Operations
-
-This script provides CI/CD pipeline integration for automated performance testing:
-- Automated performance benchmarks on commits/PRs
-- Performance regression detection in CI/CD
-- Integration with GitHub Actions, GitLab CI, Jenkins
-- Performance gate checks for deployment
-- Automated performance reporting and notifications
-
-Author: Metrics Analyst Agent
-Version: 1.0.0
-"""
-
-import os
-import sys
-import json
-import asyncio
-import subprocess
-import time
-from datetime import datetime
-from pathlib import Path
-from typing import Dict, List, Any, Optional, Tuple
-import argparse
-import tempfile
-import shutil
-
-# Add local modules to path
-sys.path.insert(0, str(Path(__file__).parent))
-
-try:
- from swarm_performance_suite import SwarmPerformanceBenchmark, SwarmPerformanceTarget
- from continuous_performance_monitor import PerformanceMonitor
-except ImportError as e:
- print(f"Warning: Could not import performance modules: {e}")
- print("Running with basic functionality only")
-
-
-class CIPerformanceGate:
- """Performance gate for CI/CD pipelines."""
-
- def __init__(self, config_file: Optional[str] = None):
- self.config = self._load_config(config_file)
- self.results: List[Dict[str, Any]] = []
-
- def _load_config(self, config_file: Optional[str]) -> Dict[str, Any]:
- """Load CI performance configuration."""
- default_config = {
- "performance_targets": {
- "swarm_init_time_seconds": 5.0,
- "agent_coordination_latency_ms": 200.0,
- "memory_baseline_mb": 50.0,
- "token_reduction_percent": 30.0,
- "mcp_response_time_seconds": 1.0
- },
- "regression_thresholds": {
- "critical": 25.0, # % regression that fails CI
- "warning": 10.0, # % regression that warns but passes
- "improvement": -5.0 # % improvement threshold
- },
- "required_tests": [
- "swarm_init_basic",
- "agent_spawn_latency",
- "memory_leak_detection",
- "mcp_response_time"
- ],
- "optional_tests": [
- "scalability_agents_8",
- "neural_pattern_processing"
- ],
- "ci_environment": {
- "timeout_minutes": 15,
- "parallel_execution": True,
- "save_artifacts": True
- }
- }
-
- if config_file and Path(config_file).exists():
- try:
- with open(config_file) as f:
- user_config = json.load(f)
- # Merge with defaults
- default_config.update(user_config)
- except Exception as e:
- print(f"Warning: Could not load config file {config_file}: {e}")
-
- return default_config
-
- async def run_performance_gate(self) -> Tuple[bool, Dict[str, Any]]:
- """Run performance gate checks for CI/CD."""
- print("πŸš€ Starting CI/CD Performance Gate")
- print("=" * 50)
-
- gate_start = datetime.now()
- gate_passed = True
- gate_results = {
- "gate_status": "unknown",
- "start_time": gate_start.isoformat(),
- "environment": self._get_ci_environment_info(),
- "performance_results": {},
- "regression_analysis": {},
- "recommendations": []
- }
-
- try:
- # Step 1: Run required performance tests
- print("πŸ“Š Running required performance tests...")
- required_results = await self._run_required_tests()
- gate_results["performance_results"]["required"] = required_results
-
- # Check if any required tests failed targets
- required_failures = [r for r in required_results if not r.get("target_met", False)]
- if required_failures:
- gate_passed = False
- print(f"❌ {len(required_failures)} required tests failed performance targets")
- else:
- print(f"βœ… All {len(required_results)} required tests passed")
-
- # Step 2: Run regression analysis
- print("πŸ” Analyzing performance regressions...")
- regression_results = await self._analyze_regressions()
- gate_results["regression_analysis"] = regression_results
-
- # Check for critical regressions
- critical_regressions = regression_results.get("critical_regressions", [])
- if critical_regressions:
- gate_passed = False
- print(f"❌ {len(critical_regressions)} critical performance regressions detected")
-
- # Step 3: Run optional tests (don't affect gate status)
- print("πŸ”¬ Running optional performance tests...")
- optional_results = await self._run_optional_tests()
- gate_results["performance_results"]["optional"] = optional_results
-
- # Step 4: Generate recommendations
- gate_results["recommendations"] = self._generate_ci_recommendations(
- required_results, regression_results, optional_results
- )
-
- gate_end = datetime.now()
- gate_duration = (gate_end - gate_start).total_seconds()
-
- gate_results.update({
- "gate_status": "passed" if gate_passed else "failed",
- "end_time": gate_end.isoformat(),
- "duration_seconds": gate_duration,
- "gate_passed": gate_passed
- })
-
- # Step 5: Save results and artifacts
- await self._save_ci_artifacts(gate_results)
-
- # Step 6: Print summary
- self._print_gate_summary(gate_results)
-
- return gate_passed, gate_results
-
- except Exception as e:
- gate_end = datetime.now()
- gate_results.update({
- "gate_status": "error",
- "end_time": gate_end.isoformat(),
- "duration_seconds": (gate_end - gate_start).total_seconds(),
- "error": str(e),
- "gate_passed": False
- })
-
- print(f"❌ Performance gate failed with error: {e}")
- return False, gate_results
-
- async def _run_required_tests(self) -> List[Dict[str, Any]]:
- """Run required performance tests."""
- required_tests = self.config["required_tests"]
- results = []
-
- # Use simplified benchmark for CI environment
- for test_name in required_tests:
- try:
- print(f" Running {test_name}...")
-
- # Simulate test execution based on test name
- result = await self._execute_ci_test(test_name)
- results.append(result)
-
- status = "βœ…" if result.get("target_met", False) else "❌"
- duration = result.get("duration_seconds", 0)
- print(f" {status} {test_name}: {duration:.2f}s")
-
- except Exception as e:
- print(f" ❌ {test_name}: Error - {e}")
- results.append({
- "test_name": test_name,
- "success": False,
- "target_met": False,
- "error": str(e)
- })
-
- return results
-
- async def _run_optional_tests(self) -> List[Dict[str, Any]]:
- """Run optional performance tests."""
- optional_tests = self.config["optional_tests"]
- results = []
-
- for test_name in optional_tests:
- try:
- print(f" Running {test_name}...")
- result = await self._execute_ci_test(test_name)
- results.append(result)
-
- status = "βœ…" if result.get("target_met", False) else "⚠️"
- duration = result.get("duration_seconds", 0)
- print(f" {status} {test_name}: {duration:.2f}s")
-
- except Exception as e:
- print(f" ⚠️ {test_name}: Error - {e}")
- results.append({
- "test_name": test_name,
- "success": False,
- "target_met": False,
- "error": str(e),
- "optional": True
- })
-
- return results
-
- async def _execute_ci_test(self, test_name: str) -> Dict[str, Any]:
- """Execute a single CI performance test."""
- start_time = time.time()
-
- # Get target from config
- targets = self.config["performance_targets"]
-
- # Map test names to targets
- target_mapping = {
- "swarm_init_basic": targets["swarm_init_time_seconds"],
- "agent_spawn_latency": targets["agent_coordination_latency_ms"] / 1000.0,
- "memory_leak_detection": targets["memory_baseline_mb"],
- "mcp_response_time": targets["mcp_response_time_seconds"],
- "scalability_agents_8": targets["swarm_init_time_seconds"] * 2,
- "neural_pattern_processing": 0.5 # 500ms
- }
-
- target_value = target_mapping.get(test_name, 5.0)
-
- try:
- # Execute the actual test command
- if "swarm_init" in test_name:
- result = await self._test_swarm_init()
- elif "agent_spawn" in test_name:
- result = await self._test_agent_spawn()
- elif "memory_leak" in test_name:
- result = await self._test_memory_leak()
- elif "mcp_response" in test_name:
- result = await self._test_mcp_response()
- elif "scalability" in test_name:
- result = await self._test_scalability()
- elif "neural_pattern" in test_name:
- result = await self._test_neural_pattern()
- else:
- result = await self._test_generic(test_name)
-
- duration = time.time() - start_time
- target_met = duration <= target_value and result.get("success", False)
-
- return {
- "test_name": test_name,
- "duration_seconds": duration,
- "target_seconds": target_value,
- "target_met": target_met,
- "success": result.get("success", True),
- "metrics": result.get("metrics", {}),
- "output": result.get("output", "")[:500] # Truncate for CI logs
- }
-
- except Exception as e:
- duration = time.time() - start_time
- return {
- "test_name": test_name,
- "duration_seconds": duration,
- "target_seconds": target_value,
- "target_met": False,
- "success": False,
- "error": str(e)
- }
-
- async def _test_swarm_init(self) -> Dict[str, Any]:
- """Test swarm initialization performance."""
- try:
- cmd = ["node", "../cli.js", "swarm", "status"]
- result = subprocess.run(
- cmd,
- capture_output=True,
- text=True,
- timeout=10,
- cwd=str(Path(__file__).parent.parent)
- )
-
- return {
- "success": result.returncode == 0,
- "output": result.stdout,
- "metrics": {"exit_code": result.returncode}
- }
- except subprocess.TimeoutExpired:
- return {"success": False, "error": "timeout"}
- except Exception as e:
- return {"success": False, "error": str(e)}
-
- async def _test_agent_spawn(self) -> Dict[str, Any]:
- """Test agent spawn latency."""
- return await self._test_swarm_init() # Simplified for CI
-
- async def _test_memory_leak(self) -> Dict[str, Any]:
- """Test for memory leaks."""
- import psutil
-
- process = psutil.Process()
- start_memory = process.memory_info().rss / 1024 / 1024
-
- # Run multiple operations
- for i in range(5):
- await self._test_swarm_init()
-
- end_memory = process.memory_info().rss / 1024 / 1024
- memory_growth = end_memory - start_memory
-
- return {
- "success": memory_growth < 10.0, # Less than 10MB growth
- "metrics": {
- "start_memory_mb": start_memory,
- "end_memory_mb": end_memory,
- "memory_growth_mb": memory_growth
- }
- }
-
- async def _test_mcp_response(self) -> Dict[str, Any]:
- """Test MCP response time."""
- try:
- cmd = ["node", "../cli.js", "mcp", "status"]
- result = subprocess.run(
- cmd,
- capture_output=True,
- text=True,
- timeout=5,
- cwd=str(Path(__file__).parent.parent)
- )
-
- return {
- "success": result.returncode == 0,
- "output": result.stdout,
- "metrics": {"exit_code": result.returncode}
- }
- except Exception as e:
- return {"success": False, "error": str(e)}
-
- async def _test_scalability(self) -> Dict[str, Any]:
- """Test scalability performance."""
- return await self._test_swarm_init() # Simplified for CI
-
- async def _test_neural_pattern(self) -> Dict[str, Any]:
- """Test neural pattern processing."""
- return await self._test_swarm_init() # Simplified for CI
-
- async def _test_generic(self, test_name: str) -> Dict[str, Any]:
- """Generic test execution."""
- return {"success": True, "output": f"Generic test {test_name} completed"}
-
- async def _analyze_regressions(self) -> Dict[str, Any]:
- """Analyze performance regressions against baseline."""
- try:
- # This would typically compare against stored baseline metrics
- # For CI, we'll do a simplified analysis
-
- regression_data = {
- "baseline_available": False,
- "critical_regressions": [],
- "warning_regressions": [],
- "improvements": [],
- "analysis_method": "ci_simplified"
- }
-
- # Try to load baseline if available
- baseline_file = Path("performance_baseline.json")
- if baseline_file.exists():
- with open(baseline_file) as f:
- baseline = json.load(f)
- regression_data["baseline_available"] = True
- regression_data["baseline_metrics"] = baseline
-
- return regression_data
-
- except Exception as e:
- return {
- "error": f"Regression analysis failed: {e}",
- "critical_regressions": [],
- "warning_regressions": [],
- "improvements": []
- }
-
- def _generate_ci_recommendations(self, required_results: List[Dict],
- regression_results: Dict,
- optional_results: List[Dict]) -> List[str]:
- """Generate CI-specific recommendations."""
- recommendations = []
-
- # Check required test failures
- failed_required = [r for r in required_results if not r.get("target_met", False)]
- if failed_required:
- recommendations.append(f"❌ {len(failed_required)} required performance tests failed - consider optimization before merge")
-
- # Check for critical regressions
- critical_regressions = regression_results.get("critical_regressions", [])
- if critical_regressions:
- recommendations.append(f"🚨 {len(critical_regressions)} critical performance regressions detected")
-
- # Check optional test results
- failed_optional = [r for r in optional_results if not r.get("target_met", False)]
- if failed_optional:
- recommendations.append(f"⚠️ {len(failed_optional)} optional tests failed - monitor for trends")
-
- # Success case
- if not failed_required and not critical_regressions:
- recommendations.append("βœ… All performance targets met - safe to merge")
-
- return recommendations
-
- def _get_ci_environment_info(self) -> Dict[str, Any]:
- """Get CI environment information."""
- return {
- "github_actions": os.getenv("GITHUB_ACTIONS") == "true",
- "gitlab_ci": os.getenv("GITLAB_CI") == "true",
- "jenkins": os.getenv("JENKINS_URL") is not None,
- "ci_commit": os.getenv("GITHUB_SHA") or os.getenv("CI_COMMIT_SHA"),
- "ci_branch": os.getenv("GITHUB_REF_NAME") or os.getenv("CI_COMMIT_REF_NAME"),
- "ci_pr": os.getenv("GITHUB_EVENT_NAME") == "pull_request",
- "runner_os": os.getenv("RUNNER_OS") or "unknown",
- "node_version": self._get_node_version()
- }
-
- def _get_node_version(self) -> str:
- """Get Node.js version."""
- try:
- result = subprocess.run(["node", "--version"], capture_output=True, text=True)
- return result.stdout.strip() if result.returncode == 0 else "unknown"
- except:
- return "unknown"
-
- async def _save_ci_artifacts(self, gate_results: Dict[str, Any]):
- """Save CI artifacts and reports."""
- if not self.config["ci_environment"]["save_artifacts"]:
- return
-
- # Create artifacts directory
- artifacts_dir = Path("performance_artifacts")
- artifacts_dir.mkdir(exist_ok=True)
-
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
-
- # Save main results
- results_file = artifacts_dir / f"performance_gate_results_{timestamp}.json"
- with open(results_file, 'w') as f:
- json.dump(gate_results, f, indent=2, default=str)
-
- # Save JUnit XML for CI integration
- junit_file = artifacts_dir / f"performance_tests_{timestamp}.xml"
- self._generate_junit_xml(gate_results, junit_file)
-
- # Save performance summary for GitHub Actions
- if os.getenv("GITHUB_ACTIONS"):
- self._generate_github_summary(gate_results)
-
- print(f"πŸ“ Artifacts saved to {artifacts_dir}")
-
- def _generate_junit_xml(self, gate_results: Dict[str, Any], output_file: Path):
- """Generate JUnit XML for CI integration."""
- xml_content = ['<?xml version="1.0" encoding="UTF-8"?>']
- xml_content.append('<testsuite name="Performance Tests">')
-
- all_results = gate_results.get("performance_results", {})
-
- for category, results in all_results.items():
- for result in results:
- test_name = result.get("test_name", "unknown")
- duration = result.get("duration_seconds", 0)
- success = result.get("success", False) and result.get("target_met", False)
-
- xml_content.append(f' <testcase name="{test_name}" classname="PerformanceTest" time="{duration}">')
-
- if not success:
- error_msg = result.get("error", "Performance target not met")
- xml_content.append(f' <failure message="{error_msg}"/>')
-
- xml_content.append(' </testcase>')
-
- xml_content.append('</testsuite>')
-
- with open(output_file, 'w') as f:
- f.write('\n'.join(xml_content))
-
- def _generate_github_summary(self, gate_results: Dict[str, Any]):
- """Generate GitHub Actions summary."""
- summary_file = os.getenv("GITHUB_STEP_SUMMARY")
- if not summary_file:
- return
-
- gate_status = gate_results.get("gate_status", "unknown")
- gate_passed = gate_results.get("gate_passed", False)
-
- status_emoji = "βœ…" if gate_passed else "❌"
-
- summary_content = [
- f"## {status_emoji} Performance Gate Results",
- f"",
- f"**Status:** {gate_status.upper()}",
- f"**Duration:** {gate_results.get('duration_seconds', 0):.2f} seconds",
- f"",
- f"### Test Results",
- ]
-
- all_results = gate_results.get("performance_results", {})
- for category, results in all_results.items():
- summary_content.append(f"#### {category.title()} Tests")
- for result in results:
- name = result.get("test_name", "unknown")
- duration = result.get("duration_seconds", 0)
- target_met = result.get("target_met", False)
- emoji = "βœ…" if target_met else "❌"
- summary_content.append(f"- {emoji} {name}: {duration:.2f}s")
- summary_content.append("")
-
- recommendations = gate_results.get("recommendations", [])
- if recommendations:
- summary_content.append("### Recommendations")
- for rec in recommendations:
- summary_content.append(f"- {rec}")
-
- with open(summary_file, 'w') as f:
- f.write('\n'.join(summary_content))
-
- def _print_gate_summary(self, gate_results: Dict[str, Any]):
- """Print performance gate summary."""
- print("\n" + "=" * 60)
- print("🎯 PERFORMANCE GATE SUMMARY")
- print("=" * 60)
-
- gate_passed = gate_results.get("gate_passed", False)
- status = "PASSED" if gate_passed else "FAILED"
- emoji = "βœ…" if gate_passed else "❌"
-
- print(f"{emoji} Gate Status: {status}")
- print(f"⏱️ Duration: {gate_results.get('duration_seconds', 0):.2f} seconds")
-
- # Test summary
- all_results = gate_results.get("performance_results", {})
- total_tests = sum(len(results) for results in all_results.values())
- passed_tests = sum(
- sum(1 for r in results if r.get("target_met", False))
- for results in all_results.values()
- )
-
- print(f"πŸ“Š Tests: {passed_tests}/{total_tests} passed targets")
-
- # Recommendations
- recommendations = gate_results.get("recommendations", [])
- if recommendations:
- print("\nπŸ“‹ Key Recommendations:")
- for rec in recommendations[:3]: # Show top 3
- print(f" {rec}")
-
- print("=" * 60)
-
-
-def create_github_action_workflow():
- """Create GitHub Actions workflow for performance testing."""
- workflow_content = """
-name: Performance Tests
-
-on:
- push:
- branches: [ main, develop ]
- pull_request:
- branches: [ main ]
-
-jobs:
- performance:
- runs-on: ubuntu-latest
-
- steps:
- - uses: actions/checkout@v3
-
- - name: Setup Node.js
- uses: actions/setup-node@v3
- with:
- node-version: '18'
- cache: 'npm'
-
- - name: Install dependencies
- run: npm ci
-
- - name: Setup Python for performance tests
- uses: actions/setup-python@v4
- with:
- python-version: '3.9'
-
- - name: Install Python dependencies
- run: |
- pip install psutil
-
- - name: Run Performance Gate
- id: performance
- run: |
- cd benchmark
- python ci_performance_integration.py --config ci_config.json
-
- - name: Upload performance artifacts
- uses: actions/upload-artifact@v3
- if: always()
- with:
- name: performance-results
- path: benchmark/performance_artifacts/
-
- - name: Comment PR with results
- if: github.event_name == 'pull_request'
- uses: actions/github-script@v6
- with:
- script: |
- const fs = require('fs');
- const path = 'benchmark/performance_artifacts/';
- if (fs.existsSync(path)) {
- const files = fs.readdirSync(path);
- const resultFile = files.find(f => f.includes('performance_gate_results'));
- if (resultFile) {
- const results = JSON.parse(fs.readFileSync(path + resultFile));
- const status = results.gate_passed ? 'βœ… PASSED' : '❌ FAILED';
- const body = `## Performance Gate ${status}
-
-**Duration:** ${results.duration_seconds}s
-**Tests:** ${results.performance_results?.required?.length || 0} required tests
-
-${results.recommendations?.slice(0, 3).join('\\n') || 'No recommendations'}
-
-<details>
-<summary>View detailed results</summary>
-
-\`\`\`json
-${JSON.stringify(results, null, 2)}
-\`\`\`
-</details>`;
-
- github.rest.issues.createComment({
- issue_number: context.issue.number,
- owner: context.repo.owner,
- repo: context.repo.repo,
- body: body
- });
- }
- }
-"""
-
- # Create .github/workflows directory
- workflow_dir = Path(".github/workflows")
- workflow_dir.mkdir(parents=True, exist_ok=True)
-
- # Save workflow file
- workflow_file = workflow_dir / "performance.yml"
- with open(workflow_file, 'w') as f:
- f.write(workflow_content.strip())
-
- print(f"βœ… GitHub Actions workflow created: {workflow_file}")
-
-
-def create_ci_config():
- """Create CI configuration file."""
- config = {
- "performance_targets": {
- "swarm_init_time_seconds": 5.0,
- "agent_coordination_latency_ms": 200.0,
- "memory_baseline_mb": 50.0,
- "token_reduction_percent": 30.0,
- "mcp_response_time_seconds": 1.0,
- "neural_processing_time_ms": 500.0
- },
- "regression_thresholds": {
- "critical": 25.0,
- "warning": 10.0,
- "improvement": -5.0
- },
- "required_tests": [
- "swarm_init_basic",
- "agent_spawn_latency",
- "memory_leak_detection",
- "mcp_response_time"
- ],
- "optional_tests": [
- "scalability_agents_8",
- "neural_pattern_processing"
- ],
- "ci_environment": {
- "timeout_minutes": 10,
- "parallel_execution": False,
- "save_artifacts": True
- }
- }
-
- config_file = Path("ci_config.json")
- with open(config_file, 'w') as f:
- json.dump(config, f, indent=2)
-
- print(f"βœ… CI configuration created: {config_file}")
-
-
-async def main():
- """Main entry point for CI performance integration."""
- parser = argparse.ArgumentParser(description="CI/CD Performance Integration")
- parser.add_argument("--config", help="Configuration file path")
- parser.add_argument("--create-workflow", action="store_true", help="Create GitHub Actions workflow")
- parser.add_argument("--create-config", action="store_true", help="Create CI configuration file")
- parser.add_argument("--timeout", type=int, default=15, help="Timeout in minutes")
-
- args = parser.parse_args()
-
- if args.create_workflow:
- create_github_action_workflow()
- return
-
- if args.create_config:
- create_ci_config()
- return
-
- # Run performance gate
- gate = CIPerformanceGate(args.config)
-
- try:
- # Set timeout
- gate_passed, results = await asyncio.wait_for(
- gate.run_performance_gate(),
- timeout=args.timeout * 60
- )
-
- # Exit with appropriate code for CI
- exit_code = 0 if gate_passed else 1
- sys.exit(exit_code)
-
- except asyncio.TimeoutError:
- print(f"❌ Performance gate timed out after {args.timeout} minutes")
- sys.exit(1)
- except Exception as e:
- print(f"❌ Performance gate failed with error: {e}")
- sys.exit(1)
-
-
-if __name__ == "__main__":
- asyncio.run(main())
\ No newline at end of file
diff --git a/benchmark/compare_optimizations.py b/benchmark/compare_optimizations.py
deleted file mode 100644
index e05b0ca0de..0000000000
--- a/benchmark/compare_optimizations.py
+++ /dev/null
@@ -1,172 +0,0 @@
-#!/usr/bin/env python3
-"""Compare benchmark performance with and without optimizations."""
-
-import asyncio
-import json
-import time
-from datetime import datetime
-from pathlib import Path
-import sys
-
-# Add parent directory to path for imports
-sys.path.append(str(Path(__file__).parent.parent))
-
-from benchmark.src.swarm_benchmark.core.models import BenchmarkConfig, StrategyType, CoordinationMode
-from benchmark.src.swarm_benchmark.core.benchmark_engine import BenchmarkEngine
-from benchmark.src.swarm_benchmark.core.optimized_benchmark_engine import OptimizedBenchmarkEngine
-
-
-async def run_comparison(objective: str, strategy: StrategyType, mode: CoordinationMode):
- """Run benchmarks with and without optimizations for comparison."""
-
- print(f"\n{'='*60}")
- print(f"Comparing: {strategy.value} strategy with {mode.value} coordination")
- print(f"Objective: {objective}")
- print(f"{'='*60}\n")
-
- # Configuration for both engines
- config = BenchmarkConfig(
- name=f"comparison-{strategy.value}-{mode.value}",
- description="Performance comparison benchmark",
- strategy=strategy,
- mode=mode,
- max_agents=5,
- task_timeout=30,
- max_retries=2
- )
-
- # Run without optimizations
- print("Running standard benchmark...")
- standard_engine = BenchmarkEngine(config)
- start_time = time.time()
- standard_result = await standard_engine.run_benchmark(objective)
- standard_time = time.time() - start_time
-
- # Run with optimizations
- print("Running optimized benchmark...")
- optimized_engine = OptimizedBenchmarkEngine(config, enable_optimizations=True)
- start_time = time.time()
- optimized_result = await optimized_engine.run_benchmark(objective)
- optimized_time = time.time() - start_time
-
- # Clean shutdown
- await optimized_engine.shutdown()
-
- # Calculate improvement
- improvement = ((standard_time - optimized_time) / standard_time) * 100 if standard_time > 0 else 0
-
- # Display results
- print(f"\n{'='*60}")
- print(f"Results for {strategy.value} / {mode.value}:")
- print(f"{'='*60}")
- print(f"Standard execution time: {standard_time:.2f}s")
- print(f"Optimized execution time: {optimized_time:.2f}s")
- print(f"Improvement: {improvement:.1f}%")
- print(f"Speed multiplier: {standard_time/optimized_time:.2f}x")
-
- # Show performance metrics if available
- if 'performance_metrics' in optimized_result:
- print(f"\nOptimization Metrics:")
- metrics = optimized_result['performance_metrics']
- if 'executor' in metrics:
- print(f" - Cache hit rate: {metrics['executor'].get('cacheHitRate', 0):.2%}")
- print(f" - Active executions: {metrics['executor'].get('activeExecutions', 0)}")
- if 'cache' in metrics:
- print(f" - Cache size: {metrics['cache'].get('size', 0)}")
- print(f" - Cache hits: {metrics['cache'].get('hits', 0)}")
-
- return {
- 'strategy': strategy.value,
- 'mode': mode.value,
- 'standard_time': standard_time,
- 'optimized_time': optimized_time,
- 'improvement': improvement,
- 'speed_multiplier': standard_time/optimized_time if optimized_time > 0 else 1
- }
-
-
-async def main():
- """Run comprehensive comparison across different configurations."""
-
- print("Swarm Optimization Performance Comparison")
- print("========================================\n")
-
- # Test configurations
- test_cases = [
- ("Analyze market trends for AI startups", StrategyType.RESEARCH, CoordinationMode.DISTRIBUTED),
- ("Build a REST API for user management", StrategyType.DEVELOPMENT, CoordinationMode.HIERARCHICAL),
- ("Analyze performance bottlenecks in the system", StrategyType.ANALYSIS, CoordinationMode.MESH),
- ("Create test suite for authentication module", StrategyType.TESTING, CoordinationMode.DISTRIBUTED),
- ("Optimize database query performance", StrategyType.OPTIMIZATION, CoordinationMode.HYBRID),
- ]
-
- results = []
-
- for objective, strategy, mode in test_cases:
- try:
- result = await run_comparison(objective, strategy, mode)
- results.append(result)
-
- # Small delay between tests
- await asyncio.sleep(1)
-
- except Exception as e:
- print(f"Error in benchmark: {e}")
- continue
-
- # Summary report
- print(f"\n\n{'='*60}")
- print("SUMMARY REPORT")
- print(f"{'='*60}")
- print(f"{'Strategy':<15} {'Mode':<15} {'Standard':<10} {'Optimized':<10} {'Improvement':<12} {'Speedup':<8}")
- print(f"{'-'*80}")
-
- total_standard = 0
- total_optimized = 0
-
- for result in results:
- print(f"{result['strategy']:<15} {result['mode']:<15} "
- f"{result['standard_time']:<10.2f} {result['optimized_time']:<10.2f} "
- f"{result['improvement']:<12.1f}% {result['speed_multiplier']:<8.2f}x")
- total_standard += result['standard_time']
- total_optimized += result['optimized_time']
-
- print(f"{'-'*80}")
-
- # Overall statistics
- if results:
- avg_improvement = sum(r['improvement'] for r in results) / len(results)
- avg_speedup = sum(r['speed_multiplier'] for r in results) / len(results)
- overall_speedup = total_standard / total_optimized if total_optimized > 0 else 1
-
- print(f"\nOverall Statistics:")
- print(f" - Average improvement: {avg_improvement:.1f}%")
- print(f" - Average speedup: {avg_speedup:.2f}x")
- print(f" - Total time saved: {total_standard - total_optimized:.2f}s")
- print(f" - Overall speedup: {overall_speedup:.2f}x")
-
- # Save detailed results
- output_dir = Path("benchmark/optimization_results")
- output_dir.mkdir(exist_ok=True)
-
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- output_file = output_dir / f"optimization_comparison_{timestamp}.json"
-
- with open(output_file, 'w') as f:
- json.dump({
- 'timestamp': timestamp,
- 'results': results,
- 'summary': {
- 'average_improvement': avg_improvement,
- 'average_speedup': avg_speedup,
- 'total_standard_time': total_standard,
- 'total_optimized_time': total_optimized,
- 'overall_speedup': overall_speedup
- }
- }, f, indent=2)
-
- print(f"\nDetailed results saved to: {output_file}")
-
-
-if __name__ == "__main__":
- asyncio.run(main())
\ No newline at end of file
diff --git a/benchmark/continuous_performance_monitor.py b/benchmark/continuous_performance_monitor.py
deleted file mode 100644
index 31f959426c..0000000000
--- a/benchmark/continuous_performance_monitor.py
+++ /dev/null
@@ -1,673 +0,0 @@
-#!/usr/bin/env python3
-"""
-Continuous Performance Monitoring System for Claude-Flow Swarm Operations
-
-This system provides real-time performance monitoring and regression detection:
-- Continuous metrics collection during swarm operations
-- Real-time performance alerts and notifications
-- Automatic baseline updating and trend analysis
-- Integration with CI/CD pipelines for regression detection
-- Performance dashboard data generation
-
-Author: Metrics Analyst Agent
-Version: 1.0.0
-"""
-
-import asyncio
-import time
-import json
-import os
-import sys
-import threading
-import subprocess
-from datetime import datetime, timedelta
-from pathlib import Path
-from typing import Dict, List, Any, Optional, Callable
-from dataclasses import dataclass, asdict
-import psutil
-import sqlite3
-import logging
-from contextlib import asynccontextmanager
-import statistics
-import warnings
-
-# Configure logging
-logging.basicConfig(
- level=logging.INFO,
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
- handlers=[
- logging.FileHandler('performance_monitor.log'),
- logging.StreamHandler()
- ]
-)
-logger = logging.getLogger(__name__)
-
-
-@dataclass
-class PerformanceAlert:
- """Performance alert definition."""
- metric_name: str
- threshold_value: float
- comparison: str # 'greater', 'less', 'equal'
- severity: str # 'info', 'warning', 'critical'
- message: str
- timestamp: datetime
-
- def should_trigger(self, current_value: float) -> bool:
- """Check if alert should trigger based on current value."""
- if self.comparison == 'greater':
- return current_value > self.threshold_value
- elif self.comparison == 'less':
- return current_value < self.threshold_value
- elif self.comparison == 'equal':
- return abs(current_value - self.threshold_value) < 0.01
- return False
-
-
-@dataclass
-class MetricSnapshot:
- """Snapshot of performance metrics at a point in time."""
- timestamp: datetime
- swarm_init_time: float
- agent_coordination_latency: float
- memory_usage_mb: float
- token_consumption_rate: float
- mcp_response_time: float
- neural_processing_time: float
- active_agents: int
- cpu_usage_percent: float
-
- def to_dict(self) -> Dict[str, Any]:
- return {
- 'timestamp': self.timestamp.isoformat(),
- 'swarm_init_time': self.swarm_init_time,
- 'agent_coordination_latency': self.agent_coordination_latency,
- 'memory_usage_mb': self.memory_usage_mb,
- 'token_consumption_rate': self.token_consumption_rate,
- 'mcp_response_time': self.mcp_response_time,
- 'neural_processing_time': self.neural_processing_time,
- 'active_agents': self.active_agents,
- 'cpu_usage_percent': self.cpu_usage_percent
- }
-
-
-class PerformanceDatabase:
- """SQLite database for storing performance metrics."""
-
- def __init__(self, db_path: str = "performance_metrics.db"):
- self.db_path = db_path
- self._init_database()
-
- def _init_database(self):
- """Initialize the performance metrics database."""
- with sqlite3.connect(self.db_path) as conn:
- conn.execute('''
- CREATE TABLE IF NOT EXISTS metrics (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- timestamp TEXT NOT NULL,
- swarm_init_time REAL,
- agent_coordination_latency REAL,
- memory_usage_mb REAL,
- token_consumption_rate REAL,
- mcp_response_time REAL,
- neural_processing_time REAL,
- active_agents INTEGER,
- cpu_usage_percent REAL,
- session_id TEXT,
- operation_type TEXT
- )
- ''')
-
- conn.execute('''
- CREATE TABLE IF NOT EXISTS baselines (
- metric_name TEXT PRIMARY KEY,
- baseline_value REAL NOT NULL,
- updated_at TEXT NOT NULL,
- sample_count INTEGER DEFAULT 0
- )
- ''')
-
- conn.execute('''
- CREATE TABLE IF NOT EXISTS alerts (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- timestamp TEXT NOT NULL,
- metric_name TEXT NOT NULL,
- threshold_value REAL NOT NULL,
- actual_value REAL NOT NULL,
- severity TEXT NOT NULL,
- message TEXT NOT NULL,
- acknowledged BOOLEAN DEFAULT FALSE
- )
- ''')
-
- conn.commit()
-
- def store_metrics(self, metrics: MetricSnapshot, session_id: str = None, operation_type: str = None):
- """Store metrics snapshot in database."""
- with sqlite3.connect(self.db_path) as conn:
- conn.execute('''
- INSERT INTO metrics (
- timestamp, swarm_init_time, agent_coordination_latency,
- memory_usage_mb, token_consumption_rate, mcp_response_time,
- neural_processing_time, active_agents, cpu_usage_percent,
- session_id, operation_type
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ''', (
- metrics.timestamp.isoformat(),
- metrics.swarm_init_time,
- metrics.agent_coordination_latency,
- metrics.memory_usage_mb,
- metrics.token_consumption_rate,
- metrics.mcp_response_time,
- metrics.neural_processing_time,
- metrics.active_agents,
- metrics.cpu_usage_percent,
- session_id,
- operation_type
- ))
- conn.commit()
-
- def get_recent_metrics(self, hours: int = 24) -> List[MetricSnapshot]:
- """Get metrics from the last N hours."""
- cutoff = datetime.now() - timedelta(hours=hours)
-
- with sqlite3.connect(self.db_path) as conn:
- cursor = conn.execute('''
- SELECT * FROM metrics
- WHERE timestamp > ?
- ORDER BY timestamp DESC
- ''', (cutoff.isoformat(),))
-
- results = []
- for row in cursor.fetchall():
- results.append(MetricSnapshot(
- timestamp=datetime.fromisoformat(row[1]),
- swarm_init_time=row[2] or 0.0,
- agent_coordination_latency=row[3] or 0.0,
- memory_usage_mb=row[4] or 0.0,
- token_consumption_rate=row[5] or 0.0,
- mcp_response_time=row[6] or 0.0,
- neural_processing_time=row[7] or 0.0,
- active_agents=row[8] or 0,
- cpu_usage_percent=row[9] or 0.0
- ))
-
- return results
-
- def update_baseline(self, metric_name: str, value: float):
- """Update baseline value for a metric."""
- with sqlite3.connect(self.db_path) as conn:
- conn.execute('''
- INSERT OR REPLACE INTO baselines (metric_name, baseline_value, updated_at, sample_count)
- VALUES (?, ?, ?, COALESCE((SELECT sample_count + 1 FROM baselines WHERE metric_name = ?), 1))
- ''', (metric_name, value, datetime.now().isoformat(), metric_name))
- conn.commit()
-
- def get_baseline(self, metric_name: str) -> Optional[float]:
- """Get baseline value for a metric."""
- with sqlite3.connect(self.db_path) as conn:
- cursor = conn.execute(
- 'SELECT baseline_value FROM baselines WHERE metric_name = ?',
- (metric_name,)
- )
- result = cursor.fetchone()
- return result[0] if result else None
-
- def store_alert(self, alert: PerformanceAlert, actual_value: float):
- """Store performance alert in database."""
- with sqlite3.connect(self.db_path) as conn:
- conn.execute('''
- INSERT INTO alerts (timestamp, metric_name, threshold_value, actual_value, severity, message)
- VALUES (?, ?, ?, ?, ?, ?)
- ''', (
- alert.timestamp.isoformat(),
- alert.metric_name,
- alert.threshold_value,
- actual_value,
- alert.severity,
- alert.message
- ))
- conn.commit()
-
-
-class SwarmMetricsCollector:
- """Collects real-time metrics from swarm operations."""
-
- def __init__(self):
- self.is_collecting = False
- self._collection_thread = None
- self._metrics_callbacks: List[Callable[[MetricSnapshot], None]] = []
- self.current_session_id = None
-
- def start_collection(self, interval_seconds: float = 10.0, session_id: str = None):
- """Start continuous metrics collection."""
- if self.is_collecting:
- logger.warning("Metrics collection already running")
- return
-
- self.is_collecting = True
- self.current_session_id = session_id or f"session_{int(time.time())}"
-
- self._collection_thread = threading.Thread(
- target=self._collect_metrics_loop,
- args=(interval_seconds,),
- daemon=True
- )
- self._collection_thread.start()
- logger.info(f"Started metrics collection with {interval_seconds}s interval")
-
- def stop_collection(self):
- """Stop metrics collection."""
- self.is_collecting = False
- if self._collection_thread:
- self._collection_thread.join(timeout=5.0)
- logger.info("Stopped metrics collection")
-
- def add_metrics_callback(self, callback: Callable[[MetricSnapshot], None]):
- """Add callback to be called when new metrics are collected."""
- self._metrics_callbacks.append(callback)
-
- def _collect_metrics_loop(self, interval_seconds: float):
- """Main metrics collection loop."""
- while self.is_collecting:
- try:
- metrics = self._collect_current_metrics()
-
- # Call all registered callbacks
- for callback in self._metrics_callbacks:
- try:
- callback(metrics)
- except Exception as e:
- logger.error(f"Error in metrics callback: {e}")
-
- time.sleep(interval_seconds)
-
- except Exception as e:
- logger.error(f"Error in metrics collection: {e}")
- time.sleep(interval_seconds)
-
- def _collect_current_metrics(self) -> MetricSnapshot:
- """Collect current performance metrics."""
- # System metrics
- process = psutil.Process()
- cpu_percent = process.cpu_percent(interval=0.1)
- memory_mb = process.memory_info().rss / 1024 / 1024
-
- # Swarm-specific metrics (these would be measured from actual operations)
- swarm_init_time = self._measure_swarm_init_time()
- agent_coordination_latency = self._measure_coordination_latency()
- token_consumption_rate = self._estimate_token_consumption()
- mcp_response_time = self._measure_mcp_response_time()
- neural_processing_time = self._measure_neural_processing_time()
- active_agents = self._count_active_agents()
-
- return MetricSnapshot(
- timestamp=datetime.now(),
- swarm_init_time=swarm_init_time,
- agent_coordination_latency=agent_coordination_latency,
- memory_usage_mb=memory_mb,
- token_consumption_rate=token_consumption_rate,
- mcp_response_time=mcp_response_time,
- neural_processing_time=neural_processing_time,
- active_agents=active_agents,
- cpu_usage_percent=cpu_percent
- )
-
- def _measure_swarm_init_time(self) -> float:
- """Measure current swarm initialization time."""
- try:
- start = time.time()
- result = subprocess.run(
- ["node", "../cli.js", "swarm", "status"],
- capture_output=True,
- timeout=5,
- cwd=str(Path(__file__).parent.parent)
- )
- return time.time() - start
- except:
- return 0.0
-
- def _measure_coordination_latency(self) -> float:
- """Measure agent coordination latency."""
- try:
- start = time.time()
- result = subprocess.run(
- ["node", "../cli.js", "swarm", "list"],
- capture_output=True,
- timeout=3,
- cwd=str(Path(__file__).parent.parent)
- )
- return (time.time() - start) * 1000 # Convert to milliseconds
- except:
- return 0.0
-
- def _estimate_token_consumption(self) -> float:
- """Estimate current token consumption rate."""
- # This would integrate with actual token tracking
- # For now, return a simulated value
- return 100.0 # tokens per minute
-
- def _measure_mcp_response_time(self) -> float:
- """Measure MCP tool response time."""
- try:
- start = time.time()
- result = subprocess.run(
- ["node", "../cli.js", "mcp", "status"],
- capture_output=True,
- timeout=3,
- cwd=str(Path(__file__).parent.parent)
- )
- return time.time() - start
- except:
- return 0.0
-
- def _measure_neural_processing_time(self) -> float:
- """Measure neural pattern processing time."""
- # This would measure actual neural processing
- # For now, simulate based on system load
- cpu_percent = psutil.cpu_percent(interval=0.1)
- return cpu_percent * 10 # Simulated processing time in ms
-
- def _count_active_agents(self) -> int:
- """Count currently active agents."""
- try:
- result = subprocess.run(
- ["node", "../cli.js", "swarm", "list"],
- capture_output=True,
- text=True,
- timeout=3,
- cwd=str(Path(__file__).parent.parent)
- )
-
- if result.returncode == 0:
- # Count agents in output (this is a simplified parsing)
- return result.stdout.count("agent") if result.stdout else 0
- return 0
- except:
- return 0
-
-
-class PerformanceMonitor:
- """Main performance monitoring system."""
-
- def __init__(self, db_path: str = "performance_metrics.db"):
- self.db = PerformanceDatabase(db_path)
- self.collector = SwarmMetricsCollector()
- self.alerts: List[PerformanceAlert] = []
- self._setup_default_alerts()
-
- # Register metrics callback
- self.collector.add_metrics_callback(self._on_metrics_collected)
-
- def _setup_default_alerts(self):
- """Setup default performance alerts."""
- self.alerts = [
- PerformanceAlert(
- metric_name="swarm_init_time",
- threshold_value=5.0,
- comparison="greater",
- severity="warning",
- message="Swarm initialization time exceeded 5 seconds",
- timestamp=datetime.now()
- ),
- PerformanceAlert(
- metric_name="agent_coordination_latency",
- threshold_value=200.0,
- comparison="greater",
- severity="warning",
- message="Agent coordination latency exceeded 200ms",
- timestamp=datetime.now()
- ),
- PerformanceAlert(
- metric_name="memory_usage_mb",
- threshold_value=100.0,
- comparison="greater",
- severity="critical",
- message="Memory usage exceeded 100MB",
- timestamp=datetime.now()
- ),
- PerformanceAlert(
- metric_name="mcp_response_time",
- threshold_value=1.0,
- comparison="greater",
- severity="warning",
- message="MCP response time exceeded 1 second",
- timestamp=datetime.now()
- )
- ]
-
- def start_monitoring(self, interval_seconds: float = 10.0, session_id: str = None):
- """Start continuous performance monitoring."""
- logger.info("Starting performance monitoring...")
- self.collector.start_collection(interval_seconds, session_id)
-
- def stop_monitoring(self):
- """Stop performance monitoring."""
- logger.info("Stopping performance monitoring...")
- self.collector.stop_collection()
-
- def _on_metrics_collected(self, metrics: MetricSnapshot):
- """Handle newly collected metrics."""
- # Store in database
- self.db.store_metrics(
- metrics,
- session_id=self.collector.current_session_id,
- operation_type="continuous_monitoring"
- )
-
- # Check alerts
- self._check_alerts(metrics)
-
- # Update baselines (every 100 samples)
- if hash(metrics.timestamp) % 100 == 0:
- self._update_baselines(metrics)
-
- # Log summary
- logger.info(f"Metrics collected - Memory: {metrics.memory_usage_mb:.1f}MB, "
- f"CPU: {metrics.cpu_usage_percent:.1f}%, "
- f"Agents: {metrics.active_agents}")
-
- def _check_alerts(self, metrics: MetricSnapshot):
- """Check if any alerts should be triggered."""
- metrics_dict = metrics.to_dict()
-
- for alert in self.alerts:
- if alert.metric_name in metrics_dict:
- current_value = metrics_dict[alert.metric_name]
-
- if isinstance(current_value, (int, float)) and alert.should_trigger(current_value):
- # Store alert
- self.db.store_alert(alert, current_value)
-
- # Log alert
- logger.warning(f"ALERT [{alert.severity.upper()}] {alert.message} "
- f"(Value: {current_value}, Threshold: {alert.threshold_value})")
-
- # Could send notifications here (email, slack, etc.)
- self._send_notification(alert, current_value)
-
- def _update_baselines(self, metrics: MetricSnapshot):
- """Update performance baselines with current metrics."""
- metrics_dict = metrics.to_dict()
-
- for metric_name, value in metrics_dict.items():
- if isinstance(value, (int, float)) and metric_name != 'timestamp':
- self.db.update_baseline(metric_name, value)
-
- def _send_notification(self, alert: PerformanceAlert, actual_value: float):
- """Send performance alert notification."""
- # This would integrate with notification systems
- # For now, just log the notification
- logger.info(f"NOTIFICATION: {alert.message} (Value: {actual_value})")
-
- def get_performance_dashboard_data(self, hours: int = 24) -> Dict[str, Any]:
- """Get data for performance dashboard."""
- recent_metrics = self.db.get_recent_metrics(hours)
-
- if not recent_metrics:
- return {"error": "No recent metrics available"}
-
- # Calculate aggregated statistics
- init_times = [m.swarm_init_time for m in recent_metrics if m.swarm_init_time > 0]
- coordination_latencies = [m.agent_coordination_latency for m in recent_metrics if m.agent_coordination_latency > 0]
- memory_usage = [m.memory_usage_mb for m in recent_metrics]
-
- dashboard_data = {
- "summary": {
- "total_samples": len(recent_metrics),
- "time_range_hours": hours,
- "last_update": recent_metrics[0].timestamp.isoformat() if recent_metrics else None
- },
- "swarm_performance": {
- "avg_init_time": statistics.mean(init_times) if init_times else 0,
- "max_init_time": max(init_times) if init_times else 0,
- "avg_coordination_latency": statistics.mean(coordination_latencies) if coordination_latencies else 0,
- "max_coordination_latency": max(coordination_latencies) if coordination_latencies else 0
- },
- "resource_usage": {
- "avg_memory_mb": statistics.mean(memory_usage) if memory_usage else 0,
- "peak_memory_mb": max(memory_usage) if memory_usage else 0,
- "memory_trend": "increasing" if len(memory_usage) > 1 and memory_usage[-1] > memory_usage[0] else "stable"
- },
- "time_series": [m.to_dict() for m in recent_metrics[-100:]], # Last 100 samples for charts
- "baselines": {
- "swarm_init_time": self.db.get_baseline("swarm_init_time"),
- "agent_coordination_latency": self.db.get_baseline("agent_coordination_latency"),
- "memory_usage_mb": self.db.get_baseline("memory_usage_mb")
- }
- }
-
- return dashboard_data
-
- def generate_regression_report(self) -> Dict[str, Any]:
- """Generate performance regression analysis report."""
- recent_metrics = self.db.get_recent_metrics(24) # Last 24 hours
- older_metrics = self.db.get_recent_metrics(168) # Last 7 days
-
- if len(recent_metrics) < 10 or len(older_metrics) < 50:
- return {"error": "Insufficient data for regression analysis"}
-
- # Calculate recent vs historical averages
- recent_avg_init = statistics.mean([m.swarm_init_time for m in recent_metrics if m.swarm_init_time > 0])
- historical_avg_init = statistics.mean([m.swarm_init_time for m in older_metrics if m.swarm_init_time > 0])
-
- recent_avg_memory = statistics.mean([m.memory_usage_mb for m in recent_metrics])
- historical_avg_memory = statistics.mean([m.memory_usage_mb for m in older_metrics])
-
- # Calculate regression percentages
- init_regression = ((recent_avg_init - historical_avg_init) / historical_avg_init) * 100 if historical_avg_init > 0 else 0
- memory_regression = ((recent_avg_memory - historical_avg_memory) / historical_avg_memory) * 100 if historical_avg_memory > 0 else 0
-
- return {
- "analysis_period": {
- "recent_period_hours": 24,
- "historical_period_hours": 168,
- "recent_samples": len(recent_metrics),
- "historical_samples": len(older_metrics)
- },
- "regression_analysis": {
- "swarm_init_time": {
- "recent_avg": recent_avg_init,
- "historical_avg": historical_avg_init,
- "regression_percent": init_regression,
- "regression_detected": abs(init_regression) > 10 # 10% threshold
- },
- "memory_usage": {
- "recent_avg": recent_avg_memory,
- "historical_avg": historical_avg_memory,
- "regression_percent": memory_regression,
- "regression_detected": abs(memory_regression) > 15 # 15% threshold
- }
- },
- "recommendations": self._generate_regression_recommendations(init_regression, memory_regression)
- }
-
- def _generate_regression_recommendations(self, init_regression: float, memory_regression: float) -> List[str]:
- """Generate recommendations based on regression analysis."""
- recommendations = []
-
- if init_regression > 10:
- recommendations.append("Swarm initialization time has regressed by >10% - investigate startup optimizations")
-
- if memory_regression > 15:
- recommendations.append("Memory usage has increased by >15% - check for memory leaks")
-
- if init_regression < -10:
- recommendations.append("Swarm initialization time has improved significantly - consider documenting optimizations")
-
- if not recommendations:
- recommendations.append("No significant performance regressions detected")
-
- return recommendations
-
-
-async def run_continuous_monitoring(duration_minutes: int = 60, interval_seconds: float = 10.0):
- """Run continuous monitoring for specified duration."""
- monitor = PerformanceMonitor()
-
- try:
- # Start monitoring
- session_id = f"continuous_{int(time.time())}"
- monitor.start_monitoring(interval_seconds, session_id)
-
- logger.info(f"Running continuous monitoring for {duration_minutes} minutes...")
-
- # Run for specified duration
- await asyncio.sleep(duration_minutes * 60)
-
- # Generate reports
- dashboard_data = monitor.get_performance_dashboard_data()
- regression_report = monitor.generate_regression_report()
-
- # Save reports
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
-
- dashboard_file = Path(f"dashboard_data_{timestamp}.json")
- with open(dashboard_file, 'w') as f:
- json.dump(dashboard_data, f, indent=2, default=str)
-
- regression_file = Path(f"regression_report_{timestamp}.json")
- with open(regression_file, 'w') as f:
- json.dump(regression_report, f, indent=2, default=str)
-
- logger.info(f"Reports saved: {dashboard_file}, {regression_file}")
-
- return {
- "monitoring_duration_minutes": duration_minutes,
- "dashboard_data": dashboard_data,
- "regression_report": regression_report
- }
-
- finally:
- monitor.stop_monitoring()
-
-
-def main():
- """Main entry point for continuous performance monitoring."""
- import argparse
-
- parser = argparse.ArgumentParser(description="Continuous Performance Monitor")
- parser.add_argument("--duration", type=int, default=60, help="Monitoring duration in minutes")
- parser.add_argument("--interval", type=float, default=10.0, help="Collection interval in seconds")
- parser.add_argument("--dashboard", action="store_true", help="Generate dashboard data only")
- parser.add_argument("--regression", action="store_true", help="Generate regression report only")
-
- args = parser.parse_args()
-
- if args.dashboard:
- # Generate dashboard data
- monitor = PerformanceMonitor()
- data = monitor.get_performance_dashboard_data()
- print(json.dumps(data, indent=2, default=str))
- elif args.regression:
- # Generate regression report
- monitor = PerformanceMonitor()
- report = monitor.generate_regression_report()
- print(json.dumps(report, indent=2, default=str))
- else:
- # Run continuous monitoring
- asyncio.run(run_continuous_monitoring(args.duration, args.interval))
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/benchmark/demo_comprehensive.py b/benchmark/demo_comprehensive.py
deleted file mode 100644
index 3312f998cc..0000000000
--- a/benchmark/demo_comprehensive.py
+++ /dev/null
@@ -1,233 +0,0 @@
-#!/usr/bin/env python3
-"""Comprehensive demonstration of the swarm benchmarking tool."""
-
-import asyncio
-import json
-import sys
-from pathlib import Path
-
-# Add the src directory to Python path
-sys.path.insert(0, str(Path(__file__).parent / "src"))
-from swarm_benchmark.core.benchmark_engine import BenchmarkEngine
-from swarm_benchmark.core.models import BenchmarkConfig, StrategyType, CoordinationMode
-
-
-async def run_comprehensive_demo():
- """Run a comprehensive demonstration of all features."""
- print("πŸš€ Starting Comprehensive Swarm Benchmark Demonstration")
- print("=" * 60)
-
- # Test scenarios with different strategy/mode combinations
- test_scenarios = [
- {
- "name": "Auto Strategy - Centralized",
- "objective": "Build a user authentication system",
- "strategy": StrategyType.AUTO,
- "mode": CoordinationMode.CENTRALIZED,
- "max_agents": 3
- },
- {
- "name": "Research Strategy - Distributed",
- "objective": "Research cloud architecture patterns and best practices",
- "strategy": StrategyType.RESEARCH,
- "mode": CoordinationMode.DISTRIBUTED,
- "max_agents": 5
- },
- {
- "name": "Development Strategy - Hierarchical",
- "objective": "Develop a microservices REST API with authentication",
- "strategy": StrategyType.DEVELOPMENT,
- "mode": CoordinationMode.HIERARCHICAL,
- "max_agents": 6
- },
- {
- "name": "Analysis Strategy - Mesh",
- "objective": "Analyze user behavior patterns and generate insights",
- "strategy": StrategyType.ANALYSIS,
- "mode": CoordinationMode.MESH,
- "max_agents": 4
- },
- {
- "name": "Optimization Strategy - Hybrid",
- "objective": "Optimize database queries and improve application performance",
- "strategy": StrategyType.OPTIMIZATION,
- "mode": CoordinationMode.HYBRID,
- "max_agents": 7
- },
- {
- "name": "Testing Strategy - Distributed",
- "objective": "Create comprehensive test suite with unit and integration tests",
- "strategy": StrategyType.TESTING,
- "mode": CoordinationMode.DISTRIBUTED,
- "max_agents": 4
- },
- {
- "name": "Maintenance Strategy - Centralized",
- "objective": "Update documentation and refactor legacy code components",
- "strategy": StrategyType.MAINTENANCE,
- "mode": CoordinationMode.CENTRALIZED,
- "max_agents": 2
- }
- ]
-
- results_summary = []
-
- for i, scenario in enumerate(test_scenarios, 1):
- print(f"\nπŸ“‹ Test {i}/{len(test_scenarios)}: {scenario['name']}")
- print(f" Objective: {scenario['objective']}")
- print(f" Strategy: {scenario['strategy'].value}")
- print(f" Mode: {scenario['mode'].value}")
- print(f" Agents: {scenario['max_agents']}")
-
- # Create configuration
- config = BenchmarkConfig(
- name=f"demo-{scenario['strategy'].value}-{scenario['mode'].value}",
- description=f"Demo: {scenario['name']}",
- strategy=scenario['strategy'],
- mode=scenario['mode'],
- max_agents=scenario['max_agents'],
- output_formats=["json"],
- output_directory="./demo_reports",
- verbose=True
- )
-
- # Run benchmark
- engine = BenchmarkEngine(config)
-
- try:
- result = await engine.run_benchmark(scenario['objective'])
-
- if result['status'] == 'success':
- print(f" βœ… Success - Duration: {result['duration']:.2f}s")
-
- # Extract key metrics
- if result['results']:
- first_result = result['results'][0]
- execution_time = first_result.get('execution_time', 0)
- cpu_usage = first_result.get('resource_usage', {}).get('cpu_percent', 0)
- memory_usage = first_result.get('resource_usage', {}).get('memory_mb', 0)
-
- summary = {
- 'scenario': scenario['name'],
- 'strategy': scenario['strategy'].value,
- 'mode': scenario['mode'].value,
- 'agents': scenario['max_agents'],
- 'duration': result['duration'],
- 'execution_time': execution_time,
- 'cpu_usage': cpu_usage,
- 'memory_usage': memory_usage,
- 'status': 'success'
- }
- else:
- summary = {
- 'scenario': scenario['name'],
- 'strategy': scenario['strategy'].value,
- 'mode': scenario['mode'].value,
- 'agents': scenario['max_agents'],
- 'duration': result['duration'],
- 'status': 'success'
- }
- else:
- print(f" ❌ Failed - Error: {result.get('error', 'Unknown error')}")
- summary = {
- 'scenario': scenario['name'],
- 'strategy': scenario['strategy'].value,
- 'mode': scenario['mode'].value,
- 'agents': scenario['max_agents'],
- 'status': 'failed',
- 'error': result.get('error', 'Unknown error')
- }
-
- results_summary.append(summary)
-
- except Exception as e:
- print(f" ❌ Exception: {e}")
- results_summary.append({
- 'scenario': scenario['name'],
- 'strategy': scenario['strategy'].value,
- 'mode': scenario['mode'].value,
- 'agents': scenario['max_agents'],
- 'status': 'exception',
- 'error': str(e)
- })
-
- # Small delay between tests
- await asyncio.sleep(0.5)
-
- # Generate summary report
- print("\n" + "=" * 60)
- print("πŸ“Š BENCHMARK SUMMARY REPORT")
- print("=" * 60)
-
- successful_tests = [r for r in results_summary if r['status'] == 'success']
- failed_tests = [r for r in results_summary if r['status'] != 'success']
-
- print(f"βœ… Successful Tests: {len(successful_tests)}/{len(test_scenarios)}")
- print(f"❌ Failed Tests: {len(failed_tests)}")
-
- if successful_tests:
- print("\nπŸ† Performance Metrics:")
- avg_duration = sum(r.get('duration', 0) for r in successful_tests) / len(successful_tests)
- avg_execution = sum(r.get('execution_time', 0) for r in successful_tests) / len(successful_tests)
-
- print(f" Average Benchmark Duration: {avg_duration:.2f}s")
- print(f" Average Task Execution Time: {avg_execution:.2f}s")
-
- # Strategy performance
- print("\nπŸ“ˆ Strategy Performance:")
- strategy_performance = {}
- for result in successful_tests:
- strategy = result['strategy']
- if strategy not in strategy_performance:
- strategy_performance[strategy] = []
- strategy_performance[strategy].append(result.get('duration', 0))
-
- for strategy, durations in strategy_performance.items():
- avg_duration = sum(durations) / len(durations)
- print(f" {strategy.capitalize()}: {avg_duration:.2f}s avg ({len(durations)} tests)")
-
- # Coordination mode performance
- print("\nπŸ”— Coordination Mode Performance:")
- mode_performance = {}
- for result in successful_tests:
- mode = result['mode']
- if mode not in mode_performance:
- mode_performance[mode] = []
- mode_performance[mode].append(result.get('duration', 0))
-
- for mode, durations in mode_performance.items():
- avg_duration = sum(durations) / len(durations)
- print(f" {mode.capitalize()}: {avg_duration:.2f}s avg ({len(durations)} tests)")
-
- if failed_tests:
- print(f"\n❌ Failed Tests:")
- for test in failed_tests:
- print(f" {test['scenario']}: {test.get('error', 'Unknown error')}")
-
- # Save detailed summary
- summary_path = Path("./demo_reports/benchmark_summary.json")
- summary_path.parent.mkdir(exist_ok=True)
-
- with open(summary_path, 'w') as f:
- json.dump({
- "demonstration_results": results_summary,
- "summary_statistics": {
- "total_tests": len(test_scenarios),
- "successful_tests": len(successful_tests),
- "failed_tests": len(failed_tests),
- "success_rate": len(successful_tests) / len(test_scenarios) * 100,
- "strategy_coverage": len(set(r['strategy'] for r in results_summary)),
- "mode_coverage": len(set(r['mode'] for r in results_summary))
- }
- }, f, indent=2)
-
- print(f"\nπŸ’Ύ Detailed summary saved to: {summary_path}")
- print(f"πŸ“ Individual benchmark reports saved to: ./demo_reports/")
-
- print("\nπŸŽ‰ Comprehensive demonstration completed!")
-
- return results_summary
-
-
-if __name__ == "__main__":
- results = asyncio.run(run_comprehensive_demo())
\ No newline at end of file
diff --git a/benchmark/demo_mle_star.py b/benchmark/demo_mle_star.py
deleted file mode 100644
index 94730af818..0000000000
--- a/benchmark/demo_mle_star.py
+++ /dev/null
@@ -1,152 +0,0 @@
-#!/usr/bin/env python3
-"""
-MLE-STAR Ensemble Demo
-
-Demonstrates the MLE-STAR ensemble integration with proper training
-and prediction workflow.
-"""
-
-import asyncio
-import sys
-import os
-import numpy as np
-import logging
-
-# Add the src directory to Python path
-sys.path.insert(0, str(Path(__file__).parent / "src"))
-
-from swarm_benchmark.mle_star import (
- MLEStarEnsembleExecutor, MLEStarConfig,
- MajorityVoting, WeightedVoting, BayesianAveraging
-)
-
-
-async def demo_simple_ensemble():
- """Demonstrate simple ensemble with synthetic data."""
- print("🧠 MLE-STAR Ensemble Integration Demo")
- print("=" * 50)
-
- # Configure logging to reduce noise
- logging.basicConfig(level=logging.WARNING)
-
- # Create simple test data
- print("πŸ“Š Generating test data...")
- np.random.seed(42)
- X_train = np.random.randn(100, 5)
- y_train = np.random.randint(0, 3, 100)
- X_test = np.random.randn(20, 5)
- y_test = np.random.randint(0, 3, 20)
-
- # Configure ensemble
- config = MLEStarConfig(
- models=[
- {"type": "random_forest", "n_estimators": 10, "task": "classification"},
- {"type": "logistic_regression", "C": 1.0, "max_iter": 100, "task": "classification"},
- ],
- voting_strategy="majority",
- ensemble_size=2,
- max_parallel=2
- )
-
- print(f"πŸ”§ Configured ensemble with {len(config.models)} models")
- print(f" - Voting strategy: {config.voting_strategy}")
-
- # Create ensemble
- ensemble = MLEStarEnsembleExecutor(config)
-
- try:
- # Manually train models for this demo
- print("πŸ‹οΈ Training models...")
-
- await ensemble._initialize_models_parallel()
- print(f" - Initialized {len(ensemble.models)} models")
-
- # Train each model manually for demo
- for i, model_agent in enumerate(ensemble.models):
- success = await model_agent.train(X_train, y_train)
- print(f" - Model {i} training: {'SUCCESS' if success else 'FAILED'}")
-
- # Make predictions
- print("🎯 Making predictions...")
- predictions = await ensemble._gather_predictions(X_test)
- print(f" - Gathered {len(predictions)} predictions")
-
- # Build consensus
- final_prediction, consensus_details = await ensemble._build_consensus(predictions)
- print(f" - Final prediction shape: {np.array(final_prediction).shape}")
- print(f" - Consensus strength: {consensus_details.get('consensus_strength', 'N/A')}")
-
- # Test different voting strategies
- print("\nπŸ—³οΈ Testing voting strategies:")
-
- # Test with simple numeric predictions for demo
- test_preds = [[0.7, 0.2, 0.1], [0.6, 0.3, 0.1], [0.8, 0.1, 0.1]]
-
- majority = MajorityVoting()
- majority_result = await majority.vote(test_preds)
- print(f" - Majority voting: {majority_result}")
-
- weighted = WeightedVoting(weights=[0.4, 0.4, 0.2])
- weighted_result = await weighted.vote(test_preds)
- print(f" - Weighted voting: {weighted_result}")
-
- bayesian = BayesianAveraging()
- bayesian_result = await bayesian.vote(test_preds)
- print(f" - Bayesian averaging: {bayesian_result}")
-
- print("\nβœ… Demo completed successfully!")
-
- except Exception as e:
- print(f"❌ Demo failed: {e}")
- import traceback
- traceback.print_exc()
-
- finally:
- # Cleanup
- await ensemble.cleanup()
-
-
-async def demo_performance_tracking():
- """Demonstrate performance tracking capabilities."""
- print("\nπŸ“ˆ Performance Tracking Demo")
- print("-" * 30)
-
- from swarm_benchmark.mle_star.performance_tracker import PerformanceTracker
-
- tracker = PerformanceTracker()
-
- # Start tracking
- await tracker.start_tracking_session("demo_session")
-
- # Register some models
- tracker.register_model("rf_model", "random_forest")
- tracker.register_model("lr_model", "logistic_regression")
-
- # Simulate some metrics
- tracker.record_training_time("rf_model", 2.5)
- tracker.record_training_time("lr_model", 1.2)
-
- tracker.record_prediction_time("rf_model", 0.1)
- tracker.record_prediction_time("lr_model", 0.05)
-
- tracker.record_model_accuracy("rf_model", accuracy=0.85, precision=0.82)
- tracker.record_model_accuracy("lr_model", accuracy=0.80, precision=0.78)
-
- # Get performance summary
- summary = tracker.get_performance_summary()
-
- print(f"πŸ“Š Performance Summary:")
- print(f" - Models tracked: {len(summary['model_performances'])}")
- for model_id, perf in summary['model_performances'].items():
- print(f" - {model_id}:")
- print(f" β€’ Training time: {perf['training_time']:.2f}s")
- print(f" β€’ Accuracy: {perf['accuracy']}")
- print(f" β€’ Success rate: {perf['success_rate']:.2f}")
-
- await tracker.end_tracking_session()
- print("βœ… Performance tracking demo completed")
-
-
-if __name__ == "__main__":
- asyncio.run(demo_simple_ensemble())
- asyncio.run(demo_performance_tracking())
\ No newline at end of file
diff --git a/benchmark/demo_real_benchmark.py b/benchmark/demo_real_benchmark.py
deleted file mode 100644
index 5698274fb9..0000000000
--- a/benchmark/demo_real_benchmark.py
+++ /dev/null
@@ -1,219 +0,0 @@
-#!/usr/bin/env python3
-"""
-Demo script for the new real claude-flow benchmark system
-Shows how to benchmark actual claude-flow commands with real metrics
-"""
-
-import asyncio
-import json
-from pathlib import Path
-import sys
-
-# Add the benchmark source to path
-sys.path.insert(0, str(Path(__file__).parent / "src"))
-
-from swarm_benchmark.core.claude_flow_executor import (
- ClaudeFlowExecutor, SwarmConfig, SparcConfig,
- ExecutionStrategy, CoordinationMode
-)
-from swarm_benchmark.metrics.performance_collector import PerformanceCollector
-from swarm_benchmark.core.parallel_executor import ParallelExecutor, ExecutionMode
-from swarm_benchmark.core.orchestration_manager import OrchestrationManager
-
-
-async def demo_basic_benchmark():
- """Demonstrate basic benchmarking with real claude-flow execution"""
- print("\nπŸš€ Demo 1: Basic Real Benchmark")
- print("=" * 60)
-
- executor = ClaudeFlowExecutor()
-
- # Test 1: Simple SPARC mode
- print("\nπŸ“Š Testing SPARC Coder Mode:")
- sparc_config = SparcConfig(
- mode="coder",
- prompt="Create a fibonacci function in Python"
- )
-
- result = executor.execute_sparc(sparc_config)
- print(f"βœ… Success: {result.success}")
- print(f"⏱️ Execution Time: {result.execution_time:.2f}s")
- print(f"πŸ’Ύ Memory Used: {result.metrics.get('peak_memory_mb', 0):.1f}MB")
-
- # Test 2: Swarm execution
- print("\nπŸ“Š Testing Swarm Research Strategy:")
- swarm_config = SwarmConfig(
- objective="Research best practices for Python async programming",
- strategy=ExecutionStrategy.RESEARCH,
- mode=CoordinationMode.DISTRIBUTED,
- max_agents=3
- )
-
- result = executor.execute_swarm(swarm_config)
- print(f"βœ… Success: {result.success}")
- print(f"⏱️ Execution Time: {result.execution_time:.2f}s")
- print(f"πŸ“‹ Output Lines: {result.metrics.get('output_lines', 0)}")
-
-
-async def demo_parallel_benchmark():
- """Demonstrate parallel benchmark execution"""
- print("\n\nπŸš€ Demo 2: Parallel Benchmark Execution")
- print("=" * 60)
-
- parallel_executor = ParallelExecutor(
- max_workers=4,
- mode=ExecutionMode.THREAD,
- resource_limits={'cpu_percent': 80, 'memory_mb': 2048}
- )
-
- # Create multiple benchmark tasks
- tasks = [
- {
- 'name': 'sparc_coder',
- 'func': lambda: ClaudeFlowExecutor().execute_sparc(
- SparcConfig(mode="coder", prompt="Write a sorting algorithm")
- ),
- 'priority': 1
- },
- {
- 'name': 'sparc_tester',
- 'func': lambda: ClaudeFlowExecutor().execute_sparc(
- SparcConfig(mode="tester", prompt="Test a login function")
- ),
- 'priority': 2
- },
- {
- 'name': 'swarm_development',
- 'func': lambda: ClaudeFlowExecutor().execute_swarm(
- SwarmConfig(
- objective="Build a simple TODO API",
- strategy=ExecutionStrategy.DEVELOPMENT,
- max_agents=3
- )
- ),
- 'priority': 1
- }
- ]
-
- print("πŸ“‹ Submitting 3 benchmark tasks...")
- futures = []
- for task in tasks:
- future = await parallel_executor.submit_task(
- task['func'],
- priority=task['priority'],
- task_name=task['name']
- )
- futures.append((task['name'], future))
-
- print("⏳ Waiting for completion...")
- for name, future in futures:
- try:
- result = await future
- print(f"βœ… {name}: Success={result.success}, Time={result.execution_time:.2f}s")
- except Exception as e:
- print(f"❌ {name}: Failed - {str(e)}")
-
- # Show metrics
- metrics = parallel_executor.get_metrics()
- print(f"\nπŸ“Š Parallel Execution Metrics:")
- print(f" - Total Tasks: {metrics['total_tasks']}")
- print(f" - Success Rate: {metrics['success_rate']:.1%}")
- print(f" - Avg Execution Time: {metrics['avg_execution_time']:.2f}s")
- print(f" - Peak Workers: {metrics['peak_workers']}")
-
-
-async def demo_comprehensive_benchmark():
- """Demonstrate comprehensive benchmarking with orchestration"""
- print("\n\nπŸš€ Demo 3: Comprehensive Benchmark Suite")
- print("=" * 60)
-
- orchestrator = OrchestrationManager()
-
- # Define benchmark suite
- benchmarks = [
- {
- 'name': 'SPARC Modes Test',
- 'mode': 'sparc',
- 'configs': [
- SparcConfig(mode="coder", prompt="Implement binary search"),
- SparcConfig(mode="reviewer", prompt="Review this code for security"),
- SparcConfig(mode="optimizer", prompt="Optimize database queries")
- ]
- },
- {
- 'name': 'Swarm Strategies Test',
- 'mode': 'swarm',
- 'configs': [
- SwarmConfig(
- objective="Create user authentication system",
- strategy=ExecutionStrategy.DEVELOPMENT,
- mode=CoordinationMode.HIERARCHICAL
- ),
- SwarmConfig(
- objective="Research microservices patterns",
- strategy=ExecutionStrategy.RESEARCH,
- mode=CoordinationMode.DISTRIBUTED
- )
- ]
- }
- ]
-
- print("πŸ“‹ Running comprehensive benchmark suite...")
- results = await orchestrator.run_parallel_benchmarks(
- benchmarks,
- max_parallel=3,
- monitor_resources=True
- )
-
- # Generate report
- print("\nπŸ“Š Benchmark Results Summary:")
- for suite_name, suite_results in results.items():
- print(f"\n {suite_name}:")
- success_count = sum(1 for r in suite_results if r.get('success', False))
- total_count = len(suite_results)
- avg_time = sum(r.get('execution_time', 0) for r in suite_results) / total_count
-
- print(f" - Success Rate: {success_count}/{total_count} ({success_count/total_count:.1%})")
- print(f" - Avg Execution Time: {avg_time:.2f}s")
-
- for result in suite_results:
- status = "βœ…" if result.get('success', False) else "❌"
- print(f" {status} {result.get('task_name', 'Unknown')}: {result.get('execution_time', 0):.2f}s")
-
- # Save detailed report
- report_path = Path(__file__).parent / "real_benchmark_report.json"
- with open(report_path, 'w') as f:
- json.dump(results, f, indent=2, default=str)
- print(f"\nπŸ’Ύ Detailed report saved to: {report_path}")
-
-
-async def main():
- """Run all demos"""
- print("🧠 Claude-Flow Real Benchmark System Demo")
- print("=" * 60)
- print("This demo showcases the new benchmark system that executes")
- print("real claude-flow commands and measures actual performance.")
-
- try:
- # Run demos
- await demo_basic_benchmark()
- await demo_parallel_benchmark()
- await demo_comprehensive_benchmark()
-
- print("\n\nβœ… All demos completed successfully!")
- print("\nKey Features Demonstrated:")
- print(" β€’ Real claude-flow command execution")
- print(" β€’ Accurate performance metrics collection")
- print(" β€’ Parallel benchmark execution")
- print(" β€’ Resource monitoring and limits")
- print(" β€’ Comprehensive test orchestration")
- print(" β€’ Support for all SPARC modes and swarm strategies")
-
- except Exception as e:
- print(f"\n❌ Demo failed: {str(e)}")
- import traceback
- traceback.print_exc()
-
-
-if __name__ == "__main__":
- asyncio.run(main())
\ No newline at end of file
diff --git a/benchmark/example_usage.py b/benchmark/example_usage.py
deleted file mode 100644
index 1298dc3b89..0000000000
--- a/benchmark/example_usage.py
+++ /dev/null
@@ -1,249 +0,0 @@
-#!/usr/bin/env python3
-"""
-Example usage of the claude-flow integration layer.
-
-This script demonstrates how to use the ClaudeFlowExecutor for various tasks.
-"""
-
-import sys
-import json
-from pathlib import Path
-
-# Add benchmark src to path
-sys.path.insert(0, str(Path(__file__).parent / "src"))
-
-from swarm_benchmark.core.claude_flow_executor import (
- ClaudeFlowExecutor, SwarmConfig, SparcConfig,
- ExecutionStrategy, CoordinationMode, SparcMode, OutputFormat
-)
-from swarm_benchmark.core.integration_utils import (
- OutputParser, ErrorHandler, performance_monitoring
-)
-
-
-def example_basic_swarm():
- """Example: Basic swarm execution with dry run."""
- print("\n=== Example: Basic Swarm Execution ===")
-
- executor = ClaudeFlowExecutor()
-
- # Configure swarm
- config = SwarmConfig(
- objective="Create a Python REST API with FastAPI",
- strategy=ExecutionStrategy.DEVELOPMENT,
- mode=CoordinationMode.HIERARCHICAL,
- max_agents=5,
- parallel=True,
- monitor=True,
- dry_run=True # Dry run to see what would happen
- )
-
- print(f"πŸ“‹ Configuration:")
- print(json.dumps(config.to_dict(), indent=2))
-
- # Execute
- result = executor.execute_swarm(config)
-
- print(f"\nπŸ“Š Results:")
- print(f" Success: {result.success}")
- print(f" Duration: {result.duration:.2f}s")
- print(f" Command: {' '.join(result.command)}")
-
- if result.stdout:
- print(f"\nπŸ“„ Output:")
- print(result.stdout)
-
-
-def example_research_swarm():
- """Example: Research swarm with output parsing."""
- print("\n=== Example: Research Swarm ===")
-
- executor = ClaudeFlowExecutor()
-
- config = SwarmConfig(
- objective="Research best practices for microservices architecture",
- strategy=ExecutionStrategy.RESEARCH,
- mode=CoordinationMode.DISTRIBUTED,
- max_agents=8,
- parallel=True,
- batch_optimized=True,
- memory_shared=True,
- output=OutputFormat.JSON,
- output_dir="./research_output",
- dry_run=True
- )
-
- # Execute with performance monitoring
- with performance_monitoring() as monitor:
- result = executor.execute_swarm(config)
-
- # Parse output
- if result.stdout:
- parsed = OutputParser.parse_output(result.stdout)
- print(f"\nπŸ“Š Parsed Results:")
- print(f" Agents started: {parsed['agents']['started']}")
- print(f" Tasks created: {parsed['tasks']['created']}")
- print(f" Memory keys: {parsed['memory_keys']}")
-
-
-def example_sparc_modes():
- """Example: Using different SPARC modes."""
- print("\n=== Example: SPARC Modes ===")
-
- executor = ClaudeFlowExecutor()
-
- # Example 1: TDD mode
- tdd_config = SparcConfig(
- prompt="Create unit tests for a user authentication module",
- mode=SparcMode.TDD,
- memory_key="auth_tests",
- parallel=True
- )
-
- print("\n1. TDD Mode:")
- print(f" Command: claude-flow sparc run {tdd_config.mode.value} \"{tdd_config.prompt}\"")
-
- # Example 2: Optimizer mode
- optimizer_config = SparcConfig(
- prompt="Optimize database queries for better performance",
- mode=SparcMode.OPTIMIZER,
- memory_key="db_optimization",
- batch=True
- )
-
- print("\n2. Optimizer Mode:")
- print(f" Command: claude-flow sparc run {optimizer_config.mode.value} \"{optimizer_config.prompt}\"")
-
- # Example 3: Workflow manager
- workflow_config = SparcConfig(
- prompt="Orchestrate CI/CD pipeline setup",
- mode=SparcMode.WORKFLOW_MANAGER,
- monitor=True
- )
-
- print("\n3. Workflow Manager Mode:")
- print(f" Command: claude-flow sparc run {workflow_config.mode.value} \"{workflow_config.prompt}\"")
-
-
-def example_error_handling():
- """Example: Handling errors and retries."""
- print("\n=== Example: Error Handling ===")
-
- executor = ClaudeFlowExecutor(
- retry_attempts=3,
- retry_delay=2.0
- )
-
- # Simulate a command that might fail
- config = SwarmConfig(
- objective="Complex task that might timeout",
- timeout=1, # Very short timeout
- dry_run=True
- )
-
- result = executor.execute_swarm(config)
-
- if not result.success:
- error_category = ErrorHandler.categorize_error(result.stderr)
- suggestion = ErrorHandler.get_recovery_suggestion(error_category)
-
- print(f"❌ Execution failed:")
- print(f" Category: {error_category}")
- print(f" Suggestion: {suggestion}")
- print(f" Should retry: {ErrorHandler.should_retry(error_category)}")
-
-
-def example_batch_operations():
- """Example: Batch operations for testing."""
- print("\n=== Example: Batch Testing Operations ===")
-
- executor = ClaudeFlowExecutor()
-
- config = SwarmConfig(
- objective="Run comprehensive test suite with coverage analysis",
- strategy=ExecutionStrategy.TESTING,
- mode=CoordinationMode.DISTRIBUTED,
- max_agents=12,
- parallel=True,
- test_types=["unit", "integration", "e2e", "performance"],
- coverage_target=90,
- file_ops_parallel=True,
- output=OutputFormat.HTML,
- output_dir="./test_reports",
- dry_run=True
- )
-
- print("πŸ“‹ Test Configuration:")
- print(f" Test types: {config.test_types}")
- print(f" Coverage target: {config.coverage_target}%")
- print(f" Parallel execution: {config.parallel}")
- print(f" Max agents: {config.max_agents}")
-
- result = executor.execute_swarm(config)
-
- if result.success:
- print("\nβœ… Test execution configured successfully")
-
-
-def example_memory_operations():
- """Example: Using memory for cross-session data."""
- print("\n=== Example: Memory Operations ===")
-
- executor = ClaudeFlowExecutor()
-
- # Store data in memory
- test_data = {
- "project": "claude-flow-benchmark",
- "metrics": {
- "performance": 95,
- "reliability": 98,
- "scalability": 92
- },
- "timestamp": "2025-06-17T10:00:00Z"
- }
-
- print("πŸ’Ύ Storing data in memory...")
- store_result = executor.execute_memory_store("benchmark_results", test_data)
-
- if store_result.success:
- print("βœ… Data stored successfully")
-
- # Retrieve data
- print("\nπŸ“₯ Retrieving data from memory...")
- get_result, retrieved_data = executor.execute_memory_get("benchmark_results")
-
- if get_result.success and retrieved_data:
- print("βœ… Data retrieved:")
- print(json.dumps(retrieved_data, indent=2))
-
-
-def main():
- """Run all examples."""
- print("πŸš€ Claude-Flow Integration Examples")
- print("=" * 50)
-
- examples = [
- ("Basic Swarm", example_basic_swarm),
- ("Research Swarm", example_research_swarm),
- ("SPARC Modes", example_sparc_modes),
- ("Error Handling", example_error_handling),
- ("Batch Operations", example_batch_operations),
- ("Memory Operations", example_memory_operations)
- ]
-
- for name, func in examples:
- try:
- func()
- except Exception as e:
- print(f"\n❌ Example '{name}' failed: {e}")
-
- print("\nβœ… Examples completed!")
- print("\nFor production use:")
- print(" - Remove dry_run=True to execute real commands")
- print(" - Set appropriate timeouts for your workloads")
- print(" - Monitor performance metrics for optimization")
- print(" - Use memory for cross-agent coordination")
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/benchmark/examples/.claude-flow/metrics/performance.json b/benchmark/examples/.claude-flow/metrics/performance.json
index bbb2224c45..e7767613f1 100644
--- a/benchmark/examples/.claude-flow/metrics/performance.json
+++ b/benchmark/examples/.claude-flow/metrics/performance.json
@@ -1,5 +1,5 @@
{
- "startTime": 1754447041800,
+ "startTime": 1754447048421,
"totalTasks": 1,
"successfulTasks": 1,
"failedTasks": 0,
diff --git a/benchmark/examples/.claude-flow/metrics/task-metrics.json b/benchmark/examples/.claude-flow/metrics/task-metrics.json
index b0336a9123..a6418b36b4 100644
--- a/benchmark/examples/.claude-flow/metrics/task-metrics.json
+++ b/benchmark/examples/.claude-flow/metrics/task-metrics.json
@@ -1,10 +1,10 @@
[
{
- "id": "cmd-hooks-1754447041910",
+ "id": "cmd-hooks-1754447048532",
"type": "hooks",
"success": true,
- "duration": 10.26506599999999,
- "timestamp": 1754447041920,
+ "duration": 6.419533999999999,
+ "timestamp": 1754447048538,
"metadata": {}
}
]
\ No newline at end of file
diff --git a/benchmark/examples/real_hive_mind_benchmark.py b/benchmark/examples/real_hive_mind_benchmark.py
old mode 100644
new mode 100755
diff --git a/benchmark/examples/real_sparc_benchmark.py b/benchmark/examples/real_sparc_benchmark.py
old mode 100644
new mode 100755
diff --git a/benchmark/examples/real_swarm_benchmark.py b/benchmark/examples/real_swarm_benchmark.py
old mode 100644
new mode 100755
diff --git a/benchmark/github_issue_599_comment.md b/benchmark/github_issue_599_comment.md
deleted file mode 100644
index 71f9a74325..0000000000
--- a/benchmark/github_issue_599_comment.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# Agent 3 Validation Report - Issue #599
-
-## βœ… VALIDATION COMPLETE - SUCCESS
-
-**Agent 3 (Test Validator)** has completed comprehensive validation of the Python code reorganization.
-
-### 🎯 Validation Summary
-
-**All critical functionality is working correctly** after the reorganization. The new modular structure maintains backward compatibility while providing improved organization.
-
-### πŸ“Š Test Results
-
-| Test Category | Status | Details |
-|---------------|--------|---------|
-| **Package Imports** | βœ… PASS | All core modules load successfully |
-| **Installation** | βœ… PASS | `pip install -e .` works, CLI functional |
-| **Unit Tests** | βœ… PASS | Core model tests passing |
-| **Example Scripts** | βœ… MOSTLY PASS | 3/6 examples working (minor issues in advanced features) |
-| **CLI Tools** | βœ… PASS | `swarm-benchmark` commands fully functional |
-| **Performance Tools** | βœ… PASS | Dashboard and monitoring tools available |
-
-### πŸ”§ Key Validation Points
-
-- βœ… **Backward compatibility maintained** - existing imports still work
-- βœ… **Package structure correct** - clean `src/swarm_benchmark/` organization
-- βœ… **CLI functional** - `swarm-benchmark run` successfully tested
-- βœ… **Reports generated** - 42+ benchmark reports created automatically
-- βœ… **Version 2.0.0** - package correctly reports new version
-
-### 🚨 Minor Issues Found (Non-blocking)
-
-1. Some SPARC mode methods missing in advanced examples
-2. Agent scheduling type errors in complex parallel scenarios
-3. Optional dependencies gracefully degraded with warnings
-
-**None of these affect core functionality.**
-
-### πŸ“‹ Reorganization Benefits Confirmed
-
-- **Modular structure** enables better maintainability
-- **Lazy imports** prevent circular dependencies
-- **Unified configuration** system working properly
-- **Tool integration** for performance monitoring functional
-
-### 🎯 Final Status
-
-**READY FOR PRODUCTION** βœ…
-
-The reorganized codebase is fully functional and ready for use. Minor issues can be addressed in future updates without blocking current work.
-
-**Full validation report:** `VALIDATION_REPORT.md` created in benchmark directory.
-
----
-**Agent 3 - Test Validator** | Issue #599 Validation Complete
\ No newline at end of file
diff --git a/benchmark/hello_world.py b/benchmark/hello_world.py
deleted file mode 100644
index a16140d6e2..0000000000
--- a/benchmark/hello_world.py
+++ /dev/null
@@ -1,21 +0,0 @@
-"""
-Simple Hello World function in Python
-"""
-
-def hello_world(name: str = "World") -> str:
- """
- Simple Hello World function
-
- Args:
- name (str): Optional name parameter, defaults to 'World'
-
- Returns:
- str: Greeting message
- """
- return f"Hello, {name}!"
-
-
-# Example usage
-if __name__ == "__main__":
- print(hello_world()) # Output: Hello, World!
- print(hello_world("Claude")) # Output: Hello, Claude!
\ No newline at end of file
diff --git a/benchmark/hive-mind-load-test.py b/benchmark/hive-mind-load-test.py
deleted file mode 100644
index 4eea92b935..0000000000
--- a/benchmark/hive-mind-load-test.py
+++ /dev/null
@@ -1,902 +0,0 @@
-#!/usr/bin/env python3
-"""
-Hive Mind Load Testing Suite - Comprehensive Stress Testing
-Benchmark-Tester Agent Implementation
-
-This script executes comprehensive load and stress testing of the Hive Mind system,
-testing scalability from 1 to 1000+ agents with various topologies and coordination modes.
-"""
-
-import os
-import sys
-import json
-import time
-import sqlite3
-import threading
-import subprocess
-import psutil
-import multiprocessing
-from datetime import datetime
-from pathlib import Path
-from dataclasses import dataclass, asdict
-from typing import Dict, List, Any, Optional, Tuple
-from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
-import statistics
-
-@dataclass
-class LoadTestConfig:
- """Configuration for load testing scenarios"""
- name: str
- description: str
- agent_count: int
- topology: str # hierarchical, mesh, ring, star
- coordination: str # queen, consensus, hybrid, democracy
- memory_type: str # sqlite, memory, distributed
- concurrent_swarms: int = 1
- task_complexity: str = "medium" # simple, medium, complex, enterprise
- duration_seconds: int = 60
- ramp_up_seconds: int = 10
- expected_success_rate: float = 0.95
- stress_mode: bool = False
-
-@dataclass
-class LoadTestResult:
- """Results from load testing"""
- config: LoadTestConfig
- start_time: str
- end_time: str
- total_duration: float
- successful_agents: int
- failed_agents: int
- peak_memory_mb: float
- peak_cpu_percent: float
- average_response_time_ms: float
- p95_response_time_ms: float
- p99_response_time_ms: float
- throughput_ops_per_sec: float
- error_rate: float
- coordination_failures: int
- consensus_timeouts: int
- memory_operations: int
- database_locks: int
- network_errors: int
- recovery_time_seconds: float
- breaking_point_reached: bool
- system_stable: bool
- resource_exhaustion: bool
- error_messages: List[str]
-
-class HiveMindLoadTester:
- """Comprehensive load testing for Hive Mind system"""
-
- def __init__(self, output_dir: str = "load-test-results"):
- self.output_dir = Path(output_dir)
- self.output_dir.mkdir(exist_ok=True)
- self.results: List[LoadTestResult] = []
- self.cli_path = self._find_cli_path()
- self.system_monitor = SystemMonitor()
-
- def _find_cli_path(self) -> Path:
- """Find the claude-flow CLI executable"""
- possible_paths = [
- Path("../src/cli/simple-cli.js"),
- Path("./src/cli/simple-cli.js"),
- Path("./claude-flow"),
- Path("../claude-flow")
- ]
-
- for path in possible_paths:
- if path.exists():
- return path
-
- # Fallback to system claude-flow
- return Path("claude-flow")
-
- def create_load_test_scenarios(self) -> List[LoadTestConfig]:
- """Create comprehensive load testing scenarios"""
- scenarios = []
-
- # Progressive scaling tests (1 -> 1000 agents)
- scaling_tests = [
- (1, "Baseline single agent", 30),
- (5, "Small team coordination", 30),
- (10, "Small organization", 45),
- (25, "Medium team", 60),
- (50, "Large team", 90),
- (100, "Department scale", 120),
- (250, "Enterprise division", 180),
- (500, "Large enterprise", 240),
- (1000, "Massive scale", 300)
- ]
-
- for count, desc, duration in scaling_tests:
- # Test optimal configuration for each scale
- scenarios.append(LoadTestConfig(
- name=f"scale_test_{count}_agents",
- description=f"{desc} - {count} agents",
- agent_count=count,
- topology="hierarchical" if count <= 100 else "mesh",
- coordination="queen" if count <= 50 else "consensus",
- memory_type="sqlite" if count <= 100 else "distributed",
- duration_seconds=duration,
- ramp_up_seconds=max(5, count // 10)
- ))
-
- # Topology stress tests
- topologies = ["hierarchical", "mesh", "ring", "star"]
- for topology in topologies:
- scenarios.append(LoadTestConfig(
- name=f"topology_stress_{topology}",
- description=f"Stress test {topology} topology with 100 agents",
- agent_count=100,
- topology=topology,
- coordination="consensus",
- memory_type="distributed",
- duration_seconds=120,
- stress_mode=True
- ))
-
- # Coordination mode stress tests
- coordination_modes = ["queen", "consensus", "hybrid", "democracy"]
- for mode in coordination_modes:
- scenarios.append(LoadTestConfig(
- name=f"coordination_stress_{mode}",
- description=f"Stress test {mode} coordination with 50 agents",
- agent_count=50,
- topology="mesh",
- coordination=mode,
- memory_type="sqlite",
- duration_seconds=90,
- stress_mode=True
- ))
-
- # Concurrent swarm tests
- scenarios.extend([
- LoadTestConfig(
- name="concurrent_swarms_2",
- description="2 concurrent swarms of 25 agents each",
- agent_count=25,
- topology="hierarchical",
- coordination="queen",
- memory_type="sqlite",
- concurrent_swarms=2,
- duration_seconds=90
- ),
- LoadTestConfig(
- name="concurrent_swarms_5",
- description="5 concurrent swarms of 20 agents each",
- agent_count=20,
- topology="mesh",
- coordination="consensus",
- memory_type="memory",
- concurrent_swarms=5,
- duration_seconds=120
- ),
- LoadTestConfig(
- name="concurrent_swarms_10",
- description="10 concurrent swarms of 10 agents each",
- agent_count=10,
- topology="star",
- coordination="hybrid",
- memory_type="distributed",
- concurrent_swarms=10,
- duration_seconds=180,
- stress_mode=True
- )
- ])
-
- # Memory system stress tests
- scenarios.extend([
- LoadTestConfig(
- name="memory_stress_sqlite",
- description="SQLite memory stress with 200 agents",
- agent_count=200,
- topology="hierarchical",
- coordination="queen",
- memory_type="sqlite",
- duration_seconds=150,
- task_complexity="complex",
- stress_mode=True
- ),
- LoadTestConfig(
- name="memory_stress_distributed",
- description="Distributed memory stress with 500 agents",
- agent_count=500,
- topology="mesh",
- coordination="consensus",
- memory_type="distributed",
- duration_seconds=200,
- task_complexity="enterprise",
- stress_mode=True
- )
- ])
-
- # Breaking point discovery tests
- scenarios.extend([
- LoadTestConfig(
- name="breaking_point_1500",
- description="Find breaking point at 1500 agents",
- agent_count=1500,
- topology="mesh",
- coordination="consensus",
- memory_type="distributed",
- duration_seconds=300,
- expected_success_rate=0.5,
- stress_mode=True
- ),
- LoadTestConfig(
- name="breaking_point_2000",
- description="Find breaking point at 2000 agents",
- agent_count=2000,
- topology="hierarchical",
- coordination="queen",
- memory_type="distributed",
- duration_seconds=300,
- expected_success_rate=0.3,
- stress_mode=True
- )
- ])
-
- return scenarios
-
- def run_hive_mind_command(self, command: List[str], timeout: int = 120) -> Dict[str, Any]:
- """Execute hive-mind command with performance monitoring"""
- start_time = time.time()
-
- try:
- # Start system monitoring
- monitor_process = self.system_monitor.start_monitoring()
-
- # Execute command
- result = subprocess.run(
- ["node", str(self.cli_path)] + command,
- capture_output=True,
- text=True,
- timeout=timeout,
- cwd=Path.cwd()
- )
-
- end_time = time.time()
- duration = end_time - start_time
-
- # Stop monitoring and get metrics
- metrics = self.system_monitor.stop_monitoring(monitor_process)
-
- return {
- "success": result.returncode == 0,
- "duration": duration,
- "stdout": result.stdout,
- "stderr": result.stderr,
- "returncode": result.returncode,
- "metrics": metrics
- }
-
- except subprocess.TimeoutExpired:
- self.system_monitor.stop_monitoring(None)
- return {
- "success": False,
- "duration": timeout,
- "stdout": "",
- "stderr": f"Command timed out after {timeout} seconds",
- "returncode": -1,
- "metrics": {}
- }
- except Exception as e:
- self.system_monitor.stop_monitoring(None)
- return {
- "success": False,
- "duration": time.time() - start_time,
- "stdout": "",
- "stderr": str(e),
- "returncode": -1,
- "metrics": {}
- }
-
- def run_single_swarm_load_test(self, config: LoadTestConfig, swarm_id: int = 0) -> Dict[str, Any]:
- """Run load test for a single swarm"""
- print(f"πŸ”₯ Starting swarm {swarm_id} load test: {config.name}")
-
- start_time = time.time()
- response_times = []
- errors = []
-
- try:
- # Initialize swarm
- init_cmd = [
- "hive-mind", "init",
- "--test-mode",
- "--swarm-id", f"{config.name}_swarm_{swarm_id}"
- ]
-
- init_result = self.run_hive_mind_command(init_cmd, timeout=60)
- if not init_result["success"]:
- raise Exception(f"Swarm initialization failed: {init_result['stderr']}")
-
- # Ramp up agents gradually
- agents_spawned = 0
- ramp_increment = max(1, config.agent_count // (config.ramp_up_seconds // 2))
-
- while agents_spawned < config.agent_count:
- batch_size = min(ramp_increment, config.agent_count - agents_spawned)
-
- spawn_start = time.time()
- spawn_cmd = [
- "hive-mind", "spawn",
- f"Load test batch {agents_spawned}-{agents_spawned + batch_size}",
- "--topology", config.topology,
- "--coordination", config.coordination,
- "--memory", config.memory_type,
- "--agents", str(batch_size),
- "--stress-test" if config.stress_mode else "--load-test"
- ]
-
- spawn_result = self.run_hive_mind_command(spawn_cmd, timeout=120)
- spawn_time = time.time() - spawn_start
- response_times.append(spawn_time * 1000) # Convert to ms
-
- if not spawn_result["success"]:
- errors.append(f"Agent spawn failed: {spawn_result['stderr']}")
- break
-
- agents_spawned += batch_size
-
- # Brief pause between batches during ramp-up
- if agents_spawned < config.agent_count:
- time.sleep(1)
-
- # Run sustained load for duration
- test_start = time.time()
- operations_completed = 0
-
- while time.time() - test_start < config.duration_seconds:
- # Execute coordination tasks
- task_start = time.time()
- task_cmd = [
- "hive-mind", "task",
- f"Load test operation {operations_completed}",
- "--complexity", config.task_complexity,
- "--timeout", "30"
- ]
-
- task_result = self.run_hive_mind_command(task_cmd, timeout=30)
- task_time = time.time() - task_start
- response_times.append(task_time * 1000)
-
- if not task_result["success"]:
- errors.append(f"Task execution failed: {task_result['stderr']}")
-
- operations_completed += 1
-
- # Brief pause between operations
- time.sleep(0.5)
-
- # Cleanup swarm
- cleanup_cmd = ["hive-mind", "cleanup", "--swarm-id", f"{config.name}_swarm_{swarm_id}"]
- cleanup_result = self.run_hive_mind_command(cleanup_cmd, timeout=60)
-
- total_duration = time.time() - start_time
-
- return {
- "swarm_id": swarm_id,
- "success": len(errors) == 0,
- "duration": total_duration,
- "agents_spawned": agents_spawned,
- "operations_completed": operations_completed,
- "response_times": response_times,
- "errors": errors,
- "throughput": operations_completed / config.duration_seconds if config.duration_seconds > 0 else 0
- }
-
- except Exception as e:
- return {
- "swarm_id": swarm_id,
- "success": False,
- "duration": time.time() - start_time,
- "agents_spawned": 0,
- "operations_completed": 0,
- "response_times": [],
- "errors": [str(e)],
- "throughput": 0
- }
-
- def run_load_test(self, config: LoadTestConfig) -> LoadTestResult:
- """Run comprehensive load test for a configuration"""
- print(f"πŸš€ Running load test: {config.name}")
- print(f" πŸ“Š {config.agent_count} agents, {config.concurrent_swarms} swarms")
- print(f" πŸ—οΈ Topology: {config.topology}, Coordination: {config.coordination}")
- print(f" πŸ’Ύ Memory: {config.memory_type}, Duration: {config.duration_seconds}s")
-
- start_time = datetime.now().isoformat()
- test_start = time.time()
-
- # Start system monitoring
- system_monitor_process = self.system_monitor.start_monitoring()
-
- try:
- # Run concurrent swarms if specified
- if config.concurrent_swarms > 1:
- with ThreadPoolExecutor(max_workers=config.concurrent_swarms) as executor:
- futures = {
- executor.submit(self.run_single_swarm_load_test, config, i): i
- for i in range(config.concurrent_swarms)
- }
-
- swarm_results = []
- for future in as_completed(futures):
- result = future.result()
- swarm_results.append(result)
- swarm_id = futures[future]
- status = "βœ…" if result["success"] else "❌"
- print(f" {status} Swarm {swarm_id}: {result['operations_completed']} ops")
- else:
- # Single swarm test
- swarm_result = self.run_single_swarm_load_test(config, 0)
- swarm_results = [swarm_result]
-
- # Stop system monitoring and collect metrics
- system_metrics = self.system_monitor.stop_monitoring(system_monitor_process)
-
- # Aggregate results from all swarms
- total_duration = time.time() - test_start
- end_time = datetime.now().isoformat()
-
- # Calculate aggregate metrics
- all_response_times = []
- all_errors = []
- total_agents = 0
- total_operations = 0
- successful_swarms = 0
-
- for result in swarm_results:
- all_response_times.extend(result["response_times"])
- all_errors.extend(result["errors"])
- total_agents += result["agents_spawned"]
- total_operations += result["operations_completed"]
- if result["success"]:
- successful_swarms += 1
-
- # Calculate performance metrics
- avg_response_time = statistics.mean(all_response_times) if all_response_times else 0
- p95_response_time = statistics.quantiles(all_response_times, n=20)[18] if len(all_response_times) > 20 else 0
- p99_response_time = statistics.quantiles(all_response_times, n=100)[98] if len(all_response_times) > 100 else 0
-
- throughput = total_operations / config.duration_seconds if config.duration_seconds > 0 else 0
- error_rate = len(all_errors) / (total_operations + len(all_errors)) if (total_operations + len(all_errors)) > 0 else 0
-
- # Determine system stability
- success_rate = successful_swarms / len(swarm_results) if swarm_results else 0
- system_stable = success_rate >= config.expected_success_rate
- breaking_point_reached = success_rate < 0.5
- resource_exhaustion = system_metrics.get("peak_memory_mb", 0) > 8000 or system_metrics.get("peak_cpu_percent", 0) > 95
-
- return LoadTestResult(
- config=config,
- start_time=start_time,
- end_time=end_time,
- total_duration=total_duration,
- successful_agents=total_agents,
- failed_agents=max(0, config.agent_count * config.concurrent_swarms - total_agents),
- peak_memory_mb=system_metrics.get("peak_memory_mb", 0),
- peak_cpu_percent=system_metrics.get("peak_cpu_percent", 0),
- average_response_time_ms=avg_response_time,
- p95_response_time_ms=p95_response_time,
- p99_response_time_ms=p99_response_time,
- throughput_ops_per_sec=throughput,
- error_rate=error_rate,
- coordination_failures=len([e for e in all_errors if "coordination" in e.lower()]),
- consensus_timeouts=len([e for e in all_errors if "timeout" in e.lower()]),
- memory_operations=total_operations * 3, # Estimated
- database_locks=len([e for e in all_errors if "lock" in e.lower()]),
- network_errors=len([e for e in all_errors if "network" in e.lower()]),
- recovery_time_seconds=0, # Would need additional monitoring
- breaking_point_reached=breaking_point_reached,
- system_stable=system_stable,
- resource_exhaustion=resource_exhaustion,
- error_messages=all_errors[:10] # Keep first 10 errors
- )
-
- except Exception as e:
- self.system_monitor.stop_monitoring(system_monitor_process)
- return LoadTestResult(
- config=config,
- start_time=start_time,
- end_time=datetime.now().isoformat(),
- total_duration=time.time() - test_start,
- successful_agents=0,
- failed_agents=config.agent_count * config.concurrent_swarms,
- peak_memory_mb=0,
- peak_cpu_percent=0,
- average_response_time_ms=0,
- p95_response_time_ms=0,
- p99_response_time_ms=0,
- throughput_ops_per_sec=0,
- error_rate=1.0,
- coordination_failures=1,
- consensus_timeouts=0,
- memory_operations=0,
- database_locks=0,
- network_errors=0,
- recovery_time_seconds=0,
- breaking_point_reached=True,
- system_stable=False,
- resource_exhaustion=True,
- error_messages=[str(e)]
- )
-
- def run_progressive_load_testing(self, scenarios: List[LoadTestConfig]) -> List[LoadTestResult]:
- """Run load tests progressively, stopping at breaking points"""
- results = []
-
- # Sort scenarios by agent count for progressive testing
- sorted_scenarios = sorted(scenarios, key=lambda s: s.agent_count)
-
- print("🎯 Starting Progressive Load Testing")
- print("=" * 50)
-
- for i, scenario in enumerate(sorted_scenarios):
- print(f"\nπŸ“ˆ Test {i+1}/{len(sorted_scenarios)}: {scenario.name}")
-
- result = self.run_load_test(scenario)
- results.append(result)
-
- # Report result
- status = "βœ…" if result.system_stable else "❌"
- print(f"{status} {scenario.name}: {result.successful_agents}/{scenario.agent_count * scenario.concurrent_swarms} agents")
- print(f" ⚑ Throughput: {result.throughput_ops_per_sec:.1f} ops/sec")
- print(f" 🧠 Memory: {result.peak_memory_mb:.1f}MB, CPU: {result.peak_cpu_percent:.1f}%")
- print(f" 🎯 Response time: {result.average_response_time_ms:.1f}ms (P95: {result.p95_response_time_ms:.1f}ms)")
-
- # Check if we should continue
- if result.breaking_point_reached:
- print(f"🚨 Breaking point reached at {scenario.agent_count} agents!")
- if scenario.agent_count >= 500: # Continue testing if we've reached a reasonable scale
- print(" Continuing with remaining tests for completeness...")
- else:
- print(" Stopping progressive testing due to early failure.")
- break
-
- # Brief pause between tests for system recovery
- time.sleep(5)
-
- return results
-
- def analyze_load_test_results(self, results: List[LoadTestResult]) -> Dict[str, Any]:
- """Analyze load test results and generate insights"""
- if not results:
- return {"error": "No results to analyze"}
-
- successful_results = [r for r in results if r.system_stable]
- failed_results = [r for r in results if not r.system_stable]
- breaking_points = [r for r in results if r.breaking_point_reached]
-
- # Find scaling limits
- max_stable_agents = max([r.successful_agents for r in successful_results], default=0)
- breaking_point_agents = min([r.config.agent_count for r in breaking_points], default=None)
-
- # Performance characteristics
- performance_by_scale = {}
- for result in successful_results:
- scale = self._categorize_scale(result.config.agent_count)
- if scale not in performance_by_scale:
- performance_by_scale[scale] = []
- performance_by_scale[scale].append({
- "agents": result.config.agent_count,
- "throughput": result.throughput_ops_per_sec,
- "response_time": result.average_response_time_ms,
- "memory_mb": result.peak_memory_mb,
- "cpu_percent": result.peak_cpu_percent
- })
-
- # Topology performance comparison
- topology_performance = {}
- for result in successful_results:
- topology = result.config.topology
- if topology not in topology_performance:
- topology_performance[topology] = []
- topology_performance[topology].append({
- "agents": result.config.agent_count,
- "throughput": result.throughput_ops_per_sec,
- "response_time": result.average_response_time_ms,
- "coordination_failures": result.coordination_failures
- })
-
- # Resource utilization analysis
- resource_analysis = {
- "memory_efficiency": {},
- "cpu_efficiency": {},
- "breaking_points": {}
- }
-
- for result in results:
- agent_count = result.config.agent_count
- if result.successful_agents > 0:
- memory_per_agent = result.peak_memory_mb / result.successful_agents
- cpu_per_agent = result.peak_cpu_percent / result.successful_agents
-
- resource_analysis["memory_efficiency"][agent_count] = memory_per_agent
- resource_analysis["cpu_efficiency"][agent_count] = cpu_per_agent
-
- if result.breaking_point_reached:
- resource_analysis["breaking_points"][agent_count] = {
- "error_rate": result.error_rate,
- "resource_exhaustion": result.resource_exhaustion,
- "coordination_failures": result.coordination_failures
- }
-
- # Recommendations
- recommendations = []
-
- if max_stable_agents < 100:
- recommendations.append("System shows scaling issues below 100 agents. Consider optimizing coordination mechanisms.")
- elif max_stable_agents < 500:
- recommendations.append("Good performance up to medium scale. Consider distributed memory for larger deployments.")
- else:
- recommendations.append("Excellent scaling characteristics. System ready for enterprise deployment.")
-
- if breaking_point_agents and breaking_point_agents < 1000:
- recommendations.append(f"Breaking point identified at {breaking_point_agents} agents. Implement sharding or federation for larger scales.")
-
- # Performance targets assessment
- targets_met = {
- "response_time_target": len([r for r in successful_results if r.average_response_time_ms < 1000]),
- "throughput_target": len([r for r in successful_results if r.throughput_ops_per_sec > 10]),
- "memory_target": len([r for r in successful_results if r.peak_memory_mb < 2000]),
- "stability_target": len([r for r in successful_results if r.error_rate < 0.05])
- }
-
- return {
- "summary": {
- "total_tests": len(results),
- "successful_tests": len(successful_results),
- "failed_tests": len(failed_results),
- "max_stable_agents": max_stable_agents,
- "breaking_point_agents": breaking_point_agents,
- "avg_throughput": statistics.mean([r.throughput_ops_per_sec for r in successful_results]) if successful_results else 0,
- "avg_response_time_ms": statistics.mean([r.average_response_time_ms for r in successful_results]) if successful_results else 0,
- "peak_memory_usage_mb": max([r.peak_memory_mb for r in results], default=0),
- "peak_cpu_usage_percent": max([r.peak_cpu_percent for r in results], default=0)
- },
- "performance_by_scale": performance_by_scale,
- "topology_performance": topology_performance,
- "resource_analysis": resource_analysis,
- "recommendations": recommendations,
- "targets_assessment": targets_met,
- "scaling_characteristics": {
- "linear_scaling_limit": max_stable_agents,
- "degradation_point": breaking_point_agents,
- "resource_efficiency_curve": resource_analysis["memory_efficiency"]
- }
- }
-
- def _categorize_scale(self, agent_count: int) -> str:
- """Categorize agent count into scale categories"""
- if agent_count <= 10:
- return "small"
- elif agent_count <= 100:
- return "medium"
- elif agent_count <= 500:
- return "large"
- else:
- return "enterprise"
-
- def save_load_test_results(self, results: List[LoadTestResult], analysis: Dict[str, Any]):
- """Save load test results and analysis"""
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
-
- # Save detailed results
- results_file = self.output_dir / f"hive_mind_load_test_results_{timestamp}.json"
- with open(results_file, 'w') as f:
- json.dump([asdict(r) for r in results], f, indent=2)
-
- # Save analysis
- analysis_file = self.output_dir / f"hive_mind_load_test_analysis_{timestamp}.json"
- with open(analysis_file, 'w') as f:
- json.dump(analysis, f, indent=2)
-
- # Save performance summary CSV
- csv_file = self.output_dir / f"hive_mind_load_test_summary_{timestamp}.csv"
- with open(csv_file, 'w') as f:
- f.write("test_name,agent_count,concurrent_swarms,topology,coordination,memory_type,")
- f.write("successful_agents,throughput_ops_sec,avg_response_ms,p95_response_ms,")
- f.write("peak_memory_mb,peak_cpu_percent,error_rate,system_stable,breaking_point\\n")
-
- for result in results:
- config = result.config
- f.write(f"{config.name},{config.agent_count},{config.concurrent_swarms},")
- f.write(f"{config.topology},{config.coordination},{config.memory_type},")
- f.write(f"{result.successful_agents},{result.throughput_ops_per_sec:.2f},")
- f.write(f"{result.average_response_time_ms:.1f},{result.p95_response_time_ms:.1f},")
- f.write(f"{result.peak_memory_mb:.1f},{result.peak_cpu_percent:.1f},")
- f.write(f"{result.error_rate:.3f},{result.system_stable},{result.breaking_point_reached}\\n")
-
- print(f"πŸ“Š Load test results saved:")
- print(f" πŸ“„ Detailed results: {results_file}")
- print(f" πŸ“ˆ Analysis: {analysis_file}")
- print(f" πŸ“‹ Summary CSV: {csv_file}")
-
- return {
- "results_file": str(results_file),
- "analysis_file": str(analysis_file),
- "csv_file": str(csv_file)
- }
-
- def run_comprehensive_load_testing(self) -> Dict[str, Any]:
- """Run complete load testing suite"""
- print("πŸ”₯ Hive Mind Comprehensive Load Testing Suite")
- print("=" * 60)
- print("🎯 Testing scalability from 1 to 1000+ agents")
- print("πŸš€ Multiple topologies and coordination modes")
- print("πŸ’Ύ Different memory backends")
- print("πŸ” Breaking point discovery")
- print("=" * 60)
-
- # Create test scenarios
- scenarios = self.create_load_test_scenarios()
- print(f"πŸ“‹ Created {len(scenarios)} load test scenarios")
-
- # Run progressive load testing
- start_time = time.time()
- results = self.run_progressive_load_testing(scenarios)
- total_duration = time.time() - start_time
-
- print(f"\\n⏱️ Total testing time: {total_duration:.1f} seconds")
-
- # Analyze results
- analysis = self.analyze_load_test_results(results)
-
- # Save results
- file_info = self.save_load_test_results(results, analysis)
-
- # Add metadata
- analysis["metadata"] = {
- "total_duration_seconds": total_duration,
- "test_time": datetime.now().isoformat(),
- "scenario_count": len(scenarios),
- "system_info": {
- "cpu_count": multiprocessing.cpu_count(),
- "memory_gb": psutil.virtual_memory().total / (1024**3),
- "python_version": sys.version,
- "platform": sys.platform
- }
- }
- analysis["files"] = file_info
-
- return analysis
-
-class SystemMonitor:
- """Monitor system resources during load testing"""
-
- def __init__(self):
- self.monitoring = False
- self.metrics = {
- "cpu_samples": [],
- "memory_samples": [],
- "io_samples": []
- }
-
- def start_monitoring(self) -> threading.Thread:
- """Start monitoring system resources"""
- self.monitoring = True
- self.metrics = {"cpu_samples": [], "memory_samples": [], "io_samples": []}
-
- def monitor():
- while self.monitoring:
- try:
- # CPU usage
- cpu_percent = psutil.cpu_percent(interval=1)
- self.metrics["cpu_samples"].append(cpu_percent)
-
- # Memory usage
- memory = psutil.virtual_memory()
- self.metrics["memory_samples"].append(memory.percent)
-
- # I/O stats
- io_counters = psutil.disk_io_counters()
- if io_counters:
- self.metrics["io_samples"].append({
- "read_bytes": io_counters.read_bytes,
- "write_bytes": io_counters.write_bytes
- })
-
- except Exception:
- pass # Continue monitoring despite errors
-
- time.sleep(1)
-
- thread = threading.Thread(target=monitor)
- thread.daemon = True
- thread.start()
- return thread
-
- def stop_monitoring(self, thread: Optional[threading.Thread]) -> Dict[str, Any]:
- """Stop monitoring and return collected metrics"""
- self.monitoring = False
-
- if thread:
- thread.join(timeout=2)
-
- if not self.metrics["cpu_samples"]:
- return {}
-
- return {
- "peak_cpu_percent": max(self.metrics["cpu_samples"]),
- "avg_cpu_percent": statistics.mean(self.metrics["cpu_samples"]),
- "peak_memory_percent": max(self.metrics["memory_samples"]),
- "avg_memory_percent": statistics.mean(self.metrics["memory_samples"]),
- "peak_memory_mb": max(self.metrics["memory_samples"]) * psutil.virtual_memory().total / (1024**2) / 100,
- "sample_count": len(self.metrics["cpu_samples"])
- }
-
-def main():
- """Main load testing execution"""
- import argparse
-
- parser = argparse.ArgumentParser(description="Hive Mind Load Testing Suite")
- parser.add_argument("--quick", action="store_true", help="Run quick load test with reduced scenarios")
- parser.add_argument("--scale", type=int, help="Test specific agent scale")
- parser.add_argument("--output", default="load-test-results", help="Output directory")
- parser.add_argument("--max-agents", type=int, default=1000, help="Maximum agents to test")
-
- args = parser.parse_args()
-
- tester = HiveMindLoadTester(output_dir=args.output)
-
- if args.quick:
- # Quick test scenarios
- scenarios = [
- LoadTestConfig("quick_small", "Quick small scale test", 5, "hierarchical", "queen", "sqlite", duration_seconds=30),
- LoadTestConfig("quick_medium", "Quick medium scale test", 25, "mesh", "consensus", "memory", duration_seconds=45),
- LoadTestConfig("quick_large", "Quick large scale test", 100, "hierarchical", "queen", "distributed", duration_seconds=60)
- ]
-
- print("πŸš€ Running quick load test...")
- results = []
- for scenario in scenarios:
- result = tester.run_load_test(scenario)
- results.append(result)
-
- analysis = tester.analyze_load_test_results(results)
- tester.save_load_test_results(results, analysis)
-
- elif args.scale:
- # Test specific scale
- scenario = LoadTestConfig(
- f"custom_scale_{args.scale}",
- f"Custom scale test with {args.scale} agents",
- args.scale,
- "hierarchical" if args.scale <= 100 else "mesh",
- "queen" if args.scale <= 50 else "consensus",
- "sqlite" if args.scale <= 100 else "distributed",
- duration_seconds=max(60, args.scale // 10)
- )
-
- print(f"🎯 Running custom scale test with {args.scale} agents...")
- result = tester.run_load_test(scenario)
- analysis = tester.analyze_load_test_results([result])
- tester.save_load_test_results([result], analysis)
-
- else:
- # Full comprehensive load testing
- analysis = tester.run_comprehensive_load_testing()
-
- # Print summary
- summary = analysis["summary"]
- print("\\n🎯 LOAD TESTING SUMMARY")
- print("=" * 50)
- print(f"Total tests: {summary['total_tests']}")
- print(f"Successful tests: {summary['successful_tests']}")
- print(f"Max stable agents: {summary['max_stable_agents']}")
- print(f"Breaking point: {summary['breaking_point_agents']} agents" if summary['breaking_point_agents'] else "No breaking point found")
- print(f"Average throughput: {summary['avg_throughput']:.1f} ops/sec")
- print(f"Average response time: {summary['avg_response_time_ms']:.1f}ms")
- print(f"Peak memory usage: {summary['peak_memory_usage_mb']:.1f}MB")
- print(f"Peak CPU usage: {summary['peak_cpu_usage_percent']:.1f}%")
-
- # Print recommendations
- if analysis["recommendations"]:
- print("\\nπŸ’‘ RECOMMENDATIONS")
- for i, rec in enumerate(analysis["recommendations"], 1):
- print(f"{i}. {rec}")
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/benchmark/hive-mind-stress-test.py b/benchmark/hive-mind-stress-test.py
deleted file mode 100644
index baa85063d9..0000000000
--- a/benchmark/hive-mind-stress-test.py
+++ /dev/null
@@ -1,935 +0,0 @@
-#!/usr/bin/env python3
-"""
-Hive Mind Stress Testing Suite - Breaking Point Discovery
-Specialized stress testing to find system limits and failure modes
-
-This script pushes the Hive Mind system beyond normal operational limits
-to discover breaking points, failure recovery patterns, and system resilience.
-"""
-
-import os
-import sys
-import json
-import time
-import psutil
-import threading
-import subprocess
-import multiprocessing
-from datetime import datetime
-from pathlib import Path
-from dataclasses import dataclass, asdict
-from typing import Dict, List, Any, Optional, Tuple
-from concurrent.futures import ThreadPoolExecutor, as_completed
-import statistics
-import random
-
-@dataclass
-class StressTestConfig:
- """Configuration for stress testing scenarios"""
- name: str
- description: str
- stress_type: str # memory, cpu, coordination, consensus, network, io
- initial_agents: int
- max_agents: int
- increment_size: int
- increment_interval: float # seconds between increments
- failure_threshold: float = 0.5 # failure rate that indicates breaking point
- resource_limit_mb: int = 8000 # memory limit before stopping
- cpu_limit_percent: float = 95.0 # CPU limit before stopping
- timeout_seconds: int = 300
- chaos_mode: bool = False # inject random failures
-
-@dataclass
-class StressTestResult:
- """Results from stress testing"""
- config: StressTestConfig
- start_time: str
- end_time: str
- breaking_point_agents: int
- max_stable_agents: int
- failure_mode: str
- total_duration: float
- peak_memory_mb: float
- peak_cpu_percent: float
- coordination_failures: int
- consensus_timeouts: int
- network_errors: int
- database_locks: int
- recovery_attempts: int
- successful_recoveries: int
- degradation_curve: List[Dict[str, Any]]
- error_patterns: Dict[str, int]
- system_metrics: Dict[str, Any]
- recommendations: List[str]
-
-class HiveMindStressTester:
- """Specialized stress testing for Hive Mind system limits"""
-
- def __init__(self, output_dir: str = "stress-test-results"):
- self.output_dir = Path(output_dir)
- self.output_dir.mkdir(exist_ok=True)
- self.results: List[StressTestResult] = []
- self.cli_path = self._find_cli_path()
- self.active_processes: List[subprocess.Popen] = []
- self.system_monitor = StressSystemMonitor()
-
- def _find_cli_path(self) -> Path:
- """Find the claude-flow CLI executable"""
- possible_paths = [
- Path("../src/cli/simple-cli.js"),
- Path("./src/cli/simple-cli.js"),
- Path("./claude-flow"),
- Path("../claude-flow")
- ]
-
- for path in possible_paths:
- if path.exists():
- return path
- return Path("claude-flow")
-
- def create_stress_test_scenarios(self) -> List[StressTestConfig]:
- """Create comprehensive stress testing scenarios"""
- scenarios = []
-
- # Memory stress tests
- scenarios.extend([
- StressTestConfig(
- name="memory_stress_progressive",
- description="Progressive memory stress until exhaustion",
- stress_type="memory",
- initial_agents=50,
- max_agents=2000,
- increment_size=50,
- increment_interval=10.0,
- resource_limit_mb=6000
- ),
- StressTestConfig(
- name="memory_stress_rapid",
- description="Rapid memory allocation stress",
- stress_type="memory",
- initial_agents=100,
- max_agents=1000,
- increment_size=100,
- increment_interval=2.0,
- resource_limit_mb=6000
- )
- ])
-
- # CPU stress tests
- scenarios.extend([
- StressTestConfig(
- name="cpu_stress_coordination",
- description="CPU stress through intensive coordination",
- stress_type="cpu",
- initial_agents=25,
- max_agents=500,
- increment_size=25,
- increment_interval=5.0,
- cpu_limit_percent=90.0
- ),
- StressTestConfig(
- name="cpu_stress_consensus",
- description="CPU stress through consensus algorithms",
- stress_type="cpu",
- initial_agents=20,
- max_agents=200,
- increment_size=20,
- increment_interval=8.0,
- cpu_limit_percent=90.0
- )
- ])
-
- # Coordination stress tests
- scenarios.extend([
- StressTestConfig(
- name="coordination_stress_mesh",
- description="Coordination stress in mesh topology",
- stress_type="coordination",
- initial_agents=10,
- max_agents=300,
- increment_size=10,
- increment_interval=5.0,
- failure_threshold=0.3
- ),
- StressTestConfig(
- name="coordination_stress_hierarchical",
- description="Coordination stress in hierarchical topology",
- stress_type="coordination",
- initial_agents=20,
- max_agents=500,
- increment_size=20,
- increment_interval=5.0,
- failure_threshold=0.3
- )
- ])
-
- # Consensus stress tests
- scenarios.extend([
- StressTestConfig(
- name="consensus_stress_democracy",
- description="Consensus stress in democratic coordination",
- stress_type="consensus",
- initial_agents=5,
- max_agents=100,
- increment_size=5,
- increment_interval=10.0,
- failure_threshold=0.4
- ),
- StressTestConfig(
- name="consensus_stress_hybrid",
- description="Consensus stress in hybrid coordination",
- stress_type="consensus",
- initial_agents=10,
- max_agents=150,
- increment_size=10,
- increment_interval=8.0,
- failure_threshold=0.4
- )
- ])
-
- # Network stress tests
- scenarios.extend([
- StressTestConfig(
- name="network_stress_distributed",
- description="Network stress with distributed memory",
- stress_type="network",
- initial_agents=30,
- max_agents=400,
- increment_size=30,
- increment_interval=6.0,
- failure_threshold=0.4
- )
- ])
-
- # I/O stress tests
- scenarios.extend([
- StressTestConfig(
- name="io_stress_sqlite",
- description="I/O stress with SQLite backend",
- stress_type="io",
- initial_agents=40,
- max_agents=600,
- increment_size=40,
- increment_interval=7.0,
- failure_threshold=0.4
- )
- ])
-
- # Chaos engineering tests
- scenarios.extend([
- StressTestConfig(
- name="chaos_random_failures",
- description="Chaos engineering with random failures",
- stress_type="chaos",
- initial_agents=25,
- max_agents=200,
- increment_size=25,
- increment_interval=10.0,
- failure_threshold=0.6,
- chaos_mode=True
- )
- ])
-
- return scenarios
-
- def run_hive_mind_command_async(self, command: List[str], timeout: int = 120) -> subprocess.Popen:
- """Execute hive-mind command asynchronously"""
- try:
- process = subprocess.Popen(
- ["node", str(self.cli_path)] + command,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True,
- cwd=Path.cwd()
- )
- self.active_processes.append(process)
- return process
- except Exception as e:
- print(f"Failed to start command: {e}")
- return None
-
- def inject_chaos(self, chaos_type: str = "random"):
- """Inject chaos into the system for resilience testing"""
- chaos_actions = [
- self._kill_random_process,
- self._corrupt_memory_operation,
- self._simulate_network_delay,
- self._force_database_lock,
- self._simulate_consensus_failure
- ]
-
- if chaos_type == "random":
- action = random.choice(chaos_actions)
- try:
- action()
- except Exception as e:
- print(f"Chaos injection failed: {e}")
-
- def _kill_random_process(self):
- """Kill a random active process"""
- if self.active_processes:
- process = random.choice(self.active_processes)
- if process.poll() is None: # Still running
- process.terminate()
- print("πŸ”₯ Chaos: Killed random process")
-
- def _corrupt_memory_operation(self):
- """Simulate memory corruption"""
- print("πŸ”₯ Chaos: Simulating memory corruption")
- # In a real implementation, this would interfere with memory operations
-
- def _simulate_network_delay(self):
- """Simulate network delays"""
- print("πŸ”₯ Chaos: Simulating network delay")
- time.sleep(random.uniform(1, 3))
-
- def _force_database_lock(self):
- """Force database contention"""
- print("πŸ”₯ Chaos: Forcing database contention")
- # In a real implementation, this would create database locks
-
- def _simulate_consensus_failure(self):
- """Simulate consensus algorithm failure"""
- print("πŸ”₯ Chaos: Simulating consensus failure")
- # In a real implementation, this would interfere with consensus
-
- def monitor_system_degradation(self, config: StressTestConfig) -> Tuple[bool, Dict[str, Any]]:
- """Monitor system for degradation indicators"""
- metrics = self.system_monitor.get_current_metrics()
-
- # Check resource limits
- memory_exceeded = metrics.get("memory_mb", 0) > config.resource_limit_mb
- cpu_exceeded = metrics.get("cpu_percent", 0) > config.cpu_limit_percent
-
- # Check system responsiveness
- load_average = os.getloadavg()[0] if hasattr(os, 'getloadavg') else 0
- high_load = load_average > multiprocessing.cpu_count() * 2
-
- # Check process health
- dead_processes = len([p for p in self.active_processes if p.poll() is not None])
- process_failure_rate = dead_processes / max(len(self.active_processes), 1)
-
- degraded = memory_exceeded or cpu_exceeded or high_load or process_failure_rate > config.failure_threshold
-
- return degraded, {
- "memory_exceeded": memory_exceeded,
- "cpu_exceeded": cpu_exceeded,
- "high_load": high_load,
- "process_failure_rate": process_failure_rate,
- "metrics": metrics
- }
-
- def attempt_system_recovery(self) -> bool:
- """Attempt to recover system from degraded state"""
- print("πŸ”§ Attempting system recovery...")
-
- recovery_successful = False
-
- try:
- # Clean up dead processes
- dead_processes = [p for p in self.active_processes if p.poll() is not None]
- for process in dead_processes:
- self.active_processes.remove(process)
-
- # Force garbage collection
- import gc
- gc.collect()
-
- # Brief pause for system stabilization
- time.sleep(5)
-
- # Check if system is responsive
- test_metrics = self.system_monitor.get_current_metrics()
- if test_metrics.get("cpu_percent", 100) < 80:
- recovery_successful = True
- print("βœ… System recovery successful")
- else:
- print("❌ System recovery failed")
-
- except Exception as e:
- print(f"❌ Recovery attempt failed: {e}")
-
- return recovery_successful
-
- def run_stress_test(self, config: StressTestConfig) -> StressTestResult:
- """Run a single stress test scenario"""
- print(f"πŸ”₯ Starting stress test: {config.name}")
- print(f" πŸ“Š Type: {config.stress_type}")
- print(f" 🎯 Range: {config.initial_agents} -> {config.max_agents} agents")
- print(f" ⚑ Increment: {config.increment_size} every {config.increment_interval}s")
-
- start_time = datetime.now().isoformat()
- test_start = time.time()
-
- # Start system monitoring
- monitor_thread = self.system_monitor.start_monitoring()
-
- # Initialize tracking variables
- current_agents = config.initial_agents
- breaking_point_agents = None
- max_stable_agents = 0
- failure_mode = "none"
- degradation_curve = []
- error_patterns = {}
- recovery_attempts = 0
- successful_recoveries = 0
-
- try:
- # Initialize Hive Mind system
- init_cmd = ["hive-mind", "init", "--stress-test", "--test-mode"]
- init_process = self.run_hive_mind_command_async(init_cmd)
-
- if init_process:
- init_process.wait(timeout=60)
- if init_process.returncode != 0:
- raise Exception("Failed to initialize Hive Mind system")
-
- print(f"πŸš€ Starting with {current_agents} agents...")
-
- # Progressive stress testing loop
- while current_agents <= config.max_agents:
- iteration_start = time.time()
-
- # Spawn agent increment
- spawn_cmd = [
- "hive-mind", "spawn",
- f"Stress test increment to {current_agents} agents",
- "--agents", str(config.increment_size),
- "--topology", self._get_optimal_topology(current_agents),
- "--coordination", self._get_optimal_coordination(current_agents, config.stress_type),
- "--memory", self._get_optimal_memory(current_agents),
- "--stress-mode"
- ]
-
- spawn_processes = []
- for _ in range(config.increment_size // 10 + 1): # Batch spawning
- process = self.run_hive_mind_command_async(spawn_cmd)
- if process:
- spawn_processes.append(process)
-
- # Wait for spawning to complete or timeout
- spawn_success = True
- for process in spawn_processes:
- try:
- process.wait(timeout=30)
- if process.returncode != 0:
- spawn_success = False
- except subprocess.TimeoutExpired:
- process.terminate()
- spawn_success = False
-
- # Inject chaos if enabled
- if config.chaos_mode:
- self.inject_chaos()
-
- # Monitor system state
- degraded, degradation_info = self.monitor_system_degradation(config)
-
- # Record metrics for this iteration
- iteration_metrics = {
- "agent_count": current_agents,
- "timestamp": time.time() - test_start,
- "spawn_success": spawn_success,
- "system_degraded": degraded,
- "metrics": degradation_info["metrics"],
- "iteration_duration": time.time() - iteration_start
- }
- degradation_curve.append(iteration_metrics)
-
- # Update tracking
- if spawn_success and not degraded:
- max_stable_agents = current_agents
- print(f"βœ… Stable at {current_agents} agents")
- else:
- if not breaking_point_agents:
- breaking_point_agents = current_agents
-
- # Determine failure mode
- if degradation_info["memory_exceeded"]:
- failure_mode = "memory_exhaustion"
- elif degradation_info["cpu_exceeded"]:
- failure_mode = "cpu_exhaustion"
- elif degradation_info["high_load"]:
- failure_mode = "system_overload"
- elif degradation_info["process_failure_rate"] > config.failure_threshold:
- failure_mode = "process_failures"
- else:
- failure_mode = "coordination_breakdown"
-
- print(f"🚨 Breaking point reached at {current_agents} agents!")
- print(f" Failure mode: {failure_mode}")
-
- # Attempt recovery
- if degraded:
- recovery_attempts += 1
- if self.attempt_system_recovery():
- successful_recoveries += 1
- else:
- print("πŸ’₯ System recovery failed, continuing test...")
-
- # Check if we should continue
- current_failure_rate = len([m for m in degradation_curve[-5:] if not m["spawn_success"]]) / min(5, len(degradation_curve))
- if current_failure_rate > config.failure_threshold and breaking_point_agents:
- print(f"πŸ›‘ Stopping test due to high failure rate: {current_failure_rate:.1%}")
- break
-
- # Resource safety checks
- current_metrics = self.system_monitor.get_current_metrics()
- if current_metrics.get("memory_mb", 0) > config.resource_limit_mb:
- print(f"πŸ›‘ Stopping test due to memory limit: {current_metrics['memory_mb']:.1f}MB")
- failure_mode = "memory_limit_reached"
- break
-
- if current_metrics.get("cpu_percent", 0) > config.cpu_limit_percent:
- print(f"πŸ›‘ Stopping test due to CPU limit: {current_metrics['cpu_percent']:.1f}%")
- failure_mode = "cpu_limit_reached"
- break
-
- # Increment for next iteration
- current_agents += config.increment_size
-
- # Wait before next increment
- time.sleep(config.increment_interval)
-
- # Cleanup all processes
- for process in self.active_processes:
- try:
- if process.poll() is None:
- process.terminate()
- process.wait(timeout=10)
- except Exception:
- pass
-
- self.active_processes.clear()
-
- except Exception as e:
- failure_mode = f"test_exception: {str(e)}"
- print(f"❌ Stress test failed: {e}")
-
- finally:
- # Stop monitoring
- system_metrics = self.system_monitor.stop_monitoring(monitor_thread)
-
- total_duration = time.time() - test_start
- end_time = datetime.now().isoformat()
-
- # Generate recommendations based on results
- recommendations = self._generate_stress_recommendations(
- config, breaking_point_agents, max_stable_agents, failure_mode, degradation_curve
- )
-
- return StressTestResult(
- config=config,
- start_time=start_time,
- end_time=end_time,
- breaking_point_agents=breaking_point_agents or config.max_agents,
- max_stable_agents=max_stable_agents,
- failure_mode=failure_mode,
- total_duration=total_duration,
- peak_memory_mb=system_metrics.get("peak_memory_mb", 0),
- peak_cpu_percent=system_metrics.get("peak_cpu_percent", 0),
- coordination_failures=len([m for m in degradation_curve if not m.get("spawn_success", True)]),
- consensus_timeouts=0, # Would need specific monitoring
- network_errors=0, # Would need specific monitoring
- database_locks=0, # Would need specific monitoring
- recovery_attempts=recovery_attempts,
- successful_recoveries=successful_recoveries,
- degradation_curve=degradation_curve,
- error_patterns=error_patterns,
- system_metrics=system_metrics,
- recommendations=recommendations
- )
-
- def _get_optimal_topology(self, agent_count: int) -> str:
- """Get optimal topology for agent count"""
- if agent_count <= 50:
- return "hierarchical"
- elif agent_count <= 200:
- return "mesh"
- else:
- return "distributed"
-
- def _get_optimal_coordination(self, agent_count: int, stress_type: str) -> str:
- """Get optimal coordination mode for stress test"""
- if stress_type == "consensus":
- return "consensus"
- elif agent_count <= 30:
- return "queen"
- elif agent_count <= 150:
- return "hybrid"
- else:
- return "consensus"
-
- def _get_optimal_memory(self, agent_count: int) -> str:
- """Get optimal memory backend for agent count"""
- if agent_count <= 100:
- return "sqlite"
- else:
- return "distributed"
-
- def _generate_stress_recommendations(self, config: StressTestConfig, breaking_point: Optional[int],
- max_stable: int, failure_mode: str, curve: List[Dict]) -> List[str]:
- """Generate recommendations based on stress test results"""
- recommendations = []
-
- if breaking_point and breaking_point < 100:
- recommendations.append(f"System shows early breaking point at {breaking_point} agents. Consider optimizing {config.stress_type} handling.")
-
- if failure_mode == "memory_exhaustion":
- recommendations.append("Memory exhaustion detected. Implement memory pooling and garbage collection optimizations.")
- elif failure_mode == "cpu_exhaustion":
- recommendations.append("CPU exhaustion detected. Consider async processing and workload distribution.")
- elif failure_mode == "coordination_breakdown":
- recommendations.append("Coordination breakdown detected. Implement hierarchical coordination for better scaling.")
- elif failure_mode == "process_failures":
- recommendations.append("Process stability issues. Implement better error handling and process supervision.")
-
- if max_stable > 500:
- recommendations.append("Excellent scaling characteristics observed. System suitable for large deployments.")
- elif max_stable > 100:
- recommendations.append("Good scaling up to medium deployments. Consider sharding for larger scales.")
- else:
- recommendations.append("Limited scaling capacity. Requires significant optimization for production use.")
-
- return recommendations
-
- def run_comprehensive_stress_testing(self) -> Dict[str, Any]:
- """Run complete stress testing suite"""
- print("πŸ’₯ Hive Mind Comprehensive Stress Testing Suite")
- print("=" * 60)
- print("🎯 Finding breaking points and failure modes")
- print("πŸ”₯ Testing system resilience and recovery")
- print("πŸ“Š Analyzing degradation patterns")
- print("=" * 60)
-
- # Create stress test scenarios
- scenarios = self.create_stress_test_scenarios()
- print(f"πŸ“‹ Created {len(scenarios)} stress test scenarios")
-
- # Run stress tests
- results = []
- start_time = time.time()
-
- for i, scenario in enumerate(scenarios):
- print(f"\\nπŸ”₯ Running stress test {i+1}/{len(scenarios)}: {scenario.name}")
-
- result = self.run_stress_test(scenario)
- results.append(result)
-
- # Report result
- print(f"πŸ“Š Breaking point: {result.breaking_point_agents} agents")
- print(f"πŸ“ˆ Max stable: {result.max_stable_agents} agents")
- print(f"πŸ’₯ Failure mode: {result.failure_mode}")
- print(f"πŸ”§ Recovery rate: {result.successful_recoveries}/{result.recovery_attempts}")
-
- # Brief pause between tests for system cleanup
- time.sleep(10)
-
- total_duration = time.time() - start_time
- print(f"\\n⏱️ Total stress testing time: {total_duration:.1f} seconds")
-
- # Analyze results
- analysis = self._analyze_stress_results(results)
-
- # Save results
- file_info = self._save_stress_results(results, analysis)
-
- # Add metadata
- analysis["metadata"] = {
- "total_duration_seconds": total_duration,
- "test_time": datetime.now().isoformat(),
- "scenario_count": len(scenarios),
- "system_info": {
- "cpu_count": multiprocessing.cpu_count(),
- "memory_gb": psutil.virtual_memory().total / (1024**3),
- "platform": sys.platform
- }
- }
- analysis["files"] = file_info
-
- return analysis
-
- def _analyze_stress_results(self, results: List[StressTestResult]) -> Dict[str, Any]:
- """Analyze stress test results"""
- if not results:
- return {"error": "No results to analyze"}
-
- # Breaking point analysis
- breaking_points = [r.breaking_point_agents for r in results if r.breaking_point_agents]
- min_breaking_point = min(breaking_points) if breaking_points else None
- avg_breaking_point = statistics.mean(breaking_points) if breaking_points else None
-
- # Stability analysis
- stable_points = [r.max_stable_agents for r in results]
- max_stability = max(stable_points) if stable_points else 0
- avg_stability = statistics.mean(stable_points) if stable_points else 0
-
- # Failure mode analysis
- failure_modes = {}
- for result in results:
- mode = result.failure_mode
- failure_modes[mode] = failure_modes.get(mode, 0) + 1
-
- # Recovery analysis
- total_recovery_attempts = sum(r.recovery_attempts for r in results)
- total_successful_recoveries = sum(r.successful_recoveries for r in results)
- recovery_rate = total_successful_recoveries / total_recovery_attempts if total_recovery_attempts > 0 else 0
-
- # Resource utilization analysis
- peak_memory = max(r.peak_memory_mb for r in results)
- peak_cpu = max(r.peak_cpu_percent for r in results)
-
- return {
- "summary": {
- "total_tests": len(results),
- "min_breaking_point": min_breaking_point,
- "avg_breaking_point": avg_breaking_point,
- "max_stable_agents": max_stability,
- "avg_stable_agents": avg_stability,
- "peak_memory_mb": peak_memory,
- "peak_cpu_percent": peak_cpu,
- "recovery_rate": recovery_rate
- },
- "failure_modes": failure_modes,
- "breaking_points_by_stress_type": {
- r.config.stress_type: r.breaking_point_agents
- for r in results if r.breaking_point_agents
- },
- "stability_by_stress_type": {
- r.config.stress_type: r.max_stable_agents
- for r in results
- },
- "recommendations": self._generate_overall_recommendations(results)
- }
-
- def _generate_overall_recommendations(self, results: List[StressTestResult]) -> List[str]:
- """Generate overall recommendations from all stress tests"""
- recommendations = []
-
- # Collect all individual recommendations
- all_recommendations = []
- for result in results:
- all_recommendations.extend(result.recommendations)
-
- # Find common themes
- if "memory" in " ".join(all_recommendations).lower():
- recommendations.append("Memory optimization is critical across multiple stress scenarios.")
-
- if "coordination" in " ".join(all_recommendations).lower():
- recommendations.append("Coordination mechanisms need optimization for high-scale deployments.")
-
- if "cpu" in " ".join(all_recommendations).lower():
- recommendations.append("CPU utilization optimization required for sustained high loads.")
-
- # Analyze breaking points
- breaking_points = [r.breaking_point_agents for r in results if r.breaking_point_agents]
- if breaking_points:
- min_bp = min(breaking_points)
- if min_bp < 100:
- recommendations.append("Early breaking points indicate fundamental scaling issues that need addressing.")
- elif min_bp < 500:
- recommendations.append("Medium-scale breaking points suggest optimization opportunities for enterprise use.")
- else:
- recommendations.append("Strong scaling characteristics observed across stress scenarios.")
-
- return recommendations
-
- def _save_stress_results(self, results: List[StressTestResult], analysis: Dict[str, Any]) -> Dict[str, str]:
- """Save stress test results and analysis"""
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
-
- # Save detailed results
- results_file = self.output_dir / f"hive_mind_stress_test_results_{timestamp}.json"
- with open(results_file, 'w') as f:
- json.dump([asdict(r) for r in results], f, indent=2)
-
- # Save analysis
- analysis_file = self.output_dir / f"hive_mind_stress_test_analysis_{timestamp}.json"
- with open(analysis_file, 'w') as f:
- json.dump(analysis, f, indent=2)
-
- # Save summary CSV
- csv_file = self.output_dir / f"hive_mind_stress_test_summary_{timestamp}.csv"
- with open(csv_file, 'w') as f:
- f.write("test_name,stress_type,max_stable_agents,breaking_point_agents,failure_mode,")
- f.write("peak_memory_mb,peak_cpu_percent,recovery_attempts,successful_recoveries,recovery_rate\\n")
-
- for result in results:
- config = result.config
- recovery_rate = result.successful_recoveries / result.recovery_attempts if result.recovery_attempts > 0 else 0
- f.write(f"{config.name},{config.stress_type},{result.max_stable_agents},")
- f.write(f"{result.breaking_point_agents},{result.failure_mode},")
- f.write(f"{result.peak_memory_mb:.1f},{result.peak_cpu_percent:.1f},")
- f.write(f"{result.recovery_attempts},{result.successful_recoveries},{recovery_rate:.2f}\\n")
-
- print(f"πŸ“Š Stress test results saved:")
- print(f" πŸ“„ Detailed results: {results_file}")
- print(f" πŸ“ˆ Analysis: {analysis_file}")
- print(f" πŸ“‹ Summary CSV: {csv_file}")
-
- return {
- "results_file": str(results_file),
- "analysis_file": str(analysis_file),
- "csv_file": str(csv_file)
- }
-
-class StressSystemMonitor:
- """Enhanced system monitoring for stress testing"""
-
- def __init__(self):
- self.monitoring = False
- self.metrics = {
- "cpu_samples": [],
- "memory_samples": [],
- "load_samples": [],
- "process_counts": []
- }
-
- def start_monitoring(self) -> threading.Thread:
- """Start enhanced monitoring"""
- self.monitoring = True
- self.metrics = {
- "cpu_samples": [],
- "memory_samples": [],
- "load_samples": [],
- "process_counts": []
- }
-
- def monitor():
- while self.monitoring:
- try:
- # Enhanced metrics collection
- cpu_percent = psutil.cpu_percent(interval=0.1)
- memory = psutil.virtual_memory()
- process_count = len(psutil.pids())
-
- self.metrics["cpu_samples"].append(cpu_percent)
- self.metrics["memory_samples"].append(memory.percent)
- self.metrics["process_counts"].append(process_count)
-
- # Load average (Unix only)
- if hasattr(os, 'getloadavg'):
- load_avg = os.getloadavg()[0]
- self.metrics["load_samples"].append(load_avg)
-
- except Exception:
- pass
-
- time.sleep(0.5) # Higher frequency monitoring for stress tests
-
- thread = threading.Thread(target=monitor)
- thread.daemon = True
- thread.start()
- return thread
-
- def get_current_metrics(self) -> Dict[str, Any]:
- """Get current system metrics"""
- try:
- memory = psutil.virtual_memory()
- return {
- "cpu_percent": psutil.cpu_percent(),
- "memory_percent": memory.percent,
- "memory_mb": memory.used / (1024**2),
- "available_memory_mb": memory.available / (1024**2),
- "process_count": len(psutil.pids()),
- "load_average": os.getloadavg()[0] if hasattr(os, 'getloadavg') else 0
- }
- except Exception:
- return {}
-
- def stop_monitoring(self, thread: Optional[threading.Thread]) -> Dict[str, Any]:
- """Stop monitoring and return comprehensive metrics"""
- self.monitoring = False
-
- if thread:
- thread.join(timeout=2)
-
- if not self.metrics["cpu_samples"]:
- return {}
-
- memory_gb = psutil.virtual_memory().total / (1024**3)
-
- return {
- "peak_cpu_percent": max(self.metrics["cpu_samples"]),
- "avg_cpu_percent": statistics.mean(self.metrics["cpu_samples"]),
- "peak_memory_percent": max(self.metrics["memory_samples"]),
- "avg_memory_percent": statistics.mean(self.metrics["memory_samples"]),
- "peak_memory_mb": max(self.metrics["memory_samples"]) * memory_gb * 1024 / 100,
- "peak_process_count": max(self.metrics["process_counts"]) if self.metrics["process_counts"] else 0,
- "peak_load_average": max(self.metrics["load_samples"]) if self.metrics["load_samples"] else 0,
- "sample_count": len(self.metrics["cpu_samples"])
- }
-
-def main():
- """Main stress testing execution"""
- import argparse
-
- parser = argparse.ArgumentParser(description="Hive Mind Stress Testing Suite")
- parser.add_argument("--quick", action="store_true", help="Run quick stress test")
- parser.add_argument("--stress-type", choices=["memory", "cpu", "coordination", "consensus", "network", "io", "chaos"],
- help="Run specific stress test type")
- parser.add_argument("--max-agents", type=int, default=1000, help="Maximum agents to test")
- parser.add_argument("--output", default="stress-test-results", help="Output directory")
-
- args = parser.parse_args()
-
- tester = HiveMindStressTester(output_dir=args.output)
-
- if args.quick:
- # Quick stress test
- scenario = StressTestConfig(
- name="quick_stress",
- description="Quick stress test",
- stress_type="memory",
- initial_agents=10,
- max_agents=100,
- increment_size=10,
- increment_interval=5.0
- )
-
- result = tester.run_stress_test(scenario)
- analysis = tester._analyze_stress_results([result])
- tester._save_stress_results([result], analysis)
-
- elif args.stress_type:
- # Specific stress type
- scenarios = [s for s in tester.create_stress_test_scenarios() if s.stress_type == args.stress_type]
-
- results = []
- for scenario in scenarios:
- result = tester.run_stress_test(scenario)
- results.append(result)
-
- analysis = tester._analyze_stress_results(results)
- tester._save_stress_results(results, analysis)
-
- else:
- # Full comprehensive stress testing
- analysis = tester.run_comprehensive_stress_testing()
-
- # Print summary
- summary = analysis["summary"]
- print("\\nπŸ’₯ STRESS TESTING SUMMARY")
- print("=" * 50)
- print(f"Total tests: {summary['total_tests']}")
- print(f"Min breaking point: {summary['min_breaking_point']} agents" if summary['min_breaking_point'] else "No breaking point found")
- print(f"Avg breaking point: {summary['avg_breaking_point']:.0f} agents" if summary['avg_breaking_point'] else "N/A")
- print(f"Max stable agents: {summary['max_stable_agents']}")
- print(f"Peak memory usage: {summary['peak_memory_mb']:.1f}MB")
- print(f"Peak CPU usage: {summary['peak_cpu_percent']:.1f}%")
- print(f"Recovery success rate: {summary['recovery_rate']:.1%}")
-
- # Print failure modes
- if analysis["failure_modes"]:
- print("\\nπŸ’₯ FAILURE MODES")
- for mode, count in analysis["failure_modes"].items():
- print(f" {mode}: {count} occurrences")
-
- # Print recommendations
- if analysis["recommendations"]:
- print("\\nπŸ’‘ RECOMMENDATIONS")
- for i, rec in enumerate(analysis["recommendations"], 1):
- print(f"{i}. {rec}")
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/benchmark/ml_pipeline_claude.md b/benchmark/ml_pipeline_claude.md
deleted file mode 100644
index e240353026..0000000000
--- a/benchmark/ml_pipeline_claude.md
+++ /dev/null
@@ -1,121 +0,0 @@
-# CLAUDE.md - Optimized for Ml Pipeline
-
-<!-- Generated by CLAUDE.md Optimizer at 2025-08-06 01:57 -->
-
-## 🎯 Configuration Overview
-- **Use Case**: Ml Pipeline
-- **Optimization Target**: balanced
-- **Team Size**: N/A
-- **Complexity**: medium
-
-## ⚑ Performance Configuration
-- **Execution Mode**: Batch-optimized
-- **Agent Count**: 7 (ml-developer, performance-benchmarker, researcher, reviewer, tester)
-- **Topology**: Mesh
-- **Batch Operations**: RECOMMENDED
-- **Parallel Execution**: STANDARD
-- **Optimizations**:
- - Gpu Optimization
- - Batch Processing
- - Distributed Training
- - Memory Mapping
-
-## 🎯 Primary Objectives
-1. Model training
-2. Data preprocessing
-3. Feature engineering
-4. Implement ensemble learning with MLE-STAR
-5. Achieve >90% model accuracy
-6. Optimize training time <30 minutes
-
-## πŸš€ Execution Rules
-
-### CRITICAL: Concurrency Requirements
-```javascript
-// ALWAYS execute in single message:
-[
- Task("Ml Developer", "...", "ml-developer"),
- Task("Performance Benchmarker", "...", "performance-benchmarker"),
- Task("Researcher", "...", "researcher"),
- Task("Reviewer", "...", "reviewer"),
- TodoWrite({ todos: [ALL_TASKS] }),
- // ... all related operations
-]```
-
-### Critical Rules
-- Use MLE-STAR for ensemble coordination
-- Implement cross-validation
-- Track all experiments
-- Optimize hyperparameters
-- ALWAYS execute models in parallel
-- Batch data processing operations
-- Enable memory persistence for training state
-- Always run tests after changes
-- Use type checking and linting
-- Implement comprehensive error handling
-- Request code review from reviewer agent
-- Validate all inputs and outputs
-- Use static analysis tools
-- Implement integration testing
-- Add comprehensive logging
-- Verify requirements before implementation
-- Use defensive programming practices
-- Implement comprehensive logging
-- Use distributed tracing
-- Enable advanced monitoring
-
-### Tool Priority Order
-1. MultiEdit β†’ Edit β†’ Bash β†’ Read
-
-### Ml Pipeline Workflow
-**Data Preprocessing**: Batch data validation and cleaning
-**Feature Engineering**: Parallel feature extraction
-**Model Training**: MLE-STAR ensemble coordination
-**Evaluation**: Cross-validation with multiple metrics
-**Deployment**: Automated model versioning and deployment
-
-## πŸ€– Agent Configuration
-- **Swarm Topology**: Mesh
-- **Maximum Agents**: 7
-- **Preferred Agent Types**: ml-developer, performance-benchmarker, researcher, reviewer, tester
-
-### Coordination Features
-- Neural Patterns: Enabled
-- Memory Sharing: Enabled
-- Collective Intelligence: Enabled
-
-## πŸ“Š Success Metrics
-- Model Accuracy: >90%
-- Training Time: <30 min
-- Memory Usage: <8GB
-- Ensemble Consensus: >95%
-
-## 🧠 MLE-STAR Configuration
-- **Ensemble Size**: 5 models
-- **Voting Strategy**: Weighted consensus
-- **Model Diversity**: High
-
-### Ensemble Coordination Pattern
-```python
-# Initialize MLE-STAR ensemble
-mcp__claude-flow__swarm_init({
- topology: "mesh",
- maxAgents: 8,
- mle_star: {
- enabled: true,
- models: ["model1", "model2", "model3", "model4", "model5"],
- consensus: "weighted_voting"
- }
-})
-
-# Spawn ML agents in parallel
-[
- Task("Data Preprocessing", "...", "ml-developer"),
- Task("Feature Engineering", "...", "ml-developer"),
- Task("Model Training", "...", "ml-developer"),
- Task("Hyperparameter Tuning", "...", "optimizer"),
- Task("Model Evaluation", "...", "tester")
-]
-```
-
-## πŸ”„ Agent Coordination Protocol
\ No newline at end of file
diff --git a/benchmark/mle_star_benchmark_example.py b/benchmark/mle_star_benchmark_example.py
deleted file mode 100644
index a8862011fc..0000000000
--- a/benchmark/mle_star_benchmark_example.py
+++ /dev/null
@@ -1,229 +0,0 @@
-#!/usr/bin/env python3
-"""
-MLE-STAR Benchmark Integration Example
-
-Shows how to integrate MLE-STAR ensemble capabilities
-with the existing Claude Flow benchmark system.
-"""
-
-import asyncio
-import sys
-import os
-import time
-from typing import Dict, Any
-
-# Add the src directory to Python path
-sys.path.insert(0, str(Path(__file__).parent / "src"))
-
-from swarm_benchmark.mle_star import MLScenarios, MLEStarEnsembleExecutor, MLEStarConfig
-# Integration with existing benchmark system would use these imports when available
-# from swarm_benchmark.core.models import BenchmarkResult, ComprehensiveBenchmarkResult
-
-
-async def run_mle_star_benchmark_suite():
- """Run a comprehensive MLE-STAR benchmark suite."""
- print("πŸš€ MLE-STAR Benchmark Suite Integration")
- print("=" * 60)
-
- start_time = time.time()
-
- # Initialize results collector
- all_results = {}
-
- # 1. Run Classification Benchmarks
- print("\n🧠 Classification Ensemble Benchmarks")
- print("-" * 40)
-
- classification_scenarios = [
- "classification_ensemble_small",
- "classification_ensemble_large"
- ]
-
- for scenario_name in classification_scenarios:
- try:
- print(f"Running {scenario_name}...")
- scenario_config = MLScenarios.get_scenario_by_name(scenario_name)
-
- if scenario_config:
- from swarm_benchmark.mle_star.ml_scenarios import ClassificationScenario
- scenario = ClassificationScenario(scenario_config)
- result = await scenario.run_scenario()
-
- all_results[scenario_name] = result
-
- status = "βœ… PASSED" if result['success'] else "❌ FAILED"
- exec_time = f"{result['execution_time']:.2f}s"
- print(f" {status} - {exec_time}")
-
- if result['success']:
- metrics = result.get('metrics', {})
- ensemble_size = metrics.get('ensemble', {}).get('ensemble_size', 'N/A')
- accuracy = metrics.get('performance', {}).get('accuracy', 'N/A')
- print(f" Ensemble: {ensemble_size} models, Accuracy: {accuracy}")
-
- except Exception as e:
- print(f" ❌ FAILED - {str(e)}")
- all_results[scenario_name] = {'success': False, 'error': str(e)}
-
- # 2. Run Regression Benchmarks
- print("\nπŸ“Š Regression Ensemble Benchmarks")
- print("-" * 40)
-
- regression_scenarios = [
- "regression_ensemble_small",
- # "regression_ensemble_large" # Skip large for demo
- ]
-
- for scenario_name in regression_scenarios:
- try:
- print(f"Running {scenario_name}...")
- scenario_config = MLScenarios.get_scenario_by_name(scenario_name)
-
- if scenario_config:
- from swarm_benchmark.mle_star.ml_scenarios import RegressionScenario
- scenario = RegressionScenario(scenario_config)
- result = await scenario.run_scenario()
-
- all_results[scenario_name] = result
-
- status = "βœ… PASSED" if result['success'] else "❌ FAILED"
- exec_time = f"{result['execution_time']:.2f}s"
- print(f" {status} - {exec_time}")
-
- if result['success']:
- metrics = result.get('metrics', {})
- ensemble_size = metrics.get('ensemble', {}).get('ensemble_size', 'N/A')
- r2_score = metrics.get('performance', {}).get('accuracy', 'N/A')
- print(f" Ensemble: {ensemble_size} models, RΒ²: {r2_score}")
-
- except Exception as e:
- print(f" ❌ FAILED - {str(e)}")
- all_results[scenario_name] = {'success': False, 'error': str(e)}
-
- # 3. Custom Ensemble Benchmark
- print("\nπŸ”§ Custom Ensemble Benchmark")
- print("-" * 40)
-
- try:
- print("Running custom weighted ensemble...")
-
- # Create custom ensemble configuration
- config = MLEStarConfig(
- models=[
- {"type": "random_forest", "n_estimators": 20, "task": "classification"},
- {"type": "gradient_boost", "n_estimators": 20, "task": "classification"},
- {"type": "logistic_regression", "C": 1.0, "max_iter": 100, "task": "classification"}
- ],
- voting_strategy="weighted",
- ensemble_size=3,
- max_parallel=3,
- timeout=60.0
- )
-
- # Generate simple test dataset
- import numpy as np
- from sklearn.datasets import make_classification
- from sklearn.model_selection import train_test_split
-
- X, y = make_classification(n_samples=500, n_features=10, n_classes=2, random_state=42)
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
-
- # Create dataset info object
- from swarm_benchmark.mle_star.ml_scenarios import DatasetInfo, DatasetSize
- dataset = DatasetInfo(
- X_train=X_train, X_test=X_test, y_train=y_train, y_test=y_test,
- feature_names=[f'feature_{i}' for i in range(10)],
- target_names=['class_0', 'class_1'],
- dataset_size=DatasetSize.SMALL,
- n_features=10,
- n_classes=2
- )
-
- # Run custom benchmark
- ensemble = MLEStarEnsembleExecutor(config)
-
- # Train models manually
- await ensemble._initialize_models_parallel()
-
- # Train each model
- for model_agent in ensemble.models:
- await model_agent.train(X_train, y_train)
-
- # Make predictions
- predictions = await ensemble._gather_predictions(X_test)
- final_prediction, consensus_details = await ensemble._build_consensus(predictions)
-
- # Calculate accuracy
- if hasattr(final_prediction, 'argmax'):
- y_pred = final_prediction.argmax(axis=1) if len(final_prediction.shape) > 1 else final_prediction.argmax()
- else:
- y_pred = final_prediction
-
- from sklearn.metrics import accuracy_score
- accuracy = accuracy_score(y_test, y_pred) if y_pred is not None else 0.0
-
- await ensemble.cleanup()
-
- print(f" βœ… PASSED - Custom ensemble")
- print(f" Models: {len(config.models)}, Voting: {config.voting_strategy}")
- print(f" Accuracy: {accuracy:.3f}, Consensus: {consensus_details.get('consensus_strength', 'N/A')}")
-
- all_results['custom_weighted_ensemble'] = {
- 'success': True,
- 'accuracy': accuracy,
- 'ensemble_size': len(config.models),
- 'voting_strategy': config.voting_strategy,
- 'consensus_strength': consensus_details.get('consensus_strength', 0.0)
- }
-
- except Exception as e:
- print(f" ❌ FAILED - {str(e)}")
- all_results['custom_weighted_ensemble'] = {'success': False, 'error': str(e)}
-
- # 4. Summary Report
- total_time = time.time() - start_time
-
- print("\n" + "=" * 60)
- print("πŸ“Š BENCHMARK SUITE SUMMARY")
- print("=" * 60)
-
- successful_benchmarks = sum(1 for result in all_results.values() if result.get('success', False))
- total_benchmarks = len(all_results)
-
- print(f"Total Benchmarks: {total_benchmarks}")
- print(f"Successful: {successful_benchmarks}")
- print(f"Failed: {total_benchmarks - successful_benchmarks}")
- print(f"Success Rate: {successful_benchmarks / total_benchmarks * 100:.1f}%")
- print(f"Total Execution Time: {total_time:.2f}s")
-
- print("\nπŸ“‹ Individual Results:")
- for benchmark_name, result in all_results.items():
- status = "βœ…" if result.get('success', False) else "❌"
- error_info = f" ({result.get('error', '')})" if not result.get('success', False) else ""
- print(f" {status} {benchmark_name}{error_info}")
-
- # 5. Integration with Existing System
- print("\nπŸ”— Integration Capabilities:")
- print(" βœ… MLE-STAR module fully integrated")
- print(" βœ… Compatible with existing benchmark framework")
- print(" βœ… Supports all standard ML metrics")
- print(" βœ… Async/await compatible")
- print(" βœ… Resource management and cleanup")
- print(" βœ… Performance tracking included")
-
- success_rate = successful_benchmarks / total_benchmarks
- return success_rate >= 0.5 # Consider success if >50% pass
-
-
-if __name__ == "__main__":
- import logging
- logging.basicConfig(level=logging.WARNING) # Reduce noise
-
- success = asyncio.run(run_mle_star_benchmark_suite())
-
- if success:
- print("\nπŸŽ‰ MLE-STAR Benchmark Suite: OVERALL SUCCESS")
- else:
- print("\n⚠️ MLE-STAR Benchmark Suite: NEEDS ATTENTION")
-
- sys.exit(0 if success else 1)
\ No newline at end of file
diff --git a/benchmark/performance_dashboard.py b/benchmark/performance_dashboard.py
deleted file mode 100644
index 96d475ddc7..0000000000
--- a/benchmark/performance_dashboard.py
+++ /dev/null
@@ -1,769 +0,0 @@
-#!/usr/bin/env python3
-"""
-Performance Dashboard Generator for Claude-Flow Swarm Operations
-
-This script generates interactive HTML dashboards for performance monitoring:
-- Real-time performance metrics visualization
-- Historical trend analysis and charts
-- Performance regression tracking
-- Interactive charts and graphs
-- Automated report generation
-
-Author: Metrics Analyst Agent
-Version: 1.0.0
-"""
-
-import json
-import os
-import sys
-from datetime import datetime, timedelta
-from pathlib import Path
-from typing import Dict, List, Any, Optional
-import statistics
-from dataclasses import asdict
-
-# Add local modules to path
-sys.path.insert(0, str(Path(__file__).parent))
-
-try:
- from continuous_performance_monitor import PerformanceMonitor, MetricSnapshot
-except ImportError:
- print("Warning: Could not import performance monitor - dashboard will use sample data")
-
-
-class PerformanceDashboard:
- """Generates interactive performance dashboards."""
-
- def __init__(self, output_dir: str = "dashboard_output"):
- self.output_dir = Path(output_dir)
- self.output_dir.mkdir(exist_ok=True)
-
- def generate_dashboard(self, data_source: str = "database") -> str:
- """Generate complete performance dashboard."""
- print("πŸ“Š Generating Performance Dashboard...")
-
- # Collect data
- if data_source == "database":
- dashboard_data = self._collect_database_data()
- else:
- dashboard_data = self._generate_sample_data()
-
- # Generate HTML dashboard
- dashboard_file = self._generate_html_dashboard(dashboard_data)
-
- # Generate additional reports
- self._generate_csv_export(dashboard_data)
- self._generate_json_export(dashboard_data)
-
- print(f"βœ… Dashboard generated: {dashboard_file}")
- return str(dashboard_file)
-
- def _collect_database_data(self) -> Dict[str, Any]:
- """Collect data from performance database."""
- try:
- monitor = PerformanceMonitor()
-
- # Get dashboard data for different time periods
- data = {
- "last_24h": monitor.get_performance_dashboard_data(24),
- "last_7d": monitor.get_performance_dashboard_data(168),
- "last_30d": monitor.get_performance_dashboard_data(720),
- "regression_report": monitor.generate_regression_report()
- }
-
- return data
-
- except Exception as e:
- print(f"Warning: Could not collect database data: {e}")
- return self._generate_sample_data()
-
- def _generate_sample_data(self) -> Dict[str, Any]:
- """Generate sample data for demonstration."""
- import random
-
- # Generate sample time series data
- now = datetime.now()
- time_series = []
-
- for i in range(100):
- timestamp = now - timedelta(hours=i)
- time_series.append({
- "timestamp": timestamp.isoformat(),
- "swarm_init_time": random.uniform(1.0, 8.0),
- "agent_coordination_latency": random.uniform(50, 300),
- "memory_usage_mb": random.uniform(20, 80),
- "token_consumption_rate": random.uniform(80, 150),
- "mcp_response_time": random.uniform(0.2, 2.0),
- "neural_processing_time": random.uniform(100, 800),
- "active_agents": random.randint(0, 8),
- "cpu_usage_percent": random.uniform(10, 70)
- })
-
- return {
- "last_24h": {
- "summary": {
- "total_samples": 100,
- "time_range_hours": 24,
- "last_update": now.isoformat()
- },
- "swarm_performance": {
- "avg_init_time": 3.2,
- "max_init_time": 7.8,
- "avg_coordination_latency": 180.5,
- "max_coordination_latency": 295.2
- },
- "resource_usage": {
- "avg_memory_mb": 45.3,
- "peak_memory_mb": 78.9,
- "memory_trend": "stable"
- },
- "time_series": time_series,
- "baselines": {
- "swarm_init_time": 5.0,
- "agent_coordination_latency": 200.0,
- "memory_usage_mb": 50.0
- }
- },
- "regression_report": {
- "analysis_period": {
- "recent_period_hours": 24,
- "historical_period_hours": 168
- },
- "regression_analysis": {
- "swarm_init_time": {
- "recent_avg": 3.2,
- "historical_avg": 3.5,
- "regression_percent": -8.6,
- "regression_detected": False
- },
- "memory_usage": {
- "recent_avg": 45.3,
- "historical_avg": 42.1,
- "regression_percent": 7.6,
- "regression_detected": False
- }
- }
- }
- }
-
- def _generate_html_dashboard(self, data: Dict[str, Any]) -> Path:
- """Generate HTML dashboard file."""
- dashboard_data = data.get("last_24h", {})
- regression_data = data.get("regression_report", {})
-
- html_content = self._create_html_template(dashboard_data, regression_data)
-
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- dashboard_file = self.output_dir / f"performance_dashboard_{timestamp}.html"
-
- with open(dashboard_file, 'w') as f:
- f.write(html_content)
-
- # Also create a 'latest' version
- latest_file = self.output_dir / "performance_dashboard_latest.html"
- with open(latest_file, 'w') as f:
- f.write(html_content)
-
- return dashboard_file
-
- def _create_html_template(self, dashboard_data: Dict[str, Any], regression_data: Dict[str, Any]) -> str:
- """Create HTML template with embedded data and charts."""
-
- summary = dashboard_data.get("summary", {})
- swarm_perf = dashboard_data.get("swarm_performance", {})
- resource_usage = dashboard_data.get("resource_usage", {})
- time_series = dashboard_data.get("time_series", [])
- baselines = dashboard_data.get("baselines", {})
-
- # Create JavaScript data for charts
- chart_data = {
- "timeSeries": time_series[-50:], # Last 50 data points
- "baselines": baselines,
- "summary": summary,
- "swarmPerf": swarm_perf,
- "resourceUsage": resource_usage,
- "regressionData": regression_data
- }
-
- html_template = f"""
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Claude-Flow Swarm Performance Dashboard</title>
- <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
- <style>
- body {{
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- margin: 0;
- padding: 20px;
- background-color: #f5f5f5;
- }}
- .container {{
- max-width: 1200px;
- margin: 0 auto;
- background: white;
- border-radius: 8px;
- box-shadow: 0 2px 10px rgba(0,0,0,0.1);
- overflow: hidden;
- }}
- .header {{
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
- color: white;
- padding: 30px;
- text-align: center;
- }}
- .header h1 {{
- margin: 0;
- font-size: 2.5em;
- font-weight: 300;
- }}
- .header p {{
- margin: 10px 0 0;
- opacity: 0.9;
- font-size: 1.1em;
- }}
- .metrics-grid {{
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
- gap: 20px;
- padding: 30px;
- }}
- .metric-card {{
- background: white;
- border: 1px solid #e1e5e9;
- border-radius: 8px;
- padding: 20px;
- text-align: center;
- transition: transform 0.2s;
- }}
- .metric-card:hover {{
- transform: translateY(-2px);
- box-shadow: 0 4px 15px rgba(0,0,0,0.1);
- }}
- .metric-value {{
- font-size: 2.5em;
- font-weight: bold;
- margin-bottom: 5px;
- }}
- .metric-label {{
- color: #666;
- font-size: 0.9em;
- text-transform: uppercase;
- letter-spacing: 1px;
- }}
- .metric-target {{
- font-size: 0.8em;
- color: #999;
- margin-top: 5px;
- }}
- .status-good {{ color: #28a745; }}
- .status-warning {{ color: #ffc107; }}
- .status-critical {{ color: #dc3545; }}
- .charts-section {{
- padding: 30px;
- background: #fafafa;
- }}
- .chart-container {{
- background: white;
- border-radius: 8px;
- padding: 20px;
- margin-bottom: 30px;
- border: 1px solid #e1e5e9;
- }}
- .chart-title {{
- font-size: 1.3em;
- font-weight: 600;
- margin-bottom: 20px;
- color: #333;
- }}
- .chart-canvas {{
- max-height: 400px;
- }}
- .regression-section {{
- padding: 30px;
- background: #f8f9fa;
- border-top: 1px solid #e1e5e9;
- }}
- .regression-item {{
- background: white;
- border-radius: 6px;
- padding: 15px;
- margin-bottom: 15px;
- border-left: 4px solid #007bff;
- }}
- .regression-item.warning {{ border-left-color: #ffc107; }}
- .regression-item.critical {{ border-left-color: #dc3545; }}
- .regression-item.improvement {{ border-left-color: #28a745; }}
- .footer {{
- background: #333;
- color: white;
- text-align: center;
- padding: 20px;
- font-size: 0.9em;
- }}
- .refresh-info {{
- position: fixed;
- top: 20px;
- right: 20px;
- background: rgba(0,0,0,0.8);
- color: white;
- padding: 10px 15px;
- border-radius: 5px;
- font-size: 0.8em;
- }}
- </style>
-</head>
-<body>
- <div class="refresh-info">
- Last updated: {summary.get("last_update", datetime.now().isoformat())[:19]}
- </div>
-
- <div class="container">
- <div class="header">
- <h1>πŸš€ Claude-Flow Swarm Performance Dashboard</h1>
- <p>Real-time monitoring and performance analytics</p>
- </div>
-
- <div class="metrics-grid">
- <div class="metric-card">
- <div class="metric-value status-{self._get_status(swarm_perf.get("avg_init_time", 0), baselines.get("swarm_init_time", 5.0))}">
- {swarm_perf.get("avg_init_time", 0):.2f}s
- </div>
- <div class="metric-label">Avg Swarm Init Time</div>
- <div class="metric-target">Target: &lt; {baselines.get("swarm_init_time", 5.0)}s</div>
- </div>
-
- <div class="metric-card">
- <div class="metric-value status-{self._get_status(swarm_perf.get("avg_coordination_latency", 0), baselines.get("agent_coordination_latency", 200.0))}">
- {swarm_perf.get("avg_coordination_latency", 0):.1f}ms
- </div>
- <div class="metric-label">Avg Coordination Latency</div>
- <div class="metric-target">Target: &lt; {baselines.get("agent_coordination_latency", 200.0)}ms</div>
- </div>
-
- <div class="metric-card">
- <div class="metric-value status-{self._get_status(resource_usage.get("avg_memory_mb", 0), baselines.get("memory_usage_mb", 50.0))}">
- {resource_usage.get("avg_memory_mb", 0):.1f}MB
- </div>
- <div class="metric-label">Avg Memory Usage</div>
- <div class="metric-target">Target: &lt; {baselines.get("memory_usage_mb", 50.0)}MB</div>
- </div>
-
- <div class="metric-card">
- <div class="metric-value status-good">
- {resource_usage.get("peak_memory_mb", 0):.1f}MB
- </div>
- <div class="metric-label">Peak Memory Usage</div>
- <div class="metric-target">Trend: {resource_usage.get("memory_trend", "unknown")}</div>
- </div>
- </div>
-
- <div class="charts-section">
- <div class="chart-container">
- <div class="chart-title">πŸ“ˆ Performance Trends (Last 24 Hours)</div>
- <canvas id="performanceTrendChart" class="chart-canvas"></canvas>
- </div>
-
- <div class="chart-container">
- <div class="chart-title">πŸ’Ύ Memory Usage Over Time</div>
- <canvas id="memoryUsageChart" class="chart-canvas"></canvas>
- </div>
-
- <div class="chart-container">
- <div class="chart-title">πŸ•’ Response Time Distribution</div>
- <canvas id="responseTimeChart" class="chart-canvas"></canvas>
- </div>
- </div>
-
- <div class="regression-section">
- <h2>πŸ” Performance Regression Analysis</h2>
- {self._generate_regression_html(regression_data)}
- </div>
-
- <div class="footer">
- Generated by Claude-Flow Metrics Analyst Agent |
- Version 1.0.0 |
- {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
- </div>
- </div>
-
- <script>
- // Dashboard data
- const dashboardData = {json.dumps(chart_data, indent=2, default=str)};
-
- // Initialize charts when page loads
- document.addEventListener('DOMContentLoaded', function() {{
- initializeCharts();
- }});
-
- function initializeCharts() {{
- createPerformanceTrendChart();
- createMemoryUsageChart();
- createResponseTimeChart();
- }}
-
- function createPerformanceTrendChart() {{
- const ctx = document.getElementById('performanceTrendChart').getContext('2d');
- const timeSeries = dashboardData.timeSeries;
-
- new Chart(ctx, {{
- type: 'line',
- data: {{
- labels: timeSeries.map(d => new Date(d.timestamp).toLocaleTimeString()),
- datasets: [{{
- label: 'Swarm Init Time (s)',
- data: timeSeries.map(d => d.swarm_init_time),
- borderColor: 'rgb(75, 192, 192)',
- backgroundColor: 'rgba(75, 192, 192, 0.1)',
- tension: 0.1
- }}, {{
- label: 'Coordination Latency (ms)',
- data: timeSeries.map(d => d.agent_coordination_latency),
- borderColor: 'rgb(255, 99, 132)',
- backgroundColor: 'rgba(255, 99, 132, 0.1)',
- yAxisID: 'y1',
- tension: 0.1
- }}]
- }},
- options: {{
- responsive: true,
- interaction: {{
- mode: 'index',
- intersect: false,
- }},
- scales: {{
- x: {{
- display: true,
- title: {{
- display: true,
- text: 'Time'
- }}
- }},
- y: {{
- type: 'linear',
- display: true,
- position: 'left',
- title: {{
- display: true,
- text: 'Init Time (seconds)'
- }}
- }},
- y1: {{
- type: 'linear',
- display: true,
- position: 'right',
- title: {{
- display: true,
- text: 'Latency (ms)'
- }},
- grid: {{
- drawOnChartArea: false,
- }},
- }}
- }}
- }}
- }});
- }}
-
- function createMemoryUsageChart() {{
- const ctx = document.getElementById('memoryUsageChart').getContext('2d');
- const timeSeries = dashboardData.timeSeries;
-
- new Chart(ctx, {{
- type: 'area',
- data: {{
- labels: timeSeries.map(d => new Date(d.timestamp).toLocaleTimeString()),
- datasets: [{{
- label: 'Memory Usage (MB)',
- data: timeSeries.map(d => d.memory_usage_mb),
- borderColor: 'rgb(153, 102, 255)',
- backgroundColor: 'rgba(153, 102, 255, 0.2)',
- fill: true,
- tension: 0.1
- }}]
- }},
- options: {{
- responsive: true,
- plugins: {{
- title: {{
- display: true,
- text: 'Memory Usage Trend'
- }}
- }},
- scales: {{
- y: {{
- beginAtZero: true,
- title: {{
- display: true,
- text: 'Memory (MB)'
- }}
- }}
- }}
- }}
- }});
- }}
-
- function createResponseTimeChart() {{
- const ctx = document.getElementById('responseTimeChart').getContext('2d');
- const timeSeries = dashboardData.timeSeries;
-
- // Create histogram data
- const responseTimeBins = [0, 0.5, 1.0, 1.5, 2.0, 2.5];
- const binCounts = new Array(responseTimeBins.length - 1).fill(0);
-
- timeSeries.forEach(d => {{
- const responseTime = d.mcp_response_time;
- for (let i = 0; i < responseTimeBins.length - 1; i++) {{
- if (responseTime >= responseTimeBins[i] && responseTime < responseTimeBins[i + 1]) {{
- binCounts[i]++;
- break;
- }}
- }}
- }});
-
- new Chart(ctx, {{
- type: 'bar',
- data: {{
- labels: responseTimeBins.slice(0, -1).map((bin, i) =>
- `${{bin}}-${{responseTimeBins[i + 1]}}s`),
- datasets: [{{
- label: 'Response Time Distribution',
- data: binCounts,
- backgroundColor: 'rgba(54, 162, 235, 0.5)',
- borderColor: 'rgba(54, 162, 235, 1)',
- borderWidth: 1
- }}]
- }},
- options: {{
- responsive: true,
- plugins: {{
- title: {{
- display: true,
- text: 'MCP Response Time Distribution'
- }}
- }},
- scales: {{
- y: {{
- beginAtZero: true,
- title: {{
- display: true,
- text: 'Frequency'
- }}
- }},
- x: {{
- title: {{
- display: true,
- text: 'Response Time Range'
- }}
- }}
- }}
- }}
- }});
- }}
- </script>
-</body>
-</html>"""
-
- return html_template
-
- def _get_status(self, value: float, target: float) -> str:
- """Get status class based on value vs target."""
- if value <= target:
- return "good"
- elif value <= target * 1.2:
- return "warning"
- else:
- return "critical"
-
- def _generate_regression_html(self, regression_data: Dict[str, Any]) -> str:
- """Generate HTML for regression analysis section."""
- if not regression_data or "regression_analysis" not in regression_data:
- return "<p>No regression data available.</p>"
-
- analysis = regression_data["regression_analysis"]
- html_parts = []
-
- for metric_name, metric_data in analysis.items():
- regression_percent = metric_data.get("regression_percent", 0)
- regression_detected = metric_data.get("regression_detected", False)
- recent_avg = metric_data.get("recent_avg", 0)
- historical_avg = metric_data.get("historical_avg", 0)
-
- # Determine status class
- if regression_percent < -5:
- status_class = "improvement"
- icon = "πŸš€"
- status_text = "Improvement"
- elif regression_percent > 15:
- status_class = "critical"
- icon = "🚨"
- status_text = "Critical Regression"
- elif regression_percent > 5:
- status_class = "warning"
- icon = "⚠️"
- status_text = "Warning"
- else:
- status_class = ""
- icon = "βœ…"
- status_text = "Stable"
-
- html_parts.append(f"""
- <div class="regression-item {status_class}">
- <h4>{icon} {metric_name.replace('_', ' ').title()}</h4>
- <p><strong>Status:</strong> {status_text}</p>
- <p><strong>Change:</strong> {regression_percent:+.1f}%</p>
- <p><strong>Recent Average:</strong> {recent_avg:.2f}</p>
- <p><strong>Historical Average:</strong> {historical_avg:.2f}</p>
- </div>
- """)
-
- return "".join(html_parts)
-
- def _generate_csv_export(self, data: Dict[str, Any]):
- """Generate CSV export of performance data."""
- dashboard_data = data.get("last_24h", {})
- time_series = dashboard_data.get("time_series", [])
-
- if not time_series:
- return
-
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- csv_file = self.output_dir / f"performance_data_{timestamp}.csv"
-
- # Write CSV header and data
- with open(csv_file, 'w') as f:
- if time_series:
- # Write header
- headers = list(time_series[0].keys())
- f.write(",".join(headers) + "\n")
-
- # Write data rows
- for row in time_series:
- values = [str(row.get(h, "")) for h in headers]
- f.write(",".join(values) + "\n")
-
- print(f"πŸ“„ CSV export saved: {csv_file}")
-
- def _generate_json_export(self, data: Dict[str, Any]):
- """Generate JSON export of all dashboard data."""
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- json_file = self.output_dir / f"dashboard_data_{timestamp}.json"
-
- with open(json_file, 'w') as f:
- json.dump(data, f, indent=2, default=str)
-
- print(f"πŸ“‹ JSON export saved: {json_file}")
-
-
-def create_dashboard_server():
- """Create a simple HTTP server for the dashboard."""
- server_script = """#!/usr/bin/env python3
-import http.server
-import socketserver
-import webbrowser
-import os
-from pathlib import Path
-
-PORT = 8000
-dashboard_dir = Path(__file__).parent / "dashboard_output"
-
-class DashboardHandler(http.server.SimpleHTTPRequestHandler):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, directory=str(dashboard_dir), **kwargs)
-
-if __name__ == "__main__":
- os.chdir(dashboard_dir)
-
- with socketserver.TCPServer(("", PORT), DashboardHandler) as httpd:
- print(f"🌐 Performance Dashboard Server started at http://localhost:{PORT}")
- print("πŸ“Š Available dashboards:")
-
- for file in dashboard_dir.glob("*.html"):
- print(f" http://localhost:{PORT}/{file.name}")
-
- try:
- # Try to open in browser
- webbrowser.open(f"http://localhost:{PORT}/performance_dashboard_latest.html")
- except:
- pass
-
- print("\\nPress Ctrl+C to stop the server")
-
- try:
- httpd.serve_forever()
- except KeyboardInterrupt:
- print("\\nπŸ›‘ Dashboard server stopped")
-"""
-
- server_file = Path("dashboard_server.py")
- with open(server_file, 'w') as f:
- f.write(server_script)
-
- # Make executable
- os.chmod(server_file, 0o755)
-
- print(f"βœ… Dashboard server created: {server_file}")
- print(f" Run with: python {server_file}")
-
-
-def main():
- """Main entry point for dashboard generation."""
- import argparse
-
- parser = argparse.ArgumentParser(description="Performance Dashboard Generator")
- parser.add_argument("--output-dir", default="dashboard_output", help="Output directory")
- parser.add_argument("--data-source", choices=["database", "sample"], default="database", help="Data source")
- parser.add_argument("--create-server", action="store_true", help="Create dashboard server script")
- parser.add_argument("--serve", action="store_true", help="Generate dashboard and start server")
-
- args = parser.parse_args()
-
- if args.create_server:
- create_dashboard_server()
- return
-
- # Generate dashboard
- dashboard = PerformanceDashboard(args.output_dir)
- dashboard_file = dashboard.generate_dashboard(args.data_source)
-
- if args.serve:
- import subprocess
- import webbrowser
- import time
-
- # Create server if it doesn't exist
- if not Path("dashboard_server.py").exists():
- create_dashboard_server()
-
- print("🌐 Starting dashboard server...")
-
- try:
- # Start server in background
- server_process = subprocess.Popen(
- ["python", "dashboard_server.py"],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE
- )
-
- # Give server time to start
- time.sleep(2)
-
- # Open in browser
- webbrowser.open("http://localhost:8000/performance_dashboard_latest.html")
-
- print("Dashboard is now running at http://localhost:8000")
- print("Press Ctrl+C to stop...")
-
- # Wait for user to stop
- server_process.wait()
-
- except KeyboardInterrupt:
- if 'server_process' in locals():
- server_process.terminate()
- print("\nπŸ›‘ Dashboard server stopped")
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/benchmark/performance_optimization_claude.md b/benchmark/performance_optimization_claude.md
deleted file mode 100644
index b8c1139da5..0000000000
--- a/benchmark/performance_optimization_claude.md
+++ /dev/null
@@ -1,76 +0,0 @@
-# CLAUDE.md - Optimized for Performance Optimization
-
-<!-- Generated by CLAUDE.md Optimizer at 2025-08-06 01:57 -->
-
-## 🎯 Configuration Overview
-- **Use Case**: Performance Optimization
-- **Optimization Target**: balanced
-- **Team Size**: N/A
-- **Complexity**: medium
-
-## ⚑ Performance Configuration
-- **Execution Mode**: Standard
-- **Agent Count**: 7 (performance-benchmarker, perf-analyzer, optimizer)
-- **Topology**: Mesh
-- **Batch Operations**: RECOMMENDED
-- **Parallel Execution**: STANDARD
-
-## 🎯 Primary Objectives
-1. Bottleneck identification
-2. Performance testing
-3. Optimization
-4. Identify and resolve performance bottlenecks
-5. Implement performance budgets and monitoring
-6. Achieve target performance metrics
-
-## πŸš€ Execution Rules
-
-### CRITICAL: Concurrency Requirements
-```javascript
-// ALWAYS execute in single message:
-[
- Task("Performance Benchmarker", "...", "performance-benchmarker"),
- Task("Perf Analyzer", "...", "perf-analyzer"),
- Task("Optimizer", "...", "optimizer"),
- TodoWrite({ todos: [ALL_TASKS] }),
- // ... all related operations
-]```
-
-### Critical Rules
-- Profile before optimizing
-- Measure everything
-- Implement performance budgets
-- Monitor continuously
-- ALWAYS batch performance tests
-- Parallel benchmarking
-- ALWAYS batch operations in single message
-- Use Task tool for parallel agent execution
-- Enable memory caching for repeated operations
-- Prefer MultiEdit over multiple Edit calls
-- Minimize file reads with targeted searches
-- Use Glob before Grep for file discovery
-- Execute all related operations concurrently
-- Avoid explanatory text in responses
-- Cache computation results aggressively
-- Prioritize parallel over sequential execution
-
-### Tool Priority Order
-1. MultiEdit β†’ Edit β†’ Bash β†’ Read
-
-### Performance Optimization Workflow
-**Planning**: Analyze requirements and plan approach
-**Implementation**: Execute development with parallel agents
-**Testing**: Comprehensive testing and validation
-**Documentation**: Generate comprehensive documentation
-**Optimization**: Performance analysis and optimization
-
-## πŸ€– Agent Configuration
-- **Swarm Topology**: Mesh
-- **Maximum Agents**: 7
-- **Preferred Agent Types**: performance-benchmarker, perf-analyzer, optimizer
-
-## πŸ“Š Success Metrics
-- Performance Score: >0.9
-- Bottleneck Resolution: 100%
-- Memory Optimization: >20%
-- Execution Time: <50% of baseline
\ No newline at end of file
diff --git a/benchmark/quick_test_integration.py b/benchmark/quick_test_integration.py
deleted file mode 100644
index 3cc80fe821..0000000000
--- a/benchmark/quick_test_integration.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/usr/bin/env python3
-"""Quick test of claude-flow integration."""
-
-import sys
-from pathlib import Path
-
-# Add benchmark src to path
-sys.path.insert(0, str(Path(__file__).parent / "src"))
-
-from swarm_benchmark.core.claude_flow_executor import ClaudeFlowExecutor
-
-def main():
- print("πŸ§ͺ Quick Integration Test")
-
- try:
- # Test initialization
- executor = ClaudeFlowExecutor()
- print(f"βœ… Executor initialized: {executor.claude_flow_path}")
-
- # Test version check
- if executor.validate_installation():
- print("βœ… Claude-flow installation validated")
- else:
- print("❌ Installation validation failed")
- return False
-
- # Test simple command
- result = executor._execute_command([executor.claude_flow_path, "--help"], timeout=5)
- print(f"βœ… Help command executed: exit_code={result.exit_code}")
-
- if result.stdout:
- print("\nπŸ“„ Help output (first 500 chars):")
- print(result.stdout[:500])
-
- return True
-
- except Exception as e:
- print(f"❌ Test failed: {e}")
- return False
-
-
-if __name__ == "__main__":
- success = main()
- sys.exit(0 if success else 1)
\ No newline at end of file
diff --git a/benchmark/run-load-tests.py b/benchmark/run-load-tests.py
deleted file mode 100644
index 1b850e456c..0000000000
--- a/benchmark/run-load-tests.py
+++ /dev/null
@@ -1,479 +0,0 @@
-#!/usr/bin/env python3
-"""
-Hive Mind Load Test Orchestrator
-Comprehensive testing orchestration for the Benchmark-Tester agent
-
-This script runs the complete load testing suite including:
-1. Progressive scaling tests (1 -> 1000+ agents)
-2. Stress testing for breaking point discovery
-3. Concurrent swarm testing
-4. Resource exhaustion testing
-5. Failure recovery testing
-"""
-
-import os
-import sys
-import json
-import time
-import subprocess
-from datetime import datetime
-from pathlib import Path
-from typing import Dict, List, Any
-
-class LoadTestOrchestrator:
- """Orchestrates comprehensive load testing suite"""
-
- def __init__(self):
- self.benchmark_dir = Path(__file__).parent
- self.results_dir = self.benchmark_dir / "test-results" / datetime.now().strftime("%Y%m%d_%H%M%S")
- self.results_dir.mkdir(parents=True, exist_ok=True)
-
- self.test_results = {}
-
- def log(self, message: str, level: str = "INFO"):
- """Log messages with timestamp"""
- timestamp = datetime.now().strftime("%H:%M:%S")
- print(f"[{timestamp}] {level}: {message}")
-
- def run_command(self, command: List[str], cwd: Path = None) -> Dict[str, Any]:
- """Run a command and return results"""
- self.log(f"Running: {' '.join(command)}")
-
- try:
- result = subprocess.run(
- command,
- capture_output=True,
- text=True,
- cwd=cwd or self.benchmark_dir,
- timeout=7200 # 2 hour timeout
- )
-
- return {
- "success": result.returncode == 0,
- "returncode": result.returncode,
- "stdout": result.stdout,
- "stderr": result.stderr
- }
- except subprocess.TimeoutExpired:
- return {
- "success": False,
- "returncode": -1,
- "stdout": "",
- "stderr": "Command timed out after 2 hours"
- }
- except Exception as e:
- return {
- "success": False,
- "returncode": -1,
- "stdout": "",
- "stderr": str(e)
- }
-
- def run_load_testing(self) -> Dict[str, Any]:
- """Run comprehensive load testing"""
- self.log("πŸ”₯ Starting Load Testing Phase", "INFO")
-
- # Run quick load test first
- self.log("Running quick load test for system validation...")
- quick_result = self.run_command([
- "python3", "hive-mind-load-test.py",
- "--quick",
- "--output", str(self.results_dir / "load-test-quick")
- ])
-
- if not quick_result["success"]:
- self.log("❌ Quick load test failed, aborting full test", "ERROR")
- return {"success": False, "error": "Quick test failed", "details": quick_result}
-
- self.log("βœ… Quick load test passed, proceeding with full load testing")
-
- # Run full load testing
- self.log("Running comprehensive load testing...")
- full_result = self.run_command([
- "python3", "hive-mind-load-test.py",
- "--output", str(self.results_dir / "load-test-full")
- ])
-
- return {
- "success": full_result["success"],
- "quick_test": quick_result,
- "full_test": full_result
- }
-
- def run_stress_testing(self) -> Dict[str, Any]:
- """Run stress testing for breaking point discovery"""
- self.log("πŸ’₯ Starting Stress Testing Phase", "INFO")
-
- stress_types = ["memory", "cpu", "coordination", "consensus"]
- stress_results = {}
-
- for stress_type in stress_types:
- self.log(f"Running {stress_type} stress test...")
-
- result = self.run_command([
- "python3", "hive-mind-stress-test.py",
- "--stress-type", stress_type,
- "--output", str(self.results_dir / f"stress-test-{stress_type}")
- ])
-
- stress_results[stress_type] = result
-
- if result["success"]:
- self.log(f"βœ… {stress_type} stress test completed")
- else:
- self.log(f"❌ {stress_type} stress test failed: {result['stderr'][:200]}", "ERROR")
-
- # Run comprehensive stress testing
- self.log("Running comprehensive stress testing...")
- comprehensive_result = self.run_command([
- "python3", "hive-mind-stress-test.py",
- "--output", str(self.results_dir / "stress-test-comprehensive")
- ])
-
- stress_results["comprehensive"] = comprehensive_result
-
- return stress_results
-
- def run_benchmark_suite(self) -> Dict[str, Any]:
- """Run existing benchmark suite"""
- self.log("πŸ“Š Starting Benchmark Suite Phase", "INFO")
-
- # Check if benchmark runner exists
- benchmark_runner = self.benchmark_dir / "hive-mind-benchmarks" / "benchmark_runner.py"
- if not benchmark_runner.exists():
- self.log("⚠️ Benchmark runner not found, skipping benchmark suite", "WARN")
- return {"success": False, "error": "Benchmark runner not found"}
-
- # Run quick benchmark
- self.log("Running quick benchmark...")
- quick_result = self.run_command([
- "python3", str(benchmark_runner),
- "--quick"
- ], cwd=benchmark_runner.parent)
-
- if quick_result["success"]:
- self.log("βœ… Quick benchmark completed")
- else:
- self.log(f"❌ Quick benchmark failed: {quick_result['stderr'][:200]}", "ERROR")
-
- return {"quick_benchmark": quick_result}
-
- def run_concurrent_swarm_tests(self) -> Dict[str, Any]:
- """Run concurrent swarm testing"""
- self.log("🐝 Starting Concurrent Swarm Testing", "INFO")
-
- concurrent_tests = [
- (2, 25, "Two swarms test"),
- (5, 20, "Five swarms test"),
- (10, 10, "Ten swarms test")
- ]
-
- results = {}
-
- for swarm_count, agents_per_swarm, description in concurrent_tests:
- self.log(f"Running {description}: {swarm_count} swarms x {agents_per_swarm} agents")
-
- # Use load test with specific parameters
- result = self.run_command([
- "python3", "hive-mind-load-test.py",
- "--scale", str(agents_per_swarm),
- "--output", str(self.results_dir / f"concurrent-{swarm_count}x{agents_per_swarm}")
- ])
-
- results[f"{swarm_count}x{agents_per_swarm}"] = result
-
- if result["success"]:
- self.log(f"βœ… {description} completed")
- else:
- self.log(f"❌ {description} failed", "ERROR")
-
- return results
-
- def analyze_combined_results(self) -> Dict[str, Any]:
- """Analyze all test results and generate combined report"""
- self.log("πŸ“ˆ Analyzing Combined Results", "INFO")
-
- # Collect all result files
- result_files = list(self.results_dir.glob("**/*.json"))
-
- combined_analysis = {
- "test_summary": {
- "total_test_files": len(result_files),
- "test_phases": list(self.test_results.keys()),
- "overall_success": all(
- result.get("success", False)
- for result in self.test_results.values()
- if isinstance(result, dict)
- ),
- "test_duration": time.time() - self.start_time
- },
- "breaking_points": {},
- "stability_limits": {},
- "performance_metrics": {},
- "recommendations": []
- }
-
- # Analyze each result file
- for result_file in result_files:
- try:
- with open(result_file, 'r') as f:
- data = json.load(f)
-
- # Extract key metrics
- if "summary" in data:
- summary = data["summary"]
-
- # Breaking points
- if "breaking_point_agents" in summary:
- test_name = result_file.stem
- combined_analysis["breaking_points"][test_name] = summary["breaking_point_agents"]
-
- # Stability limits
- if "max_stable_agents" in summary:
- test_name = result_file.stem
- combined_analysis["stability_limits"][test_name] = summary["max_stable_agents"]
-
- # Performance metrics
- if "avg_throughput" in summary:
- test_name = result_file.stem
- combined_analysis["performance_metrics"][test_name] = {
- "throughput": summary.get("avg_throughput", 0),
- "response_time": summary.get("avg_response_time_ms", 0),
- "memory_usage": summary.get("peak_memory_usage_mb", 0)
- }
-
- # Extract recommendations
- if "recommendations" in data:
- combined_analysis["recommendations"].extend(data["recommendations"])
-
- except Exception as e:
- self.log(f"⚠️ Failed to analyze {result_file}: {e}", "WARN")
-
- # Generate overall recommendations
- overall_recommendations = self._generate_overall_recommendations(combined_analysis)
- combined_analysis["overall_recommendations"] = overall_recommendations
-
- # Save combined analysis
- analysis_file = self.results_dir / "combined_analysis.json"
- with open(analysis_file, 'w') as f:
- json.dump(combined_analysis, f, indent=2)
-
- self.log(f"πŸ“Š Combined analysis saved to: {analysis_file}")
-
- return combined_analysis
-
- def _generate_overall_recommendations(self, analysis: Dict[str, Any]) -> List[str]:
- """Generate overall recommendations from combined analysis"""
- recommendations = []
-
- # Analyze breaking points
- breaking_points = list(analysis["breaking_points"].values())
- if breaking_points:
- min_breaking_point = min(breaking_points)
- avg_breaking_point = sum(breaking_points) / len(breaking_points)
-
- if min_breaking_point < 100:
- recommendations.append(
- f"CRITICAL: Minimum breaking point at {min_breaking_point} agents indicates fundamental scaling issues."
- )
- elif avg_breaking_point < 500:
- recommendations.append(
- f"OPTIMIZATION NEEDED: Average breaking point at {avg_breaking_point:.0f} agents suggests medium-scale optimization opportunities."
- )
- else:
- recommendations.append(
- f"EXCELLENT: Strong scaling characteristics with average breaking point at {avg_breaking_point:.0f} agents."
- )
-
- # Analyze stability limits
- stability_limits = list(analysis["stability_limits"].values())
- if stability_limits:
- max_stability = max(stability_limits)
-
- if max_stability >= 1000:
- recommendations.append("System demonstrates enterprise-scale stability (1000+ agents).")
- elif max_stability >= 500:
- recommendations.append("System suitable for large-scale deployments (500+ agents).")
- elif max_stability >= 100:
- recommendations.append("System suitable for medium-scale deployments (100+ agents).")
- else:
- recommendations.append("System requires optimization for production deployment.")
-
- # Analyze test success rates
- if not analysis["test_summary"]["overall_success"]:
- recommendations.append("URGENT: Some test phases failed. Review error logs and address critical issues.")
-
- return recommendations
-
- def generate_summary_report(self, analysis: Dict[str, Any]):
- """Generate human-readable summary report"""
- self.log("πŸ“‹ Generating Summary Report", "INFO")
-
- report_file = self.results_dir / "LOAD_TEST_SUMMARY.md"
-
- with open(report_file, 'w') as f:
- f.write("# Hive Mind Load Testing Summary Report\\n")
- f.write(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\\n")
-
- # Test Summary
- f.write("## Test Summary\\n")
- summary = analysis["test_summary"]
- f.write(f"- **Total Test Duration**: {summary['test_duration']:.1f} seconds\\n")
- f.write(f"- **Test Phases**: {len(summary['test_phases'])}\\n")
- f.write(f"- **Overall Success**: {'βœ… PASS' if summary['overall_success'] else '❌ FAIL'}\\n")
- f.write(f"- **Result Files**: {summary['total_test_files']}\\n\\n")
-
- # Breaking Points
- if analysis["breaking_points"]:
- f.write("## Breaking Points\\n")
- for test_name, breaking_point in analysis["breaking_points"].items():
- f.write(f"- **{test_name}**: {breaking_point} agents\\n")
- f.write("\\n")
-
- # Stability Limits
- if analysis["stability_limits"]:
- f.write("## Stability Limits\\n")
- for test_name, stability_limit in analysis["stability_limits"].items():
- f.write(f"- **{test_name}**: {stability_limit} agents\\n")
- f.write("\\n")
-
- # Performance Metrics
- if analysis["performance_metrics"]:
- f.write("## Performance Metrics\\n")
- for test_name, metrics in analysis["performance_metrics"].items():
- f.write(f"### {test_name}\\n")
- f.write(f"- **Throughput**: {metrics['throughput']:.1f} ops/sec\\n")
- f.write(f"- **Response Time**: {metrics['response_time']:.1f}ms\\n")
- f.write(f"- **Memory Usage**: {metrics['memory_usage']:.1f}MB\\n\\n")
-
- # Recommendations
- if analysis["overall_recommendations"]:
- f.write("## Recommendations\\n")
- for i, rec in enumerate(analysis["overall_recommendations"], 1):
- f.write(f"{i}. {rec}\\n")
- f.write("\\n")
-
- # Test Results Summary
- f.write("## Test Results by Phase\\n")
- for phase, result in self.test_results.items():
- if isinstance(result, dict):
- success = result.get("success", False)
- f.write(f"- **{phase}**: {'βœ… PASS' if success else '❌ FAIL'}\\n")
- f.write("\\n")
-
- # Files and Locations
- f.write("## Generated Files\\n")
- f.write(f"- **Results Directory**: `{self.results_dir}`\\n")
- f.write(f"- **Combined Analysis**: `{self.results_dir}/combined_analysis.json`\\n")
- f.write(f"- **This Report**: `{report_file}`\\n")
-
- self.log(f"πŸ“‹ Summary report saved to: {report_file}")
-
- def run_comprehensive_testing(self) -> Dict[str, Any]:
- """Run the complete testing suite"""
- self.log("πŸš€ Starting Comprehensive Hive Mind Load Testing", "INFO")
- self.log("=" * 60)
-
- self.start_time = time.time()
-
- # Phase 1: Load Testing
- self.log("Phase 1: Load Testing")
- self.test_results["load_testing"] = self.run_load_testing()
-
- # Phase 2: Stress Testing
- self.log("Phase 2: Stress Testing")
- self.test_results["stress_testing"] = self.run_stress_testing()
-
- # Phase 3: Benchmark Suite
- self.log("Phase 3: Benchmark Suite")
- self.test_results["benchmark_suite"] = self.run_benchmark_suite()
-
- # Phase 4: Concurrent Swarm Testing
- self.log("Phase 4: Concurrent Swarm Testing")
- self.test_results["concurrent_swarms"] = self.run_concurrent_swarm_tests()
-
- # Phase 5: Analysis
- self.log("Phase 5: Analysis and Reporting")
- analysis = self.analyze_combined_results()
-
- # Generate summary report
- self.generate_summary_report(analysis)
-
- total_duration = time.time() - self.start_time
-
- self.log(f"🎯 Testing Complete! Total Duration: {total_duration:.1f} seconds")
- self.log(f"πŸ“Š Results saved to: {self.results_dir}")
-
- return {
- "success": True,
- "total_duration": total_duration,
- "results_directory": str(self.results_dir),
- "test_results": self.test_results,
- "analysis": analysis
- }
-
-def main():
- """Main orchestrator execution"""
- import argparse
-
- parser = argparse.ArgumentParser(description="Hive Mind Load Testing Orchestrator")
- parser.add_argument("--phase", choices=["load", "stress", "benchmark", "concurrent", "all"],
- default="all", help="Run specific testing phase")
- parser.add_argument("--quick", action="store_true", help="Run quick tests only")
-
- args = parser.parse_args()
-
- orchestrator = LoadTestOrchestrator()
-
- try:
- if args.phase == "all":
- if args.quick:
- # Quick testing mode
- orchestrator.log("πŸš€ Running Quick Testing Mode")
- result = orchestrator.run_command([
- "python3", "hive-mind-load-test.py", "--quick"
- ])
- print("Quick test result:", "SUCCESS" if result["success"] else "FAILED")
- else:
- # Full comprehensive testing
- result = orchestrator.run_comprehensive_testing()
-
- # Print summary
- if result["success"]:
- print("\\n🎯 COMPREHENSIVE TESTING SUMMARY")
- print("=" * 50)
- print(f"βœ… Testing completed successfully!")
- print(f"⏱️ Total duration: {result['total_duration']:.1f} seconds")
- print(f"πŸ“ Results directory: {result['results_directory']}")
- print("\\nπŸ“Š Phase Results:")
- for phase, phase_result in result["test_results"].items():
- if isinstance(phase_result, dict):
- success = phase_result.get("success", False)
- print(f" {phase}: {'βœ… PASS' if success else '❌ FAIL'}")
- else:
- print("❌ Testing failed!")
-
- else:
- # Run specific phase
- orchestrator.log(f"Running specific phase: {args.phase}")
-
- if args.phase == "load":
- result = orchestrator.run_load_testing()
- elif args.phase == "stress":
- result = orchestrator.run_stress_testing()
- elif args.phase == "benchmark":
- result = orchestrator.run_benchmark_suite()
- elif args.phase == "concurrent":
- result = orchestrator.run_concurrent_swarm_tests()
-
- print(f"{args.phase} phase result:", "SUCCESS" if result.get("success", False) else "FAILED")
-
- except KeyboardInterrupt:
- orchestrator.log("Testing interrupted by user", "WARN")
- sys.exit(1)
- except Exception as e:
- orchestrator.log(f"Testing failed with error: {e}", "ERROR")
- sys.exit(1)
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/benchmark/run_performance_tests.py b/benchmark/run_performance_tests.py
deleted file mode 100644
index 927b17ea87..0000000000
--- a/benchmark/run_performance_tests.py
+++ /dev/null
@@ -1,550 +0,0 @@
-#!/usr/bin/env python3
-"""
-Comprehensive Performance Test Runner for Claude-Flow Swarm Operations
-
-This script coordinates all performance testing and monitoring tools:
-- Runs complete performance benchmark suite
-- Monitors for memory leaks and performance regressions
-- Generates dashboard reports and CI integration
-- Provides automated performance validation
-
-Author: Metrics Analyst Agent
-Version: 1.0.0
-"""
-
-import asyncio
-import sys
-import json
-import time
-import os
-import argparse
-from datetime import datetime, timedelta
-from pathlib import Path
-from typing import Dict, List, Any, Optional
-
-# Add local modules to path
-sys.path.insert(0, str(Path(__file__).parent))
-
-try:
- from swarm_performance_suite import SwarmPerformanceBenchmark
- from continuous_performance_monitor import PerformanceMonitor
- from ci_performance_integration import CIPerformanceGate
- from performance_dashboard import PerformanceDashboard
-except ImportError as e:
- print(f"Warning: Could not import all performance modules: {e}")
- print("Some functionality may be limited")
-
-
-class PerformanceTestOrchestrator:
- """Orchestrates comprehensive performance testing."""
-
- def __init__(self, config: Optional[Dict[str, Any]] = None):
- self.config = config or self._get_default_config()
- self.results: Dict[str, Any] = {}
- self.start_time = datetime.now()
-
- def _get_default_config(self) -> Dict[str, Any]:
- """Get default configuration for performance testing."""
- return {
- "test_modes": {
- "benchmark_suite": True,
- "continuous_monitoring": True,
- "memory_leak_detection": True,
- "regression_analysis": True,
- "dashboard_generation": True
- },
- "benchmark_config": {
- "quick_mode": False,
- "parallel_execution": True,
- "timeout_minutes": 30
- },
- "monitoring_config": {
- "duration_minutes": 10,
- "sample_interval_seconds": 5.0
- },
- "output_config": {
- "base_directory": "performance_results",
- "generate_reports": True,
- "save_artifacts": True
- },
- "notification_config": {
- "enable_notifications": False,
- "webhook_url": None,
- "email_recipients": []
- }
- }
-
- async def run_comprehensive_tests(self) -> Dict[str, Any]:
- """Run comprehensive performance testing suite."""
- print("πŸš€ Starting Comprehensive Performance Testing")
- print("=" * 60)
- print(f"Start Time: {self.start_time}")
- print("=" * 60)
-
- # Create output directory
- output_dir = Path(self.config["output_config"]["base_directory"])
- output_dir.mkdir(exist_ok=True)
-
- test_results = {
- "orchestrator_info": {
- "version": "1.0.0",
- "start_time": self.start_time.isoformat(),
- "config": self.config
- },
- "test_results": {},
- "summary": {}
- }
-
- # Run enabled test modes
- test_modes = self.config["test_modes"]
-
- try:
- # 1. Benchmark Suite
- if test_modes.get("benchmark_suite", True):
- print("\nπŸ“Š Running Performance Benchmark Suite...")
- benchmark_results = await self._run_benchmark_suite(output_dir)
- test_results["test_results"]["benchmark_suite"] = benchmark_results
-
- # 2. Continuous Monitoring
- if test_modes.get("continuous_monitoring", True):
- print("\nπŸ“ˆ Running Continuous Performance Monitoring...")
- monitoring_results = await self._run_continuous_monitoring(output_dir)
- test_results["test_results"]["continuous_monitoring"] = monitoring_results
-
- # 3. Memory Leak Detection
- if test_modes.get("memory_leak_detection", True):
- print("\nπŸ” Running Memory Leak Detection...")
- memory_results = await self._run_memory_leak_detection(output_dir)
- test_results["test_results"]["memory_leak_detection"] = memory_results
-
- # 4. Regression Analysis
- if test_modes.get("regression_analysis", True):
- print("\nπŸ“‰ Running Regression Analysis...")
- regression_results = await self._run_regression_analysis(output_dir)
- test_results["test_results"]["regression_analysis"] = regression_results
-
- # 5. Dashboard Generation
- if test_modes.get("dashboard_generation", True):
- print("\nπŸ“Š Generating Performance Dashboard...")
- dashboard_results = await self._generate_dashboard(output_dir)
- test_results["test_results"]["dashboard_generation"] = dashboard_results
-
- # Generate final summary
- end_time = datetime.now()
- test_results["summary"] = self._generate_summary(test_results, end_time)
-
- # Save comprehensive results
- await self._save_comprehensive_results(test_results, output_dir)
-
- # Send notifications if enabled
- if self.config["notification_config"]["enable_notifications"]:
- await self._send_notifications(test_results)
-
- # Print final summary
- self._print_final_summary(test_results)
-
- return test_results
-
- except Exception as e:
- error_time = datetime.now()
- test_results["error"] = {
- "message": str(e),
- "timestamp": error_time.isoformat(),
- "duration_seconds": (error_time - self.start_time).total_seconds()
- }
-
- print(f"\n❌ Performance testing failed: {e}")
- return test_results
-
- async def _run_benchmark_suite(self, output_dir: Path) -> Dict[str, Any]:
- """Run the performance benchmark suite."""
- try:
- benchmark = SwarmPerformanceBenchmark(str(output_dir / "benchmark"))
-
- if self.config["benchmark_config"]["quick_mode"]:
- # Run quick subset of tests
- results = await benchmark._test_startup_performance()
- return {
- "mode": "quick",
- "test_count": len(results),
- "passed_count": sum(1 for r in results if r.target_met),
- "results": [r.to_dict() for r in results]
- }
- else:
- # Run full suite
- results = await benchmark.run_full_suite()
- return {
- "mode": "full",
- "results": results
- }
-
- except Exception as e:
- return {"error": str(e), "success": False}
-
- async def _run_continuous_monitoring(self, output_dir: Path) -> Dict[str, Any]:
- """Run continuous performance monitoring."""
- try:
- duration = self.config["monitoring_config"]["duration_minutes"]
- interval = self.config["monitoring_config"]["sample_interval_seconds"]
-
- monitor = PerformanceMonitor(str(output_dir / "monitor.db"))
-
- # Start monitoring
- session_id = f"comprehensive_{int(time.time())}"
- monitor.start_monitoring(interval, session_id)
-
- print(f" Monitoring for {duration} minutes with {interval}s intervals...")
- await asyncio.sleep(duration * 60)
-
- # Stop and get results
- monitor.stop_monitoring()
-
- # Get dashboard data
- dashboard_data = monitor.get_performance_dashboard_data(hours=1)
- regression_report = monitor.generate_regression_report()
-
- return {
- "duration_minutes": duration,
- "sample_interval_seconds": interval,
- "session_id": session_id,
- "dashboard_data": dashboard_data,
- "regression_report": regression_report,
- "success": True
- }
-
- except Exception as e:
- return {"error": str(e), "success": False}
-
- async def _run_memory_leak_detection(self, output_dir: Path) -> Dict[str, Any]:
- """Run memory leak detection tests."""
- try:
- import psutil
-
- # Monitor memory during extended operations
- process = psutil.Process()
- start_memory = process.memory_info().rss / 1024 / 1024
-
- memory_samples = []
- test_operations = [
- "swarm initialization",
- "agent spawning",
- "task coordination",
- "memory persistence",
- "swarm cleanup"
- ]
-
- for i, operation in enumerate(test_operations):
- print(f" Testing {operation}...")
-
- # Simulate operation (would be real swarm operations)
- await asyncio.sleep(2)
-
- # Sample memory
- current_memory = process.memory_info().rss / 1024 / 1024
- memory_samples.append({
- "operation": operation,
- "memory_mb": current_memory,
- "growth_from_start": current_memory - start_memory
- })
-
- end_memory = process.memory_info().rss / 1024 / 1024
- total_growth = end_memory - start_memory
-
- # Analyze for leaks
- leak_detected = total_growth > 10.0 # >10MB growth = potential leak
- growth_rate = total_growth / len(test_operations)
-
- return {
- "start_memory_mb": start_memory,
- "end_memory_mb": end_memory,
- "total_growth_mb": total_growth,
- "average_growth_per_operation": growth_rate,
- "leak_detected": leak_detected,
- "memory_samples": memory_samples,
- "success": True
- }
-
- except Exception as e:
- return {"error": str(e), "success": False}
-
- async def _run_regression_analysis(self, output_dir: Path) -> Dict[str, Any]:
- """Run performance regression analysis."""
- try:
- # This would typically compare against stored baselines
- # For now, simulate regression analysis
-
- current_metrics = {
- "swarm_init_time": 3.2,
- "agent_coordination_latency": 180.5,
- "memory_usage_mb": 45.3,
- "mcp_response_time": 0.8
- }
-
- # Load or create baseline
- baseline_file = output_dir / "performance_baseline.json"
- if baseline_file.exists():
- with open(baseline_file) as f:
- baseline_metrics = json.load(f)
- else:
- # Create initial baseline
- baseline_metrics = {
- "swarm_init_time": 3.5,
- "agent_coordination_latency": 195.0,
- "memory_usage_mb": 42.1,
- "mcp_response_time": 0.9
- }
- with open(baseline_file, 'w') as f:
- json.dump(baseline_metrics, f, indent=2)
-
- # Calculate regressions
- regressions = {}
- for metric, current_value in current_metrics.items():
- baseline_value = baseline_metrics.get(metric, current_value)
- regression_percent = ((current_value - baseline_value) / baseline_value) * 100 if baseline_value > 0 else 0
-
- regressions[metric] = {
- "current_value": current_value,
- "baseline_value": baseline_value,
- "regression_percent": regression_percent,
- "regression_detected": abs(regression_percent) > 10,
- "status": "regression" if regression_percent > 10 else "improvement" if regression_percent < -5 else "stable"
- }
-
- # Update baseline with current metrics
- with open(baseline_file, 'w') as f:
- json.dump(current_metrics, f, indent=2)
-
- return {
- "baseline_file": str(baseline_file),
- "current_metrics": current_metrics,
- "baseline_metrics": baseline_metrics,
- "regressions": regressions,
- "critical_regressions": [k for k, v in regressions.items() if v["regression_percent"] > 25],
- "success": True
- }
-
- except Exception as e:
- return {"error": str(e), "success": False}
-
- async def _generate_dashboard(self, output_dir: Path) -> Dict[str, Any]:
- """Generate performance dashboard."""
- try:
- dashboard = PerformanceDashboard(str(output_dir / "dashboard"))
-
- # Generate dashboard with sample data for now
- dashboard_file = dashboard.generate_dashboard("sample")
-
- return {
- "dashboard_file": str(dashboard_file),
- "dashboard_url": f"file://{Path(dashboard_file).absolute()}",
- "success": True
- }
-
- except Exception as e:
- return {"error": str(e), "success": False}
-
- def _generate_summary(self, test_results: Dict[str, Any], end_time: datetime) -> Dict[str, Any]:
- """Generate comprehensive test summary."""
- duration = (end_time - self.start_time).total_seconds()
-
- # Count successes and failures
- results = test_results.get("test_results", {})
- successful_tests = sum(1 for r in results.values() if r.get("success", False))
- total_tests = len(results)
-
- # Identify critical issues
- critical_issues = []
-
- # Check benchmark results
- benchmark_results = results.get("benchmark_suite", {})
- if "results" in benchmark_results:
- if benchmark_results.get("mode") == "full":
- # Full suite results
- summary = benchmark_results["results"].get("summary", {})
- if summary.get("performance_score", 100) < 80:
- critical_issues.append("Performance benchmark score below 80%")
- else:
- # Quick mode results
- passed = benchmark_results.get("passed_count", 0)
- total = benchmark_results.get("test_count", 1)
- if passed / total < 0.8:
- critical_issues.append("Quick benchmark tests below 80% pass rate")
-
- # Check memory leak detection
- memory_results = results.get("memory_leak_detection", {})
- if memory_results.get("leak_detected", False):
- critical_issues.append("Memory leak detected")
-
- # Check regression analysis
- regression_results = results.get("regression_analysis", {})
- critical_regressions = regression_results.get("critical_regressions", [])
- if critical_regressions:
- critical_issues.append(f"{len(critical_regressions)} critical performance regressions")
-
- return {
- "end_time": end_time.isoformat(),
- "total_duration_seconds": duration,
- "total_duration_minutes": duration / 60,
- "successful_tests": successful_tests,
- "total_tests": total_tests,
- "success_rate": successful_tests / total_tests if total_tests > 0 else 0,
- "critical_issues": critical_issues,
- "overall_status": "passed" if not critical_issues and successful_tests == total_tests else "failed",
- "performance_score": self._calculate_overall_score(results)
- }
-
- def _calculate_overall_score(self, results: Dict[str, Any]) -> float:
- """Calculate overall performance score (0-100)."""
- scores = []
-
- # Benchmark score
- benchmark_results = results.get("benchmark_suite", {})
- if "results" in benchmark_results and benchmark_results.get("mode") == "full":
- scores.append(benchmark_results["results"].get("summary", {}).get("performance_score", 50))
- elif "passed_count" in benchmark_results and "test_count" in benchmark_results:
- scores.append((benchmark_results["passed_count"] / benchmark_results["test_count"]) * 100)
-
- # Memory score
- memory_results = results.get("memory_leak_detection", {})
- if memory_results.get("success", False):
- leak_detected = memory_results.get("leak_detected", False)
- scores.append(0 if leak_detected else 100)
-
- # Regression score
- regression_results = results.get("regression_analysis", {})
- if regression_results.get("success", False):
- critical_regressions = len(regression_results.get("critical_regressions", []))
- scores.append(max(0, 100 - critical_regressions * 25))
-
- return sum(scores) / len(scores) if scores else 50.0
-
- async def _save_comprehensive_results(self, test_results: Dict[str, Any], output_dir: Path):
- """Save comprehensive test results."""
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
-
- # Save main results file
- results_file = output_dir / f"comprehensive_performance_results_{timestamp}.json"
- with open(results_file, 'w') as f:
- json.dump(test_results, f, indent=2, default=str)
-
- # Save summary file
- summary_file = output_dir / f"performance_summary_{timestamp}.json"
- with open(summary_file, 'w') as f:
- json.dump(test_results.get("summary", {}), f, indent=2, default=str)
-
- # Create latest symlinks
- latest_results = output_dir / "latest_comprehensive_results.json"
- latest_summary = output_dir / "latest_performance_summary.json"
-
- try:
- if latest_results.exists():
- latest_results.unlink()
- if latest_summary.exists():
- latest_summary.unlink()
-
- latest_results.symlink_to(results_file.name)
- latest_summary.symlink_to(summary_file.name)
- except OSError:
- # Fallback for systems without symlink support
- import shutil
- shutil.copy2(results_file, latest_results)
- shutil.copy2(summary_file, latest_summary)
-
- print(f"πŸ“ Results saved:")
- print(f" Full results: {results_file}")
- print(f" Summary: {summary_file}")
-
- async def _send_notifications(self, test_results: Dict[str, Any]):
- """Send performance test notifications."""
- # This would integrate with notification systems
- # For now, just log the notification
- summary = test_results.get("summary", {})
- status = summary.get("overall_status", "unknown")
- score = summary.get("performance_score", 0)
- issues = summary.get("critical_issues", [])
-
- print(f"\nπŸ“’ Notification: Performance tests {status.upper()}")
- print(f" Score: {score:.1f}/100")
- if issues:
- print(f" Issues: {len(issues)} critical issues found")
-
- def _print_final_summary(self, test_results: Dict[str, Any]):
- """Print final performance test summary."""
- summary = test_results.get("summary", {})
-
- print("\n" + "=" * 60)
- print("🎯 COMPREHENSIVE PERFORMANCE TEST SUMMARY")
- print("=" * 60)
-
- status = summary.get("overall_status", "unknown")
- emoji = "βœ…" if status == "passed" else "❌"
-
- print(f"{emoji} Overall Status: {status.upper()}")
- print(f"⏱️ Total Duration: {summary.get('total_duration_minutes', 0):.1f} minutes")
- print(f"πŸ“Š Performance Score: {summary.get('performance_score', 0):.1f}/100")
- print(f"πŸ§ͺ Tests: {summary.get('successful_tests', 0)}/{summary.get('total_tests', 0)} successful")
-
- issues = summary.get("critical_issues", [])
- if issues:
- print(f"\n⚠️ Critical Issues ({len(issues)}):")
- for issue in issues:
- print(f" - {issue}")
- else:
- print("\nβœ… No critical issues detected")
-
- print("\nπŸ“‹ Test Results:")
- results = test_results.get("test_results", {})
- for test_name, test_result in results.items():
- success = test_result.get("success", False)
- emoji = "βœ…" if success else "❌"
- print(f" {emoji} {test_name.replace('_', ' ').title()}")
-
- print("\n" + "=" * 60)
-
-
-async def main():
- """Main entry point for comprehensive performance testing."""
- parser = argparse.ArgumentParser(description="Comprehensive Performance Test Runner")
- parser.add_argument("--config", help="Configuration file path")
- parser.add_argument("--quick", action="store_true", help="Run quick performance tests only")
- parser.add_argument("--benchmark-only", action="store_true", help="Run benchmark suite only")
- parser.add_argument("--monitor-only", action="store_true", help="Run continuous monitoring only")
- parser.add_argument("--output-dir", default="performance_results", help="Output directory")
- parser.add_argument("--duration", type=int, default=10, help="Monitoring duration in minutes")
-
- args = parser.parse_args()
-
- # Load configuration
- config = {}
- if args.config and Path(args.config).exists():
- with open(args.config) as f:
- config = json.load(f)
-
- # Apply command line overrides
- if args.quick:
- config.setdefault("benchmark_config", {})["quick_mode"] = True
- config.setdefault("monitoring_config", {})["duration_minutes"] = 3
-
- if args.benchmark_only:
- config["test_modes"] = {"benchmark_suite": True}
- elif args.monitor_only:
- config["test_modes"] = {"continuous_monitoring": True}
-
- if args.output_dir:
- config.setdefault("output_config", {})["base_directory"] = args.output_dir
-
- if args.duration:
- config.setdefault("monitoring_config", {})["duration_minutes"] = args.duration
-
- # Run comprehensive tests
- orchestrator = PerformanceTestOrchestrator(config)
- results = await orchestrator.run_comprehensive_tests()
-
- # Exit with appropriate code
- summary = results.get("summary", {})
- exit_code = 0 if summary.get("overall_status") == "passed" else 1
- sys.exit(exit_code)
-
-
-if __name__ == "__main__":
- asyncio.run(main())
\ No newline at end of file
diff --git a/benchmark/run_real_benchmarks.py b/benchmark/run_real_benchmarks.py
old mode 100644
new mode 100755
diff --git a/benchmark/simple-load-test.py b/benchmark/simple-load-test.py
deleted file mode 100644
index 20cd2768bf..0000000000
--- a/benchmark/simple-load-test.py
+++ /dev/null
@@ -1,322 +0,0 @@
-#!/usr/bin/env python3
-"""
-Simple Hive Mind Load Test
-Quick validation of the system's load handling capabilities
-"""
-
-import os
-import sys
-import json
-import time
-import psutil
-import subprocess
-from datetime import datetime
-from pathlib import Path
-from typing import Dict, List, Any
-
-class SimpleLoadTester:
- """Simple load tester for basic validation"""
-
- def __init__(self):
- self.cli_path = Path("../src/cli/simple-cli.js")
- self.results = []
-
- def run_cli_command(self, command: List[str], timeout: int = 30) -> Dict[str, Any]:
- """Run a CLI command with timeout"""
- start_time = time.time()
-
- try:
- result = subprocess.run(
- ["node", str(self.cli_path)] + command,
- capture_output=True,
- text=True,
- timeout=timeout,
- cwd=Path.cwd().parent
- )
-
- duration = time.time() - start_time
-
- return {
- "success": result.returncode == 0,
- "duration": duration,
- "stdout": result.stdout,
- "stderr": result.stderr,
- "returncode": result.returncode
- }
- except subprocess.TimeoutExpired:
- return {
- "success": False,
- "duration": timeout,
- "stdout": "",
- "stderr": f"Command timed out after {timeout} seconds",
- "returncode": -1
- }
- except Exception as e:
- return {
- "success": False,
- "duration": time.time() - start_time,
- "stdout": "",
- "stderr": str(e),
- "returncode": -1
- }
-
- def test_basic_commands(self) -> Dict[str, Any]:
- """Test basic CLI commands"""
- print("πŸ§ͺ Testing basic CLI commands...")
-
- tests = [
- (["--help"], "Help command"),
- (["--version"], "Version command"),
- (["status"], "Status command")
- ]
-
- results = {}
-
- for command, description in tests:
- print(f" Testing: {description}")
- result = self.run_cli_command(command, timeout=10)
- results[description] = result
-
- if result["success"]:
- print(f" βœ… {description}: {result['duration']:.2f}s")
- else:
- print(f" ❌ {description}: {result['stderr'][:100]}")
-
- return results
-
- def test_swarm_initialization(self) -> Dict[str, Any]:
- """Test swarm initialization"""
- print("🐝 Testing swarm initialization...")
-
- # Test swarm init
- result = self.run_cli_command(["swarm", "init", "--test"], timeout=30)
-
- if result["success"]:
- print(" βœ… Swarm initialization: SUCCESS")
- return {"swarm_init": result}
- else:
- print(f" ❌ Swarm initialization: FAILED - {result['stderr'][:100]}")
- return {"swarm_init": result}
-
- def test_agent_spawning(self) -> Dict[str, Any]:
- """Test agent spawning"""
- print("πŸ€– Testing agent spawning...")
-
- agent_tests = [
- (["agent", "spawn", "researcher", "--test"], "Spawn researcher"),
- (["agent", "spawn", "coder", "--test"], "Spawn coder"),
- (["agent", "list"], "List agents")
- ]
-
- results = {}
-
- for command, description in agent_tests:
- print(f" Testing: {description}")
- result = self.run_cli_command(command, timeout=20)
- results[description] = result
-
- if result["success"]:
- print(f" βœ… {description}: {result['duration']:.2f}s")
- else:
- print(f" ❌ {description}: {result['stderr'][:100]}")
-
- return results
-
- def test_memory_operations(self) -> Dict[str, Any]:
- """Test memory operations"""
- print("πŸ’Ύ Testing memory operations...")
-
- memory_tests = [
- (["memory", "store", "test_key", "test_value"], "Store memory"),
- (["memory", "retrieve", "test_key"], "Retrieve memory"),
- (["memory", "list"], "List memory")
- ]
-
- results = {}
-
- for command, description in memory_tests:
- print(f" Testing: {description}")
- result = self.run_cli_command(command, timeout=15)
- results[description] = result
-
- if result["success"]:
- print(f" βœ… {description}: {result['duration']:.2f}s")
- else:
- print(f" ❌ {description}: {result['stderr'][:100]}")
-
- return results
-
- def measure_system_resources(self) -> Dict[str, Any]:
- """Measure current system resources"""
- try:
- memory = psutil.virtual_memory()
- cpu_percent = psutil.cpu_percent(interval=1)
-
- return {
- "memory_percent": memory.percent,
- "memory_mb": memory.used / (1024**2),
- "available_memory_mb": memory.available / (1024**2),
- "cpu_percent": cpu_percent,
- "process_count": len(psutil.pids())
- }
- except Exception as e:
- return {"error": str(e)}
-
- def run_load_simulation(self, operations: int = 10) -> Dict[str, Any]:
- """Run a simple load simulation"""
- print(f"⚑ Running load simulation with {operations} operations...")
-
- start_time = time.time()
- start_resources = self.measure_system_resources()
-
- successful_operations = 0
- failed_operations = 0
- response_times = []
-
- for i in range(operations):
- print(f" Operation {i+1}/{operations}")
-
- # Test a simple command
- op_start = time.time()
- result = self.run_cli_command(["status"], timeout=10)
- op_duration = time.time() - op_start
-
- response_times.append(op_duration)
-
- if result["success"]:
- successful_operations += 1
- else:
- failed_operations += 1
-
- # Brief pause between operations
- time.sleep(0.5)
-
- total_duration = time.time() - start_time
- end_resources = self.measure_system_resources()
-
- # Calculate metrics
- avg_response_time = sum(response_times) / len(response_times) if response_times else 0
- throughput = successful_operations / total_duration if total_duration > 0 else 0
- success_rate = successful_operations / operations if operations > 0 else 0
-
- return {
- "total_operations": operations,
- "successful_operations": successful_operations,
- "failed_operations": failed_operations,
- "total_duration": total_duration,
- "avg_response_time": avg_response_time,
- "throughput": throughput,
- "success_rate": success_rate,
- "start_resources": start_resources,
- "end_resources": end_resources,
- "response_times": response_times
- }
-
- def run_simple_load_test(self) -> Dict[str, Any]:
- """Run the complete simple load test"""
- print("πŸ”₯ Simple Hive Mind Load Test")
- print("=" * 40)
-
- start_time = datetime.now()
-
- # Test phases
- results = {
- "test_start_time": start_time.isoformat(),
- "basic_commands": self.test_basic_commands(),
- "swarm_initialization": self.test_swarm_initialization(),
- "agent_spawning": self.test_agent_spawning(),
- "memory_operations": self.test_memory_operations(),
- "load_simulation": self.run_load_simulation(10),
- "system_info": {
- "cpu_count": psutil.cpu_count(),
- "memory_gb": psutil.virtual_memory().total / (1024**3),
- "platform": sys.platform
- }
- }
-
- end_time = datetime.now()
- results["test_end_time"] = end_time.isoformat()
- results["total_test_duration"] = (end_time - start_time).total_seconds()
-
- # Generate summary
- self.generate_summary(results)
-
- return results
-
- def generate_summary(self, results: Dict[str, Any]):
- """Generate test summary"""
- print("\\nπŸ“Š TEST SUMMARY")
- print("=" * 40)
-
- # Basic command results
- basic_success = sum(1 for r in results["basic_commands"].values() if r.get("success", False))
- basic_total = len(results["basic_commands"])
- print(f"Basic Commands: {basic_success}/{basic_total} passed")
-
- # Swarm initialization
- swarm_success = results["swarm_initialization"]["swarm_init"]["success"]
- print(f"Swarm Init: {'βœ… PASS' if swarm_success else '❌ FAIL'}")
-
- # Agent spawning
- agent_success = sum(1 for r in results["agent_spawning"].values() if r.get("success", False))
- agent_total = len(results["agent_spawning"])
- print(f"Agent Operations: {agent_success}/{agent_total} passed")
-
- # Memory operations
- memory_success = sum(1 for r in results["memory_operations"].values() if r.get("success", False))
- memory_total = len(results["memory_operations"])
- print(f"Memory Operations: {memory_success}/{memory_total} passed")
-
- # Load simulation
- load_sim = results["load_simulation"]
- print(f"Load Simulation:")
- print(f" Success Rate: {load_sim['success_rate']:.1%}")
- print(f" Throughput: {load_sim['throughput']:.2f} ops/sec")
- print(f" Avg Response: {load_sim['avg_response_time']:.3f}s")
-
- # Overall assessment
- total_tests = basic_total + 1 + agent_total + memory_total
- total_passed = basic_success + (1 if swarm_success else 0) + agent_success + memory_success
- overall_success_rate = total_passed / total_tests if total_tests > 0 else 0
-
- print(f"\\n🎯 OVERALL RESULT:")
- print(f"Tests Passed: {total_passed}/{total_tests} ({overall_success_rate:.1%})")
- print(f"Duration: {results['total_test_duration']:.1f} seconds")
-
- if overall_success_rate >= 0.8:
- print("βœ… SYSTEM READY FOR LOAD TESTING")
- elif overall_success_rate >= 0.5:
- print("⚠️ SYSTEM PARTIALLY READY - Some issues detected")
- else:
- print("❌ SYSTEM NOT READY - Multiple failures detected")
-
- # Save results
- output_file = Path("simple_load_test_results.json")
- with open(output_file, 'w') as f:
- json.dump(results, f, indent=2)
-
- print(f"\\nπŸ“„ Results saved to: {output_file}")
-
-def main():
- """Main execution"""
- tester = SimpleLoadTester()
-
- try:
- results = tester.run_simple_load_test()
-
- # Exit with appropriate code
- load_sim = results["load_simulation"]
- if load_sim["success_rate"] >= 0.8:
- sys.exit(0) # Success
- else:
- sys.exit(1) # Failure
-
- except KeyboardInterrupt:
- print("\\n⚠️ Test interrupted by user")
- sys.exit(1)
- except Exception as e:
- print(f"\\n❌ Test failed: {e}")
- sys.exit(1)
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/benchmark/src/swarm_benchmark/core/__pycache__/benchmark_engine.cpython-312.pyc b/benchmark/src/swarm_benchmark/core/__pycache__/benchmark_engine.cpython-312.pyc
index 0564645cd6..65bc5323d8 100644
Binary files a/benchmark/src/swarm_benchmark/core/__pycache__/benchmark_engine.cpython-312.pyc and b/benchmark/src/swarm_benchmark/core/__pycache__/benchmark_engine.cpython-312.pyc differ
diff --git a/benchmark/swarm_performance_suite.py b/benchmark/swarm_performance_suite.py
deleted file mode 100644
index 1c8373501b..0000000000
--- a/benchmark/swarm_performance_suite.py
+++ /dev/null
@@ -1,840 +0,0 @@
-#!/usr/bin/env python3
-"""
-Comprehensive Performance Benchmarking Suite for Claude-Flow Swarm Operations
-
-This suite provides automated performance testing and monitoring for:
-- Swarm initialization performance
-- Agent coordination latency
-- Memory usage patterns and leak detection
-- Token consumption optimization
-- Cross-session persistence overhead
-- MCP tool response times
-- Neural pattern processing speed
-
-Author: Metrics Analyst Agent
-Version: 1.0.0
-"""
-
-import asyncio
-import time
-import json
-import psutil
-import subprocess
-import os
-import sys
-from datetime import datetime, timedelta
-from pathlib import Path
-from typing import Dict, List, Any, Optional, Tuple
-from dataclasses import dataclass, asdict
-import threading
-import tempfile
-import signal
-from contextlib import asynccontextmanager
-import statistics
-
-# Add benchmark modules to path
-sys.path.insert(0, str(Path(__file__).parent / "src"))
-
-from swarm_benchmark.core.real_benchmark_engine import RealBenchmarkEngine
-from swarm_benchmark.core.models import BenchmarkConfig, StrategyType, CoordinationMode
-from swarm_benchmark.metrics.performance_collector import PerformanceCollector
-
-
-@dataclass
-class SwarmPerformanceTarget:
- """Performance targets for swarm operations."""
- swarm_init_time_seconds: float = 5.0
- agent_coordination_latency_ms: float = 200.0
- memory_baseline_mb: float = 1.0
- token_reduction_percent: float = 32.3
- persistence_overhead_percent: float = 10.0
- mcp_response_time_seconds: float = 1.0
- neural_processing_time_ms: float = 500.0
-
-
-@dataclass
-class SwarmBenchmarkResult:
- """Result from a swarm performance benchmark."""
- test_name: str
- start_time: datetime
- end_time: datetime
- duration_seconds: float
- success: bool
- metrics: Dict[str, Any]
- target_met: bool
- error_message: Optional[str] = None
-
- def to_dict(self) -> Dict[str, Any]:
- return {
- "test_name": self.test_name,
- "start_time": self.start_time.isoformat(),
- "end_time": self.end_time.isoformat(),
- "duration_seconds": self.duration_seconds,
- "success": self.success,
- "metrics": self.metrics,
- "target_met": self.target_met,
- "error_message": self.error_message
- }
-
-
-class SwarmMemoryLeakDetector:
- """Detects memory leaks in swarm operations."""
-
- def __init__(self):
- self.baseline_memory = 0.0
- self.peak_memory = 0.0
- self.samples = []
- self.sampling_interval = 0.5 # 500ms
- self._stop_event = threading.Event()
- self._monitor_thread = None
-
- def start_monitoring(self):
- """Start memory monitoring."""
- self.baseline_memory = psutil.Process().memory_info().rss / 1024 / 1024
- self.peak_memory = self.baseline_memory
- self.samples = []
- self._stop_event.clear()
-
- self._monitor_thread = threading.Thread(target=self._monitor_memory, daemon=True)
- self._monitor_thread.start()
-
- def stop_monitoring(self) -> Dict[str, float]:
- """Stop monitoring and return leak analysis."""
- self._stop_event.set()
- if self._monitor_thread:
- self._monitor_thread.join(timeout=5.0)
-
- current_memory = psutil.Process().memory_info().rss / 1024 / 1024
- memory_growth = current_memory - self.baseline_memory
-
- # Calculate memory growth trend
- if len(self.samples) > 10:
- # Use linear regression to detect steady growth
- times = [s[0] for s in self.samples]
- memories = [s[1] for s in self.samples]
- n = len(samples)
-
- # Simple linear regression
- sum_xy = sum(t * m for t, m in zip(times, memories))
- sum_x = sum(times)
- sum_y = sum(memories)
- sum_x2 = sum(t * t for t in times)
-
- slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x * sum_x) if n * sum_x2 - sum_x * sum_x != 0 else 0
- growth_rate_mb_per_second = slope
- else:
- growth_rate_mb_per_second = 0
-
- return {
- "baseline_memory_mb": self.baseline_memory,
- "final_memory_mb": current_memory,
- "peak_memory_mb": self.peak_memory,
- "memory_growth_mb": memory_growth,
- "growth_rate_mb_per_second": growth_rate_mb_per_second,
- "leak_detected": growth_rate_mb_per_second > 0.1, # >100KB/s growth = leak
- "sample_count": len(self.samples)
- }
-
- def _monitor_memory(self):
- """Background memory monitoring thread."""
- start_time = time.time()
- while not self._stop_event.is_set():
- try:
- current_time = time.time() - start_time
- current_memory = psutil.Process().memory_info().rss / 1024 / 1024
-
- self.samples.append((current_time, current_memory))
- self.peak_memory = max(self.peak_memory, current_memory)
-
- # Keep only last 1000 samples to prevent memory bloat
- if len(self.samples) > 1000:
- self.samples = self.samples[-500:]
-
- time.sleep(self.sampling_interval)
- except Exception:
- break
-
-
-class SwarmPerformanceBenchmark:
- """Main performance benchmark suite for swarm operations."""
-
- def __init__(self, output_dir: str = "performance_results"):
- self.output_dir = Path(output_dir)
- self.output_dir.mkdir(exist_ok=True)
- self.targets = SwarmPerformanceTarget()
- self.memory_detector = SwarmMemoryLeakDetector()
- self.results: List[SwarmBenchmarkResult] = []
-
- async def run_full_suite(self) -> Dict[str, Any]:
- """Run the complete performance benchmark suite."""
- print("πŸš€ Starting Comprehensive Swarm Performance Benchmark Suite")
- print("=" * 60)
-
- suite_start = datetime.now()
-
- # Test categories
- test_categories = [
- ("Startup Performance", self._test_startup_performance),
- ("Coordination Efficiency", self._test_coordination_efficiency),
- ("Memory Performance", self._test_memory_performance),
- ("Network Performance", self._test_network_performance),
- ("Scalability Tests", self._test_scalability),
- ("Regression Tests", self._test_regression_detection)
- ]
-
- category_results = {}
-
- for category_name, test_func in test_categories:
- print(f"\nπŸ“Š Running {category_name} Tests...")
- try:
- category_results[category_name] = await test_func()
- passed = sum(1 for r in category_results[category_name] if r.target_met)
- total = len(category_results[category_name])
- print(f"βœ… {category_name}: {passed}/{total} tests passed targets")
- except Exception as e:
- print(f"❌ {category_name} failed: {e}")
- category_results[category_name] = []
-
- suite_end = datetime.now()
-
- # Generate comprehensive report
- report = await self._generate_performance_report(category_results, suite_start, suite_end)
-
- # Save results
- await self._save_results(report)
-
- return report
-
- async def _test_startup_performance(self) -> List[SwarmBenchmarkResult]:
- """Test swarm initialization and ready state performance."""
- tests = []
-
- # Test 1: Basic swarm initialization
- result = await self._benchmark_operation(
- "swarm_init_basic",
- lambda: self._run_claude_flow_command(["swarm", "init", "--mode", "mesh", "--agents", "3"]),
- target_time=self.targets.swarm_init_time_seconds
- )
- tests.append(result)
-
- # Test 2: Large swarm initialization
- result = await self._benchmark_operation(
- "swarm_init_large",
- lambda: self._run_claude_flow_command(["swarm", "init", "--mode", "hierarchical", "--agents", "8"]),
- target_time=self.targets.swarm_init_time_seconds * 2 # Allow more time for larger swarms
- )
- tests.append(result)
-
- # Test 3: Cold start vs warm start
- # Cold start
- result = await self._benchmark_operation(
- "cold_start",
- lambda: self._run_claude_flow_command(["swarm", "status"], clear_cache=True),
- target_time=self.targets.swarm_init_time_seconds
- )
- tests.append(result)
-
- # Warm start (immediate second call)
- result = await self._benchmark_operation(
- "warm_start",
- lambda: self._run_claude_flow_command(["swarm", "status"]),
- target_time=self.targets.swarm_init_time_seconds / 2 # Should be faster
- )
- tests.append(result)
-
- return tests
-
- async def _test_coordination_efficiency(self) -> List[SwarmBenchmarkResult]:
- """Test agent-to-agent coordination and communication."""
- tests = []
-
- # Test 1: Agent spawn latency
- result = await self._benchmark_operation(
- "agent_spawn_latency",
- lambda: self._measure_agent_spawn_time(),
- target_time=self.targets.agent_coordination_latency_ms / 1000.0
- )
- tests.append(result)
-
- # Test 2: Inter-agent communication
- result = await self._benchmark_operation(
- "inter_agent_communication",
- lambda: self._measure_agent_communication(),
- target_time=self.targets.agent_coordination_latency_ms / 1000.0
- )
- tests.append(result)
-
- # Test 3: Task coordination overhead
- result = await self._benchmark_operation(
- "task_coordination_overhead",
- lambda: self._measure_coordination_overhead(),
- target_time=self.targets.agent_coordination_latency_ms / 1000.0
- )
- tests.append(result)
-
- return tests
-
- async def _test_memory_performance(self) -> List[SwarmBenchmarkResult]:
- """Test memory usage patterns and leak detection."""
- tests = []
-
- # Test 1: Memory leak detection
- result = await self._benchmark_memory_operation(
- "memory_leak_detection",
- lambda: self._run_extended_swarm_operation(),
- target_growth_mb=1.0
- )
- tests.append(result)
-
- # Test 2: Memory baseline measurement
- result = await self._benchmark_operation(
- "memory_baseline",
- lambda: self._measure_baseline_memory(),
- target_time=1.0, # Quick test
- custom_metrics=True
- )
- tests.append(result)
-
- # Test 3: Persistence overhead
- result = await self._benchmark_operation(
- "persistence_overhead",
- lambda: self._measure_persistence_overhead(),
- target_time=self.targets.persistence_overhead_percent / 100.0 # Convert to multiplier
- )
- tests.append(result)
-
- return tests
-
- async def _test_network_performance(self) -> List[SwarmBenchmarkResult]:
- """Test MCP tool response times and network efficiency."""
- tests = []
-
- # Test 1: MCP tool response time
- result = await self._benchmark_operation(
- "mcp_response_time",
- lambda: self._measure_mcp_response_time(),
- target_time=self.targets.mcp_response_time_seconds
- )
- tests.append(result)
-
- # Test 2: Neural pattern processing
- result = await self._benchmark_operation(
- "neural_pattern_processing",
- lambda: self._measure_neural_processing(),
- target_time=self.targets.neural_processing_time_ms / 1000.0
- )
- tests.append(result)
-
- return tests
-
- async def _test_scalability(self) -> List[SwarmBenchmarkResult]:
- """Test performance under increasing loads."""
- tests = []
-
- agent_counts = [1, 2, 4, 8, 16]
-
- for count in agent_counts:
- result = await self._benchmark_operation(
- f"scalability_agents_{count}",
- lambda c=count: self._run_scalability_test(c),
- target_time=self.targets.swarm_init_time_seconds * (1 + count / 10) # Linear scaling expectation
- )
- tests.append(result)
-
- return tests
-
- async def _test_regression_detection(self) -> List[SwarmBenchmarkResult]:
- """Test for performance regressions."""
- tests = []
-
- # Load baseline metrics if available
- baseline_file = self.output_dir / "baseline_metrics.json"
- baseline_metrics = {}
-
- if baseline_file.exists():
- with open(baseline_file) as f:
- baseline_metrics = json.load(f)
-
- # Test current performance against baseline
- current_metrics = await self._measure_current_performance()
-
- for metric_name, current_value in current_metrics.items():
- if metric_name in baseline_metrics:
- baseline_value = baseline_metrics[metric_name]
- regression_threshold = 1.1 # 10% regression tolerance
-
- target_met = current_value <= baseline_value * regression_threshold
-
- result = SwarmBenchmarkResult(
- test_name=f"regression_{metric_name}",
- start_time=datetime.now(),
- end_time=datetime.now(),
- duration_seconds=0.0,
- success=True,
- metrics={
- "current_value": current_value,
- "baseline_value": baseline_value,
- "regression_percent": ((current_value - baseline_value) / baseline_value) * 100
- },
- target_met=target_met
- )
- tests.append(result)
-
- # Save current metrics as new baseline
- with open(baseline_file, 'w') as f:
- json.dump(current_metrics, f, indent=2)
-
- return tests
-
- async def _benchmark_operation(self, test_name: str, operation, target_time: float, custom_metrics: bool = False) -> SwarmBenchmarkResult:
- """Benchmark a single operation against performance targets."""
- start_time = datetime.now()
-
- # Start performance monitoring
- collector = PerformanceCollector(sample_interval=0.1)
- collector.start_collection()
-
- try:
- operation_start = time.time()
- result = await asyncio.get_event_loop().run_in_executor(None, operation)
- operation_end = time.time()
-
- duration = operation_end - operation_start
- performance_metrics = collector.stop_collection()
-
- end_time = datetime.now()
-
- # Check if target was met
- target_met = duration <= target_time
-
- metrics = {
- "duration_seconds": duration,
- "target_seconds": target_time,
- "execution_time": performance_metrics.execution_time,
- "throughput": performance_metrics.throughput,
- "success_rate": performance_metrics.success_rate,
- "operation_result": str(result)[:200] if result else "N/A"
- }
-
- return SwarmBenchmarkResult(
- test_name=test_name,
- start_time=start_time,
- end_time=end_time,
- duration_seconds=duration,
- success=True,
- metrics=metrics,
- target_met=target_met
- )
-
- except Exception as e:
- collector.stop_collection()
- end_time = datetime.now()
-
- return SwarmBenchmarkResult(
- test_name=test_name,
- start_time=start_time,
- end_time=end_time,
- duration_seconds=(end_time - start_time).total_seconds(),
- success=False,
- metrics={"error": str(e)},
- target_met=False,
- error_message=str(e)
- )
-
- async def _benchmark_memory_operation(self, test_name: str, operation, target_growth_mb: float) -> SwarmBenchmarkResult:
- """Benchmark operation specifically for memory usage."""
- start_time = datetime.now()
-
- # Start memory leak detection
- self.memory_detector.start_monitoring()
-
- try:
- operation_start = time.time()
- result = await asyncio.get_event_loop().run_in_executor(None, operation)
- operation_end = time.time()
-
- # Stop memory monitoring and analyze
- memory_metrics = self.memory_detector.stop_monitoring()
- duration = operation_end - operation_start
- end_time = datetime.now()
-
- # Check if memory growth target was met
- target_met = memory_metrics["memory_growth_mb"] <= target_growth_mb and not memory_metrics["leak_detected"]
-
- metrics = {
- "duration_seconds": duration,
- "memory_metrics": memory_metrics,
- "target_growth_mb": target_growth_mb,
- "operation_result": str(result)[:200] if result else "N/A"
- }
-
- return SwarmBenchmarkResult(
- test_name=test_name,
- start_time=start_time,
- end_time=end_time,
- duration_seconds=duration,
- success=True,
- metrics=metrics,
- target_met=target_met
- )
-
- except Exception as e:
- self.memory_detector.stop_monitoring()
- end_time = datetime.now()
-
- return SwarmBenchmarkResult(
- test_name=test_name,
- start_time=start_time,
- end_time=end_time,
- duration_seconds=(end_time - start_time).total_seconds(),
- success=False,
- metrics={"error": str(e)},
- target_met=False,
- error_message=str(e)
- )
-
- def _run_claude_flow_command(self, args: List[str], clear_cache: bool = False) -> str:
- """Run a claude-flow command and return output."""
- if clear_cache:
- # Clear any potential cache
- cache_dirs = [
- Path.home() / ".claude-flow" / "cache",
- Path.cwd() / ".cache",
- Path("/tmp/claude-flow-cache")
- ]
- for cache_dir in cache_dirs:
- if cache_dir.exists():
- import shutil
- shutil.rmtree(cache_dir, ignore_errors=True)
-
- # Construct command
- cmd = ["node", str(Path(__file__).parent / "../cli.js")] + args
-
- try:
- result = subprocess.run(
- cmd,
- capture_output=True,
- text=True,
- timeout=30,
- cwd=str(Path(__file__).parent.parent)
- )
- return result.stdout
- except subprocess.TimeoutExpired:
- return "TIMEOUT"
- except Exception as e:
- return f"ERROR: {e}"
-
- def _measure_agent_spawn_time(self) -> float:
- """Measure time to spawn a new agent."""
- start = time.time()
- output = self._run_claude_flow_command(["swarm", "spawn", "researcher", "--name", "test-agent"])
- end = time.time()
- return end - start
-
- def _measure_agent_communication(self) -> float:
- """Measure inter-agent communication latency."""
- # This would measure actual communication between agents
- # For now, simulate with a simple command
- start = time.time()
- output = self._run_claude_flow_command(["swarm", "status"])
- end = time.time()
- return end - start
-
- def _measure_coordination_overhead(self) -> float:
- """Measure task coordination overhead."""
- # Compare single agent vs multi-agent task execution
- start = time.time()
- output = self._run_claude_flow_command(["swarm", "task", "simple test task", "--agents", "3"])
- end = time.time()
- return end - start
-
- def _run_extended_swarm_operation(self) -> str:
- """Run an extended operation to test for memory leaks."""
- operations = []
-
- # Run multiple operations that could cause memory leaks
- for i in range(10):
- output = self._run_claude_flow_command(["swarm", "init", "--mode", "mesh", "--agents", "2"])
- operations.append(output)
-
- output = self._run_claude_flow_command(["swarm", "spawn", "researcher"])
- operations.append(output)
-
- output = self._run_claude_flow_command(["swarm", "status"])
- operations.append(output)
-
- # Small delay to allow monitoring
- time.sleep(0.1)
-
- return "\n".join(operations)
-
- def _measure_baseline_memory(self) -> str:
- """Measure baseline memory usage."""
- process = psutil.Process()
- return f"Baseline memory: {process.memory_info().rss / 1024 / 1024:.2f} MB"
-
- def _measure_persistence_overhead(self) -> float:
- """Measure cross-session persistence overhead."""
- # Time operation with persistence vs without
- start = time.time()
- output = self._run_claude_flow_command(["swarm", "init", "--persist"])
- end = time.time()
- return end - start
-
- def _measure_mcp_response_time(self) -> float:
- """Measure MCP tool response time."""
- start = time.time()
- output = self._run_claude_flow_command(["mcp", "status"])
- end = time.time()
- return end - start
-
- def _measure_neural_processing(self) -> float:
- """Measure neural pattern processing time."""
- start = time.time()
- output = self._run_claude_flow_command(["sparc", "researcher", "quick test"])
- end = time.time()
- return end - start
-
- def _run_scalability_test(self, agent_count: int) -> float:
- """Run scalability test with specified agent count."""
- start = time.time()
- output = self._run_claude_flow_command(["swarm", "init", "--agents", str(agent_count)])
- end = time.time()
- return end - start
-
- async def _measure_current_performance(self) -> Dict[str, float]:
- """Measure current performance metrics for regression testing."""
- metrics = {}
-
- # Swarm init time
- start = time.time()
- self._run_claude_flow_command(["swarm", "init", "--mode", "mesh", "--agents", "3"])
- metrics["swarm_init_time"] = time.time() - start
-
- # Agent spawn time
- start = time.time()
- self._run_claude_flow_command(["swarm", "spawn", "researcher"])
- metrics["agent_spawn_time"] = time.time() - start
-
- # Memory usage
- process = psutil.Process()
- metrics["memory_usage_mb"] = process.memory_info().rss / 1024 / 1024
-
- return metrics
-
- async def _generate_performance_report(self, category_results: Dict[str, List[SwarmBenchmarkResult]],
- suite_start: datetime, suite_end: datetime) -> Dict[str, Any]:
- """Generate comprehensive performance report."""
-
- # Aggregate all results
- all_results = []
- for category_results_list in category_results.values():
- all_results.extend(category_results_list)
-
- # Calculate summary statistics
- total_tests = len(all_results)
- passed_tests = sum(1 for r in all_results if r.target_met)
- failed_tests = sum(1 for r in all_results if not r.success)
-
- # Calculate performance score (0-100)
- if total_tests > 0:
- performance_score = (passed_tests / total_tests) * 100
- else:
- performance_score = 0
-
- # Identify critical issues
- critical_issues = []
- for result in all_results:
- if not result.target_met and result.success:
- critical_issues.append({
- "test": result.test_name,
- "issue": "Performance target not met",
- "metrics": result.metrics
- })
- elif not result.success:
- critical_issues.append({
- "test": result.test_name,
- "issue": "Test failed",
- "error": result.error_message
- })
-
- # Generate recommendations
- recommendations = self._generate_recommendations(all_results)
-
- report = {
- "summary": {
- "test_suite": "Swarm Performance Benchmark",
- "version": "1.0.0",
- "start_time": suite_start.isoformat(),
- "end_time": suite_end.isoformat(),
- "duration_minutes": (suite_end - suite_start).total_seconds() / 60,
- "total_tests": total_tests,
- "passed_tests": passed_tests,
- "failed_tests": failed_tests,
- "performance_score": performance_score
- },
- "targets": asdict(self.targets),
- "category_results": {
- category: [result.to_dict() for result in results]
- for category, results in category_results.items()
- },
- "critical_issues": critical_issues,
- "recommendations": recommendations,
- "detailed_metrics": {
- "memory_analysis": await self._analyze_memory_patterns(all_results),
- "performance_trends": await self._analyze_performance_trends(all_results),
- "bottleneck_analysis": await self._identify_bottlenecks(all_results)
- }
- }
-
- return report
-
- def _generate_recommendations(self, results: List[SwarmBenchmarkResult]) -> List[str]:
- """Generate performance optimization recommendations."""
- recommendations = []
-
- # Analyze results for common patterns
- slow_startup_tests = [r for r in results if "init" in r.test_name and not r.target_met]
- if slow_startup_tests:
- recommendations.append("Consider optimizing swarm initialization by implementing connection pooling")
-
- memory_issues = [r for r in results if "memory" in r.test_name and not r.target_met]
- if memory_issues:
- recommendations.append("Memory usage exceeded targets - investigate memory leaks in agent cleanup")
-
- coordination_issues = [r for r in results if "coordination" in r.test_name and not r.target_met]
- if coordination_issues:
- recommendations.append("Agent coordination latency high - consider implementing async message passing")
-
- scalability_issues = [r for r in results if "scalability" in r.test_name and not r.target_met]
- if scalability_issues:
- recommendations.append("Scalability limits reached - implement load balancing and resource pooling")
-
- if not recommendations:
- recommendations.append("All performance targets met - consider tightening targets for continued optimization")
-
- return recommendations
-
- async def _analyze_memory_patterns(self, results: List[SwarmBenchmarkResult]) -> Dict[str, Any]:
- """Analyze memory usage patterns across tests."""
- memory_tests = [r for r in results if "memory" in r.metrics]
-
- if not memory_tests:
- return {"analysis": "No memory data available"}
-
- memory_values = []
- for result in memory_tests:
- if "memory_metrics" in result.metrics:
- memory_values.append(result.metrics["memory_metrics"].get("peak_memory_mb", 0))
-
- if memory_values:
- return {
- "peak_memory_mb": max(memory_values),
- "average_memory_mb": statistics.mean(memory_values),
- "memory_variance": statistics.variance(memory_values) if len(memory_values) > 1 else 0,
- "trend": "increasing" if memory_values[-1] > memory_values[0] else "stable"
- }
- else:
- return {"analysis": "No memory metrics collected"}
-
- async def _analyze_performance_trends(self, results: List[SwarmBenchmarkResult]) -> Dict[str, Any]:
- """Analyze performance trends across test categories."""
- trends = {}
-
- # Group by test category
- by_category = {}
- for result in results:
- category = result.test_name.split("_")[0]
- if category not in by_category:
- by_category[category] = []
- by_category[category].append(result.duration_seconds)
-
- for category, durations in by_category.items():
- if len(durations) > 1:
- trends[category] = {
- "average_duration": statistics.mean(durations),
- "min_duration": min(durations),
- "max_duration": max(durations),
- "consistency": 1.0 - (statistics.stdev(durations) / statistics.mean(durations)) if statistics.mean(durations) > 0 else 0
- }
-
- return trends
-
- async def _identify_bottlenecks(self, results: List[SwarmBenchmarkResult]) -> List[Dict[str, Any]]:
- """Identify performance bottlenecks from test results."""
- bottlenecks = []
-
- # Find tests that significantly exceed targets
- for result in results:
- if result.success and not result.target_met:
- if "target_seconds" in result.metrics and result.duration_seconds > result.metrics["target_seconds"] * 2:
- bottlenecks.append({
- "test": result.test_name,
- "severity": "high",
- "actual_duration": result.duration_seconds,
- "target_duration": result.metrics["target_seconds"],
- "slowdown_factor": result.duration_seconds / result.metrics["target_seconds"]
- })
-
- # Sort by severity
- bottlenecks.sort(key=lambda x: x.get("slowdown_factor", 1), reverse=True)
-
- return bottlenecks[:5] # Top 5 bottlenecks
-
- async def _save_results(self, report: Dict[str, Any]):
- """Save benchmark results to files."""
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
-
- # Save main report
- report_file = self.output_dir / f"swarm_performance_report_{timestamp}.json"
- with open(report_file, 'w') as f:
- json.dump(report, f, indent=2, default=str)
-
- # Save CSV summary for spreadsheet analysis
- csv_file = self.output_dir / f"swarm_performance_summary_{timestamp}.csv"
- with open(csv_file, 'w') as f:
- f.write("test_name,duration_seconds,target_met,success,category\n")
- for category, results in report["category_results"].items():
- for result in results:
- f.write(f"{result['test_name']},{result['duration_seconds']},{result['target_met']},{result['success']},{category}\n")
-
- print(f"\nπŸ“Š Results saved to:")
- print(f" Report: {report_file}")
- print(f" CSV: {csv_file}")
-
- # Print summary
- summary = report["summary"]
- print(f"\n🎯 Performance Summary:")
- print(f" Score: {summary['performance_score']:.1f}/100")
- print(f" Tests: {summary['passed_tests']}/{summary['total_tests']} passed")
- print(f" Duration: {summary['duration_minutes']:.1f} minutes")
-
- if report["critical_issues"]:
- print(f"\n⚠️ Critical Issues Found: {len(report['critical_issues'])}")
- for issue in report["critical_issues"][:3]: # Show top 3
- print(f" - {issue['test']}: {issue['issue']}")
-
-
-async def main():
- """Main entry point for the performance benchmark suite."""
- import argparse
-
- parser = argparse.ArgumentParser(description="Swarm Performance Benchmark Suite")
- parser.add_argument("--output-dir", default="performance_results", help="Output directory for results")
- parser.add_argument("--quick", action="store_true", help="Run quick subset of tests")
- args = parser.parse_args()
-
- benchmark = SwarmPerformanceBenchmark(output_dir=args.output_dir)
-
- if args.quick:
- # Run only essential tests for quick feedback
- print("πŸš€ Running Quick Performance Check...")
- result = await benchmark._test_startup_performance()
- print(f"Quick check completed: {len([r for r in result if r.target_met])}/{len(result)} targets met")
- else:
- # Run full suite
- await benchmark.run_full_suite()
-
-
-if __name__ == "__main__":
- asyncio.run(main())
\ No newline at end of file
diff --git a/benchmark/test_claude_optimizer.py b/benchmark/test_claude_optimizer.py
deleted file mode 100644
index a4526133fd..0000000000
--- a/benchmark/test_claude_optimizer.py
+++ /dev/null
@@ -1,235 +0,0 @@
-#!/usr/bin/env python3
-"""
-Test script for CLAUDE.md Optimizer implementation.
-Verifies all components work correctly.
-"""
-
-import sys
-import asyncio
-from pathlib import Path
-
-# Add benchmark source to path
-sys.path.insert(0, str(Path(__file__).parent / "src"))
-
-from swarm_benchmark.claude_optimizer import (
- ClaudeMdOptimizer,
- ProjectContext,
- PerformanceTargets,
- TemplateEngine,
- OptimizationRulesEngine
-)
-
-
-async def test_claude_optimizer():
- """Test the CLAUDE.md optimizer implementation."""
- print("πŸ§ͺ Testing CLAUDE.md Optimizer")
- print("=" * 40)
-
- # Test 1: Optimizer initialization
- print("\n1. Testing optimizer initialization...")
- try:
- optimizer = ClaudeMdOptimizer()
- print(" βœ… Optimizer initialized successfully")
- except Exception as e:
- print(f" ❌ Failed to initialize optimizer: {e}")
- return False
-
- # Test 2: Project context creation
- print("\n2. Testing project context...")
- try:
- context = ProjectContext(
- project_type="test_api",
- team_size=4,
- complexity="medium",
- primary_languages=["Python"],
- frameworks=["FastAPI"],
- performance_requirements={"response_time": "<100ms"},
- existing_tools=["pytest"],
- constraints={"timeline": "normal"}
- )
- print(" βœ… Project context created successfully")
- except Exception as e:
- print(f" ❌ Failed to create project context: {e}")
- return False
-
- # Test 3: Performance targets
- print("\n3. Testing performance targets...")
- try:
- targets = PerformanceTargets(
- priority="speed",
- target_completion_time=30.0,
- target_token_usage=500
- )
- print(" βœ… Performance targets created successfully")
- except Exception as e:
- print(f" ❌ Failed to create performance targets: {e}")
- return False
-
- # Test 4: Configuration generation
- print("\n4. Testing configuration generation...")
- try:
- config = optimizer.generate_optimized_config(
- "api_development", context, targets
- )
- assert isinstance(config, str)
- assert len(config) > 0
- assert "CLAUDE.md" in config
- print(" βœ… Configuration generated successfully")
- print(f" πŸ“Š Config length: {len(config)} characters")
- except Exception as e:
- print(f" ❌ Failed to generate configuration: {e}")
- return False
-
- # Test 5: Template engine
- print("\n5. Testing template engine...")
- try:
- template_engine = TemplateEngine()
- test_config = {
- "use_case": "test_case",
- "max_agents": 4,
- "swarm_topology": "hierarchical"
- }
- template = template_engine.generate_claude_md(test_config)
- assert isinstance(template, str)
- print(" βœ… Template engine works correctly")
- except Exception as e:
- print(f" ❌ Template engine failed: {e}")
- return False
-
- # Test 6: Rules engine
- print("\n6. Testing rules engine...")
- try:
- rules_engine = OptimizationRulesEngine()
- test_config = {"max_agents": 4}
-
- # Test speed optimization
- speed_config = rules_engine.optimize_for_speed(test_config.copy())
- assert "parallel_execution" in speed_config
-
- # Test accuracy optimization
- accuracy_config = rules_engine.optimize_for_accuracy(test_config.copy())
- assert "validation_level" in accuracy_config
-
- print(" βœ… Rules engine works correctly")
- except Exception as e:
- print(f" ❌ Rules engine failed: {e}")
- return False
-
- # Test 7: Benchmarking (simplified)
- print("\n7. Testing benchmarking...")
- try:
- test_tasks = [
- "Create simple API endpoint",
- "Add basic validation",
- "Write unit test"
- ]
-
- # Use a shorter timeout for testing
- metrics = await asyncio.wait_for(
- optimizer.benchmark_config_effectiveness(config, test_tasks, iterations=1),
- timeout=10.0
- )
-
- assert hasattr(metrics, 'optimization_score')
- assert hasattr(metrics, 'completion_rate')
- assert 0 <= metrics.optimization_score <= 1
- assert 0 <= metrics.completion_rate <= 1
-
- print(" βœ… Benchmarking works correctly")
- print(f" πŸ“Š Optimization score: {metrics.optimization_score:.3f}")
- print(f" πŸ“Š Completion rate: {metrics.completion_rate:.1%}")
- except asyncio.TimeoutError:
- print(" ⚠️ Benchmarking timed out (expected in test environment)")
- except Exception as e:
- print(f" ❌ Benchmarking failed: {e}")
- return False
-
- # Test 8: All use cases
- print("\n8. Testing all use cases...")
- use_cases = [
- "api_development", "ml_pipeline", "frontend_react",
- "backend_microservices", "testing_automation"
- ]
-
- for use_case in use_cases:
- try:
- config = optimizer.generate_optimized_config(use_case, context, targets)
- assert isinstance(config, str)
- assert len(config) > 0
- print(f" βœ… {use_case} - OK")
- except Exception as e:
- print(f" ❌ {use_case} failed: {e}")
- return False
-
- print("\nπŸŽ‰ All tests passed!")
- return True
-
-
-def test_file_structure():
- """Test that all required files were created."""
- print("\nπŸ“ Testing file structure...")
-
- base_path = Path(__file__).parent
- required_files = [
- "src/swarm_benchmark/claude_optimizer/__init__.py",
- "src/swarm_benchmark/claude_optimizer/optimizer.py",
- "src/swarm_benchmark/claude_optimizer/templates.py",
- "src/swarm_benchmark/claude_optimizer/rules_engine.py",
- "docs/api_reference.md",
- "docs/claude_optimizer_guide.md",
- "examples/claude_optimizer_example.py"
- ]
-
- all_exist = True
- for file_path in required_files:
- full_path = base_path / file_path
- if full_path.exists():
- print(f" βœ… {file_path}")
- else:
- print(f" ❌ {file_path} - MISSING")
- all_exist = False
-
- return all_exist
-
-
-async def main():
- """Run all tests."""
- print("πŸš€ CLAUDE.md Optimizer Implementation Test")
- print("=" * 50)
-
- # Test file structure
- files_ok = test_file_structure()
-
- if not files_ok:
- print("\n❌ File structure test failed")
- return 1
-
- # Test functionality
- try:
- functionality_ok = await test_claude_optimizer()
-
- if functionality_ok:
- print("\nβœ… All tests completed successfully!")
- print("\nπŸ“‹ Implementation Summary:")
- print(" - ClaudeMdOptimizer class: βœ… Complete")
- print(" - 10 use case templates: βœ… Complete")
- print(" - Optimization rules engine: βœ… Complete")
- print(" - Configuration benchmarking: βœ… Complete")
- print(" - API documentation: βœ… Complete")
- print(" - User guide: βœ… Complete")
- print(" - Example implementation: βœ… Complete")
- return 0
- else:
- print("\n❌ Some tests failed")
- return 1
-
- except Exception as e:
- print(f"\nπŸ’₯ Test suite crashed: {e}")
- import traceback
- traceback.print_exc()
- return 1
-
-
-if __name__ == "__main__":
- exit_code = asyncio.run(main())
- sys.exit(exit_code)
\ No newline at end of file
diff --git a/benchmark/test_hello_world.py b/benchmark/test_hello_world.py
deleted file mode 100644
index ad02be6a42..0000000000
--- a/benchmark/test_hello_world.py
+++ /dev/null
@@ -1,33 +0,0 @@
-"""
-Unit tests for Hello World function
-"""
-
-from hello_world import hello_world
-
-
-def test_hello_world_default():
- """Test default parameter"""
- assert hello_world() == "Hello, World!"
- print("βœ“ Default parameter test passed")
-
-
-def test_hello_world_custom_name():
- """Test with custom name"""
- assert hello_world("Claude") == "Hello, Claude!"
- print("βœ“ Custom name test passed")
-
-
-def test_hello_world_empty_string():
- """Test with empty string"""
- assert hello_world("") == "Hello, !"
- print("βœ“ Empty string test passed")
-
-
-if __name__ == "__main__":
- print("Running Python Hello World Tests:\n")
-
- test_hello_world_default()
- test_hello_world_custom_name()
- test_hello_world_empty_string()
-
- print("\nAll tests completed!")
\ No newline at end of file
diff --git a/benchmark/test_integration.py b/benchmark/test_integration.py
deleted file mode 100755
index 5faa0f6d6f..0000000000
--- a/benchmark/test_integration.py
+++ /dev/null
@@ -1,274 +0,0 @@
-#!/usr/bin/env python3
-"""
-Test script for claude-flow integration.
-
-This script tests the integration layer to ensure proper execution
-of claude-flow commands with comprehensive error handling and output capture.
-"""
-
-import sys
-import json
-import logging
-from pathlib import Path
-
-# Add benchmark src to path
-sys.path.insert(0, str(Path(__file__).parent / "src"))
-
-from swarm_benchmark.core.claude_flow_executor import (
- ClaudeFlowExecutor, SwarmConfig, SparcConfig,
- ExecutionStrategy, CoordinationMode, SparcMode
-)
-from swarm_benchmark.core.integration_utils import (
- OutputParser, CommandBuilder, ErrorHandler,
- ProgressTracker, performance_monitoring
-)
-
-
-# Configure logging
-logging.basicConfig(
- level=logging.INFO,
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
-)
-logger = logging.getLogger(__name__)
-
-
-def test_executor_initialization():
- """Test executor initialization and validation."""
- print("\n=== Testing Executor Initialization ===")
-
- try:
- # Initialize executor
- executor = ClaudeFlowExecutor()
- print(f"βœ… Executor initialized with path: {executor.claude_flow_path}")
-
- # Validate installation
- if executor.validate_installation():
- print("βœ… Claude-flow installation validated")
- else:
- print("❌ Claude-flow installation validation failed")
-
- except Exception as e:
- print(f"❌ Failed to initialize executor: {e}")
- return False
-
- return True
-
-
-def test_swarm_execution():
- """Test swarm command execution."""
- print("\n=== Testing Swarm Execution ===")
-
- try:
- executor = ClaudeFlowExecutor()
-
- # Test configuration
- config = SwarmConfig(
- objective="Create a simple hello world function",
- strategy=ExecutionStrategy.DEVELOPMENT,
- mode=CoordinationMode.CENTRALIZED,
- max_agents=3,
- timeout=5, # 5 minutes
- dry_run=True # Dry run for testing
- )
-
- print(f"πŸ“‹ Config: {json.dumps(config.__dict__, indent=2)}")
-
- # Execute with performance monitoring
- with performance_monitoring() as monitor:
- result = executor.execute_swarm(config)
-
- print(f"\nβœ… Execution completed:")
- print(f" - Success: {result.success}")
- print(f" - Exit code: {result.exit_code}")
- print(f" - Duration: {result.duration:.2f}s")
- print(f" - Timeout: {result.timeout}")
-
- if result.stdout:
- print(f"\nπŸ“„ Output preview:")
- print(result.stdout[:500] + "..." if len(result.stdout) > 500 else result.stdout)
-
- if result.stderr:
- print(f"\n⚠️ Errors:")
- print(result.stderr[:500] + "..." if len(result.stderr) > 500 else result.stderr)
-
- # Parse output
- parsed = OutputParser.parse_output(result.stdout)
- print(f"\nπŸ“Š Parsed output: {json.dumps(parsed, indent=2)}")
-
- except Exception as e:
- print(f"❌ Swarm execution failed: {e}")
- logger.exception("Swarm execution error")
- return False
-
- return True
-
-
-def test_sparc_execution():
- """Test SPARC command execution."""
- print("\n=== Testing SPARC Execution ===")
-
- try:
- executor = ClaudeFlowExecutor()
-
- # Test configuration
- config = SparcConfig(
- prompt="Analyze the current codebase structure",
- mode=SparcMode.ANALYZER,
- memory_key="codebase_analysis",
- timeout=5 # 5 minutes
- )
-
- print(f"πŸ“‹ Config: {json.dumps(config.__dict__, indent=2)}")
-
- # Execute
- result = executor.execute_sparc(config)
-
- print(f"\nβœ… Execution completed:")
- print(f" - Success: {result.success}")
- print(f" - Exit code: {result.exit_code}")
- print(f" - Duration: {result.duration:.2f}s")
-
- if result.stdout:
- print(f"\nπŸ“„ Output preview:")
- print(result.stdout[:500] + "..." if len(result.stdout) > 500 else result.stdout)
-
- except Exception as e:
- print(f"❌ SPARC execution failed: {e}")
- logger.exception("SPARC execution error")
- return False
-
- return True
-
-
-def test_command_building():
- """Test command building utilities."""
- print("\n=== Testing Command Building ===")
-
- # Test swarm command
- swarm_cmd = CommandBuilder.build_swarm_command(
- "Build a REST API",
- strategy="development",
- mode="hierarchical",
- max_agents=5,
- parallel=True,
- monitor=True
- )
- print(f"Swarm command: {' '.join(swarm_cmd)}")
-
- # Test SPARC command
- sparc_cmd = CommandBuilder.build_sparc_command(
- "Optimize database queries",
- mode="optimizer",
- memory_key="db_optimization",
- batch=True
- )
- print(f"SPARC command: {' '.join(sparc_cmd)}")
-
- # Test validation
- valid_config = {"objective": "Test", "strategy": "development"}
- errors = CommandBuilder.validate_swarm_config(valid_config)
- print(f"\nValid config errors: {errors}")
-
- invalid_config = {"strategy": "invalid_strategy"}
- errors = CommandBuilder.validate_swarm_config(invalid_config)
- print(f"Invalid config errors: {errors}")
-
- return True
-
-
-def test_error_handling():
- """Test error handling and categorization."""
- print("\n=== Testing Error Handling ===")
-
- test_errors = [
- "command not found: claude-flow",
- "Error: invalid option --invalid",
- "Process terminated with signal 11",
- "Connection refused while fetching data",
- "Execution timed out after 60 seconds"
- ]
-
- for error in test_errors:
- category = ErrorHandler.categorize_error(error)
- suggestion = ErrorHandler.get_recovery_suggestion(category)
- should_retry = ErrorHandler.should_retry(category)
-
- print(f"\nError: {error}")
- print(f" - Category: {category}")
- print(f" - Suggestion: {suggestion}")
- print(f" - Should retry: {should_retry}")
-
- return True
-
-
-def test_progress_tracking():
- """Test progress tracking with sample output."""
- print("\n=== Testing Progress Tracking ===")
-
- tracker = ProgressTracker()
- tracker.start()
-
- # Simulate output lines
- sample_lines = [
- "🎯 Starting swarm execution...",
- "Task created: task-001-research",
- "Agent Researcher started",
- "Task created: task-002-analysis",
- "βœ… Task completed: task-001-research",
- "❌ Error: Failed to connect to API",
- "Agent Analyzer started",
- "βœ… Task completed: task-002-analysis"
- ]
-
- for line in sample_lines:
- tracker.parse_output_stream(line)
-
- summary = tracker.get_summary()
- print(f"\nProgress summary:")
- print(json.dumps(summary, indent=2))
-
- return True
-
-
-def main():
- """Run all integration tests."""
- print("πŸ§ͺ Claude-Flow Integration Tests")
- print("=" * 50)
-
- tests = [
- ("Executor Initialization", test_executor_initialization),
- ("Command Building", test_command_building),
- ("Error Handling", test_error_handling),
- ("Progress Tracking", test_progress_tracking),
- ("Swarm Execution", test_swarm_execution),
- ("SPARC Execution", test_sparc_execution),
- ]
-
- results = []
- for test_name, test_func in tests:
- try:
- print(f"\nπŸ”„ Running: {test_name}")
- success = test_func()
- results.append((test_name, success))
- except Exception as e:
- print(f"❌ Test failed with exception: {e}")
- logger.exception(f"Test {test_name} failed")
- results.append((test_name, False))
-
- # Summary
- print("\n" + "=" * 50)
- print("πŸ“Š Test Summary:")
- for test_name, success in results:
- status = "βœ… PASS" if success else "❌ FAIL"
- print(f" {test_name}: {status}")
-
- passed = sum(1 for _, success in results if success)
- total = len(results)
- print(f"\n🏁 Total: {passed}/{total} tests passed")
-
- return passed == total
-
-
-if __name__ == "__main__":
- success = main()
- sys.exit(0 if success else 1)
\ No newline at end of file
diff --git a/benchmark/test_mle_star_integration.py b/benchmark/test_mle_star_integration.py
deleted file mode 100644
index 88eccf1be1..0000000000
--- a/benchmark/test_mle_star_integration.py
+++ /dev/null
@@ -1,225 +0,0 @@
-#!/usr/bin/env python3
-"""
-Test script for MLE-STAR ensemble integration.
-
-This script tests the basic functionality of the MLE-STAR implementation
-including ensemble execution, voting strategies, and performance tracking.
-"""
-
-import asyncio
-import logging
-import sys
-import os
-
-# Add the src directory to Python path
-sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
-
-from swarm_benchmark.mle_star import (
- MLEStarEnsembleExecutor, MLEStarConfig,
- MLScenarios, ClassificationScenario, RegressionScenario
-)
-
-
-async def test_classification_scenario():
- """Test basic classification ensemble."""
- print("🧠 Testing Classification Ensemble...")
-
- try:
- # Get small classification scenario
- scenario_config = MLScenarios.classification_benchmark_small()
- scenario = ClassificationScenario(scenario_config)
-
- # Run the scenario
- result = await scenario.run_scenario()
-
- print(f"βœ… Classification Scenario: {'SUCCESS' if result['success'] else 'FAILED'}")
- if result['success']:
- metrics = result['metrics']
- print(f" - Ensemble Size: {metrics.get('ensemble', {}).get('ensemble_size', 'N/A')}")
- print(f" - Total Time: {result['execution_time']:.2f}s")
- print(f" - Accuracy: {metrics.get('performance', {}).get('accuracy', 'N/A')}")
- print(f" - Performance Targets Met: {result['performance_targets_met']}")
- else:
- print(f" - Error: {result.get('error', 'Unknown error')}")
-
- return result['success']
-
- except Exception as e:
- print(f"❌ Classification test failed: {e}")
- return False
-
-
-async def test_regression_scenario():
- """Test basic regression ensemble."""
- print("\nπŸ“Š Testing Regression Ensemble...")
-
- try:
- # Get small regression scenario
- scenario_config = MLScenarios.regression_benchmark_small()
- scenario = RegressionScenario(scenario_config)
-
- # Run the scenario
- result = await scenario.run_scenario()
-
- print(f"βœ… Regression Scenario: {'SUCCESS' if result['success'] else 'FAILED'}")
- if result['success']:
- metrics = result['metrics']
- print(f" - Ensemble Size: {metrics.get('ensemble', {}).get('ensemble_size', 'N/A')}")
- print(f" - Total Time: {result['execution_time']:.2f}s")
- print(f" - RΒ² Score: {metrics.get('performance', {}).get('accuracy', 'N/A')}")
- print(f" - Performance Targets Met: {result['performance_targets_met']}")
- else:
- print(f" - Error: {result.get('error', 'Unknown error')}")
-
- return result['success']
-
- except Exception as e:
- print(f"❌ Regression test failed: {e}")
- return False
-
-
-async def test_voting_strategies():
- """Test different voting strategies."""
- print("\nπŸ—³οΈ Testing Voting Strategies...")
-
- try:
- from swarm_benchmark.mle_star.voting_strategies import (
- MajorityVoting, WeightedVoting, BayesianAveraging
- )
-
- # Test data
- test_predictions = [
- [0.7, 0.2, 0.1], # Model 1 prediction
- [0.6, 0.3, 0.1], # Model 2 prediction
- [0.8, 0.1, 0.1], # Model 3 prediction
- ]
-
- # Test majority voting
- majority_voter = MajorityVoting()
- majority_result = await majority_voter.vote(test_predictions)
- print(f" - Majority Voting: {majority_result}")
-
- # Test weighted voting
- weighted_voter = WeightedVoting(weights=[0.4, 0.4, 0.2])
- weighted_result = await weighted_voter.vote(test_predictions)
- print(f" - Weighted Voting: {weighted_result}")
-
- # Test Bayesian averaging
- bayesian_voter = BayesianAveraging()
- bayesian_result = await bayesian_voter.vote(test_predictions)
- print(f" - Bayesian Averaging: {bayesian_result}")
-
- print("βœ… Voting strategies test: SUCCESS")
- return True
-
- except Exception as e:
- print(f"❌ Voting strategies test failed: {e}")
- return False
-
-
-async def test_model_coordinator():
- """Test model coordinator functionality."""
- print("\nπŸ€– Testing Model Coordinator...")
-
- try:
- from swarm_benchmark.mle_star.model_coordinator import ModelCoordinator
-
- coordinator = ModelCoordinator(max_parallel=3)
-
- # Spawn a test agent
- agent = await coordinator.spawn_agent(
- agent_id="test_model_1",
- model_type="random_forest",
- capabilities=["classification"],
- hyperparameters={"n_estimators": 10, "task": "classification"}
- )
-
- print(f" - Agent spawned: {agent.agent_id}")
- print(f" - Agent status: {agent.status.value}")
-
- # Clean up
- await coordinator.cleanup()
-
- print("βœ… Model coordinator test: SUCCESS")
- return True
-
- except Exception as e:
- print(f"❌ Model coordinator test failed: {e}")
- return False
-
-
-async def test_performance_tracker():
- """Test performance tracking functionality."""
- print("\nπŸ“ˆ Testing Performance Tracker...")
-
- try:
- from swarm_benchmark.mle_star.performance_tracker import PerformanceTracker
-
- tracker = PerformanceTracker()
-
- # Start tracking session
- await tracker.start_tracking_session("test_session")
-
- # Register a model
- tracker.register_model("test_model", "random_forest")
-
- # Record some metrics
- tracker.record_training_time("test_model", 5.2)
- tracker.record_prediction_time("test_model", 0.1)
- tracker.record_prediction_confidence("test_model", 0.85)
-
- # Get summary
- summary = tracker.get_performance_summary()
- print(f" - Session info: {summary['session_info']}")
- print(f" - Models tracked: {len(summary['model_performances'])}")
-
- # End session
- await tracker.end_tracking_session()
-
- print("βœ… Performance tracker test: SUCCESS")
- return True
-
- except Exception as e:
- print(f"❌ Performance tracker test failed: {e}")
- return False
-
-
-async def run_comprehensive_test_suite():
- """Run comprehensive test suite for MLE-STAR integration."""
- print("πŸš€ Starting MLE-STAR Integration Test Suite")
- print("=" * 60)
-
- # Configure logging
- logging.basicConfig(
- level=logging.WARNING, # Reduce noise during testing
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
- )
-
- test_results = []
-
- # Run individual tests
- test_results.append(await test_voting_strategies())
- test_results.append(await test_model_coordinator())
- test_results.append(await test_performance_tracker())
- test_results.append(await test_classification_scenario())
- test_results.append(await test_regression_scenario())
-
- # Summary
- successful_tests = sum(test_results)
- total_tests = len(test_results)
-
- print("\n" + "=" * 60)
- print(f"🏁 Test Suite Results: {successful_tests}/{total_tests} tests passed")
-
- if successful_tests == total_tests:
- print("πŸŽ‰ All MLE-STAR integration tests PASSED!")
- return True
- else:
- print(f"⚠️ {total_tests - successful_tests} test(s) FAILED")
- return False
-
-
-if __name__ == "__main__":
- # Run the test suite
- success = asyncio.run(run_comprehensive_test_suite())
- sys.exit(0 if success else 1)
\ No newline at end of file
diff --git a/benchmark/test_real_benchmark_engine.py b/benchmark/test_real_benchmark_engine.py
deleted file mode 100644
index 3871fc8c1a..0000000000
--- a/benchmark/test_real_benchmark_engine.py
+++ /dev/null
@@ -1,317 +0,0 @@
-#!/usr/bin/env python3
-"""
-Test runner for the Real Claude-Flow Benchmark Engine
-Validates the real benchmark architecture with actual executions
-"""
-
-import asyncio
-import json
-import sys
-from pathlib import Path
-from datetime import datetime
-
-# Add the benchmark source to Python path
-sys.path.insert(0, str(Path(__file__).parent / "src"))
-
-from swarm_benchmark.core.real_benchmark_engine import RealBenchmarkEngine, SystemMonitor
-from swarm_benchmark.core.models import (
- BenchmarkConfig, StrategyType, CoordinationMode, Task
-)
-
-
-class RealBenchmarkTester:
- """Test harness for real benchmark engine"""
-
- def __init__(self):
- self.results = {}
- self.system_monitor = SystemMonitor()
-
- async def test_basic_execution(self):
- """Test basic claude-flow execution"""
- print("\nπŸ§ͺ Testing Basic Execution")
- print("=" * 60)
-
- config = BenchmarkConfig(
- name="basic-test",
- description="Basic execution test",
- strategy=StrategyType.AUTO,
- mode=CoordinationMode.CENTRALIZED,
- task_timeout=60,
- output_formats=["json"],
- output_directory="./test_output/real_benchmarks"
- )
-
- engine = RealBenchmarkEngine(config)
-
- try:
- # Test simple task
- result = await engine.run_benchmark("Create a hello world function")
-
- print(f"βœ… Basic execution completed")
- print(f" Duration: {result.get('duration', 0):.2f}s")
- print(f" Status: {result.get('status', 'unknown')}")
-
- self.results['basic_execution'] = result
- return True
-
- except Exception as e:
- print(f"❌ Basic execution failed: {e}")
- self.results['basic_execution'] = {"error": str(e)}
- return False
-
- async def test_sparc_modes(self):
- """Test multiple SPARC modes"""
- print("\nπŸ§ͺ Testing SPARC Modes")
- print("=" * 60)
-
- # Test a subset of SPARC modes
- test_modes = ["coder", "researcher", "analyzer", "documenter"]
- mode_results = {}
-
- config = BenchmarkConfig(
- name="sparc-test",
- task_timeout=45,
- output_formats=["json"]
- )
-
- engine = RealBenchmarkEngine(config)
-
- for mode in test_modes:
- print(f"\nπŸ“‹ Testing SPARC mode: {mode}")
-
- try:
- # Create task for SPARC mode
- result = await engine._execute_sparc_mode(
- mode,
- "Create a simple calculator function"
- )
-
- mode_results[mode] = result
- status = "βœ…" if result.get("success", False) else "❌"
- print(f"{status} {mode}: {result.get('duration', 0):.2f}s")
-
- except Exception as e:
- print(f"❌ {mode} failed: {e}")
- mode_results[mode] = {"error": str(e)}
-
- self.results['sparc_modes'] = mode_results
- return len([r for r in mode_results.values() if r.get("success", False)]) > 0
-
- async def test_swarm_strategies(self):
- """Test swarm execution strategies"""
- print("\nπŸ§ͺ Testing Swarm Strategies")
- print("=" * 60)
-
- # Test configurations
- test_configs = [
- (StrategyType.RESEARCH, CoordinationMode.DISTRIBUTED),
- (StrategyType.DEVELOPMENT, CoordinationMode.HIERARCHICAL),
- (StrategyType.ANALYSIS, CoordinationMode.MESH),
- ]
-
- swarm_results = {}
-
- for strategy, mode in test_configs:
- print(f"\nπŸ“‹ Testing {strategy.value} strategy with {mode.value} coordination")
-
- config = BenchmarkConfig(
- name=f"swarm-{strategy.value}-{mode.value}",
- strategy=strategy,
- mode=mode,
- task_timeout=60,
- max_agents=3,
- parallel=True
- )
-
- engine = RealBenchmarkEngine(config)
-
- try:
- task = Task(
- objective="Analyze code quality patterns",
- strategy=strategy,
- mode=mode
- )
-
- result = await engine._execute_real_task(task)
-
- key = f"{strategy.value}_{mode.value}"
- swarm_results[key] = {
- "success": result.status.value == "success",
- "duration": result.performance_metrics.execution_time,
- "resource_usage": {
- "cpu": result.resource_usage.average_cpu_percent,
- "memory": result.resource_usage.peak_memory_mb
- }
- }
-
- status = "βœ…" if swarm_results[key]["success"] else "❌"
- print(f"{status} Duration: {swarm_results[key]['duration']:.2f}s")
-
- except Exception as e:
- print(f"❌ Failed: {e}")
- swarm_results[f"{strategy.value}_{mode.value}"] = {"error": str(e)}
-
- self.results['swarm_strategies'] = swarm_results
- return len([r for r in swarm_results.values() if r.get("success", False)]) > 0
-
- async def test_parallel_execution(self):
- """Test parallel task execution"""
- print("\nπŸ§ͺ Testing Parallel Execution")
- print("=" * 60)
-
- config = BenchmarkConfig(
- name="parallel-test",
- parallel=True,
- max_agents=3,
- task_timeout=30
- )
-
- engine = RealBenchmarkEngine(config)
-
- # Create multiple tasks
- tasks = [
- Task(objective="Create a function to add numbers", strategy=StrategyType.AUTO),
- Task(objective="Create a function to multiply numbers", strategy=StrategyType.AUTO),
- Task(objective="Create a function to divide numbers", strategy=StrategyType.AUTO),
- ]
-
- try:
- print(f"πŸ“‹ Executing {len(tasks)} tasks in parallel...")
- start_time = asyncio.get_event_loop().time()
-
- results = await engine.execute_batch(tasks)
-
- end_time = asyncio.get_event_loop().time()
- total_duration = end_time - start_time
-
- successful = sum(1 for r in results if r.status.value == "success")
-
- print(f"βœ… Parallel execution completed")
- print(f" Total duration: {total_duration:.2f}s")
- print(f" Successful tasks: {successful}/{len(tasks)}")
-
- self.results['parallel_execution'] = {
- "total_duration": total_duration,
- "tasks_count": len(tasks),
- "successful_count": successful,
- "average_duration": total_duration / len(tasks) if tasks else 0
- }
-
- return successful > 0
-
- except Exception as e:
- print(f"❌ Parallel execution failed: {e}")
- self.results['parallel_execution'] = {"error": str(e)}
- return False
-
- async def test_resource_monitoring(self):
- """Test resource monitoring capabilities"""
- print("\nπŸ§ͺ Testing Resource Monitoring")
- print("=" * 60)
-
- config = BenchmarkConfig(
- name="resource-test",
- monitoring=True,
- task_timeout=30
- )
-
- engine = RealBenchmarkEngine(config)
-
- try:
- # Take baseline measurement
- self.system_monitor.take_measurement()
-
- # Execute a task
- result = await engine.run_benchmark("Create a sorting algorithm")
-
- # Take final measurement
- self.system_monitor.take_measurement()
-
- # Get system summary
- system_summary = self.system_monitor.get_summary()
-
- print(f"βœ… Resource monitoring completed")
- print(f" CPU Usage: {system_summary.get('avg_cpu', 0):.1f}% (avg), {system_summary.get('max_cpu', 0):.1f}% (max)")
- print(f" Memory Usage: {system_summary.get('avg_memory', 0):.1f}% (avg), {system_summary.get('max_memory', 0):.1f}% (max)")
-
- # Extract resource data from results
- if result.get('results') and len(result['results']) > 0:
- first_result = result['results'][0]
- resource_usage = first_result.get('resource_usage', {})
-
- print(f" Process CPU: {resource_usage.get('average_cpu_percent', 0):.1f}%")
- print(f" Process Memory: {resource_usage.get('peak_memory_mb', 0):.1f} MB")
-
- self.results['resource_monitoring'] = {
- "system_summary": system_summary,
- "monitoring_enabled": True
- }
-
- return True
-
- except Exception as e:
- print(f"❌ Resource monitoring failed: {e}")
- self.results['resource_monitoring'] = {"error": str(e)}
- return False
-
- async def run_all_tests(self):
- """Run all benchmark tests"""
- print("πŸš€ Starting Real Benchmark Engine Tests")
- print("=" * 60)
-
- test_results = []
-
- # Run tests
- test_results.append(await self.test_basic_execution())
- test_results.append(await self.test_sparc_modes())
- test_results.append(await self.test_swarm_strategies())
- test_results.append(await self.test_parallel_execution())
- test_results.append(await self.test_resource_monitoring())
-
- # Generate summary
- successful_tests = sum(test_results)
- total_tests = len(test_results)
-
- print("\n" + "=" * 60)
- print("πŸ“Š TEST SUMMARY")
- print("=" * 60)
- print(f"βœ… Successful Tests: {successful_tests}/{total_tests}")
- print(f"❌ Failed Tests: {total_tests - successful_tests}/{total_tests}")
-
- # Save results
- output_file = Path("test_output/real_benchmark_test_results.json")
- output_file.parent.mkdir(exist_ok=True)
-
- with open(output_file, "w") as f:
- json.dump({
- "timestamp": datetime.now().isoformat(),
- "summary": {
- "total_tests": total_tests,
- "successful_tests": successful_tests,
- "failed_tests": total_tests - successful_tests
- },
- "test_results": self.results
- }, f, indent=2)
-
- print(f"\nπŸ’Ύ Results saved to: {output_file}")
-
- return successful_tests == total_tests
-
-
-async def main():
- """Main test runner"""
- tester = RealBenchmarkTester()
- success = await tester.run_all_tests()
-
- # Exit with appropriate code
- sys.exit(0 if success else 1)
-
-
-if __name__ == "__main__":
- # Check Python version
- if sys.version_info < (3, 7):
- print("❌ Python 3.7+ required")
- sys.exit(1)
-
- # Run tests
- asyncio.run(main())
\ No newline at end of file
diff --git a/benchmark/test_real_benchmarks.py b/benchmark/test_real_benchmarks.py
old mode 100644
new mode 100755
diff --git a/benchmark/test_real_claude_flow.py b/benchmark/test_real_claude_flow.py
deleted file mode 100644
index 5d6e903616..0000000000
--- a/benchmark/test_real_claude_flow.py
+++ /dev/null
@@ -1,218 +0,0 @@
-#!/usr/bin/env python3
-"""
-Real Claude-Flow Benchmark Test
-Tests actual claude-flow execution with --non-interactive flag
-"""
-
-import subprocess
-import time
-import json
-import os
-from pathlib import Path
-import sys
-
-# Add parent directory to path to access claude-flow
-sys.path.insert(0, str(Path(__file__).parent.parent))
-
-class RealClaudeFlowBenchmark:
- def __init__(self):
- self.claude_flow_path = Path(__file__).parent.parent / "claude-flow"
- self.results = []
-
- def run_command(self, command, description):
- """Execute a claude-flow command and measure performance"""
- print(f"\n{'='*60}")
- print(f"Running: {description}")
- print(f"Command: {' '.join(command)}")
- print(f"{'='*60}")
-
- start_time = time.time()
-
- try:
- # Run the command
- result = subprocess.run(
- command,
- capture_output=True,
- text=True,
- timeout=30 # 30 second timeout
- )
-
- end_time = time.time()
- duration = end_time - start_time
-
- # Prepare result
- benchmark_result = {
- "description": description,
- "command": " ".join(command),
- "duration": duration,
- "success": result.returncode == 0,
- "stdout": result.stdout,
- "stderr": result.stderr,
- "return_code": result.returncode
- }
-
- self.results.append(benchmark_result)
-
- # Print summary
- status = "βœ… SUCCESS" if result.returncode == 0 else "❌ FAILED"
- print(f"{status} - Duration: {duration:.2f}s")
-
- if result.stdout:
- print(f"\nOutput:\n{result.stdout[:500]}...")
- if result.stderr:
- print(f"\nErrors:\n{result.stderr[:500]}...")
-
- return benchmark_result
-
- except subprocess.TimeoutExpired:
- print("❌ TIMEOUT - Command took too long")
- return {
- "description": description,
- "command": " ".join(command),
- "duration": 30,
- "success": False,
- "error": "Timeout after 30 seconds"
- }
- except Exception as e:
- print(f"❌ ERROR - {str(e)}")
- return {
- "description": description,
- "command": " ".join(command),
- "duration": 0,
- "success": False,
- "error": str(e)
- }
-
- def test_basic_commands(self):
- """Test basic claude-flow commands"""
- print("\nπŸ§ͺ Testing Basic Claude-Flow Commands")
-
- # Test 1: Version check
- self.run_command(
- [str(self.claude_flow_path), "--version"],
- "Version Check"
- )
-
- # Test 2: Help command
- self.run_command(
- [str(self.claude_flow_path), "--help"],
- "Help Command"
- )
-
- # Test 3: Status command
- self.run_command(
- [str(self.claude_flow_path), "status", "--non-interactive"],
- "Status Command (Non-Interactive)"
- )
-
- def test_sparc_commands(self):
- """Test SPARC mode commands"""
- print("\nπŸ§ͺ Testing SPARC Mode Commands")
-
- # Test 1: SPARC list
- self.run_command(
- [str(self.claude_flow_path), "sparc", "list", "--non-interactive"],
- "SPARC List Modes"
- )
-
- # Test 2: SPARC coder mode
- self.run_command(
- [str(self.claude_flow_path), "sparc", "coder",
- "Create a simple hello world function", "--non-interactive"],
- "SPARC Coder Mode"
- )
-
- # Test 3: SPARC researcher mode
- self.run_command(
- [str(self.claude_flow_path), "sparc", "researcher",
- "Research best practices for Python testing", "--non-interactive"],
- "SPARC Researcher Mode"
- )
-
- def test_swarm_commands(self):
- """Test Swarm commands"""
- print("\nπŸ§ͺ Testing Swarm Commands")
-
- # Test 1: Simple swarm with auto strategy
- self.run_command(
- [str(self.claude_flow_path), "swarm",
- "Create a basic calculator",
- "--strategy", "auto",
- "--non-interactive"],
- "Swarm Auto Strategy"
- )
-
- # Test 2: Research swarm
- self.run_command(
- [str(self.claude_flow_path), "swarm",
- "Research cloud computing trends",
- "--strategy", "research",
- "--mode", "distributed",
- "--non-interactive"],
- "Swarm Research Strategy (Distributed)"
- )
-
- # Test 3: Development swarm
- self.run_command(
- [str(self.claude_flow_path), "swarm",
- "Build a REST API endpoint",
- "--strategy", "development",
- "--mode", "hierarchical",
- "--non-interactive"],
- "Swarm Development Strategy (Hierarchical)"
- )
-
- def generate_report(self):
- """Generate benchmark report"""
- print("\n" + "="*60)
- print("πŸ“Š BENCHMARK SUMMARY REPORT")
- print("="*60)
-
- total_tests = len(self.results)
- successful_tests = sum(1 for r in self.results if r.get("success", False))
- failed_tests = total_tests - successful_tests
-
- print(f"\nβœ… Successful Tests: {successful_tests}/{total_tests}")
- print(f"❌ Failed Tests: {failed_tests}/{total_tests}")
-
- if self.results:
- avg_duration = sum(r.get("duration", 0) for r in self.results) / len(self.results)
- print(f"⏱️ Average Duration: {avg_duration:.2f}s")
-
- print("\nπŸ“‹ Test Results:")
- for result in self.results:
- status = "βœ…" if result.get("success", False) else "❌"
- duration = result.get("duration", 0)
- print(f" {status} {result['description']}: {duration:.2f}s")
-
- # Save results to JSON
- output_file = Path(__file__).parent / "real_benchmark_results.json"
- with open(output_file, "w") as f:
- json.dump({
- "timestamp": time.time(),
- "summary": {
- "total_tests": total_tests,
- "successful_tests": successful_tests,
- "failed_tests": failed_tests,
- "average_duration": avg_duration if self.results else 0
- },
- "results": self.results
- }, f, indent=2)
-
- print(f"\nπŸ’Ύ Results saved to: {output_file}")
-
- def run_all_tests(self):
- """Run all benchmark tests"""
- print("πŸš€ Starting Real Claude-Flow Benchmark Tests")
- print(f"Using: {self.claude_flow_path}")
-
- self.test_basic_commands()
- self.test_sparc_commands()
- self.test_swarm_commands()
-
- self.generate_report()
-
-
-if __name__ == "__main__":
- benchmark = RealClaudeFlowBenchmark()
- benchmark.run_all_tests()
\ No newline at end of file
diff --git a/benchmark/test_real_metrics.py b/benchmark/test_real_metrics.py
deleted file mode 100644
index 329d479b74..0000000000
--- a/benchmark/test_real_metrics.py
+++ /dev/null
@@ -1,128 +0,0 @@
-#!/usr/bin/env python3
-"""Test script for real metrics collection."""
-
-import asyncio
-import sys
-from pathlib import Path
-
-# Add the src directory to the path
-sys.path.insert(0, str(Path(__file__).parent / "src"))
-
-from swarm_benchmark.core.models import BenchmarkConfig, StrategyType, CoordinationMode
-from swarm_benchmark.core.real_benchmark_engine import RealBenchmarkEngine
-from swarm_benchmark.metrics.process_tracker import ProcessTracker
-
-
-async def test_basic_metrics():
- """Test basic metrics collection."""
- print("Testing basic metrics collection...")
-
- # Create configuration
- config = BenchmarkConfig(
- name="test-metrics",
- description="Test real metrics collection",
- strategy=StrategyType.AUTO,
- mode=CoordinationMode.CENTRALIZED,
- task_timeout=30,
- output_directory="./test_reports"
- )
-
- # Create engine
- engine = RealBenchmarkEngine(config)
-
- # Run a simple benchmark
- result = await engine.run_benchmark("Show claude-flow status")
-
- print("\nBenchmark Results:")
- print(f"Status: {result['status']}")
- print(f"Duration: {result.get('duration', 0):.2f}s")
-
- if 'metrics' in result:
- print("\nPerformance Metrics:")
- metrics = result['metrics']
- print(f" Wall clock time: {metrics.get('wall_clock_time', 0):.2f}s")
- print(f" Tasks per second: {metrics.get('tasks_per_second', 0):.2f}")
- print(f" Success rate: {metrics.get('success_rate', 0):.1%}")
- print(f" Peak memory: {metrics.get('peak_memory_mb', 0):.1f} MB")
- print(f" Average CPU: {metrics.get('average_cpu_percent', 0):.1f}%")
- print(f" Total output: {metrics.get('total_output_lines', 0)} lines")
-
-
-async def test_process_tracker():
- """Test process tracker directly."""
- print("\nTesting process tracker...")
-
- tracker = ProcessTracker()
-
- # Test a simple command
- result = await tracker.execute_command_async(
- ["status"],
- timeout=10
- )
-
- print(f"\nCommand: {' '.join(result.command)}")
- print(f"Exit code: {result.exit_code}")
- print(f"Success: {result.success}")
- print(f"Duration: {result.duration:.2f}s")
- print(f"Peak memory: {result.resource_usage.peak_memory_mb:.1f} MB")
- print(f"Average CPU: {result.resource_usage.average_cpu_percent:.1f}%")
- print(f"Output lines: {result.output_size}")
-
- # Get command statistics
- stats = tracker.get_command_statistics()
- print("\nCommand Statistics:")
- for key, stat in stats.items():
- print(f" {stat['command_type']}: {stat['execution_count']} executions, "
- f"{stat['success_rate']:.1%} success rate, "
- f"{stat['average_duration']:.2f}s avg duration")
-
-
-async def test_multiple_commands():
- """Test multiple command execution."""
- print("\nTesting multiple commands...")
-
- config = BenchmarkConfig(
- name="test-multiple",
- description="Test multiple commands",
- strategy=StrategyType.AUTO,
- mode=CoordinationMode.CENTRALIZED,
- parallel=True,
- max_agents=3,
- output_directory="./test_reports"
- )
-
- engine = RealBenchmarkEngine(config)
-
- # Test different objectives
- objectives = [
- "Show current configuration",
- "List available SPARC modes",
- "Check system status"
- ]
-
- for obj in objectives:
- print(f"\nRunning: {obj}")
- result = await engine.run_benchmark(obj)
-
- if result['status'] == 'success' and 'metrics' in result:
- metrics = result['metrics']
- print(f" βœ“ Completed in {metrics.get('wall_clock_time', 0):.2f}s")
- print(f" βœ“ Memory usage: {metrics.get('peak_memory_mb', 0):.1f} MB")
-
-
-def main():
- """Main test function."""
- print("Claude-Flow Real Metrics Collection Test")
- print("=" * 50)
-
- # Run tests
- asyncio.run(test_basic_metrics())
- asyncio.run(test_process_tracker())
- asyncio.run(test_multiple_commands())
-
- print("\n" + "=" * 50)
- print("All tests completed!")
-
-
-if __name__ == "__main__":
- main()
\ No newline at end of file
diff --git a/benchmark/test_real_simple.py b/benchmark/test_real_simple.py
deleted file mode 100644
index 738c5fadb7..0000000000
--- a/benchmark/test_real_simple.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#!/usr/bin/env python3
-"""
-Simple test of real claude-flow benchmark execution
-"""
-
-import subprocess
-import time
-import json
-from pathlib import Path
-
-def test_real_claude_flow():
- """Test actual claude-flow command execution"""
- claude_flow_path = Path(__file__).parent.parent / "claude-flow"
-
- print("🧠 Testing Real Claude-Flow Benchmark System")
- print("=" * 60)
-
- # Test 1: Version check
- print("\n1️⃣ Testing basic command:")
- start = time.time()
- result = subprocess.run(
- [str(claude_flow_path), "--version"],
- capture_output=True,
- text=True
- )
- duration = time.time() - start
-
- print(f" Command: claude-flow --version")
- print(f" Success: {result.returncode == 0}")
- print(f" Output: {result.stdout.strip()}")
- print(f" Duration: {duration:.3f}s")
-
- # Test 2: SPARC list
- print("\n2️⃣ Testing SPARC list command:")
- start = time.time()
- result = subprocess.run(
- [str(claude_flow_path), "sparc", "list"],
- capture_output=True,
- text=True
- )
- duration = time.time() - start
-
- print(f" Command: claude-flow sparc list")
- print(f" Success: {result.returncode == 0}")
- print(f" Duration: {duration:.3f}s")
- if result.returncode == 0:
- # Count modes in output
- modes = [line for line in result.stdout.split('\n') if line.strip() and not line.startswith(' ')]
- print(f" SPARC Modes Found: {len([m for m in modes if m])}")
-
- # Test 3: Simple SPARC execution with dry-run
- print("\n3️⃣ Testing SPARC execution (dry-run):")
- start = time.time()
- result = subprocess.run(
- [str(claude_flow_path), "sparc", "coder", "Write hello world", "--dry-run"],
- capture_output=True,
- text=True
- )
- duration = time.time() - start
-
- print(f" Command: claude-flow sparc coder 'Write hello world' --dry-run")
- print(f" Success: {result.returncode == 0}")
- print(f" Duration: {duration:.3f}s")
-
- # Test 4: Swarm execution with dry-run
- print("\n4️⃣ Testing Swarm execution (dry-run):")
- start = time.time()
- result = subprocess.run(
- [str(claude_flow_path), "swarm", "Build a calculator",
- "--strategy", "development", "--mode", "centralized", "--dry-run"],
- capture_output=True,
- text=True
- )
- duration = time.time() - start
-
- print(f" Command: claude-flow swarm 'Build a calculator' --strategy development --mode centralized --dry-run")
- print(f" Success: {result.returncode == 0}")
- print(f" Duration: {duration:.3f}s")
-
- # Save results
- results = {
- "test_time": time.time(),
- "tests": [
- {"name": "version", "success": True, "duration": duration},
- {"name": "sparc_list", "success": True, "duration": duration},
- {"name": "sparc_coder", "success": result.returncode == 0, "duration": duration},
- {"name": "swarm", "success": result.returncode == 0, "duration": duration}
- ]
- }
-
- output_file = Path(__file__).parent / "simple_test_results.json"
- with open(output_file, 'w') as f:
- json.dump(results, f, indent=2)
-
- print(f"\nβœ… Test completed! Results saved to: {output_file}")
- print("\nπŸ“Š Summary:")
- print(" β€’ Claude-flow commands are executable")
- print(" β€’ Basic benchmarking infrastructure works")
- print(" β€’ Real command execution with timing")
- print(" β€’ Ready for full benchmark implementation")
-
-
-if __name__ == "__main__":
- test_real_claude_flow()
\ No newline at end of file
diff --git a/benchmark/test_simple_run.py b/benchmark/test_simple_run.py
deleted file mode 100644
index 4b9647c443..0000000000
--- a/benchmark/test_simple_run.py
+++ /dev/null
@@ -1,35 +0,0 @@
-"""Simple test to check if the benchmark engine works."""
-
-import asyncio
-import sys
-from pathlib import Path
-
-# Add the src directory to Python path
-sys.path.insert(0, str(Path(__file__).parent / "src"))
-from swarm_benchmark.core.benchmark_engine import BenchmarkEngine
-from swarm_benchmark.core.models import BenchmarkConfig, StrategyType
-
-async def test_simple_benchmark():
- """Test a simple benchmark run."""
- config = BenchmarkConfig(
- name="Simple Test",
- strategy=StrategyType.AUTO,
- output_formats=["json"],
- output_directory="./test_output"
- )
-
- engine = BenchmarkEngine(config)
-
- try:
- result = await engine.run_benchmark("Build a simple REST API")
- print("Benchmark result:", result)
- return result
- except Exception as e:
- print(f"Error: {e}")
- import traceback
- traceback.print_exc()
- return None
-
-if __name__ == "__main__":
- result = asyncio.run(test_simple_benchmark())
- print("Final result:", result)
\ No newline at end of file
diff --git a/benchmark/testing_automation_claude.md b/benchmark/testing_automation_claude.md
deleted file mode 100644
index 62cb7e54f4..0000000000
--- a/benchmark/testing_automation_claude.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# CLAUDE.md - Optimized for Testing Automation
-
-<!-- Generated by CLAUDE.md Optimizer at 2025-08-06 01:57 -->
-
-## 🎯 Configuration Overview
-- **Use Case**: Testing Automation
-- **Optimization Target**: balanced
-- **Team Size**: N/A
-- **Complexity**: medium
-
-## ⚑ Performance Configuration
-- **Execution Mode**: Standard
-- **Agent Count**: 6 (tester, performance-benchmarker, reviewer)
-- **Topology**: Mesh
-- **Batch Operations**: RECOMMENDED
-- **Parallel Execution**: STANDARD
-
-## 🎯 Primary Objectives
-1. Test automation
-2. Quality assurance
-3. Coverage analysis
-
-## πŸš€ Execution Rules
-
-### CRITICAL: Concurrency Requirements
-```javascript
-// ALWAYS execute in single message:
-[
- Task("Tester", "...", "tester"),
- Task("Performance Benchmarker", "...", "performance-benchmarker"),
- Task("Reviewer", "...", "reviewer"),
- TodoWrite({ todos: [ALL_TASKS] }),
- // ... all related operations
-]```
-
-### Critical Rules
-- Achieve high test coverage
-- Implement parallel test execution
-- Use property-based testing
-- Monitor test performance
-- ALWAYS batch test runs
-- Parallel coverage analysis
-- Always run tests after changes
-- Use type checking and linting
-- Implement comprehensive error handling
-- Request code review from reviewer agent
-- Validate all inputs and outputs
-- Use static analysis tools
-- Implement integration testing
-- Add comprehensive logging
-- Verify requirements before implementation
-- Use defensive programming practices
-
-### Tool Priority Order
-1. MultiEdit β†’ Edit β†’ Bash β†’ Read
-
-### Testing Automation Workflow
-**Test Planning**: Comprehensive test strategy
-**Implementation**: Parallel test creation
-**Execution**: Distributed test execution
-**Reporting**: Automated test reporting
-**Maintenance**: Continuous test optimization
-
-## πŸ€– Agent Configuration
-- **Swarm Topology**: Mesh
-- **Maximum Agents**: 6
-- **Preferred Agent Types**: tester, performance-benchmarker, reviewer
-
-## πŸ“Š Success Metrics
-- Test Coverage: >95%
-- Test Execution Time: <5 min
-- Test Success Rate: >99%
-- Maintenance Overhead: <10%
\ No newline at end of file
diff --git a/benchmark/tests/__pycache__/conftest.cpython-312-pytest-8.4.0.pyc b/benchmark/tests/__pycache__/conftest.cpython-312-pytest-8.4.0.pyc
index 3be6cc0fba..a114de4b70 100644
Binary files a/benchmark/tests/__pycache__/conftest.cpython-312-pytest-8.4.0.pyc and b/benchmark/tests/__pycache__/conftest.cpython-312-pytest-8.4.0.pyc differ
diff --git a/benchmark/tests/integration/__pycache__/test_real_claude_flow_integration.cpython-312-pytest-8.4.0.pyc b/benchmark/tests/integration/__pycache__/test_real_claude_flow_integration.cpython-312-pytest-8.4.0.pyc
index 6ced3e86de..d83ea2376a 100644
Binary files a/benchmark/tests/integration/__pycache__/test_real_claude_flow_integration.cpython-312-pytest-8.4.0.pyc and b/benchmark/tests/integration/__pycache__/test_real_claude_flow_integration.cpython-312-pytest-8.4.0.pyc differ
diff --git a/benchmark/tests/integration/quick_test_integration.py b/benchmark/tests/integration/quick_test_integration.py
index 4d90e3435c..3cc80fe821 100644
--- a/benchmark/tests/integration/quick_test_integration.py
+++ b/benchmark/tests/integration/quick_test_integration.py
@@ -5,7 +5,7 @@ import sys
from pathlib import Path
# Add benchmark src to path
-sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
+sys.path.insert(0, str(Path(__file__).parent / "src"))
from swarm_benchmark.core.claude_flow_executor import ClaudeFlowExecutor
diff --git a/benchmark/tests/integration/test_claude_optimizer.py b/benchmark/tests/integration/test_claude_optimizer.py
index 73c7808b6d..a4526133fd 100644
--- a/benchmark/tests/integration/test_claude_optimizer.py
+++ b/benchmark/tests/integration/test_claude_optimizer.py
@@ -9,7 +9,7 @@ import asyncio
from pathlib import Path
# Add benchmark source to path
-sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
+sys.path.insert(0, str(Path(__file__).parent / "src"))
from swarm_benchmark.claude_optimizer import (
ClaudeMdOptimizer,
diff --git a/benchmark/tests/integration/test_integration.py b/benchmark/tests/integration/test_integration.py
index 4608ca47b8..5faa0f6d6f 100755
--- a/benchmark/tests/integration/test_integration.py
+++ b/benchmark/tests/integration/test_integration.py
@@ -12,7 +12,7 @@ import logging
from pathlib import Path
# Add benchmark src to path
-sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
+sys.path.insert(0, str(Path(__file__).parent / "src"))
from swarm_benchmark.core.claude_flow_executor import (
ClaudeFlowExecutor, SwarmConfig, SparcConfig,
diff --git a/benchmark/tests/integration/test_mle_star_integration.py b/benchmark/tests/integration/test_mle_star_integration.py
index b1f7cc6b75..88eccf1be1 100644
--- a/benchmark/tests/integration/test_mle_star_integration.py
+++ b/benchmark/tests/integration/test_mle_star_integration.py
@@ -9,10 +9,10 @@ including ensemble execution, voting strategies, and performance tracking.
import asyncio
import logging
import sys
-import os\nfrom pathlib import Path
+import os
# Add the src directory to Python path
-sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from swarm_benchmark.mle_star import (
MLEStarEnsembleExecutor, MLEStarConfig,
diff --git a/benchmark/tests/integration/test_real_benchmark_engine.py b/benchmark/tests/integration/test_real_benchmark_engine.py
index 9651057bff..3871fc8c1a 100644
--- a/benchmark/tests/integration/test_real_benchmark_engine.py
+++ b/benchmark/tests/integration/test_real_benchmark_engine.py
@@ -11,9 +11,9 @@ from pathlib import Path
from datetime import datetime
# Add the benchmark source to Python path
-sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
+sys.path.insert(0, str(Path(__file__).parent / "src"))
-from swarm_benchmark.core.real_benchmark_engine import RealBenchmarkEngine
+from swarm_benchmark.core.real_benchmark_engine import RealBenchmarkEngine, SystemMonitor
from swarm_benchmark.core.models import (
BenchmarkConfig, StrategyType, CoordinationMode, Task
)
diff --git a/benchmark/tests/integration/test_real_claude_flow.py b/benchmark/tests/integration/test_real_claude_flow.py
index 45892e04a0..5d6e903616 100644
--- a/benchmark/tests/integration/test_real_claude_flow.py
+++ b/benchmark/tests/integration/test_real_claude_flow.py
@@ -12,7 +12,7 @@ from pathlib import Path
import sys
# Add parent directory to path to access claude-flow
-sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
+sys.path.insert(0, str(Path(__file__).parent.parent))
class RealClaudeFlowBenchmark:
def __init__(self):
diff --git a/benchmark/tests/integration/test_real_metrics.py b/benchmark/tests/integration/test_real_metrics.py
index d5b136e04e..329d479b74 100644
--- a/benchmark/tests/integration/test_real_metrics.py
+++ b/benchmark/tests/integration/test_real_metrics.py
@@ -6,7 +6,7 @@ import sys
from pathlib import Path
# Add the src directory to the path
-sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
+sys.path.insert(0, str(Path(__file__).parent / "src"))
from swarm_benchmark.core.models import BenchmarkConfig, StrategyType, CoordinationMode
from swarm_benchmark.core.real_benchmark_engine import RealBenchmarkEngine
diff --git a/benchmark/tests/integration/test_simple_run.py b/benchmark/tests/integration/test_simple_run.py
index e29692a893..4b9647c443 100644
--- a/benchmark/tests/integration/test_simple_run.py
+++ b/benchmark/tests/integration/test_simple_run.py
@@ -5,7 +5,7 @@ import sys
from pathlib import Path
# Add the src directory to Python path
-sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
+sys.path.insert(0, str(Path(__file__).parent / "src"))
from swarm_benchmark.core.benchmark_engine import BenchmarkEngine
from swarm_benchmark.core.models import BenchmarkConfig, StrategyType