🏁 Session end checkpoint: session-20250806-025626

This commit is contained in:
rUv committed 2025-08-06 02:56:26 +00:00
1 parent 93562696b8
commit 9e2ce8f907
36 files changed
+974 -5004

No files matched your search

+528
View File
@@ -2290,5 +2290,533 @@
"cpuLoad": 0.105,
"platform": "linux",
"uptime": 15727.51
},
{
"timestamp": 1754447688923,
"memoryTotal": 67427545088,
"memoryUsed": 8111726592,
"memoryFree": 59315818496,
"memoryUsagePercent": 12.0302861114302,
"memoryEfficiency": 87.9697138885698,
"cpuCount": 16,
"cpuLoad": 0.090625,
"platform": "linux",
"uptime": 15757.54
},
{
"timestamp": 1754447718952,
"memoryTotal": 67427545088,
"memoryUsed": 8240361472,
"memoryFree": 59187183616,
"memoryUsagePercent": 12.221061083041754,
"memoryEfficiency": 87.77893891695825,
"cpuCount": 16,
"cpuLoad": 0.079375,
"platform": "linux",
"uptime": 15787.57
},
{
"timestamp": 1754447748983,
"memoryTotal": 67427545088,
"memoryUsed": 8079192064,
"memoryFree": 59348353024,
"memoryUsagePercent": 11.982035017670906,
"memoryEfficiency": 88.01796498232909,
"cpuCount": 16,
"cpuLoad": 0.100625,
"platform": "linux",
"uptime": 15817.6
},
{
"timestamp": 1754447779002,
"memoryTotal": 67427545088,
"memoryUsed": 8047865856,
"memoryFree": 59379679232,
"memoryUsagePercent": 11.935575951188335,
"memoryEfficiency": 88.06442404881166,
"cpuCount": 16,
"cpuLoad": 0.08125,
"platform": "linux",
"uptime": 15847.62
},
{
"timestamp": 1754447809033,
"memoryTotal": 67427545088,
"memoryUsed": 8120320000,
"memoryFree": 59307225088,
"memoryUsagePercent": 12.043030766435487,
"memoryEfficiency": 87.95696923356451,
"cpuCount": 16,
"cpuLoad": 0.063125,
"platform": "linux",
"uptime": 15877.65
},
{
"timestamp": 1754447839063,
"memoryTotal": 67427545088,
"memoryUsed": 8141041664,
"memoryFree": 59286503424,
"memoryUsagePercent": 12.073762515564061,
"memoryEfficiency": 87.92623748443594,
"cpuCount": 16,
"cpuLoad": 0.065,
"platform": "linux",
"uptime": 15907.68
},
{
"timestamp": 1754447869078,
"memoryTotal": 67427545088,
"memoryUsed": 8212307968,
"memoryFree": 59215237120,
"memoryUsagePercent": 12.179455676878165,
"memoryEfficiency": 87.82054432312184,
"cpuCount": 16,
"cpuLoad": 0.07625,
"platform": "linux",
"uptime": 15937.7
},
{
"timestamp": 1754447899096,
"memoryTotal": 67427545088,
"memoryUsed": 8217600000,
"memoryFree": 59209945088,
"memoryUsagePercent": 12.187304148883326,
"memoryEfficiency": 87.81269585111667,
"cpuCount": 16,
"cpuLoad": 0.0825,
"platform": "linux",
"uptime": 15967.71
},
{
"timestamp": 1754447929126,
"memoryTotal": 67427545088,
"memoryUsed": 8199114752,
"memoryFree": 59228430336,
"memoryUsagePercent": 12.15988916888387,
"memoryEfficiency": 87.84011083111614,
"cpuCount": 16,
"cpuLoad": 0.073125,
"platform": "linux",
"uptime": 15997.74
},
{
"timestamp": 1754447959147,
"memoryTotal": 67427545088,
"memoryUsed": 8260804608,
"memoryFree": 59166740480,
"memoryUsagePercent": 12.251379754696371,
"memoryEfficiency": 87.74862024530363,
"cpuCount": 16,
"cpuLoad": 0.07875,
"platform": "linux",
"uptime": 16027.77
},
{
"timestamp": 1754447989177,
"memoryTotal": 67427545088,
"memoryUsed": 8351875072,
"memoryFree": 59075670016,
"memoryUsagePercent": 12.386443939342488,
"memoryEfficiency": 87.61355606065752,
"cpuCount": 16,
"cpuLoad": 0.075625,
"platform": "linux",
"uptime": 16057.79
},
{
"timestamp": 1754448019183,
"memoryTotal": 67427545088,
"memoryUsed": 8308998144,
"memoryFree": 59118546944,
"memoryUsagePercent": 12.322854307028216,
"memoryEfficiency": 87.67714569297178,
"cpuCount": 16,
"cpuLoad": 0.094375,
"platform": "linux",
"uptime": 16087.8
},
{
"timestamp": 1754448049214,
"memoryTotal": 67427545088,
"memoryUsed": 8320286720,
"memoryFree": 59107258368,
"memoryUsagePercent": 12.3395960940609,
"memoryEfficiency": 87.6604039059391,
"cpuCount": 16,
"cpuLoad": 0.116875,
"platform": "linux",
"uptime": 16117.83
},
{
"timestamp": 1754448079243,
"memoryTotal": 67427545088,
"memoryUsed": 8312918016,
"memoryFree": 59114627072,
"memoryUsagePercent": 12.328667765007271,
"memoryEfficiency": 87.67133223499273,
"cpuCount": 16,
"cpuLoad": 0.13125,
"platform": "linux",
"uptime": 16147.86
},
{
"timestamp": 1754448109274,
"memoryTotal": 67427545088,
"memoryUsed": 8410963968,
"memoryFree": 59016581120,
"memoryUsagePercent": 12.47407711050849,
"memoryEfficiency": 87.52592288949151,
"cpuCount": 16,
"cpuLoad": 0.118125,
"platform": "linux",
"uptime": 16177.89
},
{
"timestamp": 1754448139304,
"memoryTotal": 67427545088,
"memoryUsed": 8191557632,
"memoryFree": 59235987456,
"memoryUsagePercent": 12.148681405068448,
"memoryEfficiency": 87.85131859493156,
"cpuCount": 16,
"cpuLoad": 0.113125,
"platform": "linux",
"uptime": 16207.92
},
{
"timestamp": 1754448169334,
"memoryTotal": 67427545088,
"memoryUsed": 8187174912,
"memoryFree": 59240370176,
"memoryUsagePercent": 12.142181509522377,
"memoryEfficiency": 87.85781849047763,
"cpuCount": 16,
"cpuLoad": 0.10375,
"platform": "linux",
"uptime": 16237.95
},
{
"timestamp": 1754448199344,
"memoryTotal": 67427545088,
"memoryUsed": 8347738112,
"memoryFree": 59079806976,
"memoryUsagePercent": 12.380308523920498,
"memoryEfficiency": 87.61969147607951,
"cpuCount": 16,
"cpuLoad": 0.094375,
"platform": "linux",
"uptime": 16267.96
},
{
"timestamp": 1754448229364,
"memoryTotal": 67427545088,
"memoryUsed": 8164290560,
"memoryFree": 59263254528,
"memoryUsagePercent": 12.108242335301911,
"memoryEfficiency": 87.89175766469809,
"cpuCount": 16,
"cpuLoad": 0.065,
"platform": "linux",
"uptime": 16297.98
},
{
"timestamp": 1754448259393,
"memoryTotal": 67427545088,
"memoryUsed": 8220176384,
"memoryFree": 59207368704,
"memoryUsagePercent": 12.19112511551742,
"memoryEfficiency": 87.80887488448258,
"cpuCount": 16,
"cpuLoad": 0.054375,
"platform": "linux",
"uptime": 16328.01
},
{
"timestamp": 1754448289418,
"memoryTotal": 67427545088,
"memoryUsed": 8266174464,
"memoryFree": 59161370624,
"memoryUsagePercent": 12.259343645407492,
"memoryEfficiency": 87.7406563545925,
"cpuCount": 16,
"cpuLoad": 0.03625,
"platform": "linux",
"uptime": 16358.04
},
{
"timestamp": 1754448319448,
"memoryTotal": 67427545088,
"memoryUsed": 8295034880,
"memoryFree": 59132510208,
"memoryUsagePercent": 12.302145761311808,
"memoryEfficiency": 87.6978542386882,
"cpuCount": 16,
"cpuLoad": 0.025625,
"platform": "linux",
"uptime": 16388.07
},
{
"timestamp": 1754448349479,
"memoryTotal": 67427545088,
"memoryUsed": 8274534400,
"memoryFree": 59153010688,
"memoryUsagePercent": 12.271742044294905,
"memoryEfficiency": 87.72825795570509,
"cpuCount": 16,
"cpuLoad": 0.0325,
"platform": "linux",
"uptime": 16418.1
},
{
"timestamp": 1754448379489,
"memoryTotal": 67427545088,
"memoryUsed": 8216985600,
"memoryFree": 59210559488,
"memoryUsagePercent": 12.186392948573129,
"memoryEfficiency": 87.81360705142687,
"cpuCount": 16,
"cpuLoad": 0.02,
"platform": "linux",
"uptime": 16448.11
},
{
"timestamp": 1754448409491,
"memoryTotal": 67427545088,
"memoryUsed": 8228491264,
"memoryFree": 59199053824,
"memoryUsagePercent": 12.20345669304875,
"memoryEfficiency": 87.79654330695125,
"cpuCount": 16,
"cpuLoad": 0.01875,
"platform": "linux",
"uptime": 16478.11
},
{
"timestamp": 1754448439522,
"memoryTotal": 67427545088,
"memoryUsed": 8201416704,
"memoryFree": 59226128384,
"memoryUsagePercent": 12.163303132712741,
"memoryEfficiency": 87.83669686728726,
"cpuCount": 16,
"cpuLoad": 0.025,
"platform": "linux",
"uptime": 16508.14
},
{
"timestamp": 1754448469552,
"memoryTotal": 67427545088,
"memoryUsed": 8225583104,
"memoryFree": 59201961984,
"memoryUsagePercent": 12.199143678247152,
"memoryEfficiency": 87.80085632175285,
"cpuCount": 16,
"cpuLoad": 0.028125,
"platform": "linux",
"uptime": 16538.17
},
{
"timestamp": 1754448499583,
"memoryTotal": 67427545088,
"memoryUsed": 8415969280,
"memoryFree": 59011575808,
"memoryUsagePercent": 12.481500355702229,
"memoryEfficiency": 87.51849964429778,
"cpuCount": 16,
"cpuLoad": 0.045625,
"platform": "linux",
"uptime": 16568.2
},
{
"timestamp": 1754448529613,
"memoryTotal": 67427545088,
"memoryUsed": 8250900480,
"memoryFree": 59176644608,
"memoryUsagePercent": 12.236691205696,
"memoryEfficiency": 87.763308794304,
"cpuCount": 16,
"cpuLoad": 0.03625,
"platform": "linux",
"uptime": 16598.23
},
{
"timestamp": 1754448559643,
"memoryTotal": 67427545088,
"memoryUsed": 8281088000,
"memoryFree": 59146457088,
"memoryUsagePercent": 12.281461514270338,
"memoryEfficiency": 87.71853848572967,
"cpuCount": 16,
"cpuLoad": 0.035625,
"platform": "linux",
"uptime": 16628.26
},
{
"timestamp": 1754448589672,
"memoryTotal": 67427545088,
"memoryUsed": 8357122048,
"memoryFree": 59070423040,
"memoryUsagePercent": 12.39422558999157,
"memoryEfficiency": 87.60577441000842,
"cpuCount": 16,
"cpuLoad": 0.025,
"platform": "linux",
"uptime": 16658.29
},
{
"timestamp": 1754448619698,
"memoryTotal": 67427545088,
"memoryUsed": 8254050304,
"memoryFree": 59173494784,
"memoryUsagePercent": 12.241362625952942,
"memoryEfficiency": 87.75863737404705,
"cpuCount": 16,
"cpuLoad": 0.0325,
"platform": "linux",
"uptime": 16688.32
},
{
"timestamp": 1754448649729,
"memoryTotal": 67427545088,
"memoryUsed": 8468123648,
"memoryFree": 58959421440,
"memoryUsagePercent": 12.558849112700473,
"memoryEfficiency": 87.44115088729953,
"cpuCount": 16,
"cpuLoad": 0.045625,
"platform": "linux",
"uptime": 16718.35
},
{
"timestamp": 1754448679758,
"memoryTotal": 67427545088,
"memoryUsed": 8560320512,
"memoryFree": 58867224576,
"memoryUsagePercent": 12.69558383124862,
"memoryEfficiency": 87.30441616875137,
"cpuCount": 16,
"cpuLoad": 0.056875,
"platform": "linux",
"uptime": 16748.38
},
{
"timestamp": 1754448709788,
"memoryTotal": 67427545088,
"memoryUsed": 8435757056,
"memoryFree": 58991788032,
"memoryUsagePercent": 12.510847080359303,
"memoryEfficiency": 87.4891529196407,
"cpuCount": 16,
"cpuLoad": 0.07375,
"platform": "linux",
"uptime": 16778.41
},
{
"timestamp": 1754448739791,
"memoryTotal": 67427545088,
"memoryUsed": 8497061888,
"memoryFree": 58930483200,
"memoryUsagePercent": 12.601766647310747,
"memoryEfficiency": 87.39823335268926,
"cpuCount": 16,
"cpuLoad": 0.07625,
"platform": "linux",
"uptime": 16808.41
},
{
"timestamp": 1754448769821,
"memoryTotal": 67427545088,
"memoryUsed": 8339202048,
"memoryFree": 59088343040,
"memoryUsagePercent": 12.367648914277494,
"memoryEfficiency": 87.6323510857225,
"cpuCount": 16,
"cpuLoad": 0.058125,
"platform": "linux",
"uptime": 16838.44
},
{
"timestamp": 1754448799851,
"memoryTotal": 67427545088,
"memoryUsed": 8410345472,
"memoryFree": 59017199616,
"memoryUsagePercent": 12.47315983552956,
"memoryEfficiency": 87.52684016447044,
"cpuCount": 16,
"cpuLoad": 0.079375,
"platform": "linux",
"uptime": 16868.47
},
{
"timestamp": 1754448829882,
"memoryTotal": 67427545088,
"memoryUsed": 8341360640,
"memoryFree": 59086184448,
"memoryUsagePercent": 12.370850264700653,
"memoryEfficiency": 87.62914973529935,
"cpuCount": 16,
"cpuLoad": 0.076875,
"platform": "linux",
"uptime": 16898.5
},
{
"timestamp": 1754448859913,
"memoryTotal": 67427545088,
"memoryUsed": 8491409408,
"memoryFree": 58936135680,
"memoryUsagePercent": 12.593383604456937,
"memoryEfficiency": 87.40661639554307,
"cpuCount": 16,
"cpuLoad": 0.0675,
"platform": "linux",
"uptime": 16928.53
},
{
"timestamp": 1754448889935,
"memoryTotal": 67427545088,
"memoryUsed": 8564326400,
"memoryFree": 58863218688,
"memoryUsagePercent": 12.701524857271101,
"memoryEfficiency": 87.2984751427289,
"cpuCount": 16,
"cpuLoad": 0.09875,
"platform": "linux",
"uptime": 16958.55
},
{
"timestamp": 1754448919965,
"memoryTotal": 67427545088,
"memoryUsed": 8712294400,
"memoryFree": 58715250688,
"memoryUsagePercent": 12.920972265310185,
"memoryEfficiency": 87.07902773468982,
"cpuCount": 16,
"cpuLoad": 0.113125,
"platform": "linux",
"uptime": 16988.58
},
{
"timestamp": 1754448949994,
"memoryTotal": 67427545088,
"memoryUsed": 8610455552,
"memoryFree": 58817089536,
"memoryUsagePercent": 12.769937776560683,
"memoryEfficiency": 87.23006222343932,
"cpuCount": 16,
"cpuLoad": 0.139375,
"platform": "linux",
"uptime": 17018.61
},
{
"timestamp": 1754448980010,
"memoryTotal": 67427545088,
"memoryUsed": 8617050112,
"memoryFree": 58810494976,
"memoryUsagePercent": 12.779717993223464,
"memoryEfficiency": 87.22028200677653,
"cpuCount": 16,
"cpuLoad": 0.163125,
"platform": "linux",
"uptime": 17048.63
}
]
@@ -1,5 +1,5 @@
{
"startTime": 1754447658902,
"startTime": 1754448051459,
"totalTasks": 1,
"successfulTasks": 1,
"failedTasks": 0,
@@ -1,10 +1,10 @@
[
{
"id": "cmd-hooks-1754447659008",
"id": "cmd-hooks-1754448051558",
"type": "hooks",
"success": true,
"duration": 11.502896000000021,
"timestamp": 1754447659020,
"duration": 9.677881999999983,
"timestamp": 1754448051568,
"metadata": {}
}
]
@@ -1,5 +1,5 @@
{
"startTime": 1754447048421,
"startTime": 1754448985610,
"totalTasks": 1,
"successfulTasks": 1,
"failedTasks": 0,
@@ -1,10 +1,10 @@
[
{
"id": "cmd-hooks-1754447048532",
"id": "cmd-hooks-1754448985722",
"type": "hooks",
"success": true,
"duration": 6.419533999999999,
"timestamp": 1754447048538,
"duration": 13.920774999999992,
"timestamp": 1754448985736,
"metadata": {}
}
]
@@ -0,0 +1 @@
{"branch": "checkpoint/pre-edit-20250806-025608", "file": "/workspaces/claude-code-flow/benchmark/PROJECT_SUMMARY.md", "timestamp": "2025-08-06T02:56:08Z", "type": "pre-edit", "original_branch": "alpha-88"}
@@ -0,0 +1 @@
{"tag": "checkpoint-20250806-025611", "file": "/workspaces/claude-code-flow/benchmark/PROJECT_SUMMARY.md", "timestamp": "2025-08-06T02:56:11Z", "type": "post-edit", "branch": "alpha-88", "diff_summary": " .claude-flow/metrics/system-metrics.json | 516 +++++++++++++++ benchmark/.claude-flow/metrics/performance.json | 2 +- benchmark/.claude-flow/metrics/task-metrics.json | 6 +- benchmark/PROJECT_SUMMARY.md | 103 +++ .../examples/.claude-flow/metrics/performance.json | 2 +- .../.claude-flow/metrics/task-metrics.json | 6 +- .../examples/.claude/checkpoints/1754448794.json | 1 + .../examples/.claude/checkpoints/1754448796.json | 1 + benchmark/examples/claude_optimizer_example.py | 520 --------------- benchmark/examples/cli/batch_benchmarks.sh | 0 benchmark/examples/cli/cli_examples.sh | 0 benchmark/examples/demo_comprehensive.py | 233 ------- benchmark/examples/demo_mle_star.py | 152 ----- benchmark/examples/demo_real_benchmark.py | 219 ------- benchmark/examples/demos/demo_comprehensive.py | 233 ------- benchmark/examples/demos/demo_mle_star.py | 152 ----- benchmark/examples/demos/demo_real_benchmark.py | 219 ------- benchmark/examples/example_usage.py | 249 -------- benchmark/examples/mle_star_benchmark_example.py | 229 ------- benchmark/examples/optimization_demo.py | 133 ---- benchmark/examples/parallel_benchmark_demo.py | 254 -------- benchmark/examples/quick_test.py | 0 benchmark/examples/real/real_swarm_benchmark.py | 701 ++++----------------- benchmark/examples/real_benchmark_examples.py | 376 ----------- benchmark/examples/real_hive_mind_benchmark.py | 191 ------ benchmark/examples/real_integration_results.json | 78 --- benchmark/examples/real_metrics_demo.py | 238 ------- benchmark/examples/real_sparc_benchmark.py | 228 ------- benchmark/examples/real_swarm_benchmark.py | 146 ----- benchmark/examples/verify_real_integration.py | 408 ------------ .../cli/__pycache__/main.cpython-312.pyc | Bin 21009 -> 22009 bytes .../optimized_benchmark_engine.cpython-312.pyc | Bin 15770 -> 15428 bytes .../__pycache__/engine.cpython-312.pyc | Bin 32449 -> 33620 bytes benchmark/test_optimization_fix.py | 167 ----- .../tests/.claude-flow/metrics/performance.json | 2 +- .../tests/.claude-flow/metrics/task-metrics.json | 6 +- claude-flow-wiki | 0 37 files changed, 763 insertions(+), 5008 deletions(-) "}
@@ -0,0 +1,306 @@
# Session Summary - 2025-08-06 02:56:26
## Checkpoints Created
1754447043.json
1754447045.json
1754448240.json
1754448242.json
1754448294.json
1754448295.json
1754448380.json
1754448382.json
1754448488.json
1754448490.json
1754448531.json
1754448533.json
1754448586.json
1754448587.json
1754448738.json
1754448741.json
1754448794.json
1754448796.json
1754448968.json
1754448971.json
## Files Modified
.claude-flow/metrics/performance.json
.claude-flow/metrics/system-metrics.json
.claude-flow/metrics/task-metrics.json
.claude/checkpoints/task-1754446387.json
benchmark/.claude-flow/metrics/performance.json
benchmark/.claude-flow/metrics/system-metrics.json
benchmark/.claude-flow/metrics/task-metrics.json
benchmark/.claude/checkpoints/1754445349.json
benchmark/.claude/checkpoints/1754445369.json
benchmark/.claude/checkpoints/1754446676.json
benchmark/.claude/checkpoints/1754446678.json
benchmark/.claude/checkpoints/1754446680.json
benchmark/.claude/checkpoints/1754446681.json
benchmark/.claude/checkpoints/1754446746.json
benchmark/.claude/checkpoints/1754446747.json
benchmark/.claude/checkpoints/1754446758.json
benchmark/.claude/checkpoints/1754446760.json
benchmark/.claude/checkpoints/1754446762.json
benchmark/.claude/checkpoints/1754446763.json
benchmark/.claude/checkpoints/1754446765.json
benchmark/.claude/checkpoints/1754446767.json
benchmark/.claude/checkpoints/1754446804.json
benchmark/.claude/checkpoints/1754446806.json
benchmark/.claude/checkpoints/1754446825.json
benchmark/.claude/checkpoints/1754446827.json
benchmark/.claude/checkpoints/1754446838.json
benchmark/.claude/checkpoints/1754446840.json
benchmark/.claude/checkpoints/1754446850.json
benchmark/.claude/checkpoints/1754446852.json
benchmark/.claude/checkpoints/1754446853.json
benchmark/.claude/checkpoints/1754446855.json
benchmark/.claude/checkpoints/1754446876.json
benchmark/.claude/checkpoints/1754446878.json
benchmark/.claude/checkpoints/1754446913.json
benchmark/.claude/checkpoints/1754446914.json
benchmark/.claude/checkpoints/1754446929.json
benchmark/.claude/checkpoints/1754446930.json
benchmark/.claude/checkpoints/1754447000.json
benchmark/.claude/checkpoints/1754447002.json
benchmark/.claude/checkpoints/1754447010.json
benchmark/.claude/checkpoints/1754447012.json
benchmark/.claude/checkpoints/1754447073.json
benchmark/.claude/checkpoints/1754447075.json
benchmark/.claude/checkpoints/1754447109.json
benchmark/.claude/checkpoints/1754447111.json
benchmark/.claude/checkpoints/1754447217.json
benchmark/.claude/checkpoints/1754447219.json
benchmark/.claude/checkpoints/1754447291.json
benchmark/.claude/checkpoints/1754447292.json
benchmark/.claude/checkpoints/1754447479.json
benchmark/.claude/checkpoints/1754447481.json
benchmark/.claude/checkpoints/1754447514.json
benchmark/.claude/checkpoints/1754447516.json
benchmark/.claude/checkpoints/1754447819.json
benchmark/.claude/checkpoints/1754447821.json
benchmark/.claude/checkpoints/1754447851.json
benchmark/.claude/checkpoints/1754447854.json
benchmark/.claude/checkpoints/1754447864.json
benchmark/.claude/checkpoints/1754447866.json
benchmark/.claude/checkpoints/1754447873.json
benchmark/.claude/checkpoints/1754447875.json
benchmark/.claude/checkpoints/1754447876.json
benchmark/.claude/checkpoints/1754447878.json
benchmark/.claude/checkpoints/1754447887.json
benchmark/.claude/checkpoints/1754447889.json
benchmark/.claude/checkpoints/1754447894.json
benchmark/.claude/checkpoints/1754447896.json
benchmark/.claude/checkpoints/1754447899.json
benchmark/.claude/checkpoints/1754447901.json
benchmark/.claude/checkpoints/1754447908.json
benchmark/.claude/checkpoints/1754447910.json
benchmark/.claude/checkpoints/1754447918.json
benchmark/.claude/checkpoints/1754447920.json
benchmark/.claude/checkpoints/1754447933.json
benchmark/.claude/checkpoints/1754447935.json
benchmark/.claude/checkpoints/1754447953.json
benchmark/.claude/checkpoints/1754447955.json
benchmark/.claude/checkpoints/1754447970.json
benchmark/.claude/checkpoints/1754447972.json
benchmark/.claude/checkpoints/1754447973.json
benchmark/.claude/checkpoints/1754447975.json
benchmark/.claude/checkpoints/1754447977.json
benchmark/.claude/checkpoints/1754447978.json
benchmark/.claude/checkpoints/1754447986.json
benchmark/.claude/checkpoints/1754447988.json
benchmark/.claude/checkpoints/1754448003.json
benchmark/.claude/checkpoints/1754448005.json
benchmark/.claude/checkpoints/1754448023.json
benchmark/.claude/checkpoints/1754448025.json
benchmark/.claude/checkpoints/summary-session-20250806-020959.md
benchmark/.claude/checkpoints/task-1754446496.json
benchmark/.claude/checkpoints/task-1754447669.json
benchmark/CLI_USAGE.md
benchmark/OPTIMIZATION_WARNING_FIX_REPORT.md
benchmark/PROJECT_SUMMARY.md
benchmark/README.md
benchmark/__pycache__/hello_world.cpython-312.pyc
benchmark/archive/old-files/hello_world.js
benchmark/archive/old-files/hello_world.test.js
benchmark/archive/old-files/optimization_demo_results.json
benchmark/archive/old-files/quick_real_test.py
benchmark/archive/old-files/real_benchmark_results.json
benchmark/archive/old-files/simple_load_test_results.json
benchmark/archive/old-files/simple_test_results.json
benchmark/archive/old-files/test_hello_world.js
benchmark/archive/old-files/test_real_integration.py
benchmark/archive/old-reports/AGENT2_IMPORT_FIXES_REPORT.md
benchmark/archive/old-reports/CLEANUP_REPORT.md
benchmark/archive/old-reports/GITHUB_ISSUE_599_COMPLETION.md
benchmark/archive/old-reports/GITHUB_ISSUE_599_UPDATE.md
benchmark/archive/old-reports/README.md
benchmark/archive/old-reports/README_HELLO_WORLD.md
benchmark/archive/old-reports/REAL_BENCHMARKS_README.md
benchmark/archive/old-reports/REAL_BENCHMARK_COMPLETION_REPORT.md
benchmark/archive/old-reports/REAL_CLAUDE_FLOW_INTEGRATION_REPORT.md
benchmark/archive/old-reports/REORGANIZATION_REPORT.md
benchmark/archive/old-reports/VALIDATION_REPORT.md
benchmark/archive/old-reports/api_development_accuracy_claude.md
benchmark/archive/old-reports/api_development_speed_claude.md
benchmark/archive/old-reports/api_development_tokens_claude.md
benchmark/archive/old-reports/github_issue_599_comment.md
benchmark/archive/old-reports/ml_pipeline_claude.md
benchmark/archive/old-reports/performance_optimization_claude.md
benchmark/archive/old-reports/testing_automation_claude.md
benchmark/ci_performance_integration.py
benchmark/compare_optimizations.py
benchmark/examples/.claude-flow/metrics/agent-metrics.json
benchmark/examples/.claude-flow/metrics/performance.json
benchmark/examples/.claude-flow/metrics/task-metrics.json
benchmark/examples/.claude/checkpoints/1754447043.json
benchmark/examples/.claude/checkpoints/1754447045.json
benchmark/examples/.claude/checkpoints/1754448240.json
benchmark/examples/.claude/checkpoints/1754448242.json
benchmark/examples/.claude/checkpoints/1754448294.json
benchmark/examples/.claude/checkpoints/1754448295.json
benchmark/examples/.claude/checkpoints/1754448380.json
benchmark/examples/.claude/checkpoints/1754448382.json
benchmark/examples/.claude/checkpoints/1754448488.json
benchmark/examples/.claude/checkpoints/1754448490.json
benchmark/examples/.claude/checkpoints/1754448531.json
benchmark/examples/.claude/checkpoints/1754448533.json
benchmark/examples/.claude/checkpoints/1754448586.json
benchmark/examples/.claude/checkpoints/1754448587.json
benchmark/examples/.claude/checkpoints/1754448738.json
benchmark/examples/.claude/checkpoints/1754448741.json
benchmark/examples/.claude/checkpoints/1754448794.json
benchmark/examples/.claude/checkpoints/1754448796.json
benchmark/examples/ORGANIZATION_REPORT.md
benchmark/examples/README.md
benchmark/examples/__pycache__/demo_real_benchmark.cpython-312.pyc
benchmark/examples/advanced/comparative_analysis.py
benchmark/examples/advanced/demo_comprehensive.py
benchmark/examples/advanced/demo_mle_star.py
benchmark/examples/advanced/mle_star_benchmark_example.py
benchmark/examples/advanced/optimization_demo.py
benchmark/examples/advanced/optimization_suite.py
benchmark/examples/advanced/parallel_benchmark_demo.py
benchmark/examples/advanced/parallel_benchmarks.py
benchmark/examples/basic/claude_optimizer_example.py
benchmark/examples/basic/example_usage.py
benchmark/examples/basic/simple_hive_mind.py
benchmark/examples/basic/simple_sparc.py
benchmark/examples/basic/simple_swarm.py
benchmark/examples/cli/batch_benchmarks.sh
benchmark/examples/cli/cli_examples.sh
benchmark/examples/demo_comprehensive.py
benchmark/examples/demo_mle_star.py
benchmark/examples/demo_real_benchmark.py
benchmark/examples/example_usage.py
benchmark/examples/quick_test.py
benchmark/examples/real/demo_real_benchmark.py
benchmark/examples/real/real_benchmark_examples.py
benchmark/examples/real/real_hive_mind_benchmark.py
benchmark/examples/real/real_metrics_demo.py
benchmark/examples/real/real_performance.py
benchmark/examples/real/real_sparc_benchmark.py
benchmark/examples/real/real_swarm_benchmark.py
benchmark/examples/real/real_token_tracking.py
benchmark/examples/real/verify_real_integration.py
benchmark/examples/reports/metrics_edcb3fff-6fe4-432c-ab07-f01483a4cb46.json
benchmark/examples/reports/process_report_edcb3fff-6fe4-432c-ab07-f01483a4cb46.json
benchmark/examples/reports/real-benchmark-auto-centralized_edcb3fff-6fe4-432c-ab07-f01483a4cb46.json
benchmark/mle_star_benchmark_example.py
benchmark/performance_dashboard.py
benchmark/quick_test_integration.py
benchmark/run_real_benchmarks.py
benchmark/src/swarm_benchmark/cli/__pycache__/main.cpython-312.pyc
benchmark/src/swarm_benchmark/cli/main.py
benchmark/src/swarm_benchmark/core/__pycache__/benchmark_engine.cpython-312.pyc
benchmark/src/swarm_benchmark/core/__pycache__/claude_flow_real_executor.cpython-312.pyc
benchmark/src/swarm_benchmark/core/__pycache__/optimized_benchmark_engine.cpython-312.pyc
benchmark/src/swarm_benchmark/core/__pycache__/real_benchmark_engine_v2.cpython-312.pyc
benchmark/src/swarm_benchmark/core/benchmark_engine.py
benchmark/src/swarm_benchmark/core/claude_flow_real_executor.py
benchmark/src/swarm_benchmark/core/optimized_benchmark_engine.py
benchmark/src/swarm_benchmark/core/real_benchmark_engine_v2.py
benchmark/src/swarm_benchmark/optimization/__init__.py
benchmark/src/swarm_benchmark/optimization/__pycache__/__init__.cpython-312.pyc
benchmark/src/swarm_benchmark/optimization/__pycache__/engine.cpython-312.pyc
benchmark/src/swarm_benchmark/optimization/engine.py
benchmark/src/swarm_benchmark/scenarios/__init__.py
benchmark/src/swarm_benchmark/scenarios/__pycache__/__init__.cpython-312.pyc
benchmark/src/swarm_benchmark/scenarios/__pycache__/real_benchmarks.cpython-312.pyc
benchmark/src/swarm_benchmark/scenarios/real_benchmarks.py
benchmark/test_claude_optimizer.py
benchmark/test_integration.py
benchmark/test_mle_star_integration.py
benchmark/test_real_benchmark_engine.py
benchmark/test_real_benchmarks.py
benchmark/test_real_claude_flow.py
benchmark/test_real_execution.py
benchmark/test_real_metrics.py
benchmark/test_real_simple.py
benchmark/test_simple_run.py
benchmark/tests/.claude-flow/metrics/performance.json
benchmark/tests/.claude-flow/metrics/task-metrics.json
benchmark/tests/.claude/checkpoints/1754448082.json
benchmark/tests/.claude/checkpoints/1754448084.json
benchmark/tests/.claude/checkpoints/1754448093.json
benchmark/tests/.claude/checkpoints/1754448094.json
benchmark/tests/.claude/checkpoints/1754448133.json
benchmark/tests/.claude/checkpoints/1754448135.json
benchmark/tests/.claude/checkpoints/1754448139.json
benchmark/tests/.claude/checkpoints/1754448141.json
benchmark/tests/.claude/checkpoints/1754448169.json
benchmark/tests/.claude/checkpoints/1754448171.json
benchmark/tests/__pycache__/conftest.cpython-312-pytest-8.4.0.pyc
benchmark/tests/__pycache__/test_cli.cpython-312-pytest-8.4.0.pyc
benchmark/tests/fixtures/__pycache__/test_data.cpython-312.pyc
benchmark/tests/integration/__pycache__/__init__.cpython-312.pyc
benchmark/tests/integration/__pycache__/test_real_claude_flow_integration.cpython-312-pytest-8.4.0.pyc
benchmark/tests/integration/hello_world.py
benchmark/tests/integration/quick_test_integration.py
benchmark/tests/integration/test_claude_optimizer.py
benchmark/tests/integration/test_hello_world.py
benchmark/tests/integration/test_integration.py
benchmark/tests/integration/test_mle_star_integration.py
benchmark/tests/integration/test_real_benchmark_engine.py
benchmark/tests/integration/test_real_claude_flow.py
benchmark/tests/integration/test_real_claude_flow_integration.py
benchmark/tests/integration/test_real_metrics.py
benchmark/tests/integration/test_simple_run.py
benchmark/tests/test_cli.py
benchmark/tools/continuous_performance_monitor.py
benchmark/tools/scripts/hive-mind-load-test.py
benchmark/tools/scripts/hive-mind-stress-test.py
benchmark/tools/scripts/run-load-tests.py
benchmark/tools/scripts/run_performance_tests.py
benchmark/tools/scripts/simple-load-test.py
benchmark/tools/scripts/swarm_performance_suite.py
benchmark/validate_cli.py
claude-flow-wiki
reports/benchmark-development-distributed_cb162c55-4775-41e0-933c-233bf4ece53c.json
## Recent Commits
93562696 🔖 Checkpoint: Edit /workspaces/claude-code-flow/benchmark/PROJECT_SUMMARY.md
9ede9962 🔖 Checkpoint: Edit /workspaces/claude-code-flow/benchmark/CLI_USAGE.md
b22d0a73 🔖 Checkpoint: Edit /workspaces/claude-code-flow/benchmark/examples/quick_test.py
9bdba820 🔖 Checkpoint: Edit /workspaces/claude-code-flow/benchmark/examples/ORGANIZATION_REPORT.md
9e590ec0 🔖 Checkpoint: Edit /workspaces/claude-code-flow/benchmark/examples/README.md
cd28ae69 🔖 Checkpoint: Edit /workspaces/claude-code-flow/benchmark/examples/real/real_performance.py
c9fc55fc 🔖 Checkpoint: Edit /workspaces/claude-code-flow/benchmark/examples/real/real_token_tracking.py
ff44b4b8 🔖 Checkpoint: Edit /workspaces/claude-code-flow/benchmark/examples/cli/batch_benchmarks.sh
592188c9 🔖 Checkpoint: Edit /workspaces/claude-code-flow/benchmark/examples/cli/cli_examples.sh
30e9008b 🔖 Checkpoint: Edit /workspaces/claude-code-flow/benchmark/examples/real/real_swarm_benchmark.py
## GitHub Releases Created
No GitHub releases
## Rollback Instructions
To rollback to a specific checkpoint:
```bash
# List all checkpoints
git tag -l checkpoint-* | sort -r
# List GitHub releases
gh release list
# Rollback to a checkpoint
git checkout checkpoint-YYYYMMDD-HHMMSS
```
@@ -1,520 +0,0 @@
#!/usr/bin/env python3
"""
CLAUDE.md Optimizer Example
This example demonstrates comprehensive usage of the CLAUDE.md optimizer
for different development scenarios and optimization strategies.
"""
import asyncio
import json
import sys
from pathlib import Path
from datetime import datetime
from typing import List, Dict, Any
# Add the benchmark source to Python path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from swarm_benchmark.claude_optimizer import (
ClaudeMdOptimizer,
ProjectContext,
PerformanceTargets,
BenchmarkMetrics
)
class ClaudeOptimizerDemo:
"""
Comprehensive demonstration of CLAUDE.md optimization capabilities.
"""
def __init__(self):
"""Initialize the demo with optimizer and example scenarios."""
self.optimizer = ClaudeMdOptimizer()
self.results: List[Dict] = []
async def run_complete_demo(self):
"""Run complete demonstration of all optimization features."""
print("🚀 CLAUDE.md Optimizer Comprehensive Demo")
print("=" * 50)
# Run all optimization scenarios
await self.demo_api_development()
await self.demo_ml_pipeline()
await self.demo_performance_optimization()
await self.demo_testing_automation()
await self.demo_custom_optimization()
# Generate comparison report
self.generate_comparison_report()
print("\n✅ Demo completed successfully!")
print(f"📊 Results saved to: optimization_demo_results.json")
async def demo_api_development(self):
"""Demonstrate API development optimization."""
print("\n🔧 API Development Optimization")
print("-" * 30)
# Define project context for a high-performance API
context = ProjectContext(
project_type="e_commerce_api",
team_size=6,
complexity="complex",
primary_languages=["Python", "TypeScript"],
frameworks=["FastAPI", "React", "PostgreSQL", "Redis"],
performance_requirements={
"response_time": "<50ms",
"throughput": ">1000 rps",
"availability": "99.9%",
"test_coverage": ">95%"
},
existing_tools=["pytest", "docker", "kubernetes", "prometheus"],
constraints={
"budget": "medium",
"timeline": "3 months",
"team_experience": "senior"
}
)
# Test different optimization priorities
priorities = ["speed", "accuracy", "tokens"]
for priority in priorities:
targets = PerformanceTargets(
priority=priority,
target_completion_time=60.0,
target_token_usage=500 if priority == "tokens" else 800,
target_memory_usage=2048.0,
target_error_rate=0.01 if priority == "accuracy" else 0.05
)
print(f"\n 📋 Optimizing for: {priority.upper()}")
# Generate optimized configuration
config = self.optimizer.generate_optimized_config(
"api_development", context, targets
)
# Save configuration
config_file = f"api_development_{priority}_claude.md"
with open(config_file, "w") as f:
f.write(config)
print(f" ✅ Configuration saved: {config_file}")
# Benchmark the configuration
test_tasks = [
"Design RESTful API with proper resource modeling",
"Implement CRUD endpoints with validation and error handling",
"Add comprehensive authentication and authorization",
"Create integration tests with >95% coverage",
"Generate OpenAPI documentation",
"Implement caching and performance optimization",
"Add monitoring, logging, and health checks",
"Deploy with Docker and Kubernetes"
]
metrics = await self.optimizer.benchmark_config_effectiveness(
config, test_tasks, iterations=3
)
# Store results
result = {
"use_case": "api_development",
"priority": priority,
"context": context.__dict__,
"targets": targets.__dict__,
"metrics": metrics.__dict__,
"config_file": config_file,
"timestamp": datetime.now().isoformat()
}
self.results.append(result)
# Display metrics
print(f" 📊 Optimization Score: {metrics.optimization_score:.3f}")
print(f" 📊 Completion Rate: {metrics.completion_rate:.1%}")
print(f" 📊 Avg Execution Time: {metrics.avg_execution_time:.2f}s")
print(f" 📊 Token Efficiency: {metrics.avg_tokens_per_task} tokens/task")
# Get optimization suggestions
suggestions = self.optimizer.get_optimization_suggestions(metrics, targets)
if suggestions:
print(f" 💡 Suggestions: {suggestions[0]}")
async def demo_ml_pipeline(self):
"""Demonstrate ML pipeline optimization."""
print("\n🧠 ML Pipeline Optimization")
print("-" * 30)
context = ProjectContext(
project_type="ml_classification",
team_size=4,
complexity="complex",
primary_languages=["Python", "R"],
frameworks=["PyTorch", "scikit-learn", "MLflow", "Airflow"],
performance_requirements={
"model_accuracy": ">92%",
"training_time": "<30min",
"inference_latency": "<100ms",
"reproducibility": "100%"
},
existing_tools=["jupyter", "wandb", "docker", "kubernetes"],
constraints={
"gpu_budget": "limited",
"data_size": "large",
"interpretability": "required"
}
)
targets = PerformanceTargets(
priority="accuracy",
target_completion_time=90.0,
target_token_usage=1000,
target_memory_usage=4096.0,
target_error_rate=0.005
)
print(" 📋 Optimizing ML pipeline for accuracy")
# Generate MLE-STAR optimized configuration
config = self.optimizer.generate_optimized_config(
"ml_pipeline", context, targets
)
config_file = "ml_pipeline_claude.md"
with open(config_file, "w") as f:
f.write(config)
print(f" ✅ Configuration saved: {config_file}")
# ML-specific benchmark tasks
ml_tasks = [
"Design data preprocessing pipeline with feature engineering",
"Implement cross-validation strategy for model selection",
"Create ensemble learning setup with MLE-STAR coordination",
"Build hyperparameter optimization with Bayesian search",
"Implement model evaluation with comprehensive metrics",
"Create model interpretation and explainability features",
"Set up experiment tracking and model versioning",
"Deploy model with A/B testing capabilities"
]
metrics = await self.optimizer.benchmark_config_effectiveness(
config, ml_tasks, iterations=2 # Fewer iterations for ML tasks
)
# Store results
result = {
"use_case": "ml_pipeline",
"priority": "accuracy",
"context": context.__dict__,
"targets": targets.__dict__,
"metrics": metrics.__dict__,
"config_file": config_file,
"mle_star_enabled": True,
"timestamp": datetime.now().isoformat()
}
self.results.append(result)
print(f" 📊 Optimization Score: {metrics.optimization_score:.3f}")
print(f" 📊 Completion Rate: {metrics.completion_rate:.1%}")
print(f" 🧠 MLE-STAR ensemble coordination enabled")
async def demo_performance_optimization(self):
"""Demonstrate performance optimization scenario."""
print("\n⚡ Performance Optimization")
print("-" * 30)
context = ProjectContext(
project_type="performance_tuning",
team_size=3,
complexity="medium",
primary_languages=["Python", "Go", "JavaScript"],
frameworks=["Flask", "Gin", "Node.js"],
performance_requirements={
"latency_reduction": ">50%",
"throughput_increase": ">100%",
"memory_optimization": ">30%",
"cpu_optimization": ">40%"
},
existing_tools=["profiler", "benchmark", "monitoring"],
constraints={
"no_architecture_changes": True,
"backward_compatibility": "required"
}
)
targets = PerformanceTargets(
priority="speed",
target_completion_time=45.0,
target_token_usage=400, # Aggressive token optimization
target_memory_usage=1024.0,
target_error_rate=0.02
)
print(" 📋 Optimizing for maximum performance")
config = self.optimizer.generate_optimized_config(
"performance_optimization", context, targets
)
config_file = "performance_optimization_claude.md"
with open(config_file, "w") as f:
f.write(config)
performance_tasks = [
"Profile application to identify bottlenecks",
"Optimize database queries and indexing",
"Implement caching at multiple layers",
"Optimize algorithms and data structures",
"Tune memory allocation and garbage collection",
"Implement parallel processing where possible",
"Set up continuous performance monitoring",
"Create performance regression testing"
]
metrics = await self.optimizer.benchmark_config_effectiveness(
config, performance_tasks, iterations=3
)
result = {
"use_case": "performance_optimization",
"priority": "speed",
"context": context.__dict__,
"targets": targets.__dict__,
"metrics": metrics.__dict__,
"config_file": config_file,
"timestamp": datetime.now().isoformat()
}
self.results.append(result)
print(f" 📊 Optimization Score: {metrics.optimization_score:.3f}")
print(f" ⚡ Parallel Efficiency: {metrics.parallel_efficiency:.1%}")
async def demo_testing_automation(self):
"""Demonstrate testing automation optimization."""
print("\n🧪 Testing Automation Optimization")
print("-" * 30)
context = ProjectContext(
project_type="test_automation",
team_size=5,
complexity="medium",
primary_languages=["Python", "JavaScript", "Java"],
frameworks=["pytest", "jest", "selenium", "testcontainers"],
performance_requirements={
"test_coverage": ">95%",
"test_execution_time": "<5min",
"flaky_test_rate": "<1%",
"maintenance_overhead": "<10%"
},
existing_tools=["CI/CD", "test-reporting", "parallel-execution"],
constraints={
"existing_test_suite": "large",
"integration_complexity": "high"
}
)
targets = PerformanceTargets(
priority="accuracy",
target_completion_time=30.0,
target_token_usage=600,
target_memory_usage=1536.0,
target_error_rate=0.01
)
print(" 📋 Optimizing testing automation for accuracy")
config = self.optimizer.generate_optimized_config(
"testing_automation", context, targets
)
config_file = "testing_automation_claude.md"
with open(config_file, "w") as f:
f.write(config)
testing_tasks = [
"Design comprehensive test strategy and framework",
"Implement unit tests with high coverage",
"Create integration tests for critical paths",
"Build end-to-end test automation",
"Set up performance and load testing",
"Implement test data management and fixtures",
"Create test reporting and analytics",
"Optimize test execution with parallelization"
]
metrics = await self.optimizer.benchmark_config_effectiveness(
config, testing_tasks, iterations=3
)
result = {
"use_case": "testing_automation",
"priority": "accuracy",
"context": context.__dict__,
"targets": targets.__dict__,
"metrics": metrics.__dict__,
"config_file": config_file,
"timestamp": datetime.now().isoformat()
}
self.results.append(result)
print(f" 📊 Optimization Score: {metrics.optimization_score:.3f}")
print(f" 🎯 Error Rate: {metrics.error_rate:.1%}")
async def demo_custom_optimization(self):
"""Demonstrate custom optimization rules."""
print("\n🔧 Custom Optimization Rules")
print("-" * 30)
from swarm_benchmark.claude_optimizer import OptimizationRulesEngine, OptimizationRule
# Create custom rules for a specific scenario
custom_rules = [
OptimizationRule(
name="legacy_system_integration",
description="Optimize for legacy system compatibility",
condition="legacy_integration == True",
action="enable_legacy_compatibility_mode",
priority=9,
impact="high"
),
OptimizationRule(
name="regulatory_compliance",
description="Enable compliance-focused development",
condition="regulatory_requirements == 'strict'",
action="enable_compliance_mode",
priority=10,
impact="high"
),
OptimizationRule(
name="resource_constraints",
description="Optimize for limited resources",
condition="resource_budget == 'limited'",
action="enable_resource_optimization",
priority=8,
impact="medium"
)
]
# Apply custom rules
rules_engine = OptimizationRulesEngine()
# Base configuration
base_config = {
"use_case": "custom_development",
"max_agents": 4,
"swarm_topology": "hierarchical",
"critical_rules": ["Standard development practices"]
}
# Apply custom rules
optimized_config = rules_engine.apply_custom_rules(base_config, custom_rules)
print(" ✅ Applied custom optimization rules:")
for rule in custom_rules:
print(f" - {rule.name}: {rule.description}")
# Get rules summary
summary = rules_engine.get_applied_rules_summary()
print(f" 📊 Total rule applications: {summary['total_applications']}")
# Store custom rule result
result = {
"use_case": "custom_optimization",
"priority": "custom",
"custom_rules_count": len(custom_rules),
"rules_applied": [rule.name for rule in custom_rules],
"base_config": base_config,
"optimized_config": optimized_config,
"timestamp": datetime.now().isoformat()
}
self.results.append(result)
def generate_comparison_report(self):
"""Generate comprehensive comparison report."""
print("\n📊 Optimization Results Comparison")
print("=" * 50)
# Group results by use case
use_cases = {}
for result in self.results:
use_case = result["use_case"]
if use_case not in use_cases:
use_cases[use_case] = []
use_cases[use_case].append(result)
# Generate comparison table
print(f"{'Use Case':<25} {'Priority':<10} {'Opt Score':<10} {'Completion':<12} {'Exec Time':<10}")
print("-" * 80)
for use_case, results in use_cases.items():
for result in results:
if "metrics" in result:
metrics = result["metrics"]
print(f"{use_case:<25} {result.get('priority', 'N/A'):<10} "
f"{metrics['optimization_score']:.3f} "
f"{metrics['completion_rate']:.1%} "
f"{metrics['avg_execution_time']:.2f}s")
# Find best performing configurations
best_overall = max(
[r for r in self.results if "metrics" in r],
key=lambda x: x["metrics"]["optimization_score"]
)
fastest = min(
[r for r in self.results if "metrics" in r],
key=lambda x: x["metrics"]["avg_execution_time"]
)
most_accurate = max(
[r for r in self.results if "metrics" in r],
key=lambda x: x["metrics"]["completion_rate"]
)
print(f"\n🏆 Best Performing Configurations:")
print(f" Highest Optimization Score: {best_overall['use_case']} ({best_overall['priority']}) - {best_overall['metrics']['optimization_score']:.3f}")
print(f" Fastest Execution: {fastest['use_case']} ({fastest['priority']}) - {fastest['metrics']['avg_execution_time']:.2f}s")
print(f" Most Accurate: {most_accurate['use_case']} ({most_accurate['priority']}) - {most_accurate['metrics']['completion_rate']:.1%}")
# Save detailed results
with open("optimization_demo_results.json", "w") as f:
json.dump(self.results, f, indent=2, default=str)
# Generate summary statistics
if self.results:
total_optimizations = len(self.results)
with_metrics = [r for r in self.results if "metrics" in r]
if with_metrics:
avg_score = sum(r["metrics"]["optimization_score"] for r in with_metrics) / len(with_metrics)
avg_completion = sum(r["metrics"]["completion_rate"] for r in with_metrics) / len(with_metrics)
avg_time = sum(r["metrics"]["avg_execution_time"] for r in with_metrics) / len(with_metrics)
print(f"\n📈 Summary Statistics:")
print(f" Total Optimizations: {total_optimizations}")
print(f" Average Optimization Score: {avg_score:.3f}")
print(f" Average Completion Rate: {avg_completion:.1%}")
print(f" Average Execution Time: {avg_time:.2f}s")
async def main():
"""Run the complete CLAUDE.md optimizer demonstration."""
demo = ClaudeOptimizerDemo()
try:
await demo.run_complete_demo()
except KeyboardInterrupt:
print("\n\n⚠️ Demo interrupted by user")
except Exception as e:
print(f"\n❌ Demo failed with error: {str(e)}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
# Run the demo
asyncio.run(main())
View File
File mode changed.
View File
File mode changed.
-233
View File
@@ -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())
-152
View File
@@ -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())
-219
View File
@@ -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())
@@ -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())
-152
View File
@@ -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())
@@ -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())
-249
View File
@@ -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()
@@ -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)
-133
View File
@@ -1,133 +0,0 @@
#!/usr/bin/env python3
"""
Optimization Engine Demo
This script demonstrates the real optimization capabilities that have been
implemented to fix the "Optimizations not available" warning.
Features demonstrated:
- Connection pooling
- TTL-based caching
- Circular buffer logging
- Async I/O operations
- Parallel task execution
"""
import asyncio
import sys
import os
from pathlib import Path
# Add the src directory to Python path
sys.path.insert(0, str(Path(__file__).parent.parent / 'src'))
from swarm_benchmark.optimization import OptimizedBenchmarkEngine
from swarm_benchmark.core.benchmark_engine import BenchmarkEngine
from swarm_benchmark.core.models import BenchmarkConfig, StrategyType, CoordinationMode
async def demo_optimization_features():
"""Demonstrate the optimization features."""
print("🚀 Optimization Engine Demo")
print("=" * 50)
# Create configuration
config = BenchmarkConfig(
name="optimization_demo",
description="Demonstration of optimization features",
strategy=StrategyType.DEVELOPMENT,
mode=CoordinationMode.MESH,
max_agents=5,
task_timeout=30
)
# Create base engine for comparison
base_engine = BenchmarkEngine(config)
# Create optimized engine
optimized_engine = OptimizedBenchmarkEngine(base_engine, {
'min_connections': 3,
'max_connections': 8,
'max_concurrency': 6,
'cache_ttl': 3600000, # 1 hour
'cache_size': 1000,
'history_size': 500
})
print("✅ Optimization engine initialized")
print("Features enabled:")
print(" - Connection pooling (3-8 connections)")
print(" - TTL-based result caching (1 hour)")
print(" - Circular buffer logging (500 items)")
print(" - Async I/O operations")
print(" - Parallel execution (6 concurrent tasks)")
# Enable optimizations
optimized_engine.enable_optimizations()
print("\n🏃 Running benchmark tests...")
# Test 1: Single objective
print("1. Single objective benchmark:")
result1 = await optimized_engine.run_optimized_benchmark(
"Develop a REST API with authentication"
)
print(f" Duration: {result1['execution_time']:.3f}s")
print(f" Optimized: {result1['optimized']}")
# Test 2: Same objective (should hit cache)
print("\n2. Same objective (cache test):")
result2 = await optimized_engine.run_optimized_benchmark(
"Develop a REST API with authentication"
)
print(f" Duration: {result2['execution_time']:.3f}s")
print(f" Cache hit: {result2.get('cache_hit', False)}")
# Test 3: Batch processing
print("\n3. Batch processing test:")
objectives = [
"Implement user authentication system",
"Create database schema and migrations",
"Build API endpoints for CRUD operations",
"Add input validation and error handling",
"Implement logging and monitoring"
]
batch_results = await optimized_engine.batch_process(objectives, batch_size=3)
print(f" Processed {len(batch_results)} objectives")
successful = sum(1 for r in batch_results if r.get('optimized', False))
print(f" Successful optimized executions: {successful}")
# Test 4: Performance metrics
print("\n4. Performance metrics:")
metrics = optimized_engine.get_optimization_metrics()
print(f" Optimized executions: {metrics['optimized_executions']}")
print(f" Cache hits: {metrics['cache_hits']}")
print(f" Parallel tasks: {metrics['parallel_tasks']}")
if 'executor_metrics' in metrics:
exec_metrics = metrics['executor_metrics']
print(f" Total tasks executed: {exec_metrics['tasks_executed']}")
print(f" Average execution time: {exec_metrics['average_execution_time']:.3f}s")
if 'cache_stats' in metrics:
cache_stats = metrics['cache_stats']
print(f" Cache hit rate: {cache_stats['hit_rate']:.2%}")
print(f" Cache size: {cache_stats['size']}/{cache_stats['max_size']}")
# Cleanup
await optimized_engine.shutdown()
print("\n✅ Demo completed successfully!")
print("The optimization engine provides real performance improvements:")
print(" • Parallel execution reduces overall processing time")
print(" • Caching eliminates redundant work")
print(" • Connection pooling manages resources efficiently")
print(" • Async I/O prevents blocking operations")
print(" • Circular buffers provide memory-efficient logging")
if __name__ == "__main__":
asyncio.run(demo_optimization_features())
@@ -1,254 +0,0 @@
#!/usr/bin/env python3
"""Example demonstrating parallel benchmark execution with orchestration."""
import asyncio
import logging
import sys
from pathlib import Path
from datetime import datetime
# Add the src directory to Python path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from swarm_benchmark.core import (
OrchestrationManager,
OrchestrationConfig,
BenchmarkConfig,
ExecutionMode,
SchedulingAlgorithm,
ResourceLimits,
StrategyType,
CoordinationMode
)
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
async def run_basic_parallel_benchmark():
"""Run a basic parallel benchmark demonstration."""
print("\n=== Basic Parallel Benchmark Demo ===\n")
# Configure orchestration
orch_config = OrchestrationConfig(
execution_mode=ExecutionMode.HYBRID,
scheduling_algorithm=SchedulingAlgorithm.DYNAMIC,
enable_work_stealing=True,
max_parallel_benchmarks=5,
resource_limits=ResourceLimits(
max_cpu_percent=80,
max_memory_mb=1024,
max_concurrent_tasks=10
)
)
# Create orchestration manager
orchestrator = OrchestrationManager(orch_config)
# Define benchmark objectives
objectives = [
"Research best practices for microservices architecture",
"Analyze performance bottlenecks in distributed systems",
"Test security vulnerabilities in web applications",
"Optimize database query performance",
"Develop monitoring solution for cloud infrastructure"
]
# Configure benchmark
bench_config = BenchmarkConfig(
name="parallel-demo",
strategy=StrategyType.AUTO,
mode=CoordinationMode.DISTRIBUTED,
max_agents=10,
parallel=True,
timeout=300
)
try:
# Initialize orchestrator
await orchestrator.initialize()
print(f"Starting parallel execution of {len(objectives)} benchmarks...")
start_time = datetime.now()
# Run benchmark suite
results = await orchestrator.run_benchmark_suite(objectives, bench_config)
# Display results
print(f"\nCompleted in {results['duration']:.2f} seconds")
print(f"Throughput: {results['throughput']:.2f} benchmarks/second")
print(f"\nResults Summary:")
print(f" - Total objectives: {results['total_objectives']}")
print(f" - Completed: {results['completed_objectives']}")
print(f" - Failed: {results['failed_objectives']}")
# Show execution metrics
exec_metrics = results['execution_metrics']
print(f"\nExecution Metrics:")
print(f" - Tasks completed: {exec_metrics['tasks_completed']}")
print(f" - Average execution time: {exec_metrics['average_execution_time']:.2f}s")
print(f" - Peak CPU usage: {exec_metrics['peak_cpu_usage']:.1f}%")
print(f" - Peak memory usage: {exec_metrics['peak_memory_usage']:.1f}MB")
print(f" - Queue wait time: {exec_metrics['queue_wait_time']:.2f}s")
# Show scheduling metrics
sched_metrics = results['scheduling_metrics']
print(f"\nScheduling Metrics:")
print(f" - Total scheduled: {sched_metrics['total_scheduled']}")
print(f" - Load balance score: {sched_metrics['load_balance_score']:.2f}")
print(f" - Max agent load: {sched_metrics['max_agent_load']}")
print(f" - Min agent load: {sched_metrics['min_agent_load']}")
finally:
# Shutdown orchestrator
await orchestrator.shutdown()
async def run_adaptive_benchmark():
"""Run an adaptive benchmark with auto-scaling."""
print("\n=== Adaptive Benchmark Demo ===\n")
# Configure with auto-scaling
orch_config = OrchestrationConfig(
execution_mode=ExecutionMode.HYBRID,
scheduling_algorithm=SchedulingAlgorithm.WORK_STEALING,
enable_optimizations=True,
auto_scaling=True,
load_balancing=True,
progress_reporting=True
)
orchestrator = OrchestrationManager(orch_config)
# Complex objective requiring adaptation
objective = "Build and optimize a complete e-commerce platform with microservices"
bench_config = BenchmarkConfig(
name="adaptive-demo",
strategy=StrategyType.DEVELOPMENT,
mode=CoordinationMode.HIERARCHICAL,
max_agents=15,
parallel=True,
timeout=600
)
try:
print("Starting adaptive benchmark with auto-scaling...")
# Run adaptive benchmark
result = await orchestrator.run_adaptive_benchmark(objective, bench_config)
print(f"\nBenchmark completed!")
print(f"Status: {result['status']}")
print(f"Duration: {result.get('duration', 0):.2f}s")
# Show optimization benefits
if result.get('optimized'):
print("\nOptimization Benefits:")
perf_metrics = result.get('performance_metrics', {})
if 'executor' in perf_metrics:
print(f" - Connection pooling enabled")
print(f" - Caching enabled")
print(f" - Parallel file operations")
# Get final metrics
final_metrics = orchestrator.get_orchestration_metrics()
print(f"\nAgent Status:")
for agent in final_metrics['agents'][:5]: # Show first 5 agents
print(f" - {agent['name']}: {agent['status']} "
f"(completed: {agent['tasks_completed']}, "
f"success rate: {agent['success_rate']:.1%})")
finally:
await orchestrator.shutdown()
async def run_stress_test():
"""Run a stress test with many concurrent tasks."""
print("\n=== Stress Test Demo ===\n")
# Configure for stress testing
orch_config = OrchestrationConfig(
execution_mode=ExecutionMode.HYBRID,
scheduling_algorithm=SchedulingAlgorithm.LEAST_LOADED,
max_parallel_benchmarks=20,
resource_limits=ResourceLimits(
max_cpu_percent=90,
max_memory_mb=2048,
max_concurrent_tasks=20,
task_timeout=60
)
)
orchestrator = OrchestrationManager(orch_config)
# Generate many objectives
objectives = [
f"Task {i}: Analyze and optimize component {i}"
for i in range(50)
]
bench_config = BenchmarkConfig(
name="stress-test",
strategy=StrategyType.ANALYSIS,
mode=CoordinationMode.DISTRIBUTED,
max_agents=20,
parallel=True,
timeout=300,
task_timeout=30
)
try:
await orchestrator.initialize()
print(f"Starting stress test with {len(objectives)} tasks...")
# Run stress test
results = await orchestrator.run_benchmark_suite(objectives, bench_config)
print(f"\nStress Test Results:")
print(f" - Total tasks: {len(objectives)}")
print(f" - Completed: {results['completed_objectives']}")
print(f" - Failed: {results['failed_objectives']}")
print(f" - Duration: {results['duration']:.2f}s")
print(f" - Throughput: {results['throughput']:.2f} tasks/second")
# Resource utilization
exec_metrics = results['execution_metrics']
print(f"\nResource Utilization:")
print(f" - Peak CPU: {exec_metrics['peak_cpu_usage']:.1f}%")
print(f" - Peak Memory: {exec_metrics['peak_memory_usage']:.1f}MB")
print(f" - Current CPU: {exec_metrics['current_cpu_usage']:.1f}%")
print(f" - Current Memory: {exec_metrics['current_memory_usage']:.1f}MB")
finally:
await orchestrator.shutdown()
async def main():
"""Run all demonstration scenarios."""
# Run basic parallel benchmark
await run_basic_parallel_benchmark()
# Small delay between demos
await asyncio.sleep(2)
# Run adaptive benchmark
await run_adaptive_benchmark()
# Small delay
await asyncio.sleep(2)
# Run stress test
await run_stress_test()
print("\n=== All demos completed! ===")
if __name__ == "__main__":
asyncio.run(main())
Regular → Executable
View File
File mode changed.
+126 -567
View File
@@ -1,587 +1,146 @@
#!/usr/bin/env python3
"""
Real swarm benchmark with actual claude-flow execution and comprehensive metrics.
Real Swarm Benchmark Example - Execute and measure real swarm performance.
This example demonstrates:
- Real claude-flow swarm execution
- Comprehensive metrics collection
- Performance monitoring
- Production-ready benchmarking
This example demonstrates how to:
1. Execute real Claude Flow swarm commands
2. Measure actual performance metrics
3. Parse real JSON streaming responses
4. Track token usage from actual Claude responses
Usage:
python real_swarm_benchmark.py [task_description]
"""
import subprocess
import sys
import json
import time
import psutil
import threading
import argparse
from pathlib import Path
from dataclasses import dataclass, asdict
from typing import List, Dict, Any, Optional
from contextlib import contextmanager
@dataclass
class RealSwarmConfig:
"""Configuration for real swarm benchmark."""
benchmark_id: str
task_description: str
strategy: str
coordination_mode: str
max_agents: int
timeout_seconds: int = 300
enable_metrics: bool = True
save_artifacts: bool = True
# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
@dataclass
class SwarmMetrics:
"""Comprehensive swarm metrics."""
benchmark_id: str
start_time: float
end_time: float
execution_time: float
success: bool
agents_spawned: int
coordination_events: int
task_completion_rate: float
token_consumption: int
memory_usage_mb: float
cpu_usage_percent: float
disk_io_bytes: int
network_requests: int
error_count: int
warning_count: int
quality_indicators: Dict[str, int]
performance_score: float
from swarm_benchmark.scenarios.real_benchmarks import RealSwarmBenchmark, RealBenchmarkResult
class RealSwarmBenchmark:
"""Real swarm benchmark execution with comprehensive monitoring."""
def __init__(self):
self.metrics_history: List[SwarmMetrics] = []
self.monitoring_active = False
self.resource_data = []
self.claude_flow_path = "/workspaces/claude-code-flow"
def create_real_benchmark_configs(self) -> List[RealSwarmConfig]:
"""Create real-world benchmark configurations."""
configs = [
RealSwarmConfig(
benchmark_id="api_development_swarm",
task_description="Create a complete REST API with authentication, CRUD operations, input validation, and comprehensive error handling",
strategy="development",
coordination_mode="hierarchical",
max_agents=5,
timeout_seconds=300
),
RealSwarmConfig(
benchmark_id="optimization_analysis_swarm",
task_description="Analyze existing codebase for performance bottlenecks, suggest optimizations, and implement improvements",
strategy="optimization",
coordination_mode="mesh",
max_agents=6,
timeout_seconds=240
),
RealSwarmConfig(
benchmark_id="research_documentation_swarm",
task_description="Research best practices for microservices architecture and create comprehensive documentation with examples",
strategy="research",
coordination_mode="distributed",
max_agents=4,
timeout_seconds=180
),
RealSwarmConfig(
benchmark_id="testing_automation_swarm",
task_description="Design and implement comprehensive test suite with unit tests, integration tests, and automated CI/CD pipeline",
strategy="testing",
coordination_mode="hierarchical",
max_agents=4,
timeout_seconds=200
)
]
return configs
@contextmanager
def system_monitoring(self, interval: float = 2.0):
"""Monitor system resources during benchmark execution."""
self.resource_data.clear()
self.monitoring_active = True
def monitor():
while self.monitoring_active:
try:
cpu_percent = psutil.cpu_percent(interval=0.1)
memory = psutil.virtual_memory()
disk_io = psutil.disk_io_counters()
net_io = psutil.net_io_counters()
self.resource_data.append({
"timestamp": time.time(),
"cpu_percent": cpu_percent,
"memory_mb": memory.used / 1024 / 1024,
"memory_percent": memory.percent,
"disk_read": disk_io.read_bytes if disk_io else 0,
"disk_write": disk_io.write_bytes if disk_io else 0,
"net_sent": net_io.bytes_sent if net_io else 0,
"net_recv": net_io.bytes_recv if net_io else 0
})
time.sleep(interval)
except Exception as e:
print(f"⚠️ Monitoring error: {e}")
break
monitor_thread = threading.Thread(target=monitor, daemon=True)
monitor_thread.start()
try:
yield
finally:
self.monitoring_active = False
monitor_thread.join(timeout=5.0)
def execute_real_swarm_benchmark(self, config: RealSwarmConfig) -> SwarmMetrics:
"""Execute a real swarm benchmark with full monitoring."""
print(f"🚀 Starting real swarm benchmark: {config.benchmark_id}")
print(f" 📋 Task: {config.task_description[:60]}...")
print(f" 🎯 Strategy: {config.strategy}")
print(f" 🔗 Coordination: {config.coordination_mode}")
print(f" 👥 Max Agents: {config.max_agents}")
start_time = time.time()
with self.system_monitoring():
try:
# Execute real claude-flow command
cmd = [
"npx", "claude-flow@alpha", "swarm",
config.task_description,
"--strategy", config.strategy,
"--coordination", config.coordination_mode,
"--max-agents", str(config.max_agents),
"--output-format", "json",
"--enable-metrics", "true"
]
print(f" 🔧 Executing: {' '.join(cmd[:3])} ...")
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=config.timeout_seconds,
cwd=self.claude_flow_path
)
end_time = time.time()
execution_time = end_time - start_time
# Parse results and create metrics
metrics = self._create_swarm_metrics(
config, start_time, end_time, execution_time,
result.returncode == 0, result.stdout, result.stderr
)
status = "✅" if metrics.success else "❌"
print(f" {status} Completed in {execution_time:.1f}s")
print(f" 📊 Performance Score: {metrics.performance_score:.1f}/100")
print(f" 🧠 Tokens: {metrics.token_consumption}")
print(f" 💾 Memory Peak: {metrics.memory_usage_mb:.1f}MB")
return metrics
except subprocess.TimeoutExpired:
end_time = time.time()
execution_time = end_time - start_time
print(f" ⏰ Timeout after {execution_time:.1f}s")
return self._create_timeout_metrics(config, start_time, end_time, execution_time)
except Exception as e:
end_time = time.time()
execution_time = end_time - start_time
print(f" ❌ Exception: {e}")
return self._create_error_metrics(config, start_time, end_time, execution_time, str(e))
def _create_swarm_metrics(
self,
config: RealSwarmConfig,
start_time: float,
end_time: float,
execution_time: float,
success: bool,
stdout: str,
stderr: str
) -> SwarmMetrics:
"""Create comprehensive metrics from benchmark execution."""
# Parse output for specific metrics
output_analysis = self._analyze_swarm_output(stdout, stderr)
# Calculate resource metrics
resource_metrics = self._calculate_resource_metrics()
# Calculate performance score
performance_score = self._calculate_performance_score(
execution_time, success, output_analysis, resource_metrics
)
return SwarmMetrics(
benchmark_id=config.benchmark_id,
start_time=start_time,
end_time=end_time,
execution_time=execution_time,
success=success,
agents_spawned=output_analysis.get("agents_spawned", config.max_agents),
coordination_events=output_analysis.get("coordination_events", 0),
task_completion_rate=output_analysis.get("completion_rate", 1.0 if success else 0.0),
token_consumption=output_analysis.get("token_consumption", 0),
memory_usage_mb=resource_metrics.get("peak_memory_mb", 0),
cpu_usage_percent=resource_metrics.get("avg_cpu_percent", 0),
disk_io_bytes=resource_metrics.get("total_disk_io", 0),
network_requests=output_analysis.get("network_requests", 0),
error_count=output_analysis.get("error_count", 0),
warning_count=output_analysis.get("warning_count", 0),
quality_indicators=output_analysis.get("quality_indicators", {}),
performance_score=performance_score
)
def _analyze_swarm_output(self, stdout: str, stderr: str) -> Dict[str, Any]:
"""Analyze swarm output for metrics extraction."""
analysis = {
"agents_spawned": 0,
"coordination_events": 0,
"completion_rate": 0.0,
"token_consumption": 0,
"network_requests": 0,
"error_count": 0,
"warning_count": 0,
"quality_indicators": {}
}
combined_output = stdout + stderr
# Count various indicators
analysis["error_count"] = combined_output.count("❌") + combined_output.count("Error") + combined_output.count("error")
analysis["warning_count"] = combined_output.count("⚠️") + combined_output.count("Warning") + combined_output.count("warning")
# Success indicators
success_indicators = combined_output.count("✅") + combined_output.count("Complete") + combined_output.count("Success")
analysis["quality_indicators"]["success_markers"] = success_indicators
analysis["quality_indicators"]["code_blocks"] = combined_output.count("```")
analysis["quality_indicators"]["bullet_points"] = combined_output.count("•") + combined_output.count("- ")
# Try to parse JSON metrics if present
try:
lines = stdout.split('\n')
for line in lines:
stripped = line.strip()
if stripped.startswith('{') and stripped.endswith('}'):
json_data = json.loads(stripped)
if "token_consumption" in json_data:
analysis["token_consumption"] = json_data["token_consumption"]
if "agents_spawned" in json_data:
analysis["agents_spawned"] = json_data["agents_spawned"]
break
except:
pass
# Estimate token consumption if not found
if analysis["token_consumption"] == 0:
word_count = len(combined_output.split())
analysis["token_consumption"] = int(word_count * 1.3) # Rough estimate
# Calculate completion rate
if success_indicators > 0:
analysis["completion_rate"] = min(1.0, success_indicators / 5.0) # Normalize to 0-1
return analysis
def _calculate_resource_metrics(self) -> Dict[str, float]:
"""Calculate resource usage metrics from monitoring data."""
if not self.resource_data:
return {}
cpu_values = [d["cpu_percent"] for d in self.resource_data]
memory_values = [d["memory_mb"] for d in self.resource_data]
# Calculate disk I/O delta
if len(self.resource_data) > 1:
start_disk = self.resource_data[0]["disk_read"] + self.resource_data[0]["disk_write"]
end_disk = self.resource_data[-1]["disk_read"] + self.resource_data[-1]["disk_write"]
total_disk_io = end_disk - start_disk
else:
total_disk_io = 0
return {
"avg_cpu_percent": sum(cpu_values) / len(cpu_values),
"peak_cpu_percent": max(cpu_values),
"avg_memory_mb": sum(memory_values) / len(memory_values),
"peak_memory_mb": max(memory_values),
"total_disk_io": total_disk_io,
"sample_count": len(self.resource_data)
}
def _calculate_performance_score(
self,
execution_time: float,
success: bool,
output_analysis: Dict[str, Any],
resource_metrics: Dict[str, float]
) -> float:
"""Calculate overall performance score."""
score = 0.0
# Base score for success
if success:
score += 40.0
# Time efficiency (faster is better, up to 30 points)
# Assume 120s is baseline, scale accordingly
baseline_time = 120.0
if execution_time > 0:
time_score = min(30.0, (baseline_time / execution_time) * 30.0)
score += time_score
# Quality indicators (up to 20 points)
quality_score = 0
quality_indicators = output_analysis.get("quality_indicators", {})
quality_score += min(10, quality_indicators.get("success_markers", 0) * 2)
quality_score += min(5, quality_indicators.get("code_blocks", 0))
quality_score += min(5, quality_indicators.get("bullet_points", 0) * 0.5)
score += quality_score
# Resource efficiency (up to 10 points)
if resource_metrics:
cpu_efficiency = max(0, 10 - (resource_metrics.get("avg_cpu_percent", 50) / 10))
score += cpu_efficiency
# Penalty for errors and warnings
error_penalty = output_analysis.get("error_count", 0) * 5
warning_penalty = output_analysis.get("warning_count", 0) * 2
score -= error_penalty + warning_penalty
return max(0.0, min(100.0, score))
def _create_timeout_metrics(
self,
config: RealSwarmConfig,
start_time: float,
end_time: float,
execution_time: float
) -> SwarmMetrics:
"""Create metrics for timed out benchmark."""
resource_metrics = self._calculate_resource_metrics()
return SwarmMetrics(
benchmark_id=config.benchmark_id,
start_time=start_time,
end_time=end_time,
execution_time=execution_time,
success=False,
agents_spawned=0,
coordination_events=0,
task_completion_rate=0.0,
token_consumption=0,
memory_usage_mb=resource_metrics.get("peak_memory_mb", 0),
cpu_usage_percent=resource_metrics.get("avg_cpu_percent", 0),
disk_io_bytes=resource_metrics.get("total_disk_io", 0),
network_requests=0,
error_count=1, # Timeout is an error
warning_count=0,
quality_indicators={},
performance_score=0.0
)
def _create_error_metrics(
self,
config: RealSwarmConfig,
start_time: float,
end_time: float,
execution_time: float,
error_msg: str
) -> SwarmMetrics:
"""Create metrics for failed benchmark."""
resource_metrics = self._calculate_resource_metrics()
return SwarmMetrics(
benchmark_id=config.benchmark_id,
start_time=start_time,
end_time=end_time,
execution_time=execution_time,
success=False,
agents_spawned=0,
coordination_events=0,
task_completion_rate=0.0,
token_consumption=0,
memory_usage_mb=resource_metrics.get("peak_memory_mb", 0),
cpu_usage_percent=resource_metrics.get("avg_cpu_percent", 0),
disk_io_bytes=resource_metrics.get("total_disk_io", 0),
network_requests=0,
error_count=1,
warning_count=0,
quality_indicators={},
performance_score=0.0
)
def run_real_benchmark_suite(self) -> Dict[str, Any]:
"""Run complete real benchmark suite."""
print("🔥 Real Swarm Benchmark Suite")
print("=" * 50)
configs = self.create_real_benchmark_configs()
all_metrics = []
for i, config in enumerate(configs, 1):
print(f"\n[{i}/{len(configs)}] Running {config.benchmark_id}")
print("-" * 40)
metrics = self.execute_real_swarm_benchmark(config)
all_metrics.append(metrics)
self.metrics_history.append(metrics)
# Generate suite analysis
suite_analysis = self._analyze_benchmark_suite(all_metrics)
# Save results
self._save_benchmark_results(all_metrics, suite_analysis)
return {
"suite_metrics": [asdict(m) for m in all_metrics],
"suite_analysis": suite_analysis,
"timestamp": time.time()
}
def _analyze_benchmark_suite(self, metrics_list: List[SwarmMetrics]) -> Dict[str, Any]:
"""Analyze complete benchmark suite results."""
if not metrics_list:
return {}
successful_metrics = [m for m in metrics_list if m.success]
failed_metrics = [m for m in metrics_list if not m.success]
analysis = {
"total_benchmarks": len(metrics_list),
"successful_benchmarks": len(successful_metrics),
"failed_benchmarks": len(failed_metrics),
"success_rate": len(successful_metrics) / len(metrics_list),
"average_execution_time": sum(m.execution_time for m in successful_metrics) / len(successful_metrics) if successful_metrics else 0,
"average_performance_score": sum(m.performance_score for m in successful_metrics) / len(successful_metrics) if successful_metrics else 0,
"total_token_consumption": sum(m.token_consumption for m in metrics_list),
"average_memory_usage": sum(m.memory_usage_mb for m in metrics_list) / len(metrics_list),
"best_performer": None,
"strategy_analysis": {},
"coordination_analysis": {}
}
# Find best performer
if successful_metrics:
best = max(successful_metrics, key=lambda m: m.performance_score)
analysis["best_performer"] = {
"benchmark_id": best.benchmark_id,
"performance_score": best.performance_score,
"execution_time": best.execution_time,
"token_consumption": best.token_consumption
}
# Strategy analysis
strategy_groups = {}
for metrics in successful_metrics:
# Extract strategy from benchmark_id
if "development" in metrics.benchmark_id:
strategy = "development"
elif "optimization" in metrics.benchmark_id:
strategy = "optimization"
elif "research" in metrics.benchmark_id:
strategy = "research"
elif "testing" in metrics.benchmark_id:
strategy = "testing"
else:
strategy = "unknown"
if strategy not in strategy_groups:
strategy_groups[strategy] = []
strategy_groups[strategy].append(metrics)
for strategy, strategy_metrics in strategy_groups.items():
avg_score = sum(m.performance_score for m in strategy_metrics) / len(strategy_metrics)
avg_time = sum(m.execution_time for m in strategy_metrics) / len(strategy_metrics)
analysis["strategy_analysis"][strategy] = {
"average_score": avg_score,
"average_time": avg_time,
"benchmark_count": len(strategy_metrics)
}
return analysis
def _save_benchmark_results(self, metrics_list: List[SwarmMetrics], analysis: Dict[str, Any]):
"""Save benchmark results to files."""
output_dir = Path("/workspaces/claude-code-flow/benchmark/examples/output")
output_dir.mkdir(exist_ok=True)
# Save individual metrics
timestamp = int(time.time())
for metrics in metrics_list:
filename = f"real_swarm_{metrics.benchmark_id}_{timestamp}.json"
with open(output_dir / filename, "w") as f:
json.dump(asdict(metrics), f, indent=2)
# Save suite analysis
with open(output_dir / f"real_swarm_suite_analysis_{timestamp}.json", "w") as f:
json.dump(analysis, f, indent=2)
# Save summary CSV for easy analysis
summary_file = output_dir / f"real_swarm_summary_{timestamp}.csv"
with open(summary_file, "w") as f:
f.write("benchmark_id,success,execution_time,performance_score,token_consumption,memory_mb,cpu_percent\n")
for metrics in metrics_list:
f.write(f"{metrics.benchmark_id},{metrics.success},{metrics.execution_time:.2f},"
f"{metrics.performance_score:.2f},{metrics.token_consumption},"
f"{metrics.memory_usage_mb:.2f},{metrics.cpu_usage_percent:.2f}\n")
print(f"\n📁 Results saved to: {output_dir}")
print(f" 📊 Individual metrics: real_swarm_*_{timestamp}.json")
print(f" 📈 Suite analysis: real_swarm_suite_analysis_{timestamp}.json")
print(f" 📋 Summary CSV: real_swarm_summary_{timestamp}.csv")
if __name__ == "__main__":
print("🔥 Real Swarm Benchmark Execution")
print("=" * 50)
def run_swarm_benchmark(task: str, strategy: str = "auto", mode: str = "hierarchical") -> RealBenchmarkResult:
"""
Run a real swarm benchmark.
Args:
task: Task description
strategy: Execution strategy
mode: Coordination mode
Returns:
RealBenchmarkResult with actual metrics
"""
print(f"🚀 Starting Real Swarm Benchmark")
print(f" Task: {task}")
print(f" Strategy: {strategy}")
print(f" Mode: {mode}")
print("-" * 60)
# Initialize benchmark
benchmark = RealSwarmBenchmark()
# Run benchmark suite
results = benchmark.run_real_benchmark_suite()
# Execute real swarm
result = benchmark.executor.execute_swarm(
objective=task,
strategy=strategy,
mode=mode,
max_agents=5,
timeout=10,
non_interactive=True
)
# Display summary
analysis = results.get("suite_analysis", {})
print(f"\n📊 Benchmark Suite Summary")
print("=" * 35)
print(f"Total benchmarks: {analysis.get('total_benchmarks', 0)}")
print(f"Success rate: {analysis.get('success_rate', 0):.1%}")
print(f"Average execution time: {analysis.get('average_execution_time', 0):.1f}s")
print(f"Average performance score: {analysis.get('average_performance_score', 0):.1f}/100")
print(f"Total tokens consumed: {analysis.get('total_token_consumption', 0):,}")
# Display results
print(f"✅ Benchmark Complete!")
print(f" Success: {result.success}")
print(f" Execution Time: {result.execution_time:.2f}s")
print(f" Tokens Used: {result.tokens_used}")
print(f" Agents Spawned: {result.agents_spawned}")
print(f" Memory Usage: {result.memory_usage_mb:.2f} MB")
print(f" CPU Usage: {result.cpu_usage_percent:.1f}%")
print(f" Output Size: {result.output_size_bytes} bytes")
print(f" Errors: {result.error_count}")
print(f" Warnings: {result.warning_count}")
# Best performer
best = analysis.get("best_performer")
if best:
print(f"\n🏆 Best Performer: {best['benchmark_id']}")
print(f" Score: {best['performance_score']:.1f}/100")
print(f" Time: {best['execution_time']:.1f}s")
print(f" Tokens: {best['token_consumption']:,}")
if result.stdout_excerpt:
print(f"\n📋 Output Excerpt:")
print(result.stdout_excerpt)
if result.stderr_excerpt and result.error_count > 0:
print(f"\n❌ Error Excerpt:")
print(result.stderr_excerpt)
return result
def run_multiple_benchmarks():
"""Run multiple swarm benchmarks with different configurations."""
print("🔥 Running Multiple Real Swarm Benchmarks")
print("=" * 60)
# Strategy analysis
strategy_analysis = analysis.get("strategy_analysis", {})
if strategy_analysis:
print(f"\n📈 Strategy Performance:")
for strategy, perf in strategy_analysis.items():
print(f" {strategy}: {perf['average_score']:.1f}/100 ({perf['average_time']:.1f}s avg)")
benchmark_configs = [
("Create a REST API for user management", "development", "centralized"),
("Analyze system performance bottlenecks", "analysis", "distributed"),
("Research modern web development frameworks", "research", "mesh"),
("Optimize database query performance", "optimization", "hierarchical"),
("Test API endpoint functionality", "testing", "hybrid")
]
print(f"\n🎉 Real Swarm Benchmark Complete!")
print("This benchmark provides:")
print("- Actual claude-flow execution results")
print("- Comprehensive performance metrics")
print("- Resource utilization analysis")
print("- Production readiness insights")
results = []
for i, (task, strategy, mode) in enumerate(benchmark_configs, 1):
print(f"\n🎯 Benchmark {i}/{len(benchmark_configs)}")
result = run_swarm_benchmark(task, strategy, mode)
results.append(result)
print("=" * 60)
# Save comprehensive results
output_file = Path("real_swarm_benchmark_results.json")
with open(output_file, 'w') as f:
json.dump([r.to_dict() for r in results], f, indent=2)
print(f"\n💾 Results saved to: {output_file}")
# Summary statistics
total_time = sum(r.execution_time for r in results)
total_tokens = sum(r.tokens_used for r in results)
total_agents = sum(r.agents_spawned for r in results)
success_rate = sum(1 for r in results if r.success) / len(results) * 100
print(f"\n📊 Summary Statistics:")
print(f" Total Execution Time: {total_time:.2f}s")
print(f" Total Tokens Used: {total_tokens}")
print(f" Total Agents Spawned: {total_agents}")
print(f" Success Rate: {success_rate:.1f}%")
print(f" Average Time per Benchmark: {total_time/len(results):.2f}s")
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="Real Swarm Benchmark Example")
parser.add_argument("task", nargs="?",
default="Create a simple web application with authentication",
help="Task description for the swarm")
parser.add_argument("--strategy", default="auto",
choices=["auto", "development", "research", "analysis", "testing", "optimization"],
help="Execution strategy")
parser.add_argument("--mode", default="hierarchical",
choices=["centralized", "distributed", "hierarchical", "mesh", "hybrid"],
help="Coordination mode")
parser.add_argument("--multiple", action="store_true",
help="Run multiple benchmark scenarios")
args = parser.parse_args()
if args.multiple:
run_multiple_benchmarks()
else:
run_swarm_benchmark(args.task, args.strategy, args.mode)
if __name__ == "__main__":
main()
@@ -1,376 +0,0 @@
#!/usr/bin/env python3
"""
Examples of using the Real Claude-Flow Benchmark Engine
Demonstrates various usage patterns and configurations
"""
import asyncio
import json
from pathlib import Path
import sys
# Add benchmark source to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from swarm_benchmark.core.real_benchmark_engine import RealBenchmarkEngine
from swarm_benchmark.core.models import (
BenchmarkConfig, Task, StrategyType, CoordinationMode
)
async def example_simple_benchmark():
"""Example 1: Simple benchmark execution"""
print("\n" + "="*60)
print("Example 1: Simple Benchmark")
print("="*60)
# Create configuration
config = BenchmarkConfig(
name="simple-benchmark",
description="A simple benchmark example",
strategy=StrategyType.AUTO,
mode=CoordinationMode.CENTRALIZED,
task_timeout=60,
output_formats=["json"],
output_directory="./reports/examples"
)
# Create engine
engine = RealBenchmarkEngine(config)
# Run benchmark
result = await engine.run_benchmark("Create a function to calculate fibonacci numbers")
print(f"\nBenchmark ID: {result['benchmark_id']}")
print(f"Status: {result['status']}")
print(f"Duration: {result.get('duration', 0):.2f}s")
return result
async def example_sparc_mode_comparison():
"""Example 2: Compare different SPARC modes"""
print("\n" + "="*60)
print("Example 2: SPARC Mode Comparison")
print("="*60)
objective = "Create a REST API endpoint for user management"
modes_to_test = ["coder", "architect", "tdd", "reviewer"]
results = {}
for mode in modes_to_test:
print(f"\nTesting SPARC mode: {mode}")
config = BenchmarkConfig(
name=f"sparc-{mode}-test",
task_timeout=45
)
engine = RealBenchmarkEngine(config)
# Execute SPARC mode
result = await engine._execute_sparc_mode(mode, objective)
results[mode] = result
print(f" Success: {result['success']}")
print(f" Duration: {result['duration']:.2f}s")
if 'resource_usage' in result:
print(f" CPU: {result['resource_usage'].get('avg_cpu_percent', 0):.1f}%")
print(f" Memory: {result['resource_usage'].get('peak_memory_mb', 0):.1f} MB")
return results
async def example_swarm_strategies():
"""Example 3: Test different swarm strategies"""
print("\n" + "="*60)
print("Example 3: Swarm Strategy Testing")
print("="*60)
objective = "Build a data processing pipeline"
# Define test configurations
test_configs = [
{
"strategy": StrategyType.DEVELOPMENT,
"mode": CoordinationMode.HIERARCHICAL,
"description": "Development with hierarchical coordination"
},
{
"strategy": StrategyType.RESEARCH,
"mode": CoordinationMode.DISTRIBUTED,
"description": "Research with distributed coordination"
},
{
"strategy": StrategyType.OPTIMIZATION,
"mode": CoordinationMode.HYBRID,
"description": "Optimization with hybrid coordination"
}
]
results = []
for config_def in test_configs:
print(f"\n📋 {config_def['description']}")
config = BenchmarkConfig(
name=f"swarm-{config_def['strategy'].value}",
strategy=config_def['strategy'],
mode=config_def['mode'],
max_agents=5,
parallel=True,
monitoring=True,
task_timeout=90
)
engine = RealBenchmarkEngine(config)
result = await engine.run_benchmark(objective)
results.append({
"config": config_def['description'],
"result": result
})
print(f" Status: {result['status']}")
print(f" Duration: {result.get('duration', 0):.2f}s")
return results
async def example_parallel_benchmarking():
"""Example 4: Parallel task execution"""
print("\n" + "="*60)
print("Example 4: Parallel Task Benchmarking")
print("="*60)
config = BenchmarkConfig(
name="parallel-benchmark",
parallel=True,
max_agents=4,
task_timeout=60,
monitoring=True
)
engine = RealBenchmarkEngine(config)
# Create multiple tasks
tasks = [
Task(
objective="Create a user authentication module",
strategy=StrategyType.DEVELOPMENT,
mode=CoordinationMode.CENTRALIZED
),
Task(
objective="Research best practices for API security",
strategy=StrategyType.RESEARCH,
mode=CoordinationMode.DISTRIBUTED
),
Task(
objective="Analyze code for performance bottlenecks",
strategy=StrategyType.ANALYSIS,
mode=CoordinationMode.MESH
),
Task(
objective="Generate comprehensive test suite",
strategy=StrategyType.TESTING,
mode=CoordinationMode.HIERARCHICAL
)
]
print(f"Executing {len(tasks)} tasks in parallel...")
# Execute batch
results = await engine.execute_batch(tasks)
# Analyze results
successful = sum(1 for r in results if r.status.value == "success")
total_time = sum(r.performance_metrics.execution_time for r in results)
print(f"\n📊 Results:")
print(f" Successful: {successful}/{len(tasks)}")
print(f" Total execution time: {total_time:.2f}s")
print(f" Average time per task: {total_time/len(tasks):.2f}s")
for i, result in enumerate(results):
print(f"\n Task {i+1}: {tasks[i].objective[:50]}...")
print(f" Status: {result.status.value}")
print(f" Duration: {result.performance_metrics.execution_time:.2f}s")
print(f" Quality: {result.quality_metrics.overall_quality:.2f}")
return results
async def example_comprehensive_mode_testing():
"""Example 5: Test all modes comprehensively"""
print("\n" + "="*60)
print("Example 5: Comprehensive Mode Testing")
print("="*60)
config = BenchmarkConfig(
name="comprehensive-test",
task_timeout=30, # Shorter timeout for comprehensive testing
output_formats=["json", "sqlite"],
monitoring=True
)
engine = RealBenchmarkEngine(config)
# Note: This is resource-intensive!
print("⚠️ This will test all SPARC modes and swarm strategies")
print(" This may take several minutes to complete...")
# For demo, we'll test a subset
objective = "Create a simple calculator application"
# Test subset of SPARC modes
sparc_modes = ["coder", "reviewer", "tester"]
sparc_results = {}
for mode in sparc_modes:
print(f"\n Testing SPARC {mode}...")
result = await engine._execute_sparc_mode(mode, objective)
sparc_results[mode] = result
# Test subset of swarm combinations
swarm_configs = [
(StrategyType.AUTO, CoordinationMode.CENTRALIZED),
(StrategyType.DEVELOPMENT, CoordinationMode.HIERARCHICAL),
(StrategyType.TESTING, CoordinationMode.DISTRIBUTED)
]
swarm_results = {}
for strategy, mode in swarm_configs:
print(f"\n Testing Swarm {strategy.value}/{mode.value}...")
task = Task(
objective=objective,
strategy=strategy,
mode=mode
)
result = await engine._execute_real_task(task)
swarm_results[f"{strategy.value}_{mode.value}"] = {
"success": result.status.value == "success",
"duration": result.performance_metrics.execution_time,
"quality": result.quality_metrics.overall_quality
}
return {
"sparc_modes": sparc_results,
"swarm_strategies": swarm_results
}
async def example_resource_monitoring():
"""Example 6: Detailed resource monitoring"""
print("\n" + "="*60)
print("Example 6: Resource Monitoring")
print("="*60)
# Create system monitor
system_monitor = SystemMonitor()
# Take baseline
baseline = system_monitor.take_measurement()
print(f"Baseline CPU: {baseline['cpu_percent']:.1f}%")
print(f"Baseline Memory: {baseline['memory_percent']:.1f}%")
# Configure with monitoring
config = BenchmarkConfig(
name="resource-monitor-test",
monitoring=True,
task_timeout=60,
resource_limits={
"max_memory_mb": 512,
"max_cpu_percent": 75
}
)
engine = RealBenchmarkEngine(config)
# Run intensive task
print("\nExecuting resource-intensive task...")
result = await engine.run_benchmark("Analyze a large codebase for complexity metrics")
# Take final measurement
final = system_monitor.take_measurement()
# Get summary
summary = system_monitor.get_summary()
print(f"\n📊 Resource Usage Summary:")
print(f" Average CPU: {summary['avg_cpu']:.1f}%")
print(f" Peak CPU: {summary['max_cpu']:.1f}%")
print(f" Average Memory: {summary['avg_memory']:.1f}%")
print(f" Peak Memory: {summary['max_memory']:.1f}%")
# Process-specific metrics from result
if result.get('results'):
process_metrics = result['results'][0].get('resource_usage', {})
print(f"\n📈 Process Metrics:")
print(f" Process CPU: {process_metrics.get('average_cpu_percent', 0):.1f}%")
print(f" Process Memory: {process_metrics.get('peak_memory_mb', 0):.1f} MB")
return {
"system_summary": summary,
"benchmark_result": result
}
async def main():
"""Run all examples"""
print("🚀 Real Claude-Flow Benchmark Examples")
examples = [
("Simple Benchmark", example_simple_benchmark),
("SPARC Mode Comparison", example_sparc_mode_comparison),
("Swarm Strategies", example_swarm_strategies),
("Parallel Benchmarking", example_parallel_benchmarking),
("Comprehensive Testing", example_comprehensive_mode_testing),
("Resource Monitoring", example_resource_monitoring)
]
all_results = {}
for name, example_func in examples:
try:
print(f"\n{'='*60}")
print(f"Running: {name}")
print('='*60)
result = await example_func()
all_results[name] = {
"status": "success",
"result": result
}
except Exception as e:
print(f"\n❌ Example '{name}' failed: {e}")
all_results[name] = {
"status": "failed",
"error": str(e)
}
# Save all results
output_file = Path("reports/examples/all_examples_results.json")
output_file.parent.mkdir(parents=True, exist_ok=True)
with open(output_file, "w") as f:
json.dump(all_results, f, indent=2, default=str)
print(f"\n\n💾 All results saved to: {output_file}")
# Summary
successful = sum(1 for r in all_results.values() if r["status"] == "success")
print(f"\n📊 Summary: {successful}/{len(examples)} examples completed successfully")
if __name__ == "__main__":
# Create output directories
Path("reports/examples").mkdir(parents=True, exist_ok=True)
Path("test_output/real_benchmarks").mkdir(parents=True, exist_ok=True)
# Run examples
asyncio.run(main())
@@ -1,191 +0,0 @@
#!/usr/bin/env python3
"""
Real Hive-Mind Benchmark Example - Execute and measure real hive-mind performance.
This example demonstrates how to:
1. Execute real Claude Flow hive-mind commands
2. Measure collective intelligence performance
3. Parse real distributed agent responses
4. Track swarm coordination metrics
Usage:
python real_hive_mind_benchmark.py [task_description]
"""
import sys
import json
import argparse
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from swarm_benchmark.scenarios.real_benchmarks import RealHiveMindBenchmark, RealBenchmarkResult
def run_hive_mind_benchmark(task: str, mode: str = "consensus", agents: int = 8) -> RealBenchmarkResult:
"""
Run a real hive-mind benchmark.
Args:
task: Task description
mode: Collective intelligence mode
agents: Number of agents
Returns:
RealBenchmarkResult with actual metrics
"""
print(f"🧠 Starting Real Hive-Mind Benchmark")
print(f" Task: {task}")
print(f" Mode: {mode}")
print(f" Agents: {agents}")
print("-" * 60)
# Initialize benchmark
benchmark = RealHiveMindBenchmark()
# Execute real hive-mind
result = benchmark.executor.execute_hive_mind(
task=task,
collective_mode=mode,
agent_count=agents,
timeout=15
)
# Display results
print(f"✅ Hive-Mind Benchmark Complete!")
print(f" Success: {result.success}")
print(f" Execution Time: {result.execution_time:.2f}s")
print(f" Tokens Used: {result.tokens_used}")
print(f" Agents Spawned: {result.agents_spawned}")
print(f" Memory Usage: {result.memory_usage_mb:.2f} MB")
print(f" CPU Usage: {result.cpu_usage_percent:.1f}%")
print(f" Output Size: {result.output_size_bytes} bytes")
print(f" Errors: {result.error_count}")
print(f" Warnings: {result.warning_count}")
if result.stdout_excerpt:
print(f"\n📋 Collective Output Excerpt:")
print(result.stdout_excerpt)
if result.stderr_excerpt and result.error_count > 0:
print(f"\n❌ Error Excerpt:")
print(result.stderr_excerpt)
# Display raw metrics if available
if result.metrics_raw:
print(f"\n📊 Raw Metrics:")
for key, value in result.metrics_raw.items():
print(f" {key}: {value}")
return result
def run_collective_intelligence_suite():
"""Run comprehensive collective intelligence benchmark suite."""
print("🔥 Running Collective Intelligence Benchmark Suite")
print("=" * 60)
benchmark_configs = [
("Design a distributed system architecture", "consensus", 6),
("Solve complex optimization problem: traveling salesman with 20 cities", "collective-intelligence", 10),
("Collaborate on comprehensive code review", "memory-shared", 8),
("Brainstorm innovative AI applications", "divergent-thinking", 12),
("Analyze market trends for cryptocurrency", "research-swarm", 8),
("Optimize neural network hyperparameters", "optimization-collective", 6)
]
results = []
for i, (task, mode, agents) in enumerate(benchmark_configs, 1):
print(f"\n🎯 Collective Intelligence Test {i}/{len(benchmark_configs)}")
result = run_hive_mind_benchmark(task, mode, agents)
results.append(result)
print("=" * 60)
# Save comprehensive results
output_file = Path("real_hive_mind_benchmark_results.json")
with open(output_file, 'w') as f:
json.dump([r.to_dict() for r in results], f, indent=2)
print(f"\n💾 Results saved to: {output_file}")
# Collective intelligence metrics
total_time = sum(r.execution_time for r in results)
total_tokens = sum(r.tokens_used for r in results)
total_agents = sum(r.agents_spawned for r in results)
success_rate = sum(1 for r in results if r.success) / len(results) * 100
avg_agents_per_task = total_agents / len(results)
print(f"\n📊 Collective Intelligence Summary:")
print(f" Total Execution Time: {total_time:.2f}s")
print(f" Total Tokens Used: {total_tokens}")
print(f" Total Agents Spawned: {total_agents}")
print(f" Success Rate: {success_rate:.1f}%")
print(f" Average Agents per Task: {avg_agents_per_task:.1f}")
print(f" Average Time per Task: {total_time/len(results):.2f}s")
print(f" Collective Efficiency: {total_tokens/total_time:.1f} tokens/sec")
def run_swarm_memory_benchmark():
"""Benchmark swarm with shared memory capabilities."""
print("🧬 Running Swarm Memory Benchmark")
print("=" * 60)
memory_tasks = [
"Maintain shared knowledge base while solving multi-step math problems",
"Coordinate distributed file processing with shared state",
"Collaborate on building comprehensive documentation with memory persistence",
"Execute parallel research tasks with knowledge sharing"
]
results = []
for i, task in enumerate(memory_tasks, 1):
print(f"\n🎯 Memory Test {i}/{len(memory_tasks)}")
result = run_hive_mind_benchmark(task, "memory-shared", 6)
results.append(result)
print("=" * 60)
# Analyze memory performance
avg_time = sum(r.execution_time for r in results) / len(results)
avg_memory = sum(r.memory_usage_mb for r in results) / len(results)
success_rate = sum(1 for r in results if r.success) / len(results) * 100
print(f"\n🧬 Memory Performance Analysis:")
print(f" Average Execution Time: {avg_time:.2f}s")
print(f" Average Memory Usage: {avg_memory:.2f} MB")
print(f" Memory Success Rate: {success_rate:.1f}%")
return results
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="Real Hive-Mind Benchmark Example")
parser.add_argument("task", nargs="?",
default="Design a scalable microservices architecture for e-commerce platform",
help="Task description for the hive-mind")
parser.add_argument("--mode", default="consensus",
choices=["consensus", "collective-intelligence", "memory-shared",
"divergent-thinking", "research-swarm", "optimization-collective"],
help="Collective intelligence mode")
parser.add_argument("--agents", type=int, default=8,
help="Number of agents in the hive-mind")
parser.add_argument("--suite", action="store_true",
help="Run comprehensive collective intelligence suite")
parser.add_argument("--memory", action="store_true",
help="Run swarm memory benchmark")
args = parser.parse_args()
if args.suite:
run_collective_intelligence_suite()
elif args.memory:
run_swarm_memory_benchmark()
else:
run_hive_mind_benchmark(args.task, args.mode, args.agents)
if __name__ == "__main__":
main()
@@ -1,78 +0,0 @@
{
"timestamp": 1754447040.1255798,
"verification_results": [
{
"test_name": "Version Check",
"success": true,
"duration": 0.002352476119995117,
"command": "/workspaces/claude-code-flow/bin/claude-flow --version",
"json_responses_count": 0,
"metrics": {
"output_lines": 2,
"error_lines": 1,
"json_responses_count": 0,
"agents_detected": 0,
"tasks_detected": 0,
"errors_detected": 0,
"memory_operations": 0,
"response_types": {}
}
},
{
"test_name": "Help Command",
"success": true,
"duration": 0.30375146865844727,
"command": "/workspaces/claude-code-flow/bin/claude-flow --help",
"json_responses_count": 1,
"metrics": {
"output_lines": 83,
"error_lines": 1,
"json_responses_count": 1,
"agents_detected": 1,
"tasks_detected": 0,
"errors_detected": 0,
"memory_operations": 0,
"response_types": {
"structured_output": 1
}
}
},
{
"test_name": "Simple Swarm",
"success": false,
"duration": 20.00809097290039,
"command": "/workspaces/claude-code-flow/bin/claude-flow swarm echo 'Hello World' --non-interactive --timeout 10",
"json_responses_count": 9,
"metrics": {
"output_lines": 19,
"error_lines": 1,
"json_responses_count": 9,
"agents_detected": 5,
"tasks_detected": 0,
"errors_detected": 1,
"memory_operations": 3,
"response_types": {
"system": 1,
"assistant": 8
}
}
},
{
"test_name": "SPARC Coder Mode",
"success": true,
"duration": 0.29969286918640137,
"command": "/workspaces/claude-code-flow/bin/claude-flow sparc coder print('Hello from SPARC') --non-interactive --timeout 15",
"json_responses_count": 0,
"metrics": {
"output_lines": 6,
"error_lines": 1,
"json_responses_count": 0,
"agents_detected": 0,
"tasks_detected": 0,
"errors_detected": 0,
"memory_operations": 0,
"response_types": {}
}
}
]
}
-238
View File
@@ -1,238 +0,0 @@
#!/usr/bin/env python3
"""Demonstration of real metrics collection for claude-flow benchmarks."""
import asyncio
import json
from pathlib import Path
import sys
# Add the src directory to the path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from swarm_benchmark.metrics.performance_collector import PerformanceCollector, AsyncPerformanceCollector
from swarm_benchmark.metrics.resource_monitor import ResourceMonitor, SystemResourceMonitor
from swarm_benchmark.metrics.process_tracker import ProcessTracker
from swarm_benchmark.metrics.metrics_aggregator import MetricsAggregator
async def demo_performance_collection():
"""Demonstrate performance metrics collection."""
print("\n=== Performance Metrics Collection Demo ===\n")
# Create async collector
collector = AsyncPerformanceCollector(sample_interval=0.05)
# Simulate a process
import subprocess
process = subprocess.Popen(
["python", "-c", "import time; time.sleep(2); print('Done')"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# Collect metrics for the duration
metrics = await collector.collect_for_duration(2.5, process)
print(f"Execution time: {metrics.execution_time:.2f}s")
print(f"Throughput: {metrics.throughput:.4f} tasks/s")
# Get detailed metrics
detailed = collector.get_detailed_metrics()
print(f"\nDetailed Metrics:")
print(f" Sample count: {detailed['summary']['sample_count']}")
print(f" Process count: {detailed['summary']['process_count']}")
# Save raw metrics
Path("./examples/output").mkdir(exist_ok=True, parents=True)
collector.save_raw_metrics(Path("./examples/output/performance_metrics.json"))
print(" Raw metrics saved to: ./examples/output/performance_metrics.json")
def demo_resource_monitoring():
"""Demonstrate resource monitoring."""
print("\n=== Resource Monitoring Demo ===\n")
# Create monitor with alert callback
def alert_handler(alert):
print(f"⚠️ ALERT: {alert.message}")
monitor = ResourceMonitor(alert_callback=alert_handler)
# Set custom thresholds
monitor.set_thresholds({
"cpu_percent": 50.0,
"memory_mb": 100.0
})
# Start monitoring current process
monitor.start_monitoring()
# Simulate some work
print("Simulating CPU-intensive work...")
import time
start = time.time()
while time.time() - start < 2:
# CPU-intensive calculation
sum(i * i for i in range(1000000))
# Stop and get results
usage = monitor.stop_monitoring()
stats = monitor.get_statistics()
print(f"\nResource Usage Summary:")
print(f" Average CPU: {usage.average_cpu_percent:.1f}%")
print(f" Peak memory: {usage.peak_memory_mb:.1f} MB")
print(f" Average memory: {usage.memory_mb:.1f} MB")
print(f"\nStatistics:")
print(f" CPU mean: {stats['cpu']['mean']:.1f}%")
print(f" CPU max: {stats['cpu']['max']:.1f}%")
print(f" Memory peak: {stats['memory_mb']['max']:.1f} MB")
print(f" Total alerts: {stats['alerts']}")
async def demo_process_tracking():
"""Demonstrate process tracking."""
print("\n=== Process Tracking Demo ===\n")
tracker = ProcessTracker("claude-flow")
# Execute various commands
commands = [
(["--version"], 5),
(["status"], 10),
(["sparc", "--help"], 10)
]
for cmd, timeout in commands:
print(f"\nExecuting: claude-flow {' '.join(cmd)}")
result = await tracker.execute_command_async(cmd, timeout=timeout)
print(f" Exit code: {result.exit_code}")
print(f" Duration: {result.duration:.2f}s")
print(f" Memory: {result.resource_usage.peak_memory_mb:.1f} MB")
print(f" Output lines: {result.output_size}")
if result.stderr:
print(f" Errors: {result.error_count}")
# Show command statistics
stats = tracker.get_command_statistics()
summary = tracker.get_execution_summary()
print(f"\nExecution Summary:")
print(f" Total executions: {summary['total_executions']}")
print(f" Success rate: {summary['overall_success_rate']:.1%}")
print(f" Average duration: {summary['average_duration']:.2f}s")
print(f" Peak memory: {summary['peak_memory_mb']:.1f} MB")
# Save report
tracker.save_execution_report(Path("./examples/output/process_report.json"))
print("\n Process report saved to: ./examples/output/process_report.json")
async def demo_metrics_aggregation():
"""Demonstrate comprehensive metrics aggregation."""
print("\n=== Metrics Aggregation Demo ===\n")
aggregator = MetricsAggregator()
aggregator.start_collection()
# Create multiple collectors
perf1 = aggregator.create_performance_collector("task1")
perf2 = aggregator.create_performance_collector("task2")
res1 = aggregator.create_resource_monitor("agent1")
res2 = aggregator.create_resource_monitor("agent2")
# Get process tracker
tracker = aggregator.get_process_tracker()
# Simulate parallel task execution
print("Simulating parallel task execution...")
# Start monitoring
perf1.start_collection()
res1.start_monitoring()
# Execute first command
result1 = await tracker.execute_command_async(["status"], timeout=5)
# Stop first task monitoring
perf1.stop_collection()
res1.stop_monitoring()
# Start second task
perf2.start_collection()
res2.start_monitoring()
# Execute second command
result2 = await tracker.execute_command_async(["sparc", "--list"], timeout=5)
# Stop second task monitoring
perf2.stop_collection()
res2.stop_monitoring()
# Get aggregated metrics
aggregated = aggregator.stop_collection()
print(f"\nAggregated Metrics:")
print(f" Wall clock time: {aggregated.wall_clock_time:.2f}s")
print(f" Total processes: {aggregated.total_processes}")
print(f" Success rate: {aggregated.success_rate:.1%}")
print(f" Peak memory: {aggregated.peak_memory_mb:.1f} MB")
print(f" Average CPU: {aggregated.average_cpu_percent:.1f}%")
print(f" Output complexity: {aggregated.output_complexity_score:.2f} lines/s")
# Save detailed report
aggregator.save_detailed_report(Path("./examples/output/aggregated_metrics.json"))
print("\n Detailed report saved to: ./examples/output/aggregated_metrics.json")
def demo_system_monitoring():
"""Demonstrate system-wide resource monitoring."""
print("\n=== System Resource Monitoring Demo ===\n")
monitor = SystemResourceMonitor()
# Take baseline
baseline = monitor.take_baseline()
print("System baseline:")
print(f" CPU: {baseline['cpu_percent']:.1f}%")
print(f" Memory available: {baseline['memory_available_mb']:.1f} MB")
print(f" Memory usage: {baseline['memory_percent']:.1f}%")
# Simulate some work
print("\nSimulating workload...")
import time
time.sleep(2)
# Measure delta
delta = monitor.measure_delta()
print(f"\nResource changes over {delta['duration_seconds']:.1f}s:")
print(f" CPU delta: {delta['cpu_percent_delta']:+.1f}%")
print(f" Memory delta: {delta['memory_percent_delta']:+.1f}%")
print(f" Disk read: {delta['disk_read_mb']:.2f} MB")
print(f" Disk write: {delta['disk_write_mb']:.2f} MB")
print(f" Network sent: {delta['network_sent_mb']:.2f} MB")
print(f" Network received: {delta['network_recv_mb']:.2f} MB")
async def main():
"""Run all demonstrations."""
print("Claude-Flow Real Metrics Collection Demonstration")
print("=" * 60)
# Run each demo
await demo_performance_collection()
demo_resource_monitoring()
await demo_process_tracking()
await demo_metrics_aggregation()
demo_system_monitoring()
print("\n" + "=" * 60)
print("Demonstration completed!")
print("\nCheck the ./examples/output/ directory for saved metrics reports.")
if __name__ == "__main__":
asyncio.run(main())
-228
View File
@@ -1,228 +0,0 @@
#!/usr/bin/env python3
"""
Real SPARC Benchmark Example - Execute and measure real SPARC mode performance.
This example demonstrates how to:
1. Execute real Claude Flow SPARC modes
2. Measure specialized agent performance
3. Parse real SPARC execution responses
4. Track mode-specific metrics
Usage:
python real_sparc_benchmark.py [mode] [task_description]
"""
import sys
import json
import argparse
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from swarm_benchmark.scenarios.real_benchmarks import RealSparcBenchmark, RealBenchmarkResult
def run_sparc_benchmark(mode: str, task: str, timeout: int = 10) -> RealBenchmarkResult:
"""
Run a real SPARC benchmark.
Args:
mode: SPARC mode to execute
task: Task description
timeout: Timeout in minutes
Returns:
RealBenchmarkResult with actual metrics
"""
print(f"⚡ Starting Real SPARC Benchmark")
print(f" Mode: {mode}")
print(f" Task: {task}")
print(f" Timeout: {timeout}m")
print("-" * 60)
# Initialize benchmark
benchmark = RealSparcBenchmark()
# Execute real SPARC mode
result = benchmark.executor.execute_sparc_mode(
mode=mode,
task=task,
timeout=timeout
)
# Display results
print(f"✅ SPARC Benchmark Complete!")
print(f" Success: {result.success}")
print(f" Execution Time: {result.execution_time:.2f}s")
print(f" Tokens Used: {result.tokens_used}")
print(f" Agents Spawned: {result.agents_spawned}")
print(f" Memory Usage: {result.memory_usage_mb:.2f} MB")
print(f" CPU Usage: {result.cpu_usage_percent:.1f}%")
print(f" Output Size: {result.output_size_bytes} bytes")
print(f" Errors: {result.error_count}")
print(f" Warnings: {result.warning_count}")
if result.stdout_excerpt:
print(f"\n📋 SPARC Output Excerpt:")
print(result.stdout_excerpt)
if result.stderr_excerpt and result.error_count > 0:
print(f"\n❌ Error Excerpt:")
print(result.stderr_excerpt)
# Display command executed
if result.command_executed:
print(f"\n🔧 Command Executed:")
print(f" {' '.join(result.command_executed)}")
return result
def run_sparc_mode_suite():
"""Run comprehensive SPARC mode benchmark suite."""
print("🔥 Running SPARC Mode Benchmark Suite")
print("=" * 60)
sparc_scenarios = [
("coder", "Implement user authentication system with JWT tokens", 12),
("tdd", "Create payment processing module with comprehensive tests", 15),
("architect", "Design microservices architecture for social media platform", 10),
("optimizer", "Optimize database queries and API response times", 8),
("researcher", "Research latest trends in AI and machine learning", 10),
("reviewer", "Conduct comprehensive code review of REST API", 8),
("analyzer", "Analyze system performance and identify bottlenecks", 10),
("designer", "Design user interface for mobile application", 12),
("documenter", "Create comprehensive API documentation", 8),
("debugger", "Debug and fix complex application issues", 10),
("tester", "Create automated test suite for web application", 10),
("innovator", "Brainstorm innovative features for productivity app", 8)
]
results = []
for i, (mode, task, timeout) in enumerate(sparc_scenarios, 1):
print(f"\n🎯 SPARC Mode Test {i}/{len(sparc_scenarios)}")
result = run_sparc_benchmark(mode, task, timeout)
results.append(result)
print("=" * 60)
# Save comprehensive results
output_file = Path("real_sparc_benchmark_results.json")
with open(output_file, 'w') as f:
json.dump([r.to_dict() for r in results], f, indent=2)
print(f"\n💾 Results saved to: {output_file}")
# SPARC performance analysis
total_time = sum(r.execution_time for r in results)
total_tokens = sum(r.tokens_used for r in results)
success_rate = sum(1 for r in results if r.success) / len(results) * 100
# Mode-specific analysis
mode_performance = {}
for result in results:
mode = result.benchmark_name.replace("sparc_", "")
if mode not in mode_performance:
mode_performance[mode] = {
"count": 0,
"total_time": 0,
"total_tokens": 0,
"successes": 0
}
mode_performance[mode]["count"] += 1
mode_performance[mode]["total_time"] += result.execution_time
mode_performance[mode]["total_tokens"] += result.tokens_used
if result.success:
mode_performance[mode]["successes"] += 1
print(f"\n📊 SPARC Mode Performance Summary:")
print(f" Total Execution Time: {total_time:.2f}s")
print(f" Total Tokens Used: {total_tokens}")
print(f" Overall Success Rate: {success_rate:.1f}%")
print(f" Average Time per Mode: {total_time/len(results):.2f}s")
print(f" Token Efficiency: {total_tokens/total_time:.1f} tokens/sec")
print(f"\n🎯 Per-Mode Performance:")
for mode, perf in mode_performance.items():
avg_time = perf["total_time"] / perf["count"]
avg_tokens = perf["total_tokens"] / perf["count"]
success_rate = perf["successes"] / perf["count"] * 100
print(f" {mode:12} | Time: {avg_time:6.2f}s | Tokens: {avg_tokens:6.0f} | Success: {success_rate:5.1f}%")
def run_development_workflow_benchmark():
"""Benchmark complete development workflow using SPARC modes."""
print("🚀 Running Development Workflow Benchmark")
print("=" * 60)
workflow_steps = [
("architect", "Design RESTful API for task management system", 8),
("coder", "Implement user authentication endpoints", 10),
("tdd", "Create comprehensive tests for authentication", 8),
("reviewer", "Review authentication implementation", 6),
("optimizer", "Optimize authentication performance", 6),
("documenter", "Document authentication API endpoints", 6),
("tester", "Run integration tests for complete workflow", 8)
]
results = []
workflow_start = None
for i, (mode, task, timeout) in enumerate(workflow_steps, 1):
if i == 1:
import time
workflow_start = time.time()
print(f"\n🎯 Workflow Step {i}/{len(workflow_steps)}")
result = run_sparc_benchmark(mode, task, timeout)
results.append(result)
print("=" * 60)
total_workflow_time = sum(r.execution_time for r in results)
# Save workflow results
output_file = Path("development_workflow_benchmark_results.json")
with open(output_file, 'w') as f:
json.dump([r.to_dict() for r in results], f, indent=2)
print(f"\n🚀 Development Workflow Complete!")
print(f" Total Workflow Time: {total_workflow_time:.2f}s")
print(f" Steps Completed: {len(results)}")
print(f" Success Rate: {sum(1 for r in results if r.success)/len(results)*100:.1f}%")
print(f" Average Step Time: {total_workflow_time/len(results):.2f}s")
print(f" Results saved to: {output_file}")
return results
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="Real SPARC Benchmark Example")
parser.add_argument("mode", nargs="?", default="coder",
choices=["coder", "tdd", "architect", "optimizer", "researcher",
"reviewer", "analyzer", "designer", "documenter",
"debugger", "tester", "innovator"],
help="SPARC mode to execute")
parser.add_argument("task", nargs="?",
default="Create a simple web API with authentication",
help="Task description")
parser.add_argument("--timeout", type=int, default=10,
help="Timeout in minutes")
parser.add_argument("--suite", action="store_true",
help="Run comprehensive SPARC mode suite")
parser.add_argument("--workflow", action="store_true",
help="Run development workflow benchmark")
args = parser.parse_args()
if args.suite:
run_sparc_mode_suite()
elif args.workflow:
run_development_workflow_benchmark()
else:
run_sparc_benchmark(args.mode, args.task, args.timeout)
if __name__ == "__main__":
main()
-146
View File
@@ -1,146 +0,0 @@
#!/usr/bin/env python3
"""
Real Swarm Benchmark Example - Execute and measure real swarm performance.
This example demonstrates how to:
1. Execute real Claude Flow swarm commands
2. Measure actual performance metrics
3. Parse real JSON streaming responses
4. Track token usage from actual Claude responses
Usage:
python real_swarm_benchmark.py [task_description]
"""
import sys
import json
import argparse
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from swarm_benchmark.scenarios.real_benchmarks import RealSwarmBenchmark, RealBenchmarkResult
def run_swarm_benchmark(task: str, strategy: str = "auto", mode: str = "hierarchical") -> RealBenchmarkResult:
"""
Run a real swarm benchmark.
Args:
task: Task description
strategy: Execution strategy
mode: Coordination mode
Returns:
RealBenchmarkResult with actual metrics
"""
print(f"🚀 Starting Real Swarm Benchmark")
print(f" Task: {task}")
print(f" Strategy: {strategy}")
print(f" Mode: {mode}")
print("-" * 60)
# Initialize benchmark
benchmark = RealSwarmBenchmark()
# Execute real swarm
result = benchmark.executor.execute_swarm(
objective=task,
strategy=strategy,
mode=mode,
max_agents=5,
timeout=10,
non_interactive=True
)
# Display results
print(f"✅ Benchmark Complete!")
print(f" Success: {result.success}")
print(f" Execution Time: {result.execution_time:.2f}s")
print(f" Tokens Used: {result.tokens_used}")
print(f" Agents Spawned: {result.agents_spawned}")
print(f" Memory Usage: {result.memory_usage_mb:.2f} MB")
print(f" CPU Usage: {result.cpu_usage_percent:.1f}%")
print(f" Output Size: {result.output_size_bytes} bytes")
print(f" Errors: {result.error_count}")
print(f" Warnings: {result.warning_count}")
if result.stdout_excerpt:
print(f"\n📋 Output Excerpt:")
print(result.stdout_excerpt)
if result.stderr_excerpt and result.error_count > 0:
print(f"\n❌ Error Excerpt:")
print(result.stderr_excerpt)
return result
def run_multiple_benchmarks():
"""Run multiple swarm benchmarks with different configurations."""
print("🔥 Running Multiple Real Swarm Benchmarks")
print("=" * 60)
benchmark_configs = [
("Create a REST API for user management", "development", "centralized"),
("Analyze system performance bottlenecks", "analysis", "distributed"),
("Research modern web development frameworks", "research", "mesh"),
("Optimize database query performance", "optimization", "hierarchical"),
("Test API endpoint functionality", "testing", "hybrid")
]
results = []
for i, (task, strategy, mode) in enumerate(benchmark_configs, 1):
print(f"\n🎯 Benchmark {i}/{len(benchmark_configs)}")
result = run_swarm_benchmark(task, strategy, mode)
results.append(result)
print("=" * 60)
# Save comprehensive results
output_file = Path("real_swarm_benchmark_results.json")
with open(output_file, 'w') as f:
json.dump([r.to_dict() for r in results], f, indent=2)
print(f"\n💾 Results saved to: {output_file}")
# Summary statistics
total_time = sum(r.execution_time for r in results)
total_tokens = sum(r.tokens_used for r in results)
total_agents = sum(r.agents_spawned for r in results)
success_rate = sum(1 for r in results if r.success) / len(results) * 100
print(f"\n📊 Summary Statistics:")
print(f" Total Execution Time: {total_time:.2f}s")
print(f" Total Tokens Used: {total_tokens}")
print(f" Total Agents Spawned: {total_agents}")
print(f" Success Rate: {success_rate:.1f}%")
print(f" Average Time per Benchmark: {total_time/len(results):.2f}s")
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="Real Swarm Benchmark Example")
parser.add_argument("task", nargs="?",
default="Create a simple web application with authentication",
help="Task description for the swarm")
parser.add_argument("--strategy", default="auto",
choices=["auto", "development", "research", "analysis", "testing", "optimization"],
help="Execution strategy")
parser.add_argument("--mode", default="hierarchical",
choices=["centralized", "distributed", "hierarchical", "mesh", "hybrid"],
help="Coordination mode")
parser.add_argument("--multiple", action="store_true",
help="Run multiple benchmark scenarios")
args = parser.parse_args()
if args.multiple:
run_multiple_benchmarks()
else:
run_swarm_benchmark(args.task, args.strategy, args.mode)
if __name__ == "__main__":
main()
@@ -1,408 +0,0 @@
#!/usr/bin/env python3
"""
Real Claude Flow Integration Verification
Demonstrates real command execution with JSON streaming output parsing.
"""
import subprocess
import time
import json
import os
import sys
from pathlib import Path
from typing import Dict, List, Any, Optional
from dataclasses import dataclass
import threading
import queue
@dataclass
class RealCommandResult:
"""Result from a real Claude Flow command execution."""
command: str
success: bool
duration: float
stdout: str
stderr: str
json_responses: List[Dict[str, Any]]
parsed_metrics: Dict[str, Any]
class RealIntegrationVerifier:
"""Verifier for real Claude Flow integration."""
def __init__(self):
"""Initialize the verifier."""
self.claude_flow_path = self._find_claude_flow()
print(f"🔍 Found claude-flow at: {self.claude_flow_path}")
# Verify installation
if not self._verify_installation():
raise RuntimeError("Claude Flow installation verification failed")
print("✅ Claude Flow installation verified")
def _find_claude_flow(self) -> str:
"""Find the claude-flow executable."""
# Common locations to check
possible_paths = [
# Binary directories (priority)
Path("/workspaces/claude-code-flow/bin/claude-flow"),
Path(__file__).parent.parent.parent.parent / "bin" / "claude-flow",
# Project root
Path("/workspaces/claude-code-flow/claude-flow"),
Path(__file__).parent.parent.parent.parent / "claude-flow",
Path(__file__).parent.parent.parent / "claude-flow",
Path.cwd() / "claude-flow",
# Distribution directory
Path(__file__).parent.parent.parent.parent / "dist" / "claude-flow",
]
for path in possible_paths:
if path.exists() and os.access(path, os.X_OK):
return str(path.resolve())
# Try system PATH
import shutil
system_path = shutil.which("claude-flow")
if system_path:
return system_path
raise FileNotFoundError(
"Could not find claude-flow executable. Please ensure it's built and accessible."
)
def _verify_installation(self) -> bool:
"""Verify claude-flow is properly installed."""
try:
result = subprocess.run(
[self.claude_flow_path, "--version"],
capture_output=True,
text=True,
timeout=10
)
if result.returncode == 0:
print(f"📝 Claude Flow Version: {result.stdout.strip()}")
return True
else:
print(f"❌ Version check failed: {result.stderr}")
return False
except Exception as e:
print(f"❌ Installation verification error: {e}")
return False
def parse_streaming_output(self, output: str) -> List[Dict[str, Any]]:
"""Parse streaming JSON output from claude-flow."""
json_responses = []
for line in output.split('\n'):
line = line.strip()
if not line:
continue
# Look for complete JSON objects
if line.startswith('{') and line.endswith('}'):
try:
json_obj = json.loads(line)
json_responses.append(json_obj)
except json.JSONDecodeError:
# Not valid JSON, skip
continue
# Look for stream-json markers
elif 'stream-json:' in line.lower():
try:
# Extract JSON part after marker
marker_pos = line.lower().find('stream-json:')
json_part = line[marker_pos + len('stream-json:'):].strip()
json_obj = json.loads(json_part)
json_responses.append(json_obj)
except (json.JSONDecodeError, ValueError):
continue
# Look for structured output patterns
elif any(marker in line.lower() for marker in ['agent:', 'task:', 'memory:', 'swarm:']):
# Create structured output for text patterns
json_responses.append({
"type": "structured_output",
"line": line,
"timestamp": time.time()
})
return json_responses
def extract_metrics(self, stdout: str, stderr: str, json_responses: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Extract performance and operational metrics."""
metrics = {
"output_lines": len(stdout.split('\n')),
"error_lines": len(stderr.split('\n')),
"json_responses_count": len(json_responses),
"agents_detected": 0,
"tasks_detected": 0,
"errors_detected": 0,
"memory_operations": 0,
"response_types": {}
}
# Analyze combined output
combined = (stdout + "\n" + stderr).lower()
# Count text-based indicators
for line in combined.split('\n'):
if 'agent' in line and ('spawn' in line or 'created' in line):
metrics["agents_detected"] += 1
if 'task' in line and ('complete' in line or 'finished' in line):
metrics["tasks_detected"] += 1
if 'error' in line or 'failed' in line:
metrics["errors_detected"] += 1
if 'memory' in line and ('store' in line or 'retrieve' in line):
metrics["memory_operations"] += 1
# Analyze JSON responses
for response in json_responses:
response_type = response.get('type', 'unknown')
metrics["response_types"][response_type] = metrics["response_types"].get(response_type, 0) + 1
# Specific type handling
if response_type == 'agent_spawned':
metrics["agents_detected"] += 1
elif response_type == 'task_completed':
metrics["tasks_detected"] += 1
elif response_type == 'error':
metrics["errors_detected"] += 1
elif response_type == 'memory_operation':
metrics["memory_operations"] += 1
return metrics
def execute_real_command(self, command_args: List[str], timeout: int = 30) -> RealCommandResult:
"""Execute a real claude-flow command and collect comprehensive metrics."""
full_command = [self.claude_flow_path] + command_args
command_str = ' '.join(full_command)
print(f"\n🚀 Executing: {command_str}")
print("-" * 60)
start_time = time.time()
try:
# Execute the command
result = subprocess.run(
full_command,
capture_output=True,
text=True,
timeout=timeout
)
duration = time.time() - start_time
success = result.returncode == 0
print(f"⏱️ Duration: {duration:.2f}s")
print(f"📊 Exit Code: {result.returncode}")
print(f"✅ Success: {success}")
# Parse JSON responses from output
json_responses = self.parse_streaming_output(result.stdout + "\n" + result.stderr)
# Extract metrics
metrics = self.extract_metrics(result.stdout, result.stderr, json_responses)
print(f"📈 JSON Responses: {len(json_responses)}")
print(f"🤖 Agents Detected: {metrics['agents_detected']}")
print(f"✅ Tasks Detected: {metrics['tasks_detected']}")
return RealCommandResult(
command=command_str,
success=success,
duration=duration,
stdout=result.stdout,
stderr=result.stderr,
json_responses=json_responses,
parsed_metrics=metrics
)
except subprocess.TimeoutExpired as e:
duration = time.time() - start_time
print(f"⏰ Command timed out after {duration:.2f}s")
stdout = e.stdout.decode() if e.stdout else ""
stderr = e.stderr.decode() if e.stderr else ""
json_responses = self.parse_streaming_output(stdout + "\n" + stderr)
metrics = self.extract_metrics(stdout, stderr, json_responses)
return RealCommandResult(
command=command_str,
success=False,
duration=duration,
stdout=stdout,
stderr=stderr,
json_responses=json_responses,
parsed_metrics=metrics
)
except Exception as e:
print(f"❌ Execution error: {e}")
return RealCommandResult(
command=command_str,
success=False,
duration=time.time() - start_time,
stdout="",
stderr=str(e),
json_responses=[],
parsed_metrics={"error": str(e)}
)
def demonstrate_json_streaming(self):
"""Demonstrate JSON streaming output parsing."""
print("\n" + "=" * 60)
print("🎯 JSON STREAMING DEMONSTRATION")
print("=" * 60)
# Sample JSON streaming output
sample_streaming = """
Agent initialization starting...
{"type": "agent_spawned", "id": "agent-1", "capabilities": ["research", "analysis"]}
Setting up swarm coordination...
stream-json: {"type": "swarm_status", "active_agents": 1, "mode": "centralized"}
Task assignment in progress...
{"type": "task_assigned", "task_id": "task-001", "agent_id": "agent-1"}
Processing research request...
stream-json: {"type": "progress_update", "percentage": 25, "stage": "research"}
Task completed successfully
{"type": "task_completed", "task_id": "task-001", "status": "success", "duration": 15.2}
"""
print("📝 Sample Streaming Output:")
print("-" * 40)
print(sample_streaming)
print("\n🔍 Parsing JSON Responses:")
print("-" * 40)
json_responses = self.parse_streaming_output(sample_streaming)
for i, response in enumerate(json_responses, 1):
print(f"{i}. Type: {response.get('type', 'unknown')}")
print(f" Data: {json.dumps(response, indent=2)}")
print()
print(f"📊 Total JSON responses parsed: {len(json_responses)}")
def run_verification_suite(self):
"""Run a suite of verification tests."""
print("\n" + "=" * 60)
print("🧪 REAL INTEGRATION VERIFICATION SUITE")
print("=" * 60)
tests = [
{
"name": "Version Check",
"command": ["--version"],
"timeout": 5,
"description": "Verify basic command execution"
},
{
"name": "Help Command",
"command": ["--help"],
"timeout": 5,
"description": "Test help output parsing"
},
{
"name": "Simple Swarm",
"command": ["swarm", "echo 'Hello World'", "--non-interactive", "--timeout", "10"],
"timeout": 20,
"description": "Test swarm command with JSON streaming"
},
{
"name": "SPARC Coder Mode",
"command": ["sparc", "coder", "print('Hello from SPARC')", "--non-interactive", "--timeout", "15"],
"timeout": 25,
"description": "Test SPARC mode execution"
}
]
results = []
for test in tests:
print(f"\n🧪 Test: {test['name']}")
print(f"📋 Description: {test['description']}")
result = self.execute_real_command(test['command'], test['timeout'])
results.append((test['name'], result))
# Show sample output
if result.stdout:
print(f"\n📤 Sample Output (first 200 chars):")
print(f" {result.stdout[:200]}...")
if result.json_responses:
print(f"\n🎯 JSON Responses Sample:")
for resp in result.json_responses[:2]: # Show first 2
print(f" - {resp.get('type', 'unknown')}: {json.dumps(resp, indent=4)}")
# Summary
print(f"\n" + "=" * 60)
print("📊 VERIFICATION SUMMARY")
print("=" * 60)
successful = sum(1 for name, result in results if result.success)
total = len(results)
print(f"✅ Successful Tests: {successful}/{total}")
print(f"⏱️ Total Duration: {sum(result.duration for _, result in results):.2f}s")
print(f"📈 Total JSON Responses: {sum(len(result.json_responses) for _, result in results)}")
for name, result in results:
status = "✅" if result.success else "❌"
print(f" {status} {name}: {result.duration:.2f}s")
return results
def main():
"""Main verification function."""
print("🔍 Claude Flow Real Integration Verification")
print("=" * 60)
try:
# Initialize verifier
verifier = RealIntegrationVerifier()
# Demonstrate JSON streaming parsing
verifier.demonstrate_json_streaming()
# Run verification suite
results = verifier.run_verification_suite()
# Save results
output_file = Path(__file__).parent / "real_integration_results.json"
with open(output_file, 'w') as f:
json.dump({
"timestamp": time.time(),
"verification_results": [
{
"test_name": name,
"success": result.success,
"duration": result.duration,
"command": result.command,
"json_responses_count": len(result.json_responses),
"metrics": result.parsed_metrics
}
for name, result in results
]
}, f, indent=2)
print(f"\n💾 Results saved to: {output_file}")
print("\n✅ Real integration verification completed successfully!")
except Exception as e:
print(f"\n❌ Verification failed: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
-167
View File
@@ -1,167 +0,0 @@
#!/usr/bin/env python3
"""
Test script to verify that the optimization warning has been fixed
and the optimization engine is working properly.
"""
import asyncio
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.core.optimized_benchmark_engine import OptimizedBenchmarkEngine, OPTIMIZATIONS_AVAILABLE
from swarm_benchmark.core.models import BenchmarkConfig, StrategyType, CoordinationMode
from swarm_benchmark.optimization import OptimizedExecutor, CircularBuffer, TTLMap, AsyncFileManager
async def test_optimization_components():
"""Test individual optimization components."""
print("🧪 Testing optimization components...")
# Test CircularBuffer
print(" ✓ Testing CircularBuffer...")
buffer = CircularBuffer(5)
for i in range(10):
buffer.push(f"item_{i}")
recent = buffer.get_recent(3)
print(f" Recent items: {len(recent)}")
print(f" Total written: {buffer.getTotalItemsWritten()}")
# Test TTLMap
print(" ✓ Testing TTLMap...")
ttl_map = TTLMap({'defaultTTL': 1000, 'maxSize': 100})
ttl_map.set('test_key', 'test_value')
value = ttl_map.get('test_key')
stats = ttl_map.getStats()
print(f" Cache hit rate: {stats['hit_rate']:.2f}")
# Test AsyncFileManager
print(" ✓ Testing AsyncFileManager...")
file_manager = AsyncFileManager()
test_data = {'message': 'Hello optimization!', 'timestamp': '2025-01-01'}
await file_manager.writeJSON('/tmp/test_optimization.json', test_data, pretty=True)
read_data = await file_manager.readJSON('/tmp/test_optimization.json')
print(f" File I/O test: {'✓ PASS' if read_data['message'] == test_data['message'] else '✗ FAIL'}")
# Test OptimizedExecutor
print(" ✓ Testing OptimizedExecutor...")
executor = OptimizedExecutor({
'connectionPool': {'min': 2, 'max': 5},
'concurrency': 3
})
# Create mock tasks
mock_tasks = [
type('Task', (), {'id': f'task_{i}', 'objective': f'Test task {i}'})()
for i in range(3)
]
results = await executor.execute_parallel(mock_tasks)
metrics = executor.getMetrics()
print(f" Executed {len(results)} tasks")
print(f" Average execution time: {metrics['average_execution_time']:.3f}s")
await executor.shutdown()
# Cleanup
ttl_map.destroy()
await file_manager.waitForPendingOperations()
print("✅ All optimization components tested successfully!")
async def test_optimized_benchmark_engine():
"""Test the OptimizedBenchmarkEngine."""
print("\n🏗️ Testing OptimizedBenchmarkEngine...")
config = BenchmarkConfig(
name="optimization_test",
description="Test optimization functionality",
strategy=StrategyType.DEVELOPMENT,
mode=CoordinationMode.MESH,
max_agents=3,
task_timeout=30,
max_retries=2
)
engine = OptimizedBenchmarkEngine(config, enable_optimizations=True)
print(f" Optimizations available: {OPTIMIZATIONS_AVAILABLE}")
print(f" Optimizations enabled: {engine.optimizations_enabled}")
if engine.optimizations_enabled:
print(" ✓ Optimization engine initialized successfully")
# Test a simple benchmark
result = await engine.run_benchmark("Test optimization engine functionality")
print(f" ✓ Benchmark completed: {result['status']}")
print(f" ✓ Duration: {result.get('duration', 'N/A')}s")
print(f" ✓ Optimized: {result.get('optimized', False)}")
# Test performance metrics
if 'performance_metrics' in result:
metrics = result['performance_metrics']
print(f" ✓ Performance metrics available: {len(metrics)} categories")
await engine.shutdown()
print("✅ OptimizedBenchmarkEngine tested successfully!")
else:
print("⚠️ Optimizations not enabled, but engine still functional")
def test_import_fix():
"""Test that the import issue has been resolved."""
print("🔧 Testing import fix...")
try:
from swarm_benchmark.optimization import (
OptimizedExecutor, CircularBuffer, TTLMap, AsyncFileManager
)
print(" ✓ Direct optimization imports successful")
from swarm_benchmark.core.optimized_benchmark_engine import OPTIMIZATIONS_AVAILABLE
print(f" ✓ OPTIMIZATIONS_AVAILABLE: {OPTIMIZATIONS_AVAILABLE}")
if OPTIMIZATIONS_AVAILABLE:
print("✅ Import fix successful - no more warnings!")
return True
else:
print("⚠️ Optimizations not available, but no import errors")
return False
except ImportError as e:
print(f"❌ Import failed: {e}")
return False
async def main():
"""Run all tests."""
print("🚀 Testing optimization engine fix...\n")
# Test 1: Import fix
import_success = test_import_fix()
if import_success:
# Test 2: Individual components
await test_optimization_components()
# Test 3: Full engine
await test_optimized_benchmark_engine()
print("\n🎉 All tests completed successfully!")
print("The optimization warning has been fixed and the engine is fully functional.")
else:
print("\n⚠️ Tests completed with some limitations.")
print("The optimization engine provides fallback functionality.")
if __name__ == "__main__":
asyncio.run(main())
@@ -1,5 +1,5 @@
{
"startTime": 1754445015436,
"startTime": 1754448179380,
"totalTasks": 1,
"successfulTasks": 1,
"failedTasks": 0,
@@ -1,10 +1,10 @@
[
{
"id": "cmd-hooks-1754445015540",
"id": "cmd-hooks-1754448179481",
"type": "hooks",
"success": true,
"duration": 9.455416000000014,
"timestamp": 1754445015550,
"duration": 15.611439000000018,
"timestamp": 1754448179497,
"metadata": {}
}
]