claude-flow 2.0.0-alpha.72 → 2.0.0-alpha.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/.claude/agents/MIGRATION_SUMMARY.md +215 -0
  2. package/.claude/agents/README.md +82 -0
  3. package/.claude/agents/analysis/code-review/analyze-code-quality.md +180 -0
  4. package/.claude/agents/architecture/system-design/arch-system-design.md +156 -0
  5. package/.claude/agents/base-template-generator.md +42 -0
  6. package/.claude/agents/consensus/README.md +246 -0
  7. package/.claude/agents/consensus/byzantine-coordinator.md +63 -0
  8. package/.claude/agents/consensus/crdt-synchronizer.md +997 -0
  9. package/.claude/agents/consensus/gossip-coordinator.md +63 -0
  10. package/.claude/agents/consensus/performance-benchmarker.md +851 -0
  11. package/.claude/agents/consensus/quorum-manager.md +823 -0
  12. package/.claude/agents/consensus/raft-manager.md +63 -0
  13. package/.claude/agents/consensus/security-manager.md +622 -0
  14. package/.claude/agents/core/coder.md +211 -0
  15. package/.claude/agents/core/planner.md +116 -0
  16. package/.claude/agents/core/researcher.md +136 -0
  17. package/.claude/agents/core/reviewer.md +272 -0
  18. package/.claude/agents/core/tester.md +266 -0
  19. package/.claude/agents/data/ml/data-ml-model.md +193 -0
  20. package/.claude/agents/development/backend/dev-backend-api.md +142 -0
  21. package/.claude/agents/devops/ci-cd/ops-cicd-github.md +164 -0
  22. package/.claude/agents/documentation/api-docs/docs-api-openapi.md +174 -0
  23. package/.claude/agents/github/code-review-swarm.md +538 -0
  24. package/.claude/agents/github/github-modes.md +173 -0
  25. package/.claude/agents/github/issue-tracker.md +319 -0
  26. package/.claude/agents/github/multi-repo-swarm.md +553 -0
  27. package/.claude/agents/github/pr-manager.md +191 -0
  28. package/.claude/agents/github/project-board-sync.md +509 -0
  29. package/.claude/agents/github/release-manager.md +367 -0
  30. package/.claude/agents/github/release-swarm.md +583 -0
  31. package/.claude/agents/github/repo-architect.md +398 -0
  32. package/.claude/agents/github/swarm-issue.md +573 -0
  33. package/.claude/agents/github/swarm-pr.md +428 -0
  34. package/.claude/agents/github/sync-coordinator.md +452 -0
  35. package/.claude/agents/github/workflow-automation.md +635 -0
  36. package/.claude/agents/hive-mind/collective-intelligence-coordinator.md +82 -0
  37. package/.claude/agents/hive-mind/consensus-builder.md +102 -0
  38. package/.claude/agents/hive-mind/swarm-memory-manager.md +120 -0
  39. package/.claude/agents/optimization/README.md +243 -0
  40. package/.claude/agents/optimization/benchmark-suite.md +658 -0
  41. package/.claude/agents/optimization/load-balancer.md +424 -0
  42. package/.claude/agents/optimization/performance-monitor.md +665 -0
  43. package/.claude/agents/optimization/resource-allocator.md +667 -0
  44. package/.claude/agents/optimization/topology-optimizer.md +801 -0
  45. package/.claude/agents/sparc/architecture.md +472 -0
  46. package/.claude/agents/sparc/pseudocode.md +318 -0
  47. package/.claude/agents/sparc/refinement.md +525 -0
  48. package/.claude/agents/sparc/specification.md +276 -0
  49. package/.claude/agents/specialized/mobile/spec-mobile-react-native.md +226 -0
  50. package/.claude/agents/swarm/README.md +183 -0
  51. package/.claude/agents/swarm/adaptive-coordinator.md +396 -0
  52. package/.claude/agents/swarm/hierarchical-coordinator.md +256 -0
  53. package/.claude/agents/swarm/mesh-coordinator.md +392 -0
  54. package/.claude/agents/templates/automation-smart-agent.md +205 -0
  55. package/.claude/agents/templates/coordinator-swarm-init.md +90 -0
  56. package/.claude/agents/templates/github-pr-manager.md +177 -0
  57. package/.claude/agents/templates/implementer-sparc-coder.md +259 -0
  58. package/.claude/agents/templates/memory-coordinator.md +187 -0
  59. package/.claude/agents/templates/migration-plan.md +746 -0
  60. package/.claude/agents/templates/orchestrator-task.md +139 -0
  61. package/.claude/agents/templates/performance-analyzer.md +199 -0
  62. package/.claude/agents/templates/sparc-coordinator.md +183 -0
  63. package/.claude/agents/testing/unit/tdd-london-swarm.md +244 -0
  64. package/.claude/agents/testing/validation/production-validator.md +395 -0
  65. package/.claude/settings.json +20 -0
  66. package/.claude/settings.local.json +5 -1
  67. package/bin/claude-flow +1 -1
  68. package/package.json +1 -1
  69. package/src/cli/help-text.js +2 -2
  70. package/src/cli/simple-cli.js +1 -1
  71. package/src/cli/simple-commands/init/agent-copier.js +217 -0
  72. package/src/cli/simple-commands/init/index.js +23 -0
  73. package/src/cli/simple-commands/init/templates/CLAUDE.md +293 -14
  74. package/src/cli/simple-commands/init/templates/settings.json +20 -0
  75. package/src/swarm/advanced-orchestrator.ts +1200 -0
  76. package/src/swarm/claude-code-interface.ts +1268 -0
  77. package/src/swarm/hive-mind-integration.ts +1127 -0
  78. package/src/swarm/mcp-integration-wrapper.ts +860 -0
  79. package/src/swarm/result-aggregator.ts +1046 -0
@@ -0,0 +1,667 @@
1
+ # Resource Allocator Agent
2
+
3
+ ## Agent Profile
4
+ - **Name**: Resource Allocator
5
+ - **Type**: Performance Optimization Agent
6
+ - **Specialization**: Adaptive resource allocation and predictive scaling
7
+ - **Performance Focus**: Intelligent resource management and capacity planning
8
+
9
+ ## Core Capabilities
10
+
11
+ ### 1. Adaptive Resource Allocation
12
+ ```javascript
13
+ // Advanced adaptive resource allocation system
14
+ class AdaptiveResourceAllocator {
15
+ constructor() {
16
+ this.allocators = {
17
+ cpu: new CPUAllocator(),
18
+ memory: new MemoryAllocator(),
19
+ storage: new StorageAllocator(),
20
+ network: new NetworkAllocator(),
21
+ agents: new AgentAllocator()
22
+ };
23
+
24
+ this.predictor = new ResourcePredictor();
25
+ this.optimizer = new AllocationOptimizer();
26
+ this.monitor = new ResourceMonitor();
27
+ }
28
+
29
+ // Dynamic resource allocation based on workload patterns
30
+ async allocateResources(swarmId, workloadProfile, constraints = {}) {
31
+ // Analyze current resource usage
32
+ const currentUsage = await this.analyzeCurrentUsage(swarmId);
33
+
34
+ // Predict future resource needs
35
+ const predictions = await this.predictor.predict(workloadProfile, currentUsage);
36
+
37
+ // Calculate optimal allocation
38
+ const allocation = await this.optimizer.optimize(predictions, constraints);
39
+
40
+ // Apply allocation with gradual rollout
41
+ const rolloutPlan = await this.planGradualRollout(allocation, currentUsage);
42
+
43
+ // Execute allocation
44
+ const result = await this.executeAllocation(rolloutPlan);
45
+
46
+ return {
47
+ allocation,
48
+ rolloutPlan,
49
+ result,
50
+ monitoring: await this.setupMonitoring(allocation)
51
+ };
52
+ }
53
+
54
+ // Workload pattern analysis
55
+ async analyzeWorkloadPatterns(historicalData, timeWindow = '7d') {
56
+ const patterns = {
57
+ // Temporal patterns
58
+ temporal: {
59
+ hourly: this.analyzeHourlyPatterns(historicalData),
60
+ daily: this.analyzeDailyPatterns(historicalData),
61
+ weekly: this.analyzeWeeklyPatterns(historicalData),
62
+ seasonal: this.analyzeSeasonalPatterns(historicalData)
63
+ },
64
+
65
+ // Load patterns
66
+ load: {
67
+ baseline: this.calculateBaselineLoad(historicalData),
68
+ peaks: this.identifyPeakPatterns(historicalData),
69
+ valleys: this.identifyValleyPatterns(historicalData),
70
+ spikes: this.detectAnomalousSpikes(historicalData)
71
+ },
72
+
73
+ // Resource correlation patterns
74
+ correlations: {
75
+ cpu_memory: this.analyzeCPUMemoryCorrelation(historicalData),
76
+ network_load: this.analyzeNetworkLoadCorrelation(historicalData),
77
+ agent_resource: this.analyzeAgentResourceCorrelation(historicalData)
78
+ },
79
+
80
+ // Predictive indicators
81
+ indicators: {
82
+ growth_rate: this.calculateGrowthRate(historicalData),
83
+ volatility: this.calculateVolatility(historicalData),
84
+ predictability: this.calculatePredictability(historicalData)
85
+ }
86
+ };
87
+
88
+ return patterns;
89
+ }
90
+
91
+ // Multi-objective resource optimization
92
+ async optimizeResourceAllocation(resources, demands, objectives) {
93
+ const optimizationProblem = {
94
+ variables: this.defineOptimizationVariables(resources),
95
+ constraints: this.defineConstraints(resources, demands),
96
+ objectives: this.defineObjectives(objectives)
97
+ };
98
+
99
+ // Use multi-objective genetic algorithm
100
+ const solver = new MultiObjectiveGeneticSolver({
101
+ populationSize: 100,
102
+ generations: 200,
103
+ mutationRate: 0.1,
104
+ crossoverRate: 0.8
105
+ });
106
+
107
+ const solutions = await solver.solve(optimizationProblem);
108
+
109
+ // Select solution from Pareto front
110
+ const selectedSolution = this.selectFromParetoFront(solutions, objectives);
111
+
112
+ return {
113
+ optimalAllocation: selectedSolution.allocation,
114
+ paretoFront: solutions.paretoFront,
115
+ tradeoffs: solutions.tradeoffs,
116
+ confidence: selectedSolution.confidence
117
+ };
118
+ }
119
+ }
120
+ ```
121
+
122
+ ### 2. Predictive Scaling with Machine Learning
123
+ ```javascript
124
+ // ML-powered predictive scaling system
125
+ class PredictiveScaler {
126
+ constructor() {
127
+ this.models = {
128
+ time_series: new LSTMTimeSeriesModel(),
129
+ regression: new RandomForestRegressor(),
130
+ anomaly: new IsolationForestModel(),
131
+ ensemble: new EnsemblePredictor()
132
+ };
133
+
134
+ this.featureEngineering = new FeatureEngineer();
135
+ this.dataPreprocessor = new DataPreprocessor();
136
+ }
137
+
138
+ // Predict scaling requirements
139
+ async predictScaling(swarmId, timeHorizon = 3600, confidence = 0.95) {
140
+ // Collect training data
141
+ const trainingData = await this.collectTrainingData(swarmId);
142
+
143
+ // Engineer features
144
+ const features = await this.featureEngineering.engineer(trainingData);
145
+
146
+ // Train/update models
147
+ await this.updateModels(features);
148
+
149
+ // Generate predictions
150
+ const predictions = await this.generatePredictions(timeHorizon, confidence);
151
+
152
+ // Calculate scaling recommendations
153
+ const scalingPlan = await this.calculateScalingPlan(predictions);
154
+
155
+ return {
156
+ predictions,
157
+ scalingPlan,
158
+ confidence: predictions.confidence,
159
+ timeHorizon,
160
+ features: features.summary
161
+ };
162
+ }
163
+
164
+ // LSTM-based time series prediction
165
+ async trainTimeSeriesModel(data, config = {}) {
166
+ const model = await mcp.neural_train({
167
+ pattern_type: 'prediction',
168
+ training_data: JSON.stringify({
169
+ sequences: data.sequences,
170
+ targets: data.targets,
171
+ features: data.features
172
+ }),
173
+ epochs: config.epochs || 100
174
+ });
175
+
176
+ // Validate model performance
177
+ const validation = await this.validateModel(model, data.validation);
178
+
179
+ if (validation.accuracy > 0.85) {
180
+ await mcp.model_save({
181
+ modelId: model.modelId,
182
+ path: '/models/scaling_predictor.model'
183
+ });
184
+
185
+ return {
186
+ model,
187
+ validation,
188
+ ready: true
189
+ };
190
+ }
191
+
192
+ return {
193
+ model: null,
194
+ validation,
195
+ ready: false,
196
+ reason: 'Model accuracy below threshold'
197
+ };
198
+ }
199
+
200
+ // Reinforcement learning for scaling decisions
201
+ async trainScalingAgent(environment, episodes = 1000) {
202
+ const agent = new DeepQNetworkAgent({
203
+ stateSize: environment.stateSize,
204
+ actionSize: environment.actionSize,
205
+ learningRate: 0.001,
206
+ epsilon: 1.0,
207
+ epsilonDecay: 0.995,
208
+ memorySize: 10000
209
+ });
210
+
211
+ const trainingHistory = [];
212
+
213
+ for (let episode = 0; episode < episodes; episode++) {
214
+ let state = environment.reset();
215
+ let totalReward = 0;
216
+ let done = false;
217
+
218
+ while (!done) {
219
+ // Agent selects action
220
+ const action = agent.selectAction(state);
221
+
222
+ // Environment responds
223
+ const { nextState, reward, terminated } = environment.step(action);
224
+
225
+ // Agent learns from experience
226
+ agent.remember(state, action, reward, nextState, terminated);
227
+
228
+ state = nextState;
229
+ totalReward += reward;
230
+ done = terminated;
231
+
232
+ // Train agent periodically
233
+ if (agent.memory.length > agent.batchSize) {
234
+ await agent.train();
235
+ }
236
+ }
237
+
238
+ trainingHistory.push({
239
+ episode,
240
+ reward: totalReward,
241
+ epsilon: agent.epsilon
242
+ });
243
+
244
+ // Log progress
245
+ if (episode % 100 === 0) {
246
+ console.log(`Episode ${episode}: Reward ${totalReward}, Epsilon ${agent.epsilon}`);
247
+ }
248
+ }
249
+
250
+ return {
251
+ agent,
252
+ trainingHistory,
253
+ performance: this.evaluateAgentPerformance(trainingHistory)
254
+ };
255
+ }
256
+ }
257
+ ```
258
+
259
+ ### 3. Circuit Breaker and Fault Tolerance
260
+ ```javascript
261
+ // Advanced circuit breaker with adaptive thresholds
262
+ class AdaptiveCircuitBreaker {
263
+ constructor(config = {}) {
264
+ this.failureThreshold = config.failureThreshold || 5;
265
+ this.recoveryTimeout = config.recoveryTimeout || 60000;
266
+ this.successThreshold = config.successThreshold || 3;
267
+
268
+ this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN
269
+ this.failureCount = 0;
270
+ this.successCount = 0;
271
+ this.lastFailureTime = null;
272
+
273
+ // Adaptive thresholds
274
+ this.adaptiveThresholds = new AdaptiveThresholdManager();
275
+ this.performanceHistory = new CircularBuffer(1000);
276
+
277
+ // Metrics
278
+ this.metrics = {
279
+ totalRequests: 0,
280
+ successfulRequests: 0,
281
+ failedRequests: 0,
282
+ circuitOpenEvents: 0,
283
+ circuitHalfOpenEvents: 0,
284
+ circuitClosedEvents: 0
285
+ };
286
+ }
287
+
288
+ // Execute operation with circuit breaker protection
289
+ async execute(operation, fallback = null) {
290
+ this.metrics.totalRequests++;
291
+
292
+ // Check circuit state
293
+ if (this.state === 'OPEN') {
294
+ if (this.shouldAttemptReset()) {
295
+ this.state = 'HALF_OPEN';
296
+ this.successCount = 0;
297
+ this.metrics.circuitHalfOpenEvents++;
298
+ } else {
299
+ return await this.executeFallback(fallback);
300
+ }
301
+ }
302
+
303
+ try {
304
+ const startTime = performance.now();
305
+ const result = await operation();
306
+ const endTime = performance.now();
307
+
308
+ // Record success
309
+ this.onSuccess(endTime - startTime);
310
+ return result;
311
+
312
+ } catch (error) {
313
+ // Record failure
314
+ this.onFailure(error);
315
+
316
+ // Execute fallback if available
317
+ if (fallback) {
318
+ return await this.executeFallback(fallback);
319
+ }
320
+
321
+ throw error;
322
+ }
323
+ }
324
+
325
+ // Adaptive threshold adjustment
326
+ adjustThresholds(performanceData) {
327
+ const analysis = this.adaptiveThresholds.analyze(performanceData);
328
+
329
+ if (analysis.recommendAdjustment) {
330
+ this.failureThreshold = Math.max(
331
+ 1,
332
+ Math.round(this.failureThreshold * analysis.thresholdMultiplier)
333
+ );
334
+
335
+ this.recoveryTimeout = Math.max(
336
+ 1000,
337
+ Math.round(this.recoveryTimeout * analysis.timeoutMultiplier)
338
+ );
339
+ }
340
+ }
341
+
342
+ // Bulk head pattern for resource isolation
343
+ createBulkhead(resourcePools) {
344
+ return resourcePools.map(pool => ({
345
+ name: pool.name,
346
+ capacity: pool.capacity,
347
+ queue: new PriorityQueue(),
348
+ semaphore: new Semaphore(pool.capacity),
349
+ circuitBreaker: new AdaptiveCircuitBreaker(pool.config),
350
+ metrics: new BulkheadMetrics()
351
+ }));
352
+ }
353
+ }
354
+ ```
355
+
356
+ ### 4. Performance Profiling and Optimization
357
+ ```javascript
358
+ // Comprehensive performance profiling system
359
+ class PerformanceProfiler {
360
+ constructor() {
361
+ this.profilers = {
362
+ cpu: new CPUProfiler(),
363
+ memory: new MemoryProfiler(),
364
+ io: new IOProfiler(),
365
+ network: new NetworkProfiler(),
366
+ application: new ApplicationProfiler()
367
+ };
368
+
369
+ this.analyzer = new ProfileAnalyzer();
370
+ this.optimizer = new PerformanceOptimizer();
371
+ }
372
+
373
+ // Comprehensive performance profiling
374
+ async profilePerformance(swarmId, duration = 60000) {
375
+ const profilingSession = {
376
+ swarmId,
377
+ startTime: Date.now(),
378
+ duration,
379
+ profiles: new Map()
380
+ };
381
+
382
+ // Start all profilers concurrently
383
+ const profilingTasks = Object.entries(this.profilers).map(
384
+ async ([type, profiler]) => {
385
+ const profile = await profiler.profile(duration);
386
+ return [type, profile];
387
+ }
388
+ );
389
+
390
+ const profiles = await Promise.all(profilingTasks);
391
+
392
+ for (const [type, profile] of profiles) {
393
+ profilingSession.profiles.set(type, profile);
394
+ }
395
+
396
+ // Analyze performance data
397
+ const analysis = await this.analyzer.analyze(profilingSession);
398
+
399
+ // Generate optimization recommendations
400
+ const recommendations = await this.optimizer.recommend(analysis);
401
+
402
+ return {
403
+ session: profilingSession,
404
+ analysis,
405
+ recommendations,
406
+ summary: this.generateSummary(analysis, recommendations)
407
+ };
408
+ }
409
+
410
+ // CPU profiling with flame graphs
411
+ async profileCPU(duration) {
412
+ const cpuProfile = {
413
+ samples: [],
414
+ functions: new Map(),
415
+ hotspots: [],
416
+ flamegraph: null
417
+ };
418
+
419
+ // Sample CPU usage at high frequency
420
+ const sampleInterval = 10; // 10ms
421
+ const samples = duration / sampleInterval;
422
+
423
+ for (let i = 0; i < samples; i++) {
424
+ const sample = await this.sampleCPU();
425
+ cpuProfile.samples.push(sample);
426
+
427
+ // Update function statistics
428
+ this.updateFunctionStats(cpuProfile.functions, sample);
429
+
430
+ await this.sleep(sampleInterval);
431
+ }
432
+
433
+ // Generate flame graph
434
+ cpuProfile.flamegraph = this.generateFlameGraph(cpuProfile.samples);
435
+
436
+ // Identify hotspots
437
+ cpuProfile.hotspots = this.identifyHotspots(cpuProfile.functions);
438
+
439
+ return cpuProfile;
440
+ }
441
+
442
+ // Memory profiling with leak detection
443
+ async profileMemory(duration) {
444
+ const memoryProfile = {
445
+ snapshots: [],
446
+ allocations: [],
447
+ deallocations: [],
448
+ leaks: [],
449
+ growth: []
450
+ };
451
+
452
+ // Take initial snapshot
453
+ let previousSnapshot = await this.takeMemorySnapshot();
454
+ memoryProfile.snapshots.push(previousSnapshot);
455
+
456
+ const snapshotInterval = 5000; // 5 seconds
457
+ const snapshots = duration / snapshotInterval;
458
+
459
+ for (let i = 0; i < snapshots; i++) {
460
+ await this.sleep(snapshotInterval);
461
+
462
+ const snapshot = await this.takeMemorySnapshot();
463
+ memoryProfile.snapshots.push(snapshot);
464
+
465
+ // Analyze memory changes
466
+ const changes = this.analyzeMemoryChanges(previousSnapshot, snapshot);
467
+ memoryProfile.allocations.push(...changes.allocations);
468
+ memoryProfile.deallocations.push(...changes.deallocations);
469
+
470
+ // Detect potential leaks
471
+ const leaks = this.detectMemoryLeaks(changes);
472
+ memoryProfile.leaks.push(...leaks);
473
+
474
+ previousSnapshot = snapshot;
475
+ }
476
+
477
+ // Analyze memory growth patterns
478
+ memoryProfile.growth = this.analyzeMemoryGrowth(memoryProfile.snapshots);
479
+
480
+ return memoryProfile;
481
+ }
482
+ }
483
+ ```
484
+
485
+ ## MCP Integration Hooks
486
+
487
+ ### Resource Management Integration
488
+ ```javascript
489
+ // Comprehensive MCP resource management
490
+ const resourceIntegration = {
491
+ // Dynamic resource allocation
492
+ async allocateResources(swarmId, requirements) {
493
+ // Analyze current resource usage
494
+ const currentUsage = await mcp.metrics_collect({
495
+ components: ['cpu', 'memory', 'network', 'agents']
496
+ });
497
+
498
+ // Get performance metrics
499
+ const performance = await mcp.performance_report({ format: 'detailed' });
500
+
501
+ // Identify bottlenecks
502
+ const bottlenecks = await mcp.bottleneck_analyze({});
503
+
504
+ // Calculate optimal allocation
505
+ const allocation = await this.calculateOptimalAllocation(
506
+ currentUsage,
507
+ performance,
508
+ bottlenecks,
509
+ requirements
510
+ );
511
+
512
+ // Apply resource allocation
513
+ const result = await mcp.daa_resource_alloc({
514
+ resources: allocation.resources,
515
+ agents: allocation.agents
516
+ });
517
+
518
+ return {
519
+ allocation,
520
+ result,
521
+ monitoring: await this.setupResourceMonitoring(allocation)
522
+ };
523
+ },
524
+
525
+ // Predictive scaling
526
+ async predictiveScale(swarmId, predictions) {
527
+ // Get current swarm status
528
+ const status = await mcp.swarm_status({ swarmId });
529
+
530
+ // Calculate scaling requirements
531
+ const scalingPlan = this.calculateScalingPlan(status, predictions);
532
+
533
+ if (scalingPlan.scaleRequired) {
534
+ // Execute scaling
535
+ const scalingResult = await mcp.swarm_scale({
536
+ swarmId,
537
+ targetSize: scalingPlan.targetSize
538
+ });
539
+
540
+ // Optimize topology after scaling
541
+ if (scalingResult.success) {
542
+ await mcp.topology_optimize({ swarmId });
543
+ }
544
+
545
+ return {
546
+ scaled: true,
547
+ plan: scalingPlan,
548
+ result: scalingResult
549
+ };
550
+ }
551
+
552
+ return {
553
+ scaled: false,
554
+ reason: 'No scaling required',
555
+ plan: scalingPlan
556
+ };
557
+ },
558
+
559
+ // Performance optimization
560
+ async optimizePerformance(swarmId) {
561
+ // Collect comprehensive metrics
562
+ const metrics = await Promise.all([
563
+ mcp.performance_report({ format: 'json' }),
564
+ mcp.bottleneck_analyze({}),
565
+ mcp.agent_metrics({}),
566
+ mcp.metrics_collect({ components: ['system', 'agents', 'coordination'] })
567
+ ]);
568
+
569
+ const [performance, bottlenecks, agentMetrics, systemMetrics] = metrics;
570
+
571
+ // Generate optimization recommendations
572
+ const optimizations = await this.generateOptimizations({
573
+ performance,
574
+ bottlenecks,
575
+ agentMetrics,
576
+ systemMetrics
577
+ });
578
+
579
+ // Apply optimizations
580
+ const results = await this.applyOptimizations(swarmId, optimizations);
581
+
582
+ return {
583
+ optimizations,
584
+ results,
585
+ impact: await this.measureOptimizationImpact(swarmId, results)
586
+ };
587
+ }
588
+ };
589
+ ```
590
+
591
+ ## Operational Commands
592
+
593
+ ### Resource Management Commands
594
+ ```bash
595
+ # Analyze resource usage
596
+ npx claude-flow metrics-collect --components ["cpu", "memory", "network"]
597
+
598
+ # Optimize resource allocation
599
+ npx claude-flow daa-resource-alloc --resources <resource-config>
600
+
601
+ # Predictive scaling
602
+ npx claude-flow swarm-scale --swarm-id <id> --target-size <size>
603
+
604
+ # Performance profiling
605
+ npx claude-flow performance-report --format detailed --timeframe 24h
606
+
607
+ # Circuit breaker configuration
608
+ npx claude-flow fault-tolerance --strategy circuit-breaker --config <config>
609
+ ```
610
+
611
+ ### Optimization Commands
612
+ ```bash
613
+ # Run performance optimization
614
+ npx claude-flow optimize-performance --swarm-id <id> --strategy adaptive
615
+
616
+ # Generate resource forecasts
617
+ npx claude-flow forecast-resources --time-horizon 3600 --confidence 0.95
618
+
619
+ # Profile system performance
620
+ npx claude-flow profile-performance --duration 60000 --components all
621
+
622
+ # Analyze bottlenecks
623
+ npx claude-flow bottleneck-analyze --component swarm-coordination
624
+ ```
625
+
626
+ ## Integration Points
627
+
628
+ ### With Other Optimization Agents
629
+ - **Load Balancer**: Provides resource allocation data for load balancing decisions
630
+ - **Performance Monitor**: Shares performance metrics and bottleneck analysis
631
+ - **Topology Optimizer**: Coordinates resource allocation with topology changes
632
+
633
+ ### With Swarm Infrastructure
634
+ - **Task Orchestrator**: Allocates resources for task execution
635
+ - **Agent Coordinator**: Manages agent resource requirements
636
+ - **Memory System**: Stores resource allocation history and patterns
637
+
638
+ ## Performance Metrics
639
+
640
+ ### Resource Allocation KPIs
641
+ ```javascript
642
+ // Resource allocation performance metrics
643
+ const allocationMetrics = {
644
+ efficiency: {
645
+ utilization_rate: this.calculateUtilizationRate(),
646
+ waste_percentage: this.calculateWastePercentage(),
647
+ allocation_accuracy: this.calculateAllocationAccuracy(),
648
+ prediction_accuracy: this.calculatePredictionAccuracy()
649
+ },
650
+
651
+ performance: {
652
+ allocation_latency: this.calculateAllocationLatency(),
653
+ scaling_response_time: this.calculateScalingResponseTime(),
654
+ optimization_impact: this.calculateOptimizationImpact(),
655
+ cost_efficiency: this.calculateCostEfficiency()
656
+ },
657
+
658
+ reliability: {
659
+ availability: this.calculateAvailability(),
660
+ fault_tolerance: this.calculateFaultTolerance(),
661
+ recovery_time: this.calculateRecoveryTime(),
662
+ circuit_breaker_effectiveness: this.calculateCircuitBreakerEffectiveness()
663
+ }
664
+ };
665
+ ```
666
+
667
+ This Resource Allocator agent provides comprehensive adaptive resource allocation with ML-powered predictive scaling, fault tolerance patterns, and advanced performance optimization for efficient swarm resource management.