π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
π Checkpoint: Edit /workspaces/claude-code-flow/benchmark/examples/real_benchmark_examples.py
rUv905cc2160e6b
diff --git a/benchmark/.claude/checkpoints/1754444998.json b/benchmark/.claude/checkpoints/1754444998.jsonnew file mode 100644index 0000000000..dc25b8d95a--- /dev/null+++ b/benchmark/.claude/checkpoints/1754444998.json@@ -0,0 +1 @@+{"branch": "checkpoint/pre-edit-20250806-014958", "file": "/workspaces/claude-code-flow/benchmark/tests/conftest.py", "timestamp": "2025-08-06T01:49:58Z", "type": "pre-edit", "original_branch": "alpha-88"}diff --git a/benchmark/.claude/checkpoints/1754445000.json b/benchmark/.claude/checkpoints/1754445000.jsonnew file mode 100644index 0000000000..f704d0ebe7--- /dev/null+++ b/benchmark/.claude/checkpoints/1754445000.json@@ -0,0 +1 @@+{"tag": "checkpoint-20250806-015000", "file": "/workspaces/claude-code-flow/benchmark/tests/conftest.py", "timestamp": "2025-08-06T01:50:00Z", "type": "post-edit", "branch": "alpha-88", "diff_summary": " .claude-flow/metrics/system-metrics.json | 108 +++ benchmark/.claude-flow/metrics/performance.json | 2 +- benchmark/.claude-flow/metrics/task-metrics.json | 6 +- benchmark/.claude/checkpoints/1754444972.json | 1 + benchmark/.claude/checkpoints/1754444974.json | 1 + benchmark/compare_optimizations.py | 172 ----- benchmark/demo_comprehensive.py | 233 ------- benchmark/demo_mle_star.py | 152 ---- benchmark/demo_real_benchmark.py | 219 ------ benchmark/example_usage.py | 249 ------- .../__pycache__/benchmark_runner.cpython-312.pyc | Bin 24173 -> 0 bytes .../automated_test_runner.cpython-312.pyc | Bin 32696 -> 0 bytes .../__pycache__/parallel_executor.cpython-312.pyc | Bin 23676 -> 0 bytes .../__pycache__/result_collector.cpython-312.pyc | Bin 39201 -> 0 bytes benchmark/mle_star_benchmark_example.py | 229 ------ benchmark/performance_dashboard.py | 769 --------------------- .../__pycache__/__init__.cpython-312.pyc | Bin 2870 -> 0 bytes .../__pycache__/__init__.cpython-312.pyc | Bin 1345 -> 0 bytes .../__pycache__/memory_profiler.cpython-312.pyc | Bin 43459 -> 0 bytes .../__pycache__/metric_aggregator.cpython-312.pyc | Bin 42675 -> 0 bytes .../__pycache__/neural_benchmarks.cpython-312.pyc | Bin 44186 -> 0 bytes .../performance_analyzer.cpython-312.pyc | Bin 57821 -> 0 bytes .../__pycache__/token_optimizer.cpython-312.pyc | Bin 40053 -> 0 bytes .../__pycache__/__init__.cpython-312.pyc | Bin 1652 -> 0 bytes .../__pycache__/batch_processor.cpython-312.pyc | Bin 40756 -> 0 bytes .../__pycache__/decision_engine.cpython-312.pyc | Bin 44984 -> 0 bytes .../automation/__pycache__/models.cpython-312.pyc | Bin 2252 -> 0 bytes .../__pycache__/pipeline_manager.cpython-312.pyc | Bin 32505 -> 0 bytes .../__pycache__/resource_pool.cpython-312.pyc | Bin 38372 -> 0 bytes .../__pycache__/workflow_executor.cpython-312.pyc | Bin 43709 -> 0 bytes .../__pycache__/__init__.cpython-312.pyc | Bin 738 -> 0 bytes .../__pycache__/optimizer.cpython-312.pyc | Bin 27444 -> 0 bytes .../__pycache__/rules_engine.cpython-312.pyc | Bin 20977 -> 0 bytes .../__pycache__/templates.cpython-312.pyc | Bin 21167 -> 0 bytes .../__pycache__/__init__.cpython-312.pyc | Bin 2698 -> 0 bytes .../config/__pycache__/__init__.cpython-312.pyc | Bin 524 -> 0 bytes .../__pycache__/unified_config.cpython-312.pyc | Bin 27458 -> 0 bytes .../core/__pycache__/__init__.cpython-312.pyc | Bin 1415 -> 0 bytes .../__pycache__/base_interfaces.cpython-312.pyc | Bin 20843 -> 0 bytes .../__pycache__/benchmark_engine.cpython-312.pyc | Bin 7620 -> 0 bytes .../core/__pycache__/models.cpython-312.pyc | Bin 18629 -> 0 bytes .../optimized_benchmark_engine.cpython-312.pyc | Bin 15770 -> 0 bytes .../orchestration_manager.cpython-312.pyc | Bin 25940 -> 0 bytes .../__pycache__/parallel_executor.cpython-312.pyc | Bin 35716 -> 0 bytes .../__pycache__/result_aggregator.cpython-312.pyc | Bin 1029 -> 0 bytes .../__pycache__/task_scheduler.cpython-312.pyc | Bin 22516 -> 0 bytes .../mle_star/__pycache__/__init__.cpython-312.pyc | Bin 1091 -> 0 bytes .../__pycache__/ensemble_executor.cpython-312.pyc | Bin 24374 -> 0 bytes .../__pycache__/ml_scenarios.cpython-312.pyc | Bin 28015 -> 0 bytes .../__pycache__/model_coordinator.cpython-312.pyc | Bin 38329 -> 0 bytes .../performance_tracker.cpython-312.pyc | Bin 31006 -> 0 bytes .../__pycache__/voting_strategies.cpython-312.pyc | Bin 31206 -> 0 bytes .../__pycache__/__init__.cpython-312.pyc | Bin 2003 -> 0 bytes .../__pycache__/analysis_strategy.cpython-312.pyc | Bin 3220 -> 0 bytes .../__pycache__/auto_strategy.cpython-312.pyc | Bin 5525 -> 0 bytes .../__pycache__/base_strategy.cpython-312.pyc | Bin 2972 -> 0 bytes .../development_strategy.cpython-312.pyc | Bin 6692 -> 0 bytes .../maintenance_strategy.cpython-312.pyc | Bin 3239 -> 0 bytes .../optimization_strategy.cpython-312.pyc | Bin 3290 -> 0 bytes .../__pycache__/research_strategy.cpython-312.pyc | Bin 6215 -> 0 bytes .../__pycache__/testing_strategy.cpython-312.pyc | Bin 3181 -> 0 bytes benchmark/tests/conftest.py | 5 +- .../{ => tools}/ci_performance_integration.py | 0 claude-flow-wiki | 0 64 files changed, 118 insertions(+), 2028 deletions(-) "}diff --git a/benchmark/examples/real_benchmark_examples.py b/benchmark/examples/real_benchmark_examples.pyindex 3968cfa4dc..31c0f2c2a5 100644--- a/benchmark/examples/real_benchmark_examples.py+++ b/benchmark/examples/real_benchmark_examples.py@@ -12,7 +12,7 @@ import sys# Add benchmark source to pathsys.path.insert(0, str(Path(__file__).parent.parent / "src"))-from swarm_benchmark.core.real_benchmark_engine import RealBenchmarkEngine, SystemMonitor+from swarm_benchmark.core.real_benchmark_engine import RealBenchmarkEnginefrom swarm_benchmark.core.models import (BenchmarkConfig, Task, StrategyType, CoordinationMode)diff --git a/benchmark/tests/integration/quick_test_integration.py b/benchmark/tests/integration/quick_test_integration.pynew file mode 100644index 0000000000..3cc80fe821--- /dev/null+++ b/benchmark/tests/integration/quick_test_integration.py@@ -0,0 +1,44 @@+#!/usr/bin/env python3+"""Quick test of claude-flow integration."""++import sys+from pathlib import Path++# Add benchmark src to path+sys.path.insert(0, str(Path(__file__).parent / "src"))++from swarm_benchmark.core.claude_flow_executor import ClaudeFlowExecutor++def main():+ print("π§ͺ Quick Integration Test")++ try:+ # Test initialization+ executor = ClaudeFlowExecutor()+ print(f"β Executor initialized: {executor.claude_flow_path}")++ # Test version check+ if executor.validate_installation():+ print("β Claude-flow installation validated")+ else:+ print("β Installation validation failed")+ return False++ # Test simple command+ result = executor._execute_command([executor.claude_flow_path, "--help"], timeout=5)+ print(f"β Help command executed: exit_code={result.exit_code}")++ if result.stdout:+ print("\nπ Help output (first 500 chars):")+ print(result.stdout[:500])++ return True++ except Exception as e:+ print(f"β Test failed: {e}")+ return False+++if __name__ == "__main__":+ success = main()+ sys.exit(0 if success else 1)\ No newline at end of filediff --git a/benchmark/tests/integration/test_claude_optimizer.py b/benchmark/tests/integration/test_claude_optimizer.pynew file mode 100644index 0000000000..a4526133fd--- /dev/null+++ b/benchmark/tests/integration/test_claude_optimizer.py@@ -0,0 +1,235 @@+#!/usr/bin/env python3+"""+Test script for CLAUDE.md Optimizer implementation.+Verifies all components work correctly.+"""++import sys+import asyncio+from pathlib import Path++# Add benchmark source to path+sys.path.insert(0, str(Path(__file__).parent / "src"))++from swarm_benchmark.claude_optimizer import (+ ClaudeMdOptimizer,+ ProjectContext,+ PerformanceTargets,+ TemplateEngine,+ OptimizationRulesEngine+)+++async def test_claude_optimizer():+ """Test the CLAUDE.md optimizer implementation."""+ print("π§ͺ Testing CLAUDE.md Optimizer")+ print("=" * 40)++ # Test 1: Optimizer initialization+ print("\n1. Testing optimizer initialization...")+ try:+ optimizer = ClaudeMdOptimizer()+ print(" β Optimizer initialized successfully")+ except Exception as e:+ print(f" β Failed to initialize optimizer: {e}")+ return False++ # Test 2: Project context creation+ print("\n2. Testing project context...")+ try:+ context = ProjectContext(+ project_type="test_api",+ team_size=4,+ complexity="medium",+ primary_languages=["Python"],+ frameworks=["FastAPI"],+ performance_requirements={"response_time": "<100ms"},+ existing_tools=["pytest"],+ constraints={"timeline": "normal"}+ )+ print(" β Project context created successfully")+ except Exception as e:+ print(f" β Failed to create project context: {e}")+ return False++ # Test 3: Performance targets+ print("\n3. Testing performance targets...")+ try:+ targets = PerformanceTargets(+ priority="speed",+ target_completion_time=30.0,+ target_token_usage=500+ )+ print(" β Performance targets created successfully")+ except Exception as e:+ print(f" β Failed to create performance targets: {e}")+ return False++ # Test 4: Configuration generation+ print("\n4. Testing configuration generation...")+ try:+ config = optimizer.generate_optimized_config(+ "api_development", context, targets+ )+ assert isinstance(config, str)+ assert len(config) > 0+ assert "CLAUDE.md" in config+ print(" β Configuration generated successfully")+ print(f" π Config length: {len(config)} characters")+ except Exception as e:+ print(f" β Failed to generate configuration: {e}")+ return False++ # Test 5: Template engine+ print("\n5. Testing template engine...")+ try:+ template_engine = TemplateEngine()+ test_config = {+ "use_case": "test_case",+ "max_agents": 4,+ "swarm_topology": "hierarchical"+ }+ template = template_engine.generate_claude_md(test_config)+ assert isinstance(template, str)+ print(" β Template engine works correctly")+ except Exception as e:+ print(f" β Template engine failed: {e}")+ return False++ # Test 6: Rules engine+ print("\n6. Testing rules engine...")+ try:+ rules_engine = OptimizationRulesEngine()+ test_config = {"max_agents": 4}++ # Test speed optimization+ speed_config = rules_engine.optimize_for_speed(test_config.copy())+ assert "parallel_execution" in speed_config++ # Test accuracy optimization+ accuracy_config = rules_engine.optimize_for_accuracy(test_config.copy())+ assert "validation_level" in accuracy_config++ print(" β Rules engine works correctly")+ except Exception as e:+ print(f" β Rules engine failed: {e}")+ return False++ # Test 7: Benchmarking (simplified)+ print("\n7. Testing benchmarking...")+ try:+ test_tasks = [+ "Create simple API endpoint",+ "Add basic validation",+ "Write unit test"+ ]++ # Use a shorter timeout for testing+ metrics = await asyncio.wait_for(+ optimizer.benchmark_config_effectiveness(config, test_tasks, iterations=1),+ timeout=10.0+ )++ assert hasattr(metrics, 'optimization_score')+ assert hasattr(metrics, 'completion_rate')+ assert 0 <= metrics.optimization_score <= 1+ assert 0 <= metrics.completion_rate <= 1++ print(" β Benchmarking works correctly")+ print(f" π Optimization score: {metrics.optimization_score:.3f}")+ print(f" π Completion rate: {metrics.completion_rate:.1%}")+ except asyncio.TimeoutError:+ print(" β οΈ Benchmarking timed out (expected in test environment)")+ except Exception as e:+ print(f" β Benchmarking failed: {e}")+ return False++ # Test 8: All use cases+ print("\n8. Testing all use cases...")+ use_cases = [+ "api_development", "ml_pipeline", "frontend_react",+ "backend_microservices", "testing_automation"+ ]++ for use_case in use_cases:+ try:+ config = optimizer.generate_optimized_config(use_case, context, targets)+ assert isinstance(config, str)+ assert len(config) > 0+ print(f" β {use_case} - OK")+ except Exception as e:+ print(f" β {use_case} failed: {e}")+ return False++ print("\nπ All tests passed!")+ return True+++def test_file_structure():+ """Test that all required files were created."""+ print("\nπ Testing file structure...")++ base_path = Path(__file__).parent+ required_files = [+ "src/swarm_benchmark/claude_optimizer/__init__.py",+ "src/swarm_benchmark/claude_optimizer/optimizer.py",+ "src/swarm_benchmark/claude_optimizer/templates.py",+ "src/swarm_benchmark/claude_optimizer/rules_engine.py",+ "docs/api_reference.md",+ "docs/claude_optimizer_guide.md",+ "examples/claude_optimizer_example.py"+ ]++ all_exist = True+ for file_path in required_files:+ full_path = base_path / file_path+ if full_path.exists():+ print(f" β {file_path}")+ else:+ print(f" β {file_path} - MISSING")+ all_exist = False++ return all_exist+++async def main():+ """Run all tests."""+ print("π CLAUDE.md Optimizer Implementation Test")+ print("=" * 50)++ # Test file structure+ files_ok = test_file_structure()++ if not files_ok:+ print("\nβ File structure test failed")+ return 1++ # Test functionality+ try:+ functionality_ok = await test_claude_optimizer()++ if functionality_ok:+ print("\nβ All tests completed successfully!")+ print("\nπ Implementation Summary:")+ print(" - ClaudeMdOptimizer class: β Complete")+ print(" - 10 use case templates: β Complete")+ print(" - Optimization rules engine: β Complete")+ print(" - Configuration benchmarking: β Complete")+ print(" - API documentation: β Complete")+ print(" - User guide: β Complete")+ print(" - Example implementation: β Complete")+ return 0+ else:+ print("\nβ Some tests failed")+ return 1++ except Exception as e:+ print(f"\nπ₯ Test suite crashed: {e}")+ import traceback+ traceback.print_exc()+ return 1+++if __name__ == "__main__":+ exit_code = asyncio.run(main())+ sys.exit(exit_code)\ No newline at end of filediff --git a/benchmark/tests/integration/test_integration.py b/benchmark/tests/integration/test_integration.pynew file mode 100755index 0000000000..5faa0f6d6f--- /dev/null+++ b/benchmark/tests/integration/test_integration.py@@ -0,0 +1,274 @@+#!/usr/bin/env python3+"""+Test script for claude-flow integration.++This script tests the integration layer to ensure proper execution+of claude-flow commands with comprehensive error handling and output capture.+"""++import sys+import json+import logging+from pathlib import Path++# Add benchmark src to path+sys.path.insert(0, str(Path(__file__).parent / "src"))++from swarm_benchmark.core.claude_flow_executor import (+ ClaudeFlowExecutor, SwarmConfig, SparcConfig,+ ExecutionStrategy, CoordinationMode, SparcMode+)+from swarm_benchmark.core.integration_utils import (+ OutputParser, CommandBuilder, ErrorHandler,+ ProgressTracker, performance_monitoring+)+++# Configure logging+logging.basicConfig(+ level=logging.INFO,+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'+)+logger = logging.getLogger(__name__)+++def test_executor_initialization():+ """Test executor initialization and validation."""+ print("\n=== Testing Executor Initialization ===")++ try:+ # Initialize executor+ executor = ClaudeFlowExecutor()+ print(f"β Executor initialized with path: {executor.claude_flow_path}")++ # Validate installation+ if executor.validate_installation():+ print("β Claude-flow installation validated")+ else:+ print("β Claude-flow installation validation failed")++ except Exception as e:+ print(f"β Failed to initialize executor: {e}")+ return False++ return True+++def test_swarm_execution():+ """Test swarm command execution."""+ print("\n=== Testing Swarm Execution ===")++ try:+ executor = ClaudeFlowExecutor()++ # Test configuration+ config = SwarmConfig(+ objective="Create a simple hello world function",+ strategy=ExecutionStrategy.DEVELOPMENT,+ mode=CoordinationMode.CENTRALIZED,+ max_agents=3,+ timeout=5, # 5 minutes+ dry_run=True # Dry run for testing+ )++ print(f"π Config: {json.dumps(config.__dict__, indent=2)}")++ # Execute with performance monitoring+ with performance_monitoring() as monitor:+ result = executor.execute_swarm(config)++ print(f"\nβ Execution completed:")+ print(f" - Success: {result.success}")+ print(f" - Exit code: {result.exit_code}")+ print(f" - Duration: {result.duration:.2f}s")+ print(f" - Timeout: {result.timeout}")++ if result.stdout:+ print(f"\nπ Output preview:")+ print(result.stdout[:500] + "..." if len(result.stdout) > 500 else result.stdout)++ if result.stderr:+ print(f"\nβ οΈ Errors:")+ print(result.stderr[:500] + "..." if len(result.stderr) > 500 else result.stderr)++ # Parse output+ parsed = OutputParser.parse_output(result.stdout)+ print(f"\nπ Parsed output: {json.dumps(parsed, indent=2)}")++ except Exception as e:+ print(f"β Swarm execution failed: {e}")+ logger.exception("Swarm execution error")+ return False++ return True+++def test_sparc_execution():+ """Test SPARC command execution."""+ print("\n=== Testing SPARC Execution ===")++ try:+ executor = ClaudeFlowExecutor()++ # Test configuration+ config = SparcConfig(+ prompt="Analyze the current codebase structure",+ mode=SparcMode.ANALYZER,+ memory_key="codebase_analysis",+ timeout=5 # 5 minutes+ )++ print(f"π Config: {json.dumps(config.__dict__, indent=2)}")++ # Execute+ result = executor.execute_sparc(config)++ print(f"\nβ Execution completed:")+ print(f" - Success: {result.success}")+ print(f" - Exit code: {result.exit_code}")+ print(f" - Duration: {result.duration:.2f}s")++ if result.stdout:+ print(f"\nπ Output preview:")+ print(result.stdout[:500] + "..." if len(result.stdout) > 500 else result.stdout)++ except Exception as e:+ print(f"β SPARC execution failed: {e}")+ logger.exception("SPARC execution error")+ return False++ return True+++def test_command_building():+ """Test command building utilities."""+ print("\n=== Testing Command Building ===")++ # Test swarm command+ swarm_cmd = CommandBuilder.build_swarm_command(+ "Build a REST API",+ strategy="development",+ mode="hierarchical",+ max_agents=5,+ parallel=True,+ monitor=True+ )+ print(f"Swarm command: {' '.join(swarm_cmd)}")++ # Test SPARC command+ sparc_cmd = CommandBuilder.build_sparc_command(+ "Optimize database queries",+ mode="optimizer",+ memory_key="db_optimization",+ batch=True+ )+ print(f"SPARC command: {' '.join(sparc_cmd)}")++ # Test validation+ valid_config = {"objective": "Test", "strategy": "development"}+ errors = CommandBuilder.validate_swarm_config(valid_config)+ print(f"\nValid config errors: {errors}")++ invalid_config = {"strategy": "invalid_strategy"}+ errors = CommandBuilder.validate_swarm_config(invalid_config)+ print(f"Invalid config errors: {errors}")++ return True+++def test_error_handling():+ """Test error handling and categorization."""+ print("\n=== Testing Error Handling ===")++ test_errors = [+ "command not found: claude-flow",+ "Error: invalid option --invalid",+ "Process terminated with signal 11",+ "Connection refused while fetching data",+ "Execution timed out after 60 seconds"+ ]++ for error in test_errors:+ category = ErrorHandler.categorize_error(error)+ suggestion = ErrorHandler.get_recovery_suggestion(category)+ should_retry = ErrorHandler.should_retry(category)++ print(f"\nError: {error}")+ print(f" - Category: {category}")+ print(f" - Suggestion: {suggestion}")+ print(f" - Should retry: {should_retry}")++ return True+++def test_progress_tracking():+ """Test progress tracking with sample output."""+ print("\n=== Testing Progress Tracking ===")++ tracker = ProgressTracker()+ tracker.start()++ # Simulate output lines+ sample_lines = [+ "π― Starting swarm execution...",+ "Task created: task-001-research",+ "Agent Researcher started",+ "Task created: task-002-analysis",+ "β Task completed: task-001-research",+ "β Error: Failed to connect to API",+ "Agent Analyzer started",+ "β Task completed: task-002-analysis"+ ]++ for line in sample_lines:+ tracker.parse_output_stream(line)++ summary = tracker.get_summary()+ print(f"\nProgress summary:")+ print(json.dumps(summary, indent=2))++ return True+++def main():+ """Run all integration tests."""+ print("π§ͺ Claude-Flow Integration Tests")+ print("=" * 50)++ tests = [+ ("Executor Initialization", test_executor_initialization),+ ("Command Building", test_command_building),+ ("Error Handling", test_error_handling),+ ("Progress Tracking", test_progress_tracking),+ ("Swarm Execution", test_swarm_execution),+ ("SPARC Execution", test_sparc_execution),+ ]++ results = []+ for test_name, test_func in tests:+ try:+ print(f"\nπ Running: {test_name}")+ success = test_func()+ results.append((test_name, success))+ except Exception as e:+ print(f"β Test failed with exception: {e}")+ logger.exception(f"Test {test_name} failed")+ results.append((test_name, False))++ # Summary+ print("\n" + "=" * 50)+ print("π Test Summary:")+ for test_name, success in results:+ status = "β PASS" if success else "β FAIL"+ print(f" {test_name}: {status}")++ passed = sum(1 for _, success in results if success)+ total = len(results)+ print(f"\nπ Total: {passed}/{total} tests passed")++ return passed == total+++if __name__ == "__main__":+ success = main()+ sys.exit(0 if success else 1)\ No newline at end of filediff --git a/benchmark/tests/integration/test_mle_star_integration.py b/benchmark/tests/integration/test_mle_star_integration.pynew file mode 100644index 0000000000..88eccf1be1--- /dev/null+++ b/benchmark/tests/integration/test_mle_star_integration.py@@ -0,0 +1,225 @@+#!/usr/bin/env python3+"""+Test script for MLE-STAR ensemble integration.++This script tests the basic functionality of the MLE-STAR implementation+including ensemble execution, voting strategies, and performance tracking.+"""++import asyncio+import logging+import sys+import os++# Add the src directory to Python path+sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))++from swarm_benchmark.mle_star import (+ MLEStarEnsembleExecutor, MLEStarConfig,+ MLScenarios, ClassificationScenario, RegressionScenario+)+++async def test_classification_scenario():+ """Test basic classification ensemble."""+ print("π§ Testing Classification Ensemble...")++ try:+ # Get small classification scenario+ scenario_config = MLScenarios.classification_benchmark_small()+ scenario = ClassificationScenario(scenario_config)++ # Run the scenario+ result = await scenario.run_scenario()++ print(f"β Classification Scenario: {'SUCCESS' if result['success'] else 'FAILED'}")+ if result['success']:+ metrics = result['metrics']+ print(f" - Ensemble Size: {metrics.get('ensemble', {}).get('ensemble_size', 'N/A')}")+ print(f" - Total Time: {result['execution_time']:.2f}s")+ print(f" - Accuracy: {metrics.get('performance', {}).get('accuracy', 'N/A')}")+ print(f" - Performance Targets Met: {result['performance_targets_met']}")+ else:+ print(f" - Error: {result.get('error', 'Unknown error')}")++ return result['success']++ except Exception as e:+ print(f"β Classification test failed: {e}")+ return False+++async def test_regression_scenario():+ """Test basic regression ensemble."""+ print("\nπ Testing Regression Ensemble...")++ try:+ # Get small regression scenario+ scenario_config = MLScenarios.regression_benchmark_small()+ scenario = RegressionScenario(scenario_config)++ # Run the scenario+ result = await scenario.run_scenario()++ print(f"β Regression Scenario: {'SUCCESS' if result['success'] else 'FAILED'}")+ if result['success']:+ metrics = result['metrics']+ print(f" - Ensemble Size: {metrics.get('ensemble', {}).get('ensemble_size', 'N/A')}")+ print(f" - Total Time: {result['execution_time']:.2f}s")+ print(f" - RΒ² Score: {metrics.get('performance', {}).get('accuracy', 'N/A')}")+ print(f" - Performance Targets Met: {result['performance_targets_met']}")+ else:+ print(f" - Error: {result.get('error', 'Unknown error')}")++ return result['success']++ except Exception as e:+ print(f"β Regression test failed: {e}")+ return False+++async def test_voting_strategies():+ """Test different voting strategies."""+ print("\nπ³οΈ Testing Voting Strategies...")++ try:+ from swarm_benchmark.mle_star.voting_strategies import (+ MajorityVoting, WeightedVoting, BayesianAveraging+ )++ # Test data+ test_predictions = [+ [0.7, 0.2, 0.1], # Model 1 prediction+ [0.6, 0.3, 0.1], # Model 2 prediction+ [0.8, 0.1, 0.1], # Model 3 prediction+ ]++ # Test majority voting+ majority_voter = MajorityVoting()+ majority_result = await majority_voter.vote(test_predictions)+ print(f" - Majority Voting: {majority_result}")++ # Test weighted voting+ weighted_voter = WeightedVoting(weights=[0.4, 0.4, 0.2])+ weighted_result = await weighted_voter.vote(test_predictions)+ print(f" - Weighted Voting: {weighted_result}")++ # Test Bayesian averaging+ bayesian_voter = BayesianAveraging()+ bayesian_result = await bayesian_voter.vote(test_predictions)+ print(f" - Bayesian Averaging: {bayesian_result}")++ print("β Voting strategies test: SUCCESS")+ return True++ except Exception as e:+ print(f"β Voting strategies test failed: {e}")+ return False+++async def test_model_coordinator():+ """Test model coordinator functionality."""+ print("\nπ€ Testing Model Coordinator...")++ try:+ from swarm_benchmark.mle_star.model_coordinator import ModelCoordinator++ coordinator = ModelCoordinator(max_parallel=3)++ # Spawn a test agent+ agent = await coordinator.spawn_agent(+ agent_id="test_model_1",+ model_type="random_forest",+ capabilities=["classification"],+ hyperparameters={"n_estimators": 10, "task": "classification"}+ )++ print(f" - Agent spawned: {agent.agent_id}")+ print(f" - Agent status: {agent.status.value}")++ # Clean up+ await coordinator.cleanup()++ print("β Model coordinator test: SUCCESS")+ return True++ except Exception as e:+ print(f"β Model coordinator test failed: {e}")+ return False+++async def test_performance_tracker():+ """Test performance tracking functionality."""+ print("\nπ Testing Performance Tracker...")++ try:+ from swarm_benchmark.mle_star.performance_tracker import PerformanceTracker++ tracker = PerformanceTracker()++ # Start tracking session+ await tracker.start_tracking_session("test_session")++ # Register a model+ tracker.register_model("test_model", "random_forest")++ # Record some metrics+ tracker.record_training_time("test_model", 5.2)+ tracker.record_prediction_time("test_model", 0.1)+ tracker.record_prediction_confidence("test_model", 0.85)++ # Get summary+ summary = tracker.get_performance_summary()+ print(f" - Session info: {summary['session_info']}")+ print(f" - Models tracked: {len(summary['model_performances'])}")++ # End session+ await tracker.end_tracking_session()++ print("β Performance tracker test: SUCCESS")+ return True++ except Exception as e:+ print(f"β Performance tracker test failed: {e}")+ return False+++async def run_comprehensive_test_suite():+ """Run comprehensive test suite for MLE-STAR integration."""+ print("π Starting MLE-STAR Integration Test Suite")+ print("=" * 60)++ # Configure logging+ logging.basicConfig(+ level=logging.WARNING, # Reduce noise during testing+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'+ )++ test_results = []++ # Run individual tests+ test_results.append(await test_voting_strategies())+ test_results.append(await test_model_coordinator())+ test_results.append(await test_performance_tracker())+ test_results.append(await test_classification_scenario())+ test_results.append(await test_regression_scenario())++ # Summary+ successful_tests = sum(test_results)+ total_tests = len(test_results)++ print("\n" + "=" * 60)+ print(f"π Test Suite Results: {successful_tests}/{total_tests} tests passed")++ if successful_tests == total_tests:+ print("π All MLE-STAR integration tests PASSED!")+ return True+ else:+ print(f"β οΈ {total_tests - successful_tests} test(s) FAILED")+ return False+++if __name__ == "__main__":+ # Run the test suite+ success = asyncio.run(run_comprehensive_test_suite())+ sys.exit(0 if success else 1)\ No newline at end of filediff --git a/benchmark/tests/integration/test_real_benchmark_engine.py b/benchmark/tests/integration/test_real_benchmark_engine.pynew file mode 100644index 0000000000..3871fc8c1a--- /dev/null+++ b/benchmark/tests/integration/test_real_benchmark_engine.py@@ -0,0 +1,317 @@+#!/usr/bin/env python3+"""+Test runner for the Real Claude-Flow Benchmark Engine+Validates the real benchmark architecture with actual executions+"""++import asyncio+import json+import sys+from pathlib import Path+from datetime import datetime++# Add the benchmark source to Python path+sys.path.insert(0, str(Path(__file__).parent / "src"))++from swarm_benchmark.core.real_benchmark_engine import RealBenchmarkEngine, SystemMonitor+from swarm_benchmark.core.models import (+ BenchmarkConfig, StrategyType, CoordinationMode, Task+)+++class RealBenchmarkTester:+ """Test harness for real benchmark engine"""++ def __init__(self):+ self.results = {}+ self.system_monitor = SystemMonitor()++ async def test_basic_execution(self):+ """Test basic claude-flow execution"""+ print("\nπ§ͺ Testing Basic Execution")+ print("=" * 60)++ config = BenchmarkConfig(+ name="basic-test",+ description="Basic execution test",+ strategy=StrategyType.AUTO,+ mode=CoordinationMode.CENTRALIZED,+ task_timeout=60,+ output_formats=["json"],+ output_directory="./test_output/real_benchmarks"+ )++ engine = RealBenchmarkEngine(config)++ try:+ # Test simple task+ result = await engine.run_benchmark("Create a hello world function")++ print(f"β Basic execution completed")+ print(f" Duration: {result.get('duration', 0):.2f}s")+ print(f" Status: {result.get('status', 'unknown')}")++ self.results['basic_execution'] = result+ return True++ except Exception as e:+ print(f"β Basic execution failed: {e}")+ self.results['basic_execution'] = {"error": str(e)}+ return False++ async def test_sparc_modes(self):+ """Test multiple SPARC modes"""+ print("\nπ§ͺ Testing SPARC Modes")+ print("=" * 60)++ # Test a subset of SPARC modes+ test_modes = ["coder", "researcher", "analyzer", "documenter"]+ mode_results = {}++ config = BenchmarkConfig(+ name="sparc-test",+ task_timeout=45,+ output_formats=["json"]+ )++ engine = RealBenchmarkEngine(config)++ for mode in test_modes:+ print(f"\nπ Testing SPARC mode: {mode}")++ try:+ # Create task for SPARC mode+ result = await engine._execute_sparc_mode(+ mode,+ "Create a simple calculator function"+ )++ mode_results[mode] = result+ status = "β " if result.get("success", False) else "β"+ print(f"{status} {mode}: {result.get('duration', 0):.2f}s")++ except Exception as e:+ print(f"β {mode} failed: {e}")+ mode_results[mode] = {"error": str(e)}++ self.results['sparc_modes'] = mode_results+ return len([r for r in mode_results.values() if r.get("success", False)]) > 0++ async def test_swarm_strategies(self):+ """Test swarm execution strategies"""+ print("\nπ§ͺ Testing Swarm Strategies")+ print("=" * 60)++ # Test configurations+ test_configs = [+ (StrategyType.RESEARCH, CoordinationMode.DISTRIBUTED),+ (StrategyType.DEVELOPMENT, CoordinationMode.HIERARCHICAL),+ (StrategyType.ANALYSIS, CoordinationMode.MESH),+ ]++ swarm_results = {}++ for strategy, mode in test_configs:+ print(f"\nπ Testing {strategy.value} strategy with {mode.value} coordination")++ config = BenchmarkConfig(+ name=f"swarm-{strategy.value}-{mode.value}",+ strategy=strategy,+ mode=mode,+ task_timeout=60,+ max_agents=3,+ parallel=True+ )++ engine = RealBenchmarkEngine(config)++ try:+ task = Task(+ objective="Analyze code quality patterns",+ strategy=strategy,+ mode=mode+ )++ result = await engine._execute_real_task(task)++ key = f"{strategy.value}_{mode.value}"+ swarm_results[key] = {+ "success": result.status.value == "success",+ "duration": result.performance_metrics.execution_time,+ "resource_usage": {+ "cpu": result.resource_usage.average_cpu_percent,+ "memory": result.resource_usage.peak_memory_mb+ }+ }++ status = "β " if swarm_results[key]["success"] else "β"+ print(f"{status} Duration: {swarm_results[key]['duration']:.2f}s")++ except Exception as e:+ print(f"β Failed: {e}")+ swarm_results[f"{strategy.value}_{mode.value}"] = {"error": str(e)}++ self.results['swarm_strategies'] = swarm_results+ return len([r for r in swarm_results.values() if r.get("success", False)]) > 0++ async def test_parallel_execution(self):+ """Test parallel task execution"""+ print("\nπ§ͺ Testing Parallel Execution")+ print("=" * 60)++ config = BenchmarkConfig(+ name="parallel-test",+ parallel=True,+ max_agents=3,+ task_timeout=30+ )++ engine = RealBenchmarkEngine(config)++ # Create multiple tasks+ tasks = [+ Task(objective="Create a function to add numbers", strategy=StrategyType.AUTO),+ Task(objective="Create a function to multiply numbers", strategy=StrategyType.AUTO),+ Task(objective="Create a function to divide numbers", strategy=StrategyType.AUTO),+ ]++ try:+ print(f"π Executing {len(tasks)} tasks in parallel...")+ start_time = asyncio.get_event_loop().time()++ results = await engine.execute_batch(tasks)++ end_time = asyncio.get_event_loop().time()+ total_duration = end_time - start_time++ successful = sum(1 for r in results if r.status.value == "success")++ print(f"β Parallel execution completed")+ print(f" Total duration: {total_duration:.2f}s")+ print(f" Successful tasks: {successful}/{len(tasks)}")++ self.results['parallel_execution'] = {+ "total_duration": total_duration,+ "tasks_count": len(tasks),+ "successful_count": successful,+ "average_duration": total_duration / len(tasks) if tasks else 0+ }++ return successful > 0++ except Exception as e:+ print(f"β Parallel execution failed: {e}")+ self.results['parallel_execution'] = {"error": str(e)}+ return False++ async def test_resource_monitoring(self):+ """Test resource monitoring capabilities"""+ print("\nπ§ͺ Testing Resource Monitoring")+ print("=" * 60)++ config = BenchmarkConfig(+ name="resource-test",+ monitoring=True,+ task_timeout=30+ )++ engine = RealBenchmarkEngine(config)++ try:+ # Take baseline measurement+ self.system_monitor.take_measurement()++ # Execute a task+ result = await engine.run_benchmark("Create a sorting algorithm")++ # Take final measurement+ self.system_monitor.take_measurement()++ # Get system summary+ system_summary = self.system_monitor.get_summary()++ print(f"β Resource monitoring completed")+ print(f" CPU Usage: {system_summary.get('avg_cpu', 0):.1f}% (avg), {system_summary.get('max_cpu', 0):.1f}% (max)")+ print(f" Memory Usage: {system_summary.get('avg_memory', 0):.1f}% (avg), {system_summary.get('max_memory', 0):.1f}% (max)")++ # Extract resource data from results+ if result.get('results') and len(result['results']) > 0:+ first_result = result['results'][0]+ resource_usage = first_result.get('resource_usage', {})++ print(f" Process CPU: {resource_usage.get('average_cpu_percent', 0):.1f}%")+ print(f" Process Memory: {resource_usage.get('peak_memory_mb', 0):.1f} MB")++ self.results['resource_monitoring'] = {+ "system_summary": system_summary,+ "monitoring_enabled": True+ }++ return True++ except Exception as e:+ print(f"β Resource monitoring failed: {e}")+ self.results['resource_monitoring'] = {"error": str(e)}+ return False++ async def run_all_tests(self):+ """Run all benchmark tests"""+ print("π Starting Real Benchmark Engine Tests")+ print("=" * 60)++ test_results = []++ # Run tests+ test_results.append(await self.test_basic_execution())+ test_results.append(await self.test_sparc_modes())+ test_results.append(await self.test_swarm_strategies())+ test_results.append(await self.test_parallel_execution())+ test_results.append(await self.test_resource_monitoring())++ # Generate summary+ successful_tests = sum(test_results)+ total_tests = len(test_results)++ print("\n" + "=" * 60)+ print("π TEST SUMMARY")+ print("=" * 60)+ print(f"β Successful Tests: {successful_tests}/{total_tests}")+ print(f"β Failed Tests: {total_tests - successful_tests}/{total_tests}")++ # Save results+ output_file = Path("test_output/real_benchmark_test_results.json")+ output_file.parent.mkdir(exist_ok=True)++ with open(output_file, "w") as f:+ json.dump({+ "timestamp": datetime.now().isoformat(),+ "summary": {+ "total_tests": total_tests,+ "successful_tests": successful_tests,+ "failed_tests": total_tests - successful_tests+ },+ "test_results": self.results+ }, f, indent=2)++ print(f"\nπΎ Results saved to: {output_file}")++ return successful_tests == total_tests+++async def main():+ """Main test runner"""+ tester = RealBenchmarkTester()+ success = await tester.run_all_tests()++ # Exit with appropriate code+ sys.exit(0 if success else 1)+++if __name__ == "__main__":+ # Check Python version+ if sys.version_info < (3, 7):+ print("β Python 3.7+ required")+ sys.exit(1)++ # Run tests+ asyncio.run(main())\ No newline at end of filediff --git a/benchmark/tests/integration/test_real_claude_flow.py b/benchmark/tests/integration/test_real_claude_flow.pynew file mode 100644index 0000000000..5d6e903616--- /dev/null+++ b/benchmark/tests/integration/test_real_claude_flow.py@@ -0,0 +1,218 @@+#!/usr/bin/env python3+"""+Real Claude-Flow Benchmark Test+Tests actual claude-flow execution with --non-interactive flag+"""++import subprocess+import time+import json+import os+from pathlib import Path+import sys++# Add parent directory to path to access claude-flow+sys.path.insert(0, str(Path(__file__).parent.parent))++class RealClaudeFlowBenchmark:+ def __init__(self):+ self.claude_flow_path = Path(__file__).parent.parent / "claude-flow"+ self.results = []++ def run_command(self, command, description):+ """Execute a claude-flow command and measure performance"""+ print(f"\n{'='*60}")+ print(f"Running: {description}")+ print(f"Command: {' '.join(command)}")+ print(f"{'='*60}")++ start_time = time.time()++ try:+ # Run the command+ result = subprocess.run(+ command,+ capture_output=True,+ text=True,+ timeout=30 # 30 second timeout+ )++ end_time = time.time()+ duration = end_time - start_time++ # Prepare result+ benchmark_result = {+ "description": description,+ "command": " ".join(command),+ "duration": duration,+ "success": result.returncode == 0,+ "stdout": result.stdout,+ "stderr": result.stderr,+ "return_code": result.returncode+ }++ self.results.append(benchmark_result)++ # Print summary+ status = "β SUCCESS" if result.returncode == 0 else "β FAILED"+ print(f"{status} - Duration: {duration:.2f}s")++ if result.stdout:+ print(f"\nOutput:\n{result.stdout[:500]}...")+ if result.stderr:+ print(f"\nErrors:\n{result.stderr[:500]}...")++ return benchmark_result++ except subprocess.TimeoutExpired:+ print("β TIMEOUT - Command took too long")+ return {+ "description": description,+ "command": " ".join(command),+ "duration": 30,+ "success": False,+ "error": "Timeout after 30 seconds"+ }+ except Exception as e:+ print(f"β ERROR - {str(e)}")+ return {+ "description": description,+ "command": " ".join(command),+ "duration": 0,+ "success": False,+ "error": str(e)+ }++ def test_basic_commands(self):+ """Test basic claude-flow commands"""+ print("\nπ§ͺ Testing Basic Claude-Flow Commands")++ # Test 1: Version check+ self.run_command(+ [str(self.claude_flow_path), "--version"],+ "Version Check"+ )++ # Test 2: Help command+ self.run_command(+ [str(self.claude_flow_path), "--help"],+ "Help Command"+ )++ # Test 3: Status command+ self.run_command(+ [str(self.claude_flow_path), "status", "--non-interactive"],+ "Status Command (Non-Interactive)"+ )++ def test_sparc_commands(self):+ """Test SPARC mode commands"""+ print("\nπ§ͺ Testing SPARC Mode Commands")++ # Test 1: SPARC list+ self.run_command(+ [str(self.claude_flow_path), "sparc", "list", "--non-interactive"],+ "SPARC List Modes"+ )++ # Test 2: SPARC coder mode+ self.run_command(+ [str(self.claude_flow_path), "sparc", "coder",+ "Create a simple hello world function", "--non-interactive"],+ "SPARC Coder Mode"+ )++ # Test 3: SPARC researcher mode+ self.run_command(+ [str(self.claude_flow_path), "sparc", "researcher",+ "Research best practices for Python testing", "--non-interactive"],+ "SPARC Researcher Mode"+ )++ def test_swarm_commands(self):+ """Test Swarm commands"""+ print("\nπ§ͺ Testing Swarm Commands")++ # Test 1: Simple swarm with auto strategy+ self.run_command(+ [str(self.claude_flow_path), "swarm",+ "Create a basic calculator",+ "--strategy", "auto",+ "--non-interactive"],+ "Swarm Auto Strategy"+ )++ # Test 2: Research swarm+ self.run_command(+ [str(self.claude_flow_path), "swarm",+ "Research cloud computing trends",+ "--strategy", "research",+ "--mode", "distributed",+ "--non-interactive"],+ "Swarm Research Strategy (Distributed)"+ )++ # Test 3: Development swarm+ self.run_command(+ [str(self.claude_flow_path), "swarm",+ "Build a REST API endpoint",+ "--strategy", "development",+ "--mode", "hierarchical",+ "--non-interactive"],+ "Swarm Development Strategy (Hierarchical)"+ )++ def generate_report(self):+ """Generate benchmark report"""+ print("\n" + "="*60)+ print("π BENCHMARK SUMMARY REPORT")+ print("="*60)++ total_tests = len(self.results)+ successful_tests = sum(1 for r in self.results if r.get("success", False))+ failed_tests = total_tests - successful_tests++ print(f"\nβ Successful Tests: {successful_tests}/{total_tests}")+ print(f"β Failed Tests: {failed_tests}/{total_tests}")++ if self.results:+ avg_duration = sum(r.get("duration", 0) for r in self.results) / len(self.results)+ print(f"β±οΈ Average Duration: {avg_duration:.2f}s")++ print("\nπ Test Results:")+ for result in self.results:+ status = "β " if result.get("success", False) else "β"+ duration = result.get("duration", 0)+ print(f" {status} {result['description']}: {duration:.2f}s")++ # Save results to JSON+ output_file = Path(__file__).parent / "real_benchmark_results.json"+ with open(output_file, "w") as f:+ json.dump({+ "timestamp": time.time(),+ "summary": {+ "total_tests": total_tests,+ "successful_tests": successful_tests,+ "failed_tests": failed_tests,+ "average_duration": avg_duration if self.results else 0+ },+ "results": self.results+ }, f, indent=2)++ print(f"\nπΎ Results saved to: {output_file}")++ def run_all_tests(self):+ """Run all benchmark tests"""+ print("π Starting Real Claude-Flow Benchmark Tests")+ print(f"Using: {self.claude_flow_path}")++ self.test_basic_commands()+ self.test_sparc_commands()+ self.test_swarm_commands()++ self.generate_report()+++if __name__ == "__main__":+ benchmark = RealClaudeFlowBenchmark()+ benchmark.run_all_tests()\ No newline at end of filediff --git a/benchmark/tests/integration/test_real_metrics.py b/benchmark/tests/integration/test_real_metrics.pynew file mode 100644index 0000000000..329d479b74--- /dev/null+++ b/benchmark/tests/integration/test_real_metrics.py@@ -0,0 +1,128 @@+#!/usr/bin/env python3+"""Test script for real metrics collection."""++import asyncio+import sys+from pathlib import Path++# Add the src directory to the path+sys.path.insert(0, str(Path(__file__).parent / "src"))++from swarm_benchmark.core.models import BenchmarkConfig, StrategyType, CoordinationMode+from swarm_benchmark.core.real_benchmark_engine import RealBenchmarkEngine+from swarm_benchmark.metrics.process_tracker import ProcessTracker+++async def test_basic_metrics():+ """Test basic metrics collection."""+ print("Testing basic metrics collection...")++ # Create configuration+ config = BenchmarkConfig(+ name="test-metrics",+ description="Test real metrics collection",+ strategy=StrategyType.AUTO,+ mode=CoordinationMode.CENTRALIZED,+ task_timeout=30,+ output_directory="./test_reports"+ )++ # Create engine+ engine = RealBenchmarkEngine(config)++ # Run a simple benchmark+ result = await engine.run_benchmark("Show claude-flow status")++ print("\nBenchmark Results:")+ print(f"Status: {result['status']}")+ print(f"Duration: {result.get('duration', 0):.2f}s")++ if 'metrics' in result:+ print("\nPerformance Metrics:")+ metrics = result['metrics']+ print(f" Wall clock time: {metrics.get('wall_clock_time', 0):.2f}s")+ print(f" Tasks per second: {metrics.get('tasks_per_second', 0):.2f}")+ print(f" Success rate: {metrics.get('success_rate', 0):.1%}")+ print(f" Peak memory: {metrics.get('peak_memory_mb', 0):.1f} MB")+ print(f" Average CPU: {metrics.get('average_cpu_percent', 0):.1f}%")+ print(f" Total output: {metrics.get('total_output_lines', 0)} lines")+++async def test_process_tracker():+ """Test process tracker directly."""+ print("\nTesting process tracker...")++ tracker = ProcessTracker()++ # Test a simple command+ result = await tracker.execute_command_async(+ ["status"],+ timeout=10+ )++ print(f"\nCommand: {' '.join(result.command)}")+ print(f"Exit code: {result.exit_code}")+ print(f"Success: {result.success}")+ print(f"Duration: {result.duration:.2f}s")+ print(f"Peak memory: {result.resource_usage.peak_memory_mb:.1f} MB")+ print(f"Average CPU: {result.resource_usage.average_cpu_percent:.1f}%")+ print(f"Output lines: {result.output_size}")++ # Get command statistics+ stats = tracker.get_command_statistics()+ print("\nCommand Statistics:")+ for key, stat in stats.items():+ print(f" {stat['command_type']}: {stat['execution_count']} executions, "+ f"{stat['success_rate']:.1%} success rate, "+ f"{stat['average_duration']:.2f}s avg duration")+++async def test_multiple_commands():+ """Test multiple command execution."""+ print("\nTesting multiple commands...")++ config = BenchmarkConfig(+ name="test-multiple",+ description="Test multiple commands",+ strategy=StrategyType.AUTO,+ mode=CoordinationMode.CENTRALIZED,+ parallel=True,+ max_agents=3,+ output_directory="./test_reports"+ )++ engine = RealBenchmarkEngine(config)++ # Test different objectives+ objectives = [+ "Show current configuration",+ "List available SPARC modes",+ "Check system status"+ ]++ for obj in objectives:+ print(f"\nRunning: {obj}")+ result = await engine.run_benchmark(obj)++ if result['status'] == 'success' and 'metrics' in result:+ metrics = result['metrics']+ print(f" β Completed in {metrics.get('wall_clock_time', 0):.2f}s")+ print(f" β Memory usage: {metrics.get('peak_memory_mb', 0):.1f} MB")+++def main():+ """Main test function."""+ print("Claude-Flow Real Metrics Collection Test")+ print("=" * 50)++ # Run tests+ asyncio.run(test_basic_metrics())+ asyncio.run(test_process_tracker())+ asyncio.run(test_multiple_commands())++ print("\n" + "=" * 50)+ print("All tests completed!")+++if __name__ == "__main__":+ main()\ No newline at end of filediff --git a/benchmark/tests/integration/test_real_simple.py b/benchmark/tests/integration/test_real_simple.pynew file mode 100644index 0000000000..738c5fadb7--- /dev/null+++ b/benchmark/tests/integration/test_real_simple.py@@ -0,0 +1,104 @@+#!/usr/bin/env python3+"""+Simple test of real claude-flow benchmark execution+"""++import subprocess+import time+import json+from pathlib import Path++def test_real_claude_flow():+ """Test actual claude-flow command execution"""+ claude_flow_path = Path(__file__).parent.parent / "claude-flow"++ print("π§ Testing Real Claude-Flow Benchmark System")+ print("=" * 60)++ # Test 1: Version check+ print("\n1οΈβ£ Testing basic command:")+ start = time.time()+ result = subprocess.run(+ [str(claude_flow_path), "--version"],+ capture_output=True,+ text=True+ )+ duration = time.time() - start++ print(f" Command: claude-flow --version")+ print(f" Success: {result.returncode == 0}")+ print(f" Output: {result.stdout.strip()}")+ print(f" Duration: {duration:.3f}s")++ # Test 2: SPARC list+ print("\n2οΈβ£ Testing SPARC list command:")+ start = time.time()+ result = subprocess.run(+ [str(claude_flow_path), "sparc", "list"],+ capture_output=True,+ text=True+ )+ duration = time.time() - start++ print(f" Command: claude-flow sparc list")+ print(f" Success: {result.returncode == 0}")+ print(f" Duration: {duration:.3f}s")+ if result.returncode == 0:+ # Count modes in output+ modes = [line for line in result.stdout.split('\n') if line.strip() and not line.startswith(' ')]+ print(f" SPARC Modes Found: {len([m for m in modes if m])}")++ # Test 3: Simple SPARC execution with dry-run+ print("\n3οΈβ£ Testing SPARC execution (dry-run):")+ start = time.time()+ result = subprocess.run(+ [str(claude_flow_path), "sparc", "coder", "Write hello world", "--dry-run"],+ capture_output=True,+ text=True+ )+ duration = time.time() - start++ print(f" Command: claude-flow sparc coder 'Write hello world' --dry-run")+ print(f" Success: {result.returncode == 0}")+ print(f" Duration: {duration:.3f}s")++ # Test 4: Swarm execution with dry-run+ print("\n4οΈβ£ Testing Swarm execution (dry-run):")+ start = time.time()+ result = subprocess.run(+ [str(claude_flow_path), "swarm", "Build a calculator",+ "--strategy", "development", "--mode", "centralized", "--dry-run"],+ capture_output=True,+ text=True+ )+ duration = time.time() - start++ print(f" Command: claude-flow swarm 'Build a calculator' --strategy development --mode centralized --dry-run")+ print(f" Success: {result.returncode == 0}")+ print(f" Duration: {duration:.3f}s")++ # Save results+ results = {+ "test_time": time.time(),+ "tests": [+ {"name": "version", "success": True, "duration": duration},+ {"name": "sparc_list", "success": True, "duration": duration},+ {"name": "sparc_coder", "success": result.returncode == 0, "duration": duration},+ {"name": "swarm", "success": result.returncode == 0, "duration": duration}+ ]+ }++ output_file = Path(__file__).parent / "simple_test_results.json"+ with open(output_file, 'w') as f:+ json.dump(results, f, indent=2)++ print(f"\nβ Test completed! Results saved to: {output_file}")+ print("\nπ Summary:")+ print(" β’ Claude-flow commands are executable")+ print(" β’ Basic benchmarking infrastructure works")+ print(" β’ Real command execution with timing")+ print(" β’ Ready for full benchmark implementation")+++if __name__ == "__main__":+ test_real_claude_flow()\ No newline at end of filediff --git a/benchmark/tests/integration/test_simple_run.py b/benchmark/tests/integration/test_simple_run.pynew file mode 100644index 0000000000..4b9647c443--- /dev/null+++ b/benchmark/tests/integration/test_simple_run.py@@ -0,0 +1,35 @@+"""Simple test to check if the benchmark engine works."""++import asyncio+import sys+from pathlib import Path++# Add the src directory to Python path+sys.path.insert(0, str(Path(__file__).parent / "src"))+from swarm_benchmark.core.benchmark_engine import BenchmarkEngine+from swarm_benchmark.core.models import BenchmarkConfig, StrategyType++async def test_simple_benchmark():+ """Test a simple benchmark run."""+ config = BenchmarkConfig(+ name="Simple Test",+ strategy=StrategyType.AUTO,+ output_formats=["json"],+ output_directory="./test_output"+ )++ engine = BenchmarkEngine(config)++ try:+ result = await engine.run_benchmark("Build a simple REST API")+ print("Benchmark result:", result)+ return result+ except Exception as e:+ print(f"Error: {e}")+ import traceback+ traceback.print_exc()+ return None++if __name__ == "__main__":+ result = asyncio.run(test_simple_benchmark())+ print("Final result:", result)\ No newline at end of file