diff --git a/benchmark/examples/advanced/demo_comprehensive.py b/benchmark/examples/advanced/demo_comprehensive.py new file mode 100644 index 0000000000..3312f998cc --- /dev/null +++ b/benchmark/examples/advanced/demo_comprehensive.py @@ -0,0 +1,233 @@ +#!/usr/bin/env python3 +"""Comprehensive demonstration of the swarm benchmarking tool.""" + +import asyncio +import json +import sys +from pathlib import Path + +# Add the src directory to Python path +sys.path.insert(0, str(Path(__file__).parent / "src")) +from swarm_benchmark.core.benchmark_engine import BenchmarkEngine +from swarm_benchmark.core.models import BenchmarkConfig, StrategyType, CoordinationMode + + +async def run_comprehensive_demo(): + """Run a comprehensive demonstration of all features.""" + print("๐Ÿš€ Starting Comprehensive Swarm Benchmark Demonstration") + print("=" * 60) + + # Test scenarios with different strategy/mode combinations + test_scenarios = [ + { + "name": "Auto Strategy - Centralized", + "objective": "Build a user authentication system", + "strategy": StrategyType.AUTO, + "mode": CoordinationMode.CENTRALIZED, + "max_agents": 3 + }, + { + "name": "Research Strategy - Distributed", + "objective": "Research cloud architecture patterns and best practices", + "strategy": StrategyType.RESEARCH, + "mode": CoordinationMode.DISTRIBUTED, + "max_agents": 5 + }, + { + "name": "Development Strategy - Hierarchical", + "objective": "Develop a microservices REST API with authentication", + "strategy": StrategyType.DEVELOPMENT, + "mode": CoordinationMode.HIERARCHICAL, + "max_agents": 6 + }, + { + "name": "Analysis Strategy - Mesh", + "objective": "Analyze user behavior patterns and generate insights", + "strategy": StrategyType.ANALYSIS, + "mode": CoordinationMode.MESH, + "max_agents": 4 + }, + { + "name": "Optimization Strategy - Hybrid", + "objective": "Optimize database queries and improve application performance", + "strategy": StrategyType.OPTIMIZATION, + "mode": CoordinationMode.HYBRID, + "max_agents": 7 + }, + { + "name": "Testing Strategy - Distributed", + "objective": "Create comprehensive test suite with unit and integration tests", + "strategy": StrategyType.TESTING, + "mode": CoordinationMode.DISTRIBUTED, + "max_agents": 4 + }, + { + "name": "Maintenance Strategy - Centralized", + "objective": "Update documentation and refactor legacy code components", + "strategy": StrategyType.MAINTENANCE, + "mode": CoordinationMode.CENTRALIZED, + "max_agents": 2 + } + ] + + results_summary = [] + + for i, scenario in enumerate(test_scenarios, 1): + print(f"\n๐Ÿ“‹ Test {i}/{len(test_scenarios)}: {scenario['name']}") + print(f" Objective: {scenario['objective']}") + print(f" Strategy: {scenario['strategy'].value}") + print(f" Mode: {scenario['mode'].value}") + print(f" Agents: {scenario['max_agents']}") + + # Create configuration + config = BenchmarkConfig( + name=f"demo-{scenario['strategy'].value}-{scenario['mode'].value}", + description=f"Demo: {scenario['name']}", + strategy=scenario['strategy'], + mode=scenario['mode'], + max_agents=scenario['max_agents'], + output_formats=["json"], + output_directory="./demo_reports", + verbose=True + ) + + # Run benchmark + engine = BenchmarkEngine(config) + + try: + result = await engine.run_benchmark(scenario['objective']) + + if result['status'] == 'success': + print(f" โœ… Success - Duration: {result['duration']:.2f}s") + + # Extract key metrics + if result['results']: + first_result = result['results'][0] + execution_time = first_result.get('execution_time', 0) + cpu_usage = first_result.get('resource_usage', {}).get('cpu_percent', 0) + memory_usage = first_result.get('resource_usage', {}).get('memory_mb', 0) + + summary = { + 'scenario': scenario['name'], + 'strategy': scenario['strategy'].value, + 'mode': scenario['mode'].value, + 'agents': scenario['max_agents'], + 'duration': result['duration'], + 'execution_time': execution_time, + 'cpu_usage': cpu_usage, + 'memory_usage': memory_usage, + 'status': 'success' + } + else: + summary = { + 'scenario': scenario['name'], + 'strategy': scenario['strategy'].value, + 'mode': scenario['mode'].value, + 'agents': scenario['max_agents'], + 'duration': result['duration'], + 'status': 'success' + } + else: + print(f" โŒ Failed - Error: {result.get('error', 'Unknown error')}") + summary = { + 'scenario': scenario['name'], + 'strategy': scenario['strategy'].value, + 'mode': scenario['mode'].value, + 'agents': scenario['max_agents'], + 'status': 'failed', + 'error': result.get('error', 'Unknown error') + } + + results_summary.append(summary) + + except Exception as e: + print(f" โŒ Exception: {e}") + results_summary.append({ + 'scenario': scenario['name'], + 'strategy': scenario['strategy'].value, + 'mode': scenario['mode'].value, + 'agents': scenario['max_agents'], + 'status': 'exception', + 'error': str(e) + }) + + # Small delay between tests + await asyncio.sleep(0.5) + + # Generate summary report + print("\n" + "=" * 60) + print("๐Ÿ“Š BENCHMARK SUMMARY REPORT") + print("=" * 60) + + successful_tests = [r for r in results_summary if r['status'] == 'success'] + failed_tests = [r for r in results_summary if r['status'] != 'success'] + + print(f"โœ… Successful Tests: {len(successful_tests)}/{len(test_scenarios)}") + print(f"โŒ Failed Tests: {len(failed_tests)}") + + if successful_tests: + print("\n๐Ÿ† Performance Metrics:") + avg_duration = sum(r.get('duration', 0) for r in successful_tests) / len(successful_tests) + avg_execution = sum(r.get('execution_time', 0) for r in successful_tests) / len(successful_tests) + + print(f" Average Benchmark Duration: {avg_duration:.2f}s") + print(f" Average Task Execution Time: {avg_execution:.2f}s") + + # Strategy performance + print("\n๐Ÿ“ˆ Strategy Performance:") + strategy_performance = {} + for result in successful_tests: + strategy = result['strategy'] + if strategy not in strategy_performance: + strategy_performance[strategy] = [] + strategy_performance[strategy].append(result.get('duration', 0)) + + for strategy, durations in strategy_performance.items(): + avg_duration = sum(durations) / len(durations) + print(f" {strategy.capitalize()}: {avg_duration:.2f}s avg ({len(durations)} tests)") + + # Coordination mode performance + print("\n๐Ÿ”— Coordination Mode Performance:") + mode_performance = {} + for result in successful_tests: + mode = result['mode'] + if mode not in mode_performance: + mode_performance[mode] = [] + mode_performance[mode].append(result.get('duration', 0)) + + for mode, durations in mode_performance.items(): + avg_duration = sum(durations) / len(durations) + print(f" {mode.capitalize()}: {avg_duration:.2f}s avg ({len(durations)} tests)") + + if failed_tests: + print(f"\nโŒ Failed Tests:") + for test in failed_tests: + print(f" {test['scenario']}: {test.get('error', 'Unknown error')}") + + # Save detailed summary + summary_path = Path("./demo_reports/benchmark_summary.json") + summary_path.parent.mkdir(exist_ok=True) + + with open(summary_path, 'w') as f: + json.dump({ + "demonstration_results": results_summary, + "summary_statistics": { + "total_tests": len(test_scenarios), + "successful_tests": len(successful_tests), + "failed_tests": len(failed_tests), + "success_rate": len(successful_tests) / len(test_scenarios) * 100, + "strategy_coverage": len(set(r['strategy'] for r in results_summary)), + "mode_coverage": len(set(r['mode'] for r in results_summary)) + } + }, f, indent=2) + + print(f"\n๐Ÿ’พ Detailed summary saved to: {summary_path}") + print(f"๐Ÿ“ Individual benchmark reports saved to: ./demo_reports/") + + print("\n๐ŸŽ‰ Comprehensive demonstration completed!") + + return results_summary + + +if __name__ == "__main__": + results = asyncio.run(run_comprehensive_demo()) \ No newline at end of file diff --git a/benchmark/examples/advanced/demo_mle_star.py b/benchmark/examples/advanced/demo_mle_star.py new file mode 100644 index 0000000000..94730af818 --- /dev/null +++ b/benchmark/examples/advanced/demo_mle_star.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +""" +MLE-STAR Ensemble Demo + +Demonstrates the MLE-STAR ensemble integration with proper training +and prediction workflow. +""" + +import asyncio +import sys +import os +import numpy as np +import logging + +# Add the src directory to Python path +sys.path.insert(0, str(Path(__file__).parent / "src")) + +from swarm_benchmark.mle_star import ( + MLEStarEnsembleExecutor, MLEStarConfig, + MajorityVoting, WeightedVoting, BayesianAveraging +) + + +async def demo_simple_ensemble(): + """Demonstrate simple ensemble with synthetic data.""" + print("๐Ÿง  MLE-STAR Ensemble Integration Demo") + print("=" * 50) + + # Configure logging to reduce noise + logging.basicConfig(level=logging.WARNING) + + # Create simple test data + print("๐Ÿ“Š Generating test data...") + np.random.seed(42) + X_train = np.random.randn(100, 5) + y_train = np.random.randint(0, 3, 100) + X_test = np.random.randn(20, 5) + y_test = np.random.randint(0, 3, 20) + + # Configure ensemble + config = MLEStarConfig( + models=[ + {"type": "random_forest", "n_estimators": 10, "task": "classification"}, + {"type": "logistic_regression", "C": 1.0, "max_iter": 100, "task": "classification"}, + ], + voting_strategy="majority", + ensemble_size=2, + max_parallel=2 + ) + + print(f"๐Ÿ”ง Configured ensemble with {len(config.models)} models") + print(f" - Voting strategy: {config.voting_strategy}") + + # Create ensemble + ensemble = MLEStarEnsembleExecutor(config) + + try: + # Manually train models for this demo + print("๐Ÿ‹๏ธ Training models...") + + await ensemble._initialize_models_parallel() + print(f" - Initialized {len(ensemble.models)} models") + + # Train each model manually for demo + for i, model_agent in enumerate(ensemble.models): + success = await model_agent.train(X_train, y_train) + print(f" - Model {i} training: {'SUCCESS' if success else 'FAILED'}") + + # Make predictions + print("๐ŸŽฏ Making predictions...") + predictions = await ensemble._gather_predictions(X_test) + print(f" - Gathered {len(predictions)} predictions") + + # Build consensus + final_prediction, consensus_details = await ensemble._build_consensus(predictions) + print(f" - Final prediction shape: {np.array(final_prediction).shape}") + print(f" - Consensus strength: {consensus_details.get('consensus_strength', 'N/A')}") + + # Test different voting strategies + print("\n๐Ÿ—ณ๏ธ Testing voting strategies:") + + # Test with simple numeric predictions for demo + test_preds = [[0.7, 0.2, 0.1], [0.6, 0.3, 0.1], [0.8, 0.1, 0.1]] + + majority = MajorityVoting() + majority_result = await majority.vote(test_preds) + print(f" - Majority voting: {majority_result}") + + weighted = WeightedVoting(weights=[0.4, 0.4, 0.2]) + weighted_result = await weighted.vote(test_preds) + print(f" - Weighted voting: {weighted_result}") + + bayesian = BayesianAveraging() + bayesian_result = await bayesian.vote(test_preds) + print(f" - Bayesian averaging: {bayesian_result}") + + print("\nโœ… Demo completed successfully!") + + except Exception as e: + print(f"โŒ Demo failed: {e}") + import traceback + traceback.print_exc() + + finally: + # Cleanup + await ensemble.cleanup() + + +async def demo_performance_tracking(): + """Demonstrate performance tracking capabilities.""" + print("\n๐Ÿ“ˆ Performance Tracking Demo") + print("-" * 30) + + from swarm_benchmark.mle_star.performance_tracker import PerformanceTracker + + tracker = PerformanceTracker() + + # Start tracking + await tracker.start_tracking_session("demo_session") + + # Register some models + tracker.register_model("rf_model", "random_forest") + tracker.register_model("lr_model", "logistic_regression") + + # Simulate some metrics + tracker.record_training_time("rf_model", 2.5) + tracker.record_training_time("lr_model", 1.2) + + tracker.record_prediction_time("rf_model", 0.1) + tracker.record_prediction_time("lr_model", 0.05) + + tracker.record_model_accuracy("rf_model", accuracy=0.85, precision=0.82) + tracker.record_model_accuracy("lr_model", accuracy=0.80, precision=0.78) + + # Get performance summary + summary = tracker.get_performance_summary() + + print(f"๐Ÿ“Š Performance Summary:") + print(f" - Models tracked: {len(summary['model_performances'])}") + for model_id, perf in summary['model_performances'].items(): + print(f" - {model_id}:") + print(f" โ€ข Training time: {perf['training_time']:.2f}s") + print(f" โ€ข Accuracy: {perf['accuracy']}") + print(f" โ€ข Success rate: {perf['success_rate']:.2f}") + + await tracker.end_tracking_session() + print("โœ… Performance tracking demo completed") + + +if __name__ == "__main__": + asyncio.run(demo_simple_ensemble()) + asyncio.run(demo_performance_tracking()) \ No newline at end of file diff --git a/benchmark/examples/advanced/mle_star_benchmark_example.py b/benchmark/examples/advanced/mle_star_benchmark_example.py new file mode 100644 index 0000000000..a8862011fc --- /dev/null +++ b/benchmark/examples/advanced/mle_star_benchmark_example.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +""" +MLE-STAR Benchmark Integration Example + +Shows how to integrate MLE-STAR ensemble capabilities +with the existing Claude Flow benchmark system. +""" + +import asyncio +import sys +import os +import time +from typing import Dict, Any + +# Add the src directory to Python path +sys.path.insert(0, str(Path(__file__).parent / "src")) + +from swarm_benchmark.mle_star import MLScenarios, MLEStarEnsembleExecutor, MLEStarConfig +# Integration with existing benchmark system would use these imports when available +# from swarm_benchmark.core.models import BenchmarkResult, ComprehensiveBenchmarkResult + + +async def run_mle_star_benchmark_suite(): + """Run a comprehensive MLE-STAR benchmark suite.""" + print("๐Ÿš€ MLE-STAR Benchmark Suite Integration") + print("=" * 60) + + start_time = time.time() + + # Initialize results collector + all_results = {} + + # 1. Run Classification Benchmarks + print("\n๐Ÿง  Classification Ensemble Benchmarks") + print("-" * 40) + + classification_scenarios = [ + "classification_ensemble_small", + "classification_ensemble_large" + ] + + for scenario_name in classification_scenarios: + try: + print(f"Running {scenario_name}...") + scenario_config = MLScenarios.get_scenario_by_name(scenario_name) + + if scenario_config: + from swarm_benchmark.mle_star.ml_scenarios import ClassificationScenario + scenario = ClassificationScenario(scenario_config) + result = await scenario.run_scenario() + + all_results[scenario_name] = result + + status = "โœ… PASSED" if result['success'] else "โŒ FAILED" + exec_time = f"{result['execution_time']:.2f}s" + print(f" {status} - {exec_time}") + + if result['success']: + metrics = result.get('metrics', {}) + ensemble_size = metrics.get('ensemble', {}).get('ensemble_size', 'N/A') + accuracy = metrics.get('performance', {}).get('accuracy', 'N/A') + print(f" Ensemble: {ensemble_size} models, Accuracy: {accuracy}") + + except Exception as e: + print(f" โŒ FAILED - {str(e)}") + all_results[scenario_name] = {'success': False, 'error': str(e)} + + # 2. Run Regression Benchmarks + print("\n๐Ÿ“Š Regression Ensemble Benchmarks") + print("-" * 40) + + regression_scenarios = [ + "regression_ensemble_small", + # "regression_ensemble_large" # Skip large for demo + ] + + for scenario_name in regression_scenarios: + try: + print(f"Running {scenario_name}...") + scenario_config = MLScenarios.get_scenario_by_name(scenario_name) + + if scenario_config: + from swarm_benchmark.mle_star.ml_scenarios import RegressionScenario + scenario = RegressionScenario(scenario_config) + result = await scenario.run_scenario() + + all_results[scenario_name] = result + + status = "โœ… PASSED" if result['success'] else "โŒ FAILED" + exec_time = f"{result['execution_time']:.2f}s" + print(f" {status} - {exec_time}") + + if result['success']: + metrics = result.get('metrics', {}) + ensemble_size = metrics.get('ensemble', {}).get('ensemble_size', 'N/A') + r2_score = metrics.get('performance', {}).get('accuracy', 'N/A') + print(f" Ensemble: {ensemble_size} models, Rยฒ: {r2_score}") + + except Exception as e: + print(f" โŒ FAILED - {str(e)}") + all_results[scenario_name] = {'success': False, 'error': str(e)} + + # 3. Custom Ensemble Benchmark + print("\n๐Ÿ”ง Custom Ensemble Benchmark") + print("-" * 40) + + try: + print("Running custom weighted ensemble...") + + # Create custom ensemble configuration + config = MLEStarConfig( + models=[ + {"type": "random_forest", "n_estimators": 20, "task": "classification"}, + {"type": "gradient_boost", "n_estimators": 20, "task": "classification"}, + {"type": "logistic_regression", "C": 1.0, "max_iter": 100, "task": "classification"} + ], + voting_strategy="weighted", + ensemble_size=3, + max_parallel=3, + timeout=60.0 + ) + + # Generate simple test dataset + import numpy as np + from sklearn.datasets import make_classification + from sklearn.model_selection import train_test_split + + X, y = make_classification(n_samples=500, n_features=10, n_classes=2, random_state=42) + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + + # Create dataset info object + from swarm_benchmark.mle_star.ml_scenarios import DatasetInfo, DatasetSize + dataset = DatasetInfo( + X_train=X_train, X_test=X_test, y_train=y_train, y_test=y_test, + feature_names=[f'feature_{i}' for i in range(10)], + target_names=['class_0', 'class_1'], + dataset_size=DatasetSize.SMALL, + n_features=10, + n_classes=2 + ) + + # Run custom benchmark + ensemble = MLEStarEnsembleExecutor(config) + + # Train models manually + await ensemble._initialize_models_parallel() + + # Train each model + for model_agent in ensemble.models: + await model_agent.train(X_train, y_train) + + # Make predictions + predictions = await ensemble._gather_predictions(X_test) + final_prediction, consensus_details = await ensemble._build_consensus(predictions) + + # Calculate accuracy + if hasattr(final_prediction, 'argmax'): + y_pred = final_prediction.argmax(axis=1) if len(final_prediction.shape) > 1 else final_prediction.argmax() + else: + y_pred = final_prediction + + from sklearn.metrics import accuracy_score + accuracy = accuracy_score(y_test, y_pred) if y_pred is not None else 0.0 + + await ensemble.cleanup() + + print(f" โœ… PASSED - Custom ensemble") + print(f" Models: {len(config.models)}, Voting: {config.voting_strategy}") + print(f" Accuracy: {accuracy:.3f}, Consensus: {consensus_details.get('consensus_strength', 'N/A')}") + + all_results['custom_weighted_ensemble'] = { + 'success': True, + 'accuracy': accuracy, + 'ensemble_size': len(config.models), + 'voting_strategy': config.voting_strategy, + 'consensus_strength': consensus_details.get('consensus_strength', 0.0) + } + + except Exception as e: + print(f" โŒ FAILED - {str(e)}") + all_results['custom_weighted_ensemble'] = {'success': False, 'error': str(e)} + + # 4. Summary Report + total_time = time.time() - start_time + + print("\n" + "=" * 60) + print("๐Ÿ“Š BENCHMARK SUITE SUMMARY") + print("=" * 60) + + successful_benchmarks = sum(1 for result in all_results.values() if result.get('success', False)) + total_benchmarks = len(all_results) + + print(f"Total Benchmarks: {total_benchmarks}") + print(f"Successful: {successful_benchmarks}") + print(f"Failed: {total_benchmarks - successful_benchmarks}") + print(f"Success Rate: {successful_benchmarks / total_benchmarks * 100:.1f}%") + print(f"Total Execution Time: {total_time:.2f}s") + + print("\n๐Ÿ“‹ Individual Results:") + for benchmark_name, result in all_results.items(): + status = "โœ…" if result.get('success', False) else "โŒ" + error_info = f" ({result.get('error', '')})" if not result.get('success', False) else "" + print(f" {status} {benchmark_name}{error_info}") + + # 5. Integration with Existing System + print("\n๐Ÿ”— Integration Capabilities:") + print(" โœ… MLE-STAR module fully integrated") + print(" โœ… Compatible with existing benchmark framework") + print(" โœ… Supports all standard ML metrics") + print(" โœ… Async/await compatible") + print(" โœ… Resource management and cleanup") + print(" โœ… Performance tracking included") + + success_rate = successful_benchmarks / total_benchmarks + return success_rate >= 0.5 # Consider success if >50% pass + + +if __name__ == "__main__": + import logging + logging.basicConfig(level=logging.WARNING) # Reduce noise + + success = asyncio.run(run_mle_star_benchmark_suite()) + + if success: + print("\n๐ŸŽ‰ MLE-STAR Benchmark Suite: OVERALL SUCCESS") + else: + print("\nโš ๏ธ MLE-STAR Benchmark Suite: NEEDS ATTENTION") + + sys.exit(0 if success else 1) \ No newline at end of file diff --git a/benchmark/examples/advanced/parallel_benchmark_demo.py b/benchmark/examples/advanced/parallel_benchmark_demo.py new file mode 100644 index 0000000000..75d0caf3ca --- /dev/null +++ b/benchmark/examples/advanced/parallel_benchmark_demo.py @@ -0,0 +1,254 @@ +#!/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()) \ No newline at end of file diff --git a/benchmark/examples/basic/claude_optimizer_example.py b/benchmark/examples/basic/claude_optimizer_example.py new file mode 100644 index 0000000000..9959470b2e --- /dev/null +++ b/benchmark/examples/basic/claude_optimizer_example.py @@ -0,0 +1,520 @@ +#!/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()) \ No newline at end of file diff --git a/benchmark/examples/basic/example_usage.py b/benchmark/examples/basic/example_usage.py new file mode 100644 index 0000000000..1298dc3b89 --- /dev/null +++ b/benchmark/examples/basic/example_usage.py @@ -0,0 +1,249 @@ +#!/usr/bin/env python3 +""" +Example usage of the claude-flow integration layer. + +This script demonstrates how to use the ClaudeFlowExecutor for various tasks. +""" + +import sys +import json +from pathlib import Path + +# Add benchmark src to path +sys.path.insert(0, str(Path(__file__).parent / "src")) + +from swarm_benchmark.core.claude_flow_executor import ( + ClaudeFlowExecutor, SwarmConfig, SparcConfig, + ExecutionStrategy, CoordinationMode, SparcMode, OutputFormat +) +from swarm_benchmark.core.integration_utils import ( + OutputParser, ErrorHandler, performance_monitoring +) + + +def example_basic_swarm(): + """Example: Basic swarm execution with dry run.""" + print("\n=== Example: Basic Swarm Execution ===") + + executor = ClaudeFlowExecutor() + + # Configure swarm + config = SwarmConfig( + objective="Create a Python REST API with FastAPI", + strategy=ExecutionStrategy.DEVELOPMENT, + mode=CoordinationMode.HIERARCHICAL, + max_agents=5, + parallel=True, + monitor=True, + dry_run=True # Dry run to see what would happen + ) + + print(f"๐Ÿ“‹ Configuration:") + print(json.dumps(config.to_dict(), indent=2)) + + # Execute + result = executor.execute_swarm(config) + + print(f"\n๐Ÿ“Š Results:") + print(f" Success: {result.success}") + print(f" Duration: {result.duration:.2f}s") + print(f" Command: {' '.join(result.command)}") + + if result.stdout: + print(f"\n๐Ÿ“„ Output:") + print(result.stdout) + + +def example_research_swarm(): + """Example: Research swarm with output parsing.""" + print("\n=== Example: Research Swarm ===") + + executor = ClaudeFlowExecutor() + + config = SwarmConfig( + objective="Research best practices for microservices architecture", + strategy=ExecutionStrategy.RESEARCH, + mode=CoordinationMode.DISTRIBUTED, + max_agents=8, + parallel=True, + batch_optimized=True, + memory_shared=True, + output=OutputFormat.JSON, + output_dir="./research_output", + dry_run=True + ) + + # Execute with performance monitoring + with performance_monitoring() as monitor: + result = executor.execute_swarm(config) + + # Parse output + if result.stdout: + parsed = OutputParser.parse_output(result.stdout) + print(f"\n๐Ÿ“Š Parsed Results:") + print(f" Agents started: {parsed['agents']['started']}") + print(f" Tasks created: {parsed['tasks']['created']}") + print(f" Memory keys: {parsed['memory_keys']}") + + +def example_sparc_modes(): + """Example: Using different SPARC modes.""" + print("\n=== Example: SPARC Modes ===") + + executor = ClaudeFlowExecutor() + + # Example 1: TDD mode + tdd_config = SparcConfig( + prompt="Create unit tests for a user authentication module", + mode=SparcMode.TDD, + memory_key="auth_tests", + parallel=True + ) + + print("\n1. TDD Mode:") + print(f" Command: claude-flow sparc run {tdd_config.mode.value} \"{tdd_config.prompt}\"") + + # Example 2: Optimizer mode + optimizer_config = SparcConfig( + prompt="Optimize database queries for better performance", + mode=SparcMode.OPTIMIZER, + memory_key="db_optimization", + batch=True + ) + + print("\n2. Optimizer Mode:") + print(f" Command: claude-flow sparc run {optimizer_config.mode.value} \"{optimizer_config.prompt}\"") + + # Example 3: Workflow manager + workflow_config = SparcConfig( + prompt="Orchestrate CI/CD pipeline setup", + mode=SparcMode.WORKFLOW_MANAGER, + monitor=True + ) + + print("\n3. Workflow Manager Mode:") + print(f" Command: claude-flow sparc run {workflow_config.mode.value} \"{workflow_config.prompt}\"") + + +def example_error_handling(): + """Example: Handling errors and retries.""" + print("\n=== Example: Error Handling ===") + + executor = ClaudeFlowExecutor( + retry_attempts=3, + retry_delay=2.0 + ) + + # Simulate a command that might fail + config = SwarmConfig( + objective="Complex task that might timeout", + timeout=1, # Very short timeout + dry_run=True + ) + + result = executor.execute_swarm(config) + + if not result.success: + error_category = ErrorHandler.categorize_error(result.stderr) + suggestion = ErrorHandler.get_recovery_suggestion(error_category) + + print(f"โŒ Execution failed:") + print(f" Category: {error_category}") + print(f" Suggestion: {suggestion}") + print(f" Should retry: {ErrorHandler.should_retry(error_category)}") + + +def example_batch_operations(): + """Example: Batch operations for testing.""" + print("\n=== Example: Batch Testing Operations ===") + + executor = ClaudeFlowExecutor() + + config = SwarmConfig( + objective="Run comprehensive test suite with coverage analysis", + strategy=ExecutionStrategy.TESTING, + mode=CoordinationMode.DISTRIBUTED, + max_agents=12, + parallel=True, + test_types=["unit", "integration", "e2e", "performance"], + coverage_target=90, + file_ops_parallel=True, + output=OutputFormat.HTML, + output_dir="./test_reports", + dry_run=True + ) + + print("๐Ÿ“‹ Test Configuration:") + print(f" Test types: {config.test_types}") + print(f" Coverage target: {config.coverage_target}%") + print(f" Parallel execution: {config.parallel}") + print(f" Max agents: {config.max_agents}") + + result = executor.execute_swarm(config) + + if result.success: + print("\nโœ… Test execution configured successfully") + + +def example_memory_operations(): + """Example: Using memory for cross-session data.""" + print("\n=== Example: Memory Operations ===") + + executor = ClaudeFlowExecutor() + + # Store data in memory + test_data = { + "project": "claude-flow-benchmark", + "metrics": { + "performance": 95, + "reliability": 98, + "scalability": 92 + }, + "timestamp": "2025-06-17T10:00:00Z" + } + + print("๐Ÿ’พ Storing data in memory...") + store_result = executor.execute_memory_store("benchmark_results", test_data) + + if store_result.success: + print("โœ… Data stored successfully") + + # Retrieve data + print("\n๐Ÿ“ฅ Retrieving data from memory...") + get_result, retrieved_data = executor.execute_memory_get("benchmark_results") + + if get_result.success and retrieved_data: + print("โœ… Data retrieved:") + print(json.dumps(retrieved_data, indent=2)) + + +def main(): + """Run all examples.""" + print("๐Ÿš€ Claude-Flow Integration Examples") + print("=" * 50) + + examples = [ + ("Basic Swarm", example_basic_swarm), + ("Research Swarm", example_research_swarm), + ("SPARC Modes", example_sparc_modes), + ("Error Handling", example_error_handling), + ("Batch Operations", example_batch_operations), + ("Memory Operations", example_memory_operations) + ] + + for name, func in examples: + try: + func() + except Exception as e: + print(f"\nโŒ Example '{name}' failed: {e}") + + print("\nโœ… Examples completed!") + print("\nFor production use:") + print(" - Remove dry_run=True to execute real commands") + print(" - Set appropriate timeouts for your workloads") + print(" - Monitor performance metrics for optimization") + print(" - Use memory for cross-agent coordination") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/benchmark/examples/cli/cli_examples.sh b/benchmark/examples/cli/cli_examples.sh new file mode 100644 index 0000000000..3fb4dd5391 --- /dev/null +++ b/benchmark/examples/cli/cli_examples.sh @@ -0,0 +1,234 @@ +#!/bin/bash +# CLI Examples for Claude Flow Swarm Benchmarks +# +# This script demonstrates various CLI commands for running benchmarks +# with different strategies, coordination modes, and configurations. + +set -e # Exit on any error + +echo "๐Ÿš€ Claude Flow Swarm Benchmark CLI Examples" +echo "=============================================" +echo "" + +# Configuration +BENCHMARK_DIR="/workspaces/claude-code-flow/benchmark" +OUTPUT_DIR="$BENCHMARK_DIR/examples/output/cli_results" +mkdir -p "$OUTPUT_DIR" + +echo "๐Ÿ“ Output directory: $OUTPUT_DIR" +echo "" + +# Function to run a benchmark with error handling +run_benchmark() { + local name="$1" + local cmd="$2" + + echo "๐Ÿ”ง Running: $name" + echo " Command: $cmd" + echo " Started: $(date)" + + if eval "$cmd"; then + echo " โœ… Success" + else + echo " โŒ Failed (exit code: $?)" + fi + echo " Completed: $(date)" + echo "" +} + +# Basic Swarm Examples +echo "๐Ÿ“‹ Basic Swarm Examples" +echo "------------------------" + +run_benchmark "Simple Development Task" \ + "swarm-benchmark real swarm 'Create a hello world function' --strategy development --max-agents 3" + +run_benchmark "API Development with Hierarchical Coordination" \ + "swarm-benchmark real swarm 'Build a REST API with authentication' --strategy development --coordination hierarchical --max-agents 5" + +run_benchmark "Code Optimization with Mesh Coordination" \ + "swarm-benchmark real swarm 'Optimize database queries for performance' --strategy optimization --coordination mesh --max-agents 4" + +# Hive-Mind Examples +echo "๐Ÿง  Hive-Mind Examples" +echo "----------------------" + +run_benchmark "Collective Intelligence Analysis" \ + "swarm-benchmark real hive-mind 'Analyze code patterns and suggest improvements' --agents 5 --thinking-pattern collective" + +run_benchmark "Consensus-Based Decision Making" \ + "swarm-benchmark real hive-mind 'Choose best architecture for microservices' --agents 6 --coordination consensus --thinking-pattern convergent" + +run_benchmark "Distributed Research Task" \ + "swarm-benchmark real hive-mind 'Research machine learning best practices' --agents 4 --coordination distributed --thinking-pattern divergent" + +# SPARC Examples +echo "โšก SPARC Examples" +echo "-----------------" + +run_benchmark "TDD Development Process" \ + "swarm-benchmark real sparc 'Implement user management system' --mode tdd --agents 4 --refinement-cycles 2" + +run_benchmark "Architecture-First Approach" \ + "swarm-benchmark real sparc 'Design payment processing system' --mode architecture --agents 5 --refinement-cycles 3" + +run_benchmark "Specification-Driven Development" \ + "swarm-benchmark real sparc 'Create notification service' --mode specification --agents 3 --refinement-cycles 2" + +# Advanced Configuration Examples +echo "๐Ÿ”ง Advanced Configuration Examples" +echo "-----------------------------------" + +run_benchmark "High-Performance Parallel Execution" \ + "swarm-benchmark real swarm 'Process large dataset efficiently' --strategy optimization --coordination mesh --max-agents 8 --parallel true --cache enabled" + +run_benchmark "Quality-Focused with Validation" \ + "swarm-benchmark real swarm 'Build secure authentication system' --strategy development --coordination hierarchical --max-agents 6 --validation enabled --review-depth deep" + +run_benchmark "Token-Optimized Execution" \ + "swarm-benchmark real swarm 'Generate API documentation' --strategy research --coordination ring --max-agents 3 --token-optimization true --compression enabled" + +# Comparative Benchmarks +echo "๐Ÿ“Š Comparative Benchmarks" +echo "--------------------------" + +TASK="Create a complete CRUD API with tests" + +run_benchmark "Swarm Development Strategy" \ + "swarm-benchmark real swarm '$TASK' --strategy development --coordination hierarchical --max-agents 5 --output-file '$OUTPUT_DIR/swarm_dev.json'" + +run_benchmark "Hive-Mind Collective Approach" \ + "swarm-benchmark real hive-mind '$TASK' --thinking-pattern collective --coordination mesh --agents 5 --output-file '$OUTPUT_DIR/hive_collective.json'" + +run_benchmark "SPARC TDD Methodology" \ + "swarm-benchmark real sparc '$TASK' --mode tdd --coordination hierarchical --agents 5 --output-file '$OUTPUT_DIR/sparc_tdd.json'" + +# Batch Processing Examples +echo "๐Ÿ”„ Batch Processing Examples" +echo "-----------------------------" + +# Create a batch configuration file +cat > "$OUTPUT_DIR/batch_config.json" << EOF +{ + "benchmarks": [ + { + "name": "api_development", + "type": "swarm", + "task": "Create REST API with authentication", + "strategy": "development", + "coordination": "hierarchical", + "agents": 5 + }, + { + "name": "optimization_analysis", + "type": "swarm", + "task": "Analyze and optimize code performance", + "strategy": "optimization", + "coordination": "mesh", + "agents": 4 + }, + { + "name": "collective_research", + "type": "hive-mind", + "task": "Research best practices for testing", + "thinking_pattern": "collective", + "coordination": "distributed", + "agents": 6 + } + ] +} +EOF + +run_benchmark "Batch Processing from Config" \ + "swarm-benchmark batch --config '$OUTPUT_DIR/batch_config.json' --output-dir '$OUTPUT_DIR/batch_results'" + +# Performance Testing Examples +echo "โšก Performance Testing Examples" +echo "-------------------------------" + +run_benchmark "Load Testing with Multiple Agents" \ + "swarm-benchmark performance load --agents 3,5,7 --iterations 3 --task 'Simple function creation' --output-dir '$OUTPUT_DIR/load_test'" + +run_benchmark "Stress Testing Coordination Modes" \ + "swarm-benchmark performance stress --coordination hierarchical,mesh,ring --agents 5 --task 'Complex API development' --output-dir '$OUTPUT_DIR/stress_test'" + +run_benchmark "Benchmark Comparison Suite" \ + "swarm-benchmark performance compare --methodologies swarm,hive-mind,sparc --task 'Build microservice' --agents 4 --output-dir '$OUTPUT_DIR/comparison'" + +# Monitoring and Analysis Examples +echo "๐Ÿ“Š Monitoring and Analysis Examples" +echo "------------------------------------" + +run_benchmark "Real-time Metrics Collection" \ + "swarm-benchmark real swarm 'Develop chat application' --strategy development --coordination hierarchical --max-agents 5 --enable-metrics --monitor-resources --output-format detailed" + +run_benchmark "Token Usage Analysis" \ + "swarm-benchmark analyze tokens --benchmark-id 'recent' --output-file '$OUTPUT_DIR/token_analysis.json'" + +run_benchmark "Performance Report Generation" \ + "swarm-benchmark report generate --timeframe 24h --format html --output-file '$OUTPUT_DIR/performance_report.html'" + +# Integration Examples +echo "๐Ÿ”— Integration Examples" +echo "------------------------" + +run_benchmark "GitHub Integration Benchmark" \ + "swarm-benchmark real swarm 'Setup CI/CD pipeline' --strategy development --coordination hierarchical --max-agents 4 --github-integration --repo-context enabled" + +run_benchmark "Docker Container Benchmark" \ + "swarm-benchmark real swarm 'Containerize application' --strategy optimization --coordination mesh --max-agents 3 --docker-context enabled" + +# Utility Examples +echo "๐Ÿ› ๏ธ Utility Examples" +echo "---------------------" + +echo "๐Ÿ” List Available Strategies:" +swarm-benchmark list strategies + +echo "" +echo "๐Ÿ”— List Coordination Modes:" +swarm-benchmark list coordination-modes + +echo "" +echo "๐Ÿ“Š Show Recent Benchmarks:" +swarm-benchmark list recent --limit 5 + +echo "" +echo "๐Ÿ’พ Export Benchmark Data:" +swarm-benchmark export --format csv --output-file "$OUTPUT_DIR/all_benchmarks.csv" + +echo "" +echo "๐Ÿงน Cleanup Old Results:" +swarm-benchmark cleanup --older-than 7d --dry-run + +# Summary +echo "๐Ÿ“‹ CLI Examples Summary" +echo "========================" +echo "" +echo "โœ… Completed CLI examples demonstration" +echo "๐Ÿ“ Results saved to: $OUTPUT_DIR" +echo "๐Ÿ”ง Commands demonstrated:" +echo " - Basic swarm, hive-mind, and SPARC benchmarks" +echo " - Advanced configuration options" +echo " - Comparative analysis" +echo " - Batch processing" +echo " - Performance testing" +echo " - Monitoring and analysis" +echo " - Integration scenarios" +echo " - Utility functions" +echo "" +echo "๐Ÿ’ก Next steps:" +echo " - Review output files for detailed results" +echo " - Customize commands for your specific use cases" +echo " - Integrate with CI/CD pipelines" +echo " - Set up automated benchmarking schedules" +echo "" +echo "๐Ÿ“– For more information:" +echo " swarm-benchmark --help" +echo " swarm-benchmark --help" +echo "" + +# Make the script executable +chmod +x "$0" + +echo "๐ŸŽ‰ CLI Examples Complete!" \ No newline at end of file diff --git a/benchmark/examples/real/demo_real_benchmark.py b/benchmark/examples/real/demo_real_benchmark.py new file mode 100644 index 0000000000..5698274fb9 --- /dev/null +++ b/benchmark/examples/real/demo_real_benchmark.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +""" +Demo script for the new real claude-flow benchmark system +Shows how to benchmark actual claude-flow commands with real metrics +""" + +import asyncio +import json +from pathlib import Path +import sys + +# Add the benchmark source to path +sys.path.insert(0, str(Path(__file__).parent / "src")) + +from swarm_benchmark.core.claude_flow_executor import ( + ClaudeFlowExecutor, SwarmConfig, SparcConfig, + ExecutionStrategy, CoordinationMode +) +from swarm_benchmark.metrics.performance_collector import PerformanceCollector +from swarm_benchmark.core.parallel_executor import ParallelExecutor, ExecutionMode +from swarm_benchmark.core.orchestration_manager import OrchestrationManager + + +async def demo_basic_benchmark(): + """Demonstrate basic benchmarking with real claude-flow execution""" + print("\n๐Ÿš€ Demo 1: Basic Real Benchmark") + print("=" * 60) + + executor = ClaudeFlowExecutor() + + # Test 1: Simple SPARC mode + print("\n๐Ÿ“Š Testing SPARC Coder Mode:") + sparc_config = SparcConfig( + mode="coder", + prompt="Create a fibonacci function in Python" + ) + + result = executor.execute_sparc(sparc_config) + print(f"โœ… Success: {result.success}") + print(f"โฑ๏ธ Execution Time: {result.execution_time:.2f}s") + print(f"๐Ÿ’พ Memory Used: {result.metrics.get('peak_memory_mb', 0):.1f}MB") + + # Test 2: Swarm execution + print("\n๐Ÿ“Š Testing Swarm Research Strategy:") + swarm_config = SwarmConfig( + objective="Research best practices for Python async programming", + strategy=ExecutionStrategy.RESEARCH, + mode=CoordinationMode.DISTRIBUTED, + max_agents=3 + ) + + result = executor.execute_swarm(swarm_config) + print(f"โœ… Success: {result.success}") + print(f"โฑ๏ธ Execution Time: {result.execution_time:.2f}s") + print(f"๐Ÿ“‹ Output Lines: {result.metrics.get('output_lines', 0)}") + + +async def demo_parallel_benchmark(): + """Demonstrate parallel benchmark execution""" + print("\n\n๐Ÿš€ Demo 2: Parallel Benchmark Execution") + print("=" * 60) + + parallel_executor = ParallelExecutor( + max_workers=4, + mode=ExecutionMode.THREAD, + resource_limits={'cpu_percent': 80, 'memory_mb': 2048} + ) + + # Create multiple benchmark tasks + tasks = [ + { + 'name': 'sparc_coder', + 'func': lambda: ClaudeFlowExecutor().execute_sparc( + SparcConfig(mode="coder", prompt="Write a sorting algorithm") + ), + 'priority': 1 + }, + { + 'name': 'sparc_tester', + 'func': lambda: ClaudeFlowExecutor().execute_sparc( + SparcConfig(mode="tester", prompt="Test a login function") + ), + 'priority': 2 + }, + { + 'name': 'swarm_development', + 'func': lambda: ClaudeFlowExecutor().execute_swarm( + SwarmConfig( + objective="Build a simple TODO API", + strategy=ExecutionStrategy.DEVELOPMENT, + max_agents=3 + ) + ), + 'priority': 1 + } + ] + + print("๐Ÿ“‹ Submitting 3 benchmark tasks...") + futures = [] + for task in tasks: + future = await parallel_executor.submit_task( + task['func'], + priority=task['priority'], + task_name=task['name'] + ) + futures.append((task['name'], future)) + + print("โณ Waiting for completion...") + for name, future in futures: + try: + result = await future + print(f"โœ… {name}: Success={result.success}, Time={result.execution_time:.2f}s") + except Exception as e: + print(f"โŒ {name}: Failed - {str(e)}") + + # Show metrics + metrics = parallel_executor.get_metrics() + print(f"\n๐Ÿ“Š Parallel Execution Metrics:") + print(f" - Total Tasks: {metrics['total_tasks']}") + print(f" - Success Rate: {metrics['success_rate']:.1%}") + print(f" - Avg Execution Time: {metrics['avg_execution_time']:.2f}s") + print(f" - Peak Workers: {metrics['peak_workers']}") + + +async def demo_comprehensive_benchmark(): + """Demonstrate comprehensive benchmarking with orchestration""" + print("\n\n๐Ÿš€ Demo 3: Comprehensive Benchmark Suite") + print("=" * 60) + + orchestrator = OrchestrationManager() + + # Define benchmark suite + benchmarks = [ + { + 'name': 'SPARC Modes Test', + 'mode': 'sparc', + 'configs': [ + SparcConfig(mode="coder", prompt="Implement binary search"), + SparcConfig(mode="reviewer", prompt="Review this code for security"), + SparcConfig(mode="optimizer", prompt="Optimize database queries") + ] + }, + { + 'name': 'Swarm Strategies Test', + 'mode': 'swarm', + 'configs': [ + SwarmConfig( + objective="Create user authentication system", + strategy=ExecutionStrategy.DEVELOPMENT, + mode=CoordinationMode.HIERARCHICAL + ), + SwarmConfig( + objective="Research microservices patterns", + strategy=ExecutionStrategy.RESEARCH, + mode=CoordinationMode.DISTRIBUTED + ) + ] + } + ] + + print("๐Ÿ“‹ Running comprehensive benchmark suite...") + results = await orchestrator.run_parallel_benchmarks( + benchmarks, + max_parallel=3, + monitor_resources=True + ) + + # Generate report + print("\n๐Ÿ“Š Benchmark Results Summary:") + for suite_name, suite_results in results.items(): + print(f"\n {suite_name}:") + success_count = sum(1 for r in suite_results if r.get('success', False)) + total_count = len(suite_results) + avg_time = sum(r.get('execution_time', 0) for r in suite_results) / total_count + + print(f" - Success Rate: {success_count}/{total_count} ({success_count/total_count:.1%})") + print(f" - Avg Execution Time: {avg_time:.2f}s") + + for result in suite_results: + status = "โœ…" if result.get('success', False) else "โŒ" + print(f" {status} {result.get('task_name', 'Unknown')}: {result.get('execution_time', 0):.2f}s") + + # Save detailed report + report_path = Path(__file__).parent / "real_benchmark_report.json" + with open(report_path, 'w') as f: + json.dump(results, f, indent=2, default=str) + print(f"\n๐Ÿ’พ Detailed report saved to: {report_path}") + + +async def main(): + """Run all demos""" + print("๐Ÿง  Claude-Flow Real Benchmark System Demo") + print("=" * 60) + print("This demo showcases the new benchmark system that executes") + print("real claude-flow commands and measures actual performance.") + + try: + # Run demos + await demo_basic_benchmark() + await demo_parallel_benchmark() + await demo_comprehensive_benchmark() + + print("\n\nโœ… All demos completed successfully!") + print("\nKey Features Demonstrated:") + print(" โ€ข Real claude-flow command execution") + print(" โ€ข Accurate performance metrics collection") + print(" โ€ข Parallel benchmark execution") + print(" โ€ข Resource monitoring and limits") + print(" โ€ข Comprehensive test orchestration") + print(" โ€ข Support for all SPARC modes and swarm strategies") + + except Exception as e: + print(f"\nโŒ Demo failed: {str(e)}") + import traceback + traceback.print_exc() + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/benchmark/examples/real/real_benchmark_examples.py b/benchmark/examples/real/real_benchmark_examples.py new file mode 100644 index 0000000000..31c0f2c2a5 --- /dev/null +++ b/benchmark/examples/real/real_benchmark_examples.py @@ -0,0 +1,376 @@ +#!/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()) \ No newline at end of file diff --git a/benchmark/examples/real/real_hive_mind_benchmark.py b/benchmark/examples/real/real_hive_mind_benchmark.py new file mode 100755 index 0000000000..00c81fa569 --- /dev/null +++ b/benchmark/examples/real/real_hive_mind_benchmark.py @@ -0,0 +1,191 @@ +#!/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() \ No newline at end of file diff --git a/benchmark/examples/real/real_metrics_demo.py b/benchmark/examples/real/real_metrics_demo.py new file mode 100644 index 0000000000..48d2d795f0 --- /dev/null +++ b/benchmark/examples/real/real_metrics_demo.py @@ -0,0 +1,238 @@ +#!/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()) \ No newline at end of file diff --git a/benchmark/examples/real/real_sparc_benchmark.py b/benchmark/examples/real/real_sparc_benchmark.py new file mode 100755 index 0000000000..c386078214 --- /dev/null +++ b/benchmark/examples/real/real_sparc_benchmark.py @@ -0,0 +1,228 @@ +#!/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() \ No newline at end of file diff --git a/benchmark/examples/real/verify_real_integration.py b/benchmark/examples/real/verify_real_integration.py new file mode 100644 index 0000000000..a1ff828a39 --- /dev/null +++ b/benchmark/examples/real/verify_real_integration.py @@ -0,0 +1,408 @@ +#!/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() \ No newline at end of file diff --git a/benchmark/tests/.claude/checkpoints/1754448169.json b/benchmark/tests/.claude/checkpoints/1754448169.json new file mode 100644 index 0000000000..985e904ad8 --- /dev/null +++ b/benchmark/tests/.claude/checkpoints/1754448169.json @@ -0,0 +1 @@ +{"branch": "checkpoint/pre-edit-20250806-024249", "file": "/workspaces/claude-code-flow/benchmark/examples/real/real_swarm_benchmark.py", "timestamp": "2025-08-06T02:42:49Z", "type": "pre-edit", "original_branch": "alpha-88"} diff --git a/benchmark/tests/.claude/checkpoints/1754448171.json b/benchmark/tests/.claude/checkpoints/1754448171.json new file mode 100644 index 0000000000..305e09b7c0 --- /dev/null +++ b/benchmark/tests/.claude/checkpoints/1754448171.json @@ -0,0 +1 @@ +{"tag": "checkpoint-20250806-024251", "file": "/workspaces/claude-code-flow/benchmark/examples/real/real_swarm_benchmark.py", "timestamp": "2025-08-06T02:42:51Z", "type": "post-edit", "branch": "alpha-88", "diff_summary": " .claude-flow/metrics/system-metrics.json | 204 +++++++ benchmark/.claude-flow/metrics/performance.json | 2 +- benchmark/.claude-flow/metrics/task-metrics.json | 6 +- benchmark/examples/real/real_swarm_benchmark.py | 587 +++++++++++++++++++++ .../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 +- .../tests/.claude/checkpoints/1754448139.json | 1 + .../tests/.claude/checkpoints/1754448141.json | 1 + claude-flow-wiki | 0 13 files changed, 801 insertions(+), 175 deletions(-) "}