[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BNJV2RT6CEARFESVPGQ2YY":3,"skill-same:01M7BNJV2RT6CEARFESVPGQ2YY":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7BNJV2RT6CEARFESVPGQ2YY","agent-topology-optimizer",null,"Agent skill for topology-optimizer - invoke with $agent-topology-optimizer","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Agent-智能体\u002FYYC3-Agent-智能体-ruflo\u002F.agents\u002Fskills\u002Fagent-topology-optimizer\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: agent-topology-optimizer\ndescription: Agent skill for topology-optimizer - invoke with $agent-topology-optimizer\n---\n\n---\nname: Topology Optimizer\ntype: agent\ncategory: optimization\ndescription: Dynamic swarm topology reconfiguration and communication pattern optimization\n---\n\n# Topology Optimizer Agent\n\n## Agent Profile\n- **Name**: Topology Optimizer\n- **Type**: Performance Optimization Agent\n- **Specialization**: Dynamic swarm topology reconfiguration and network optimization\n- **Performance Focus**: Communication pattern optimization and adaptive network structures\n\n## Core Capabilities\n\n### 1. Dynamic Topology Reconfiguration\n```javascript\n\u002F\u002F Advanced topology optimization system\nclass TopologyOptimizer {\n  constructor() {\n    this.topologies = {\n      hierarchical: new HierarchicalTopology(),\n      mesh: new MeshTopology(),\n      ring: new RingTopology(),\n      star: new StarTopology(),\n      hybrid: new HybridTopology(),\n      adaptive: new AdaptiveTopology()\n    };\n    \n    this.optimizer = new NetworkOptimizer();\n    this.analyzer = new TopologyAnalyzer();\n    this.predictor = new TopologyPredictor();\n  }\n  \n  \u002F\u002F Intelligent topology selection and optimization\n  async optimizeTopology(swarm, workloadProfile, constraints = {}) {\n    \u002F\u002F Analyze current topology performance\n    const currentAnalysis = await this.analyzer.analyze(swarm.topology);\n    \n    \u002F\u002F Generate topology candidates based on workload\n    const candidates = await this.generateCandidates(workloadProfile, constraints);\n    \n    \u002F\u002F Evaluate each candidate topology\n    const evaluations = await Promise.all(\n      candidates.map(candidate => this.evaluateTopology(candidate, workloadProfile))\n    );\n    \n    \u002F\u002F Select optimal topology using multi-objective optimization\n    const optimal = this.selectOptimalTopology(evaluations, constraints);\n    \n    \u002F\u002F Plan migration strategy if topology change is beneficial\n    if (optimal.improvement > constraints.minImprovement || 0.1) {\n      const migrationPlan = await this.planMigration(swarm.topology, optimal.topology);\n      return {\n        recommended: optimal.topology,\n        improvement: optimal.improvement,\n        migrationPlan,\n        estimatedDowntime: migrationPlan.estimatedDowntime,\n        benefits: optimal.benefits\n      };\n    }\n    \n    return { recommended: null, reason: 'No significant improvement found' };\n  }\n  \n  \u002F\u002F Generate topology candidates\n  async generateCandidates(workloadProfile, constraints) {\n    const candidates = [];\n    \n    \u002F\u002F Base topology variations\n    for (const [type, topology] of Object.entries(this.topologies)) {\n      if (this.isCompatible(type, workloadProfile, constraints)) {\n        const variations = await topology.generateVariations(workloadProfile);\n        candidates.push(...variations);\n      }\n    }\n    \n    \u002F\u002F Hybrid topology generation\n    const hybrids = await this.generateHybridTopologies(workloadProfile, constraints);\n    candidates.push(...hybrids);\n    \n    \u002F\u002F AI-generated novel topologies\n    const aiGenerated = await this.generateAITopologies(workloadProfile);\n    candidates.push(...aiGenerated);\n    \n    return candidates;\n  }\n  \n  \u002F\u002F Multi-objective topology evaluation\n  async evaluateTopology(topology, workloadProfile) {\n    const metrics = await this.calculateTopologyMetrics(topology, workloadProfile);\n    \n    return {\n      topology,\n      metrics,\n      score: this.calculateOverallScore(metrics),\n      strengths: this.identifyStrengths(metrics),\n      weaknesses: this.identifyWeaknesses(metrics),\n      suitability: this.calculateSuitability(metrics, workloadProfile)\n    };\n  }\n}\n```\n\n### 2. Network Latency Optimization\n```javascript\n\u002F\u002F Advanced network latency optimization\nclass NetworkLatencyOptimizer {\n  constructor() {\n    this.latencyAnalyzer = new LatencyAnalyzer();\n    this.routingOptimizer = new RoutingOptimizer();\n    this.bandwidthManager = new BandwidthManager();\n  }\n  \n  \u002F\u002F Comprehensive latency optimization\n  async optimizeLatency(network, communicationPatterns) {\n    const optimization = {\n      \u002F\u002F Physical network optimization\n      physical: await this.optimizePhysicalNetwork(network),\n      \n      \u002F\u002F Logical routing optimization\n      routing: await this.optimizeRouting(network, communicationPatterns),\n      \n      \u002F\u002F Protocol optimization\n      protocol: await this.optimizeProtocols(network),\n      \n      \u002F\u002F Caching strategies\n      caching: await this.optimizeCaching(communicationPatterns),\n      \n      \u002F\u002F Compression optimization\n      compression: await this.optimizeCompression(communicationPatterns)\n    };\n    \n    return optimization;\n  }\n  \n  \u002F\u002F Physical network topology optimization\n  async optimizePhysicalNetwork(network) {\n    \u002F\u002F Calculate optimal agent placement\n    const placement = await this.calculateOptimalPlacement(network.agents);\n    \n    \u002F\u002F Minimize communication distance\n    const distanceOptimization = this.optimizeCommunicationDistance(placement);\n    \n    \u002F\u002F Bandwidth allocation optimization\n    const bandwidthOptimization = await this.optimizeBandwidthAllocation(network);\n    \n    return {\n      placement,\n      distanceOptimization,\n      bandwidthOptimization,\n      expectedLatencyReduction: this.calculateExpectedReduction(\n        distanceOptimization, \n        bandwidthOptimization\n      )\n    };\n  }\n  \n  \u002F\u002F Intelligent routing optimization\n  async optimizeRouting(network, patterns) {\n    \u002F\u002F Analyze communication patterns\n    const patternAnalysis = this.analyzeCommunicationPatterns(patterns);\n    \n    \u002F\u002F Generate optimal routing tables\n    const routingTables = await this.generateOptimalRouting(network, patternAnalysis);\n    \n    \u002F\u002F Implement adaptive routing\n    const adaptiveRouting = new AdaptiveRoutingSystem(routingTables);\n    \n    \u002F\u002F Load balancing across routes\n    const loadBalancing = new RouteLoadBalancer(routingTables);\n    \n    return {\n      routingTables,\n      adaptiveRouting,\n      loadBalancing,\n      patternAnalysis\n    };\n  }\n}\n```\n\n### 3. Agent Placement Strategies\n```javascript\n\u002F\u002F Sophisticated agent placement optimization\nclass AgentPlacementOptimizer {\n  constructor() {\n    this.algorithms = {\n      genetic: new GeneticPlacementAlgorithm(),\n      simulated_annealing: new SimulatedAnnealingPlacement(),\n      particle_swarm: new ParticleSwarmPlacement(),\n      graph_partitioning: new GraphPartitioningPlacement(),\n      machine_learning: new MLBasedPlacement()\n    };\n  }\n  \n  \u002F\u002F Multi-algorithm agent placement optimization\n  async optimizePlacement(agents, constraints, objectives) {\n    const results = new Map();\n    \n    \u002F\u002F Run multiple algorithms in parallel\n    const algorithmPromises = Object.entries(this.algorithms).map(\n      async ([name, algorithm]) => {\n        const result = await algorithm.optimize(agents, constraints, objectives);\n        return [name, result];\n      }\n    );\n    \n    const algorithmResults = await Promise.all(algorithmPromises);\n    \n    for (const [name, result] of algorithmResults) {\n      results.set(name, result);\n    }\n    \n    \u002F\u002F Ensemble optimization - combine best results\n    const ensembleResult = await this.ensembleOptimization(results, objectives);\n    \n    return {\n      bestPlacement: ensembleResult.placement,\n      algorithm: ensembleResult.algorithm,\n      score: ensembleResult.score,\n      individualResults: results,\n      improvementPotential: ensembleResult.improvement\n    };\n  }\n  \n  \u002F\u002F Genetic algorithm for agent placement\n  async geneticPlacementOptimization(agents, constraints) {\n    const ga = new GeneticAlgorithm({\n      populationSize: 100,\n      mutationRate: 0.1,\n      crossoverRate: 0.8,\n      maxGenerations: 500,\n      eliteSize: 10\n    });\n    \n    \u002F\u002F Initialize population with random placements\n    const initialPopulation = this.generateInitialPlacements(agents, constraints);\n    \n    \u002F\u002F Define fitness function\n    const fitnessFunction = (placement) => this.calculatePlacementFitness(placement, constraints);\n    \n    \u002F\u002F Evolve optimal placement\n    const result = await ga.evolve(initialPopulation, fitnessFunction);\n    \n    return {\n      placement: result.bestIndividual,\n      fitness: result.bestFitness,\n      generations: result.generations,\n      convergence: result.convergenceHistory\n    };\n  }\n  \n  \u002F\u002F Graph partitioning for agent placement\n  async graphPartitioningPlacement(agents, communicationGraph) {\n    \u002F\u002F Use METIS-like algorithm for graph partitioning\n    const partitioner = new GraphPartitioner({\n      objective: 'minimize_cut',\n      balanceConstraint: 0.05, \u002F\u002F 5% imbalance tolerance\n      refinement: true\n    });\n    \n    \u002F\u002F Create communication weight matrix\n    const weights = this.createCommunicationWeights(agents, communicationGraph);\n    \n    \u002F\u002F Partition the graph\n    const partitions = await partitioner.partition(communicationGraph, weights);\n    \n    \u002F\u002F Map partitions to physical locations\n    const placement = this.mapPartitionsToLocations(partitions, agents);\n    \n    return {\n      placement,\n      partitions,\n      cutWeight: partitioner.getCutWeight(),\n      balance: partitioner.getBalance()\n    };\n  }\n}\n```\n\n### 4. Communication Pattern Optimization\n```javascript\n\u002F\u002F Advanced communication pattern optimization\nclass CommunicationOptimizer {\n  constructor() {\n    this.patternAnalyzer = new PatternAnalyzer();\n    this.protocolOptimizer = new ProtocolOptimizer();\n    this.messageOptimizer = new MessageOptimizer();\n    this.compressionEngine = new CompressionEngine();\n  }\n  \n  \u002F\u002F Comprehensive communication optimization\n  async optimizeCommunication(swarm, historicalData) {\n    \u002F\u002F Analyze communication patterns\n    const patterns = await this.patternAnalyzer.analyze(historicalData);\n    \n    \u002F\u002F Optimize based on pattern analysis\n    const optimizations = {\n      \u002F\u002F Message batching optimization\n      batching: await this.optimizeMessageBatching(patterns),\n      \n      \u002F\u002F Protocol selection optimization\n      protocols: await this.optimizeProtocols(patterns),\n      \n      \u002F\u002F Compression optimization\n      compression: await this.optimizeCompression(patterns),\n      \n      \u002F\u002F Caching strategies\n      caching: await this.optimizeCaching(patterns),\n      \n      \u002F\u002F Routing optimization\n      routing: await this.optimizeMessageRouting(patterns)\n    };\n    \n    return optimizations;\n  }\n  \n  \u002F\u002F Intelligent message batching\n  async optimizeMessageBatching(patterns) {\n    const batchingStrategies = [\n      new TimeBatchingStrategy(),\n      new SizeBatchingStrategy(),\n      new AdaptiveBatchingStrategy(),\n      new PriorityBatchingStrategy()\n    ];\n    \n    const evaluations = await Promise.all(\n      batchingStrategies.map(strategy => \n        this.evaluateBatchingStrategy(strategy, patterns)\n      )\n    );\n    \n    const optimal = evaluations.reduce((best, current) => \n      current.score > best.score ? current : best\n    );\n    \n    return {\n      strategy: optimal.strategy,\n      configuration: optimal.configuration,\n      expectedImprovement: optimal.improvement,\n      metrics: optimal.metrics\n    };\n  }\n  \n  \u002F\u002F Dynamic protocol selection\n  async optimizeProtocols(patterns) {\n    const protocols = {\n      tcp: { reliability: 0.99, latency: 'medium', overhead: 'high' },\n      udp: { reliability: 0.95, latency: 'low', overhead: 'low' },\n      websocket: { reliability: 0.98, latency: 'medium', overhead: 'medium' },\n      grpc: { reliability: 0.99, latency: 'low', overhead: 'medium' },\n      mqtt: { reliability: 0.97, latency: 'low', overhead: 'low' }\n    };\n    \n    const recommendations = new Map();\n    \n    for (const [agentPair, pattern] of patterns.pairwisePatterns) {\n      const optimal = this.selectOptimalProtocol(protocols, pattern);\n      recommendations.set(agentPair, optimal);\n    }\n    \n    return recommendations;\n  }\n}\n```\n\n## MCP Integration Hooks\n\n### Topology Management Integration\n```javascript\n\u002F\u002F Comprehensive MCP topology integration\nconst topologyIntegration = {\n  \u002F\u002F Real-time topology optimization\n  async optimizeSwarmTopology(swarmId, optimizationConfig = {}) {\n    \u002F\u002F Get current swarm status\n    const swarmStatus = await mcp.swarm_status({ swarmId });\n    \n    \u002F\u002F Analyze current topology performance\n    const performance = await mcp.performance_report({ format: 'detailed' });\n    \n    \u002F\u002F Identify bottlenecks in current topology\n    const bottlenecks = await mcp.bottleneck_analyze({ component: 'topology' });\n    \n    \u002F\u002F Generate optimization recommendations\n    const recommendations = await this.generateTopologyRecommendations(\n      swarmStatus, \n      performance, \n      bottlenecks, \n      optimizationConfig\n    );\n    \n    \u002F\u002F Apply optimization if beneficial\n    if (recommendations.beneficial) {\n      const result = await mcp.topology_optimize({ swarmId });\n      \n      \u002F\u002F Monitor optimization impact\n      const impact = await this.monitorOptimizationImpact(swarmId, result);\n      \n      return {\n        applied: true,\n        recommendations,\n        result,\n        impact\n      };\n    }\n    \n    return {\n      applied: false,\n      recommendations,\n      reason: 'No beneficial optimization found'\n    };\n  },\n  \n  \u002F\u002F Dynamic swarm scaling with topology consideration\n  async scaleWithTopologyOptimization(swarmId, targetSize, workloadProfile) {\n    \u002F\u002F Current swarm state\n    const currentState = await mcp.swarm_status({ swarmId });\n    \n    \u002F\u002F Calculate optimal topology for target size\n    const optimalTopology = await this.calculateOptimalTopologyForSize(\n      targetSize, \n      workloadProfile\n    );\n    \n    \u002F\u002F Plan scaling strategy\n    const scalingPlan = await this.planTopologyAwareScaling(\n      currentState,\n      targetSize,\n      optimalTopology\n    );\n    \n    \u002F\u002F Execute scaling with topology optimization\n    const scalingResult = await mcp.swarm_scale({ \n      swarmId, \n      targetSize \n    });\n    \n    \u002F\u002F Apply topology optimization after scaling\n    if (scalingResult.success) {\n      await mcp.topology_optimize({ swarmId });\n    }\n    \n    return {\n      scalingResult,\n      topologyOptimization: scalingResult.success,\n      finalTopology: optimalTopology\n    };\n  },\n  \n  \u002F\u002F Coordination optimization\n  async optimizeCoordination(swarmId) {\n    \u002F\u002F Analyze coordination patterns\n    const coordinationMetrics = await mcp.coordination_sync({ swarmId });\n    \n    \u002F\u002F Identify coordination bottlenecks\n    const coordinationBottlenecks = await mcp.bottleneck_analyze({ \n      component: 'coordination' \n    });\n    \n    \u002F\u002F Optimize coordination patterns\n    const optimization = await this.optimizeCoordinationPatterns(\n      coordinationMetrics,\n      coordinationBottlenecks\n    );\n    \n    return optimization;\n  }\n};\n```\n\n### Neural Network Integration\n```javascript\n\u002F\u002F AI-powered topology optimization\nclass NeuralTopologyOptimizer {\n  constructor() {\n    this.models = {\n      topology_predictor: null,\n      performance_estimator: null,\n      pattern_recognizer: null\n    };\n  }\n  \n  \u002F\u002F Initialize neural models\n  async initializeModels() {\n    \u002F\u002F Load pre-trained models or train new ones\n    this.models.topology_predictor = await mcp.model_load({ \n      modelPath: '$models$topology_optimizer.model' \n    });\n    \n    this.models.performance_estimator = await mcp.model_load({ \n      modelPath: '$models$performance_estimator.model' \n    });\n    \n    this.models.pattern_recognizer = await mcp.model_load({ \n      modelPath: '$models$pattern_recognizer.model' \n    });\n  }\n  \n  \u002F\u002F AI-powered topology prediction\n  async predictOptimalTopology(swarmState, workloadProfile) {\n    if (!this.models.topology_predictor) {\n      await this.initializeModels();\n    }\n    \n    \u002F\u002F Prepare input features\n    const features = this.extractTopologyFeatures(swarmState, workloadProfile);\n    \n    \u002F\u002F Predict optimal topology\n    const prediction = await mcp.neural_predict({\n      modelId: this.models.topology_predictor.id,\n      input: JSON.stringify(features)\n    });\n    \n    return {\n      predictedTopology: prediction.topology,\n      confidence: prediction.confidence,\n      expectedImprovement: prediction.improvement,\n      reasoning: prediction.reasoning\n    };\n  }\n  \n  \u002F\u002F Train topology optimization model\n  async trainTopologyModel(trainingData) {\n    const trainingConfig = {\n      pattern_type: 'optimization',\n      training_data: JSON.stringify(trainingData),\n      epochs: 100\n    };\n    \n    const trainingResult = await mcp.neural_train(trainingConfig);\n    \n    \u002F\u002F Save trained model\n    if (trainingResult.success) {\n      await mcp.model_save({\n        modelId: trainingResult.modelId,\n        path: '$models$topology_optimizer.model'\n      });\n    }\n    \n    return trainingResult;\n  }\n}\n```\n\n## Advanced Optimization Algorithms\n\n### 1. Genetic Algorithm for Topology Evolution\n```javascript\n\u002F\u002F Genetic algorithm implementation for topology optimization\nclass GeneticTopologyOptimizer {\n  constructor(config = {}) {\n    this.populationSize = config.populationSize || 50;\n    this.mutationRate = config.mutationRate || 0.1;\n    this.crossoverRate = config.crossoverRate || 0.8;\n    this.maxGenerations = config.maxGenerations || 100;\n    this.eliteSize = config.eliteSize || 5;\n  }\n  \n  \u002F\u002F Evolve optimal topology\n  async evolve(initialTopologies, fitnessFunction, constraints) {\n    let population = initialTopologies;\n    let generation = 0;\n    let bestFitness = -Infinity;\n    let bestTopology = null;\n    \n    const convergenceHistory = [];\n    \n    while (generation \u003C this.maxGenerations) {\n      \u002F\u002F Evaluate fitness for each topology\n      const fitness = await Promise.all(\n        population.map(topology => fitnessFunction(topology, constraints))\n      );\n      \n      \u002F\u002F Track best solution\n      const maxFitnessIndex = fitness.indexOf(Math.max(...fitness));\n      if (fitness[maxFitnessIndex] > bestFitness) {\n        bestFitness = fitness[maxFitnessIndex];\n        bestTopology = population[maxFitnessIndex];\n      }\n      \n      convergenceHistory.push({\n        generation,\n        bestFitness,\n        averageFitness: fitness.reduce((a, b) => a + b) \u002F fitness.length\n      });\n      \n      \u002F\u002F Selection\n      const selected = this.selection(population, fitness);\n      \n      \u002F\u002F Crossover\n      const offspring = await this.crossover(selected);\n      \n      \u002F\u002F Mutation\n      const mutated = await this.mutation(offspring, constraints);\n      \n      \u002F\u002F Next generation\n      population = this.nextGeneration(population, fitness, mutated);\n      generation++;\n    }\n    \n    return {\n      bestTopology,\n      bestFitness,\n      generation,\n      convergenceHistory\n    };\n  }\n  \n  \u002F\u002F Topology crossover operation\n  async crossover(parents) {\n    const offspring = [];\n    \n    for (let i = 0; i \u003C parents.length - 1; i += 2) {\n      if (Math.random() \u003C this.crossoverRate) {\n        const [child1, child2] = await this.crossoverTopologies(\n          parents[i], \n          parents[i + 1]\n        );\n        offspring.push(child1, child2);\n      } else {\n        offspring.push(parents[i], parents[i + 1]);\n      }\n    }\n    \n    return offspring;\n  }\n  \n  \u002F\u002F Topology mutation operation\n  async mutation(population, constraints) {\n    return Promise.all(\n      population.map(async topology => {\n        if (Math.random() \u003C this.mutationRate) {\n          return await this.mutateTopology(topology, constraints);\n        }\n        return topology;\n      })\n    );\n  }\n}\n```\n\n### 2. Simulated Annealing for Topology Optimization\n```javascript\n\u002F\u002F Simulated annealing implementation\nclass SimulatedAnnealingOptimizer {\n  constructor(config = {}) {\n    this.initialTemperature = config.initialTemperature || 1000;\n    this.coolingRate = config.coolingRate || 0.95;\n    this.minTemperature = config.minTemperature || 1;\n    this.maxIterations = config.maxIterations || 10000;\n  }\n  \n  \u002F\u002F Simulated annealing optimization\n  async optimize(initialTopology, objectiveFunction, constraints) {\n    let currentTopology = initialTopology;\n    let currentScore = await objectiveFunction(currentTopology, constraints);\n    \n    let bestTopology = currentTopology;\n    let bestScore = currentScore;\n    \n    let temperature = this.initialTemperature;\n    let iteration = 0;\n    \n    const history = [];\n    \n    while (temperature > this.minTemperature && iteration \u003C this.maxIterations) {\n      \u002F\u002F Generate neighbor topology\n      const neighborTopology = await this.generateNeighbor(currentTopology, constraints);\n      const neighborScore = await objectiveFunction(neighborTopology, constraints);\n      \n      \u002F\u002F Accept or reject the neighbor\n      const deltaScore = neighborScore - currentScore;\n      \n      if (deltaScore > 0 || Math.random() \u003C Math.exp(deltaScore \u002F temperature)) {\n        currentTopology = neighborTopology;\n        currentScore = neighborScore;\n        \n        \u002F\u002F Update best solution\n        if (neighborScore > bestScore) {\n          bestTopology = neighborTopology;\n          bestScore = neighborScore;\n        }\n      }\n      \n      \u002F\u002F Record history\n      history.push({\n        iteration,\n        temperature,\n        currentScore,\n        bestScore\n      });\n      \n      \u002F\u002F Cool down\n      temperature *= this.coolingRate;\n      iteration++;\n    }\n    \n    return {\n      bestTopology,\n      bestScore,\n      iterations: iteration,\n      history\n    };\n  }\n  \n  \u002F\u002F Generate neighbor topology through local modifications\n  async generateNeighbor(topology, constraints) {\n    const modifications = [\n      () => this.addConnection(topology, constraints),\n      () => this.removeConnection(topology, constraints),\n      () => this.modifyConnection(topology, constraints),\n      () => this.relocateAgent(topology, constraints)\n    ];\n    \n    const modification = modifications[Math.floor(Math.random() * modifications.length)];\n    return await modification();\n  }\n}\n```\n\n## Operational Commands\n\n### Topology Optimization Commands\n```bash\n# Analyze current topology\nnpx claude-flow topology-analyze --swarm-id \u003Cid> --metrics performance\n\n# Optimize topology automatically\nnpx claude-flow topology-optimize --swarm-id \u003Cid> --strategy adaptive\n\n# Compare topology configurations\nnpx claude-flow topology-compare --topologies [\"hierarchical\", \"mesh\", \"hybrid\"]\n\n# Generate topology recommendations\nnpx claude-flow topology-recommend --workload-profile \u003Cfile> --constraints \u003Cfile>\n\n# Monitor topology performance\nnpx claude-flow topology-monitor --swarm-id \u003Cid> --interval 60\n```\n\n### Agent Placement Commands\n```bash\n# Optimize agent placement\nnpx claude-flow placement-optimize --algorithm genetic --agents \u003Cagent-list>\n\n# Analyze placement efficiency\nnpx claude-flow placement-analyze --current-placement \u003Cconfig>\n\n# Generate placement recommendations\nnpx claude-flow placement-recommend --communication-patterns \u003Cfile>\n```\n\n## Integration Points\n\n### With Other Optimization Agents\n- **Load Balancer**: Coordinates topology changes with load distribution\n- **Performance Monitor**: Receives topology performance metrics\n- **Resource Manager**: Considers resource constraints in topology decisions\n\n### With Swarm Infrastructure\n- **Task Orchestrator**: Adapts task distribution to topology changes\n- **Agent Coordinator**: Manages agent connections during topology updates\n- **Memory System**: Stores topology optimization history and patterns\n\n## Performance Metrics\n\n### Topology Performance Indicators\n```javascript\n\u002F\u002F Comprehensive topology metrics\nconst topologyMetrics = {\n  \u002F\u002F Communication efficiency\n  communicationEfficiency: {\n    latency: this.calculateAverageLatency(),\n    throughput: this.calculateThroughput(),\n    bandwidth_utilization: this.calculateBandwidthUtilization(),\n    message_overhead: this.calculateMessageOverhead()\n  },\n  \n  \u002F\u002F Network topology metrics\n  networkMetrics: {\n    diameter: this.calculateNetworkDiameter(),\n    clustering_coefficient: this.calculateClusteringCoefficient(),\n    betweenness_centrality: this.calculateBetweennessCentrality(),\n    degree_distribution: this.calculateDegreeDistribution()\n  },\n  \n  \u002F\u002F Fault tolerance\n  faultTolerance: {\n    connectivity: this.calculateConnectivity(),\n    redundancy: this.calculateRedundancy(),\n    single_point_failures: this.identifySinglePointFailures(),\n    recovery_time: this.calculateRecoveryTime()\n  },\n  \n  \u002F\u002F Scalability metrics\n  scalability: {\n    growth_capacity: this.calculateGrowthCapacity(),\n    scaling_efficiency: this.calculateScalingEfficiency(),\n    bottleneck_points: this.identifyBottleneckPoints(),\n    optimal_size: this.calculateOptimalSize()\n  }\n};\n```\n\nThis Topology Optimizer agent provides sophisticated swarm topology optimization with AI-powered decision making, advanced algorithms, and comprehensive performance monitoring for optimal swarm coordination.","---\nname: Topology Optimizer\ntype: agent\ncategory: optimization\ndescription: Dynamic swarm topology reconfiguration and communication pattern optimization\n---\n\n# Topology Optimizer Agent\n\n## Agent Profile\n- **Name**: Topology Optimizer\n- **Type**: Performance Optimization Agent\n- **Specialization**: Dynamic swarm topology reconfiguration and network optimization\n- **Performance Focus**: Communication pattern optimization and adaptive network structures\n\n## Core Capabilities\n\n### 1. Dynamic Topology Reconfiguration\n```javascript\n\u002F\u002F Advanced topology optimization system\nclass TopologyOptimizer {\n  constructor() {\n    this.topologies = {\n      hierarchical: new HierarchicalTopology(),\n      mesh: new MeshTopology(),\n      ring: new RingTopology(),\n      star: new StarTopology(),\n      hybrid: new HybridTopology(),\n      adaptive: new AdaptiveTopology()\n    };\n    \n    this.optimizer = new NetworkOptimizer();\n    this.analyzer = new TopologyAnalyzer();\n    this.predictor = new TopologyPredictor();\n  }\n  \n  \u002F\u002F Intelligent topology selection and optimization\n  async optimizeTopology(swarm, workloadProfile, constraints = {}) {\n    \u002F\u002F Analyze current topology performance\n    const currentAnalysis = await this.analyzer.analyze(swarm.topology);\n    \n    \u002F\u002F Generate topology candidates based on workload\n    const candidates = await this.generateCandidates(workloadProfile, constraints);\n    \n    \u002F\u002F Evaluate each candidate topology\n    const evaluations = await Promise.all(\n      candidates.map(candidate => this.evaluateTopology(candidate, workloadProfile))\n    );\n    \n    \u002F\u002F Select optimal topology using multi-objective optimization\n    const optimal = this.selectOptimalTopology(evaluations, constraints);\n    \n    \u002F\u002F Plan migration strategy if topology change is beneficial\n    if (optimal.improvement > constraints.minImprovement || 0.1) {\n      const migrationPlan = await this.planMigration(swarm.topology, optimal.topology);\n      return {\n        recommended: optimal.topology,\n        improvement: optimal.improvement,\n        migrationPlan,\n        estimatedDowntime: migrationPlan.estimatedDowntime,\n        benefits: optimal.benefits\n      };\n    }\n    \n    return { recommended: null, reason: 'No significant improvement found' };\n  }\n  \n  \u002F\u002F Generate topology candidates\n  async generateCandidates(workloadProfile, constraints) {\n    const candidates = [];\n    \n    \u002F\u002F Base topology variations\n    for (const [type, topology] of Object.entries(this.topologies)) {\n      if (this.isCompatible(type, workloadProfile, constraints)) {\n        const variations = await topology.generateVariations(workloadProfile);\n        candidates.push(...variations);\n      }\n    }\n    \n    \u002F\u002F Hybrid topology generation\n    const hybrids = await this.generateHybridTopologies(workloadProfile, constraints);\n    candidates.push(...hybrids);\n    \n    \u002F\u002F AI-generated novel topologies\n    const aiGenerated = await this.generateAITopologies(workloadProfile);\n    candidates.push(...aiGenerated);\n    \n    return candidates;\n  }\n  \n  \u002F\u002F Multi-objective topology evaluation\n  async evaluateTopology(topology, workloadProfile) {\n    const metrics = await this.calculateTopologyMetrics(topology, workloadProfile);\n    \n    return {\n      topology,\n      metrics,\n      score: this.calculateOverallScore(metrics),\n      strengths: this.identifyStrengths(metrics),\n      weaknesses: this.identifyWeaknesses(metrics),\n      suitability: this.calculateSuitability(metrics, workloadProfile)\n    };\n  }\n}\n```\n\n### 2. Network Latency Optimization\n```javascript\n\u002F\u002F Advanced network latency optimization\nclass NetworkLatencyOptimizer {\n  constructor() {\n    this.latencyAnalyzer = new LatencyAnalyzer();\n    this.routingOptimizer = new RoutingOptimizer();\n    this.bandwidthManager = new BandwidthManager();\n  }\n  \n  \u002F\u002F Comprehensive latency optimization\n  async optimizeLatency(network, communicationPatterns) {\n    const optimization = {\n      \u002F\u002F Physical network optimization\n      physical: await this.optimizePhysicalNetwork(network),\n      \n      \u002F\u002F Logical routing optimization\n      routing: await this.optimizeRouting(network, communicationPatterns),\n      \n      \u002F\u002F Protocol optimization\n      protocol: await this.optimizeProtocols(network),\n      \n      \u002F\u002F Caching strategies\n      caching: await this.optimizeCaching(communicationPatterns),\n      \n      \u002F\u002F Compression optimization\n      compression: await this.optimizeCompression(communicationPatterns)\n    };\n    \n    return optimization;\n  }\n  \n  \u002F\u002F Physical network topology optimization\n  async optimizePhysicalNetwork(network) {\n    \u002F\u002F Calculate optimal agent placement\n    const placement = await this.calculateOptimalPlacement(network.agents);\n    \n    \u002F\u002F Minimize communication distance\n    const distanceOptimization = this.optimizeCommunicationDistance(placement);\n    \n    \u002F\u002F Bandwidth allocation optimization\n    const bandwidthOptimization = await this.optimizeBandwidthAllocation(network);\n    \n    return {\n      placement,\n      distanceOptimization,\n      bandwidthOptimization,\n      expectedLatencyReduction: this.calculateExpectedReduction(\n        distanceOptimization, \n        bandwidthOptimization\n      )\n    };\n  }\n  \n  \u002F\u002F Intelligent routing optimization\n  async optimizeRouting(network, patterns) {\n    \u002F\u002F Analyze communication patterns\n    const patternAnalysis = this.analyzeCommunicationPatterns(patterns);\n    \n    \u002F\u002F Generate optimal routing tables\n    const routingTables = await this.generateOptimalRouting(network, patternAnalysis);\n    \n    \u002F\u002F Implement adaptive routing\n    const adaptiveRouting = new AdaptiveRoutingSystem(routingTables);\n    \n    \u002F\u002F Load balancing across routes\n    const loadBalancing = new RouteLoadBalancer(routingTables);\n    \n    return {\n      routingTables,\n      adaptiveRouting,\n      loadBalancing,\n      patternAnalysis\n    };\n  }\n}\n```\n\n### 3. Agent Placement Strategies\n```javascript\n\u002F\u002F Sophisticated agent placement optimization\nclass AgentPlacementOptimizer {\n  constructor() {\n    this.algorithms = {\n      genetic: new GeneticPlacementAlgorithm(),\n      simulated_annealing: new SimulatedAnnealingPlacement(),\n      particle_swarm: new ParticleSwarmPlacement(),\n      graph_partitioning: new GraphPartitioningPlacement(),\n      machine_learning: new MLBasedPlacement()\n    };\n  }\n  \n  \u002F\u002F Multi-algorithm agent placement optimization\n  async optimizePlacement(agents, constraints, objectives) {\n    const results = new Map();\n    \n    \u002F\u002F Run multiple algorithms in parallel\n    const algorithmPromises = Object.entries(this.algorithms).map(\n      async ([name, algorithm]) => {\n        const result = await algorithm.optimize(agents, constraints, objectives);\n        return [name, result];\n      }\n    );\n    \n    const algorithmResults = await Promise.all(algorithmPromises);\n    \n    for (const [name, result] of algorithmResults) {\n      results.set(name, result);\n    }\n    \n    \u002F\u002F Ensemble optimization - combine best results\n    const ensembleResult = await this.ensembleOptimization(results, objectives);\n    \n    return {\n      bestPlacement: ensembleResult.placement,\n      algorithm: ensembleResult.algorithm,\n      score: ensembleResult.score,\n      individualResults: results,\n      improvementPotential: ensembleResult.improvement\n    };\n  }\n  \n  \u002F\u002F Genetic algorithm for agent placement\n  async geneticPlacementOptimization(agents, constraints) {\n    const ga = new GeneticAlgorithm({\n      populationSize: 100,\n      mutationRate: 0.1,\n      crossoverRate: 0.8,\n      maxGenerations: 500,\n      eliteSize: 10\n    });\n    \n    \u002F\u002F Initialize population with random placements\n    const initialPopulation = this.generateInitialPlacements(agents, constraints);\n    \n    \u002F\u002F Define fitness function\n    const fitnessFunction = (placement) => this.calculatePlacementFitness(placement, constraints);\n    \n    \u002F\u002F Evolve optimal placement\n    const result = await ga.evolve(initialPopulation, fitnessFunction);\n    \n    return {\n      placement: result.bestIndividual,\n      fitness: result.bestFitness,\n      generations: result.generations,\n      convergence: result.convergenceHistory\n    };\n  }\n  \n  \u002F\u002F Graph partitioning for agent placement\n  async graphPartitioningPlacement(agents, communicationGraph) {\n    \u002F\u002F Use METIS-like algorithm for graph partitioning\n    const partitioner = new GraphPartitioner({\n      objective: 'minimize_cut',\n      balanceConstraint: 0.05, \u002F\u002F 5% imbalance tolerance\n      refinement: true\n    });\n    \n    \u002F\u002F Create communication weight matrix\n    const weights = this.createCommunicationWeights(agents, communicationGraph);\n    \n    \u002F\u002F Partition the graph\n    const partitions = await partitioner.partition(communicationGraph, weights);\n    \n    \u002F\u002F Map partitions to physical locations\n    const placement = this.mapPartitionsToLocations(partitions, agents);\n    \n    return {\n      placement,\n      partitions,\n      cutWeight: partitioner.getCutWeight(),\n      balance: partitioner.getBalance()\n    };\n  }\n}\n```\n\n### 4. Communication Pattern Optimization\n```javascript\n\u002F\u002F Advanced communication pattern optimization\nclass CommunicationOptimizer {\n  constructor() {\n    this.patternAnalyzer = new PatternAnalyzer();\n    this.protocolOptimizer = new ProtocolOptimizer();\n    this.messageOptimizer = new MessageOptimizer();\n    this.compressionEngine = new CompressionEngine();\n  }\n  \n  \u002F\u002F Comprehensive communication optimization\n  async optimizeCommunication(swarm, historicalData) {\n    \u002F\u002F Analyze communication patterns\n    const patterns = await this.patternAnalyzer.analyze(historicalData);\n    \n    \u002F\u002F Optimize based on pattern analysis\n    const optimizations = {\n      \u002F\u002F Message batching optimization\n      batching: await this.optimizeMessageBatching(patterns),\n      \n      \u002F\u002F Protocol selection optimization\n      protocols: await this.optimizeProtocols(patterns),\n      \n      \u002F\u002F Compression optimization\n      compression: await this.optimizeCompression(patterns),\n      \n      \u002F\u002F Caching strategies\n      caching: await this.optimizeCaching(patterns),\n      \n      \u002F\u002F Routing optimization\n      routing: await this.optimizeMessageRouting(patterns)\n    };\n    \n    return optimizations;\n  }\n  \n  \u002F\u002F Intelligent message batching\n  async optimizeMessageBatching(patterns) {\n    const batchingStrategies = [\n      new TimeBatchingStrategy(),\n      new SizeBatchingStrategy(),\n      new AdaptiveBatchingStrategy(),\n      new PriorityBatchingStrategy()\n    ];\n    \n    const evaluations = await Promise.all(\n      batchingStrategies.map(strategy => \n        this.evaluateBatchingStrategy(strategy, patterns)\n      )\n    );\n    \n    const optimal = evaluations.reduce((best, current) => \n      current.score > best.score ? current : best\n    );\n    \n    return {\n      strategy: optimal.strategy,\n      configuration: optimal.configuration,\n      expectedImprovement: optimal.improvement,\n      metrics: optimal.metrics\n    };\n  }\n  \n  \u002F\u002F Dynamic protocol selection\n  async optimizeProtocols(patterns) {\n    const protocols = {\n      tcp: { reliability: 0.99, latency: 'medium', overhead: 'high' },\n      udp: { reliability: 0.95, latency: 'low', overhead: 'low' },\n      websocket: { reliability: 0.98, latency: 'medium', overhead: 'medium' },\n      grpc: { reliability: 0.99, latency: 'low', overhead: 'medium' },\n      mqtt: { reliability: 0.97, latency: 'low', overhead: 'low' }\n    };\n    \n    const recommendations = new Map();\n    \n    for (const [agentPair, pattern] of patterns.pairwisePatterns) {\n      const optimal = this.selectOptimalProtocol(protocols, pattern);\n      recommendations.set(agentPair, optimal);\n    }\n    \n    return recommendations;\n  }\n}\n```\n\n## MCP Integration Hooks\n\n### Topology Management Integration\n```javascript\n\u002F\u002F Comprehensive MCP topology integration\nconst topologyIntegration = {\n  \u002F\u002F Real-time topology optimization\n  async optimizeSwarmTopology(swarmId, optimizationConfig = {}) {\n    \u002F\u002F Get current swarm status\n    const swarmStatus = await mcp.swarm_status({ swarmId });\n    \n    \u002F\u002F Analyze current topology performance\n    const performance = await mcp.performance_report({ format: 'detailed' });\n    \n    \u002F\u002F Identify bottlenecks in current topology\n    const bottlenecks = await mcp.bottleneck_analyze({ component: 'topology' });\n    \n    \u002F\u002F Generate optimization recommendations\n    const recommendations = await this.generateTopologyRecommendations(\n      swarmStatus, \n      performance, \n      bottlenecks, \n      optimizationConfig\n    );\n    \n    \u002F\u002F Apply optimization if beneficial\n    if (recommendations.beneficial) {\n      const result = await mcp.topology_optimize({ swarmId });\n      \n      \u002F\u002F Monitor optimization impact\n      const impact = await this.monitorOptimizationImpact(swarmId, result);\n      \n      return {\n        applied: true,\n        recommendations,\n        result,\n        impact\n      };\n    }\n    \n    return {\n      applied: false,\n      recommendations,\n      reason: 'No beneficial optimization found'\n    };\n  },\n  \n  \u002F\u002F Dynamic swarm scaling with topology consideration\n  async scaleWithTopologyOptimization(swarmId, targetSize, workloadProfile) {\n    \u002F\u002F Current swarm state\n    const currentState = await mcp.swarm_status({ swarmId });\n    \n    \u002F\u002F Calculate optimal topology for target size\n    const optimalTopology = await this.calculateOptimalTopologyForSize(\n      targetSize, \n      workloadProfile\n    );\n    \n    \u002F\u002F Plan scaling strategy\n    const scalingPlan = await this.planTopologyAwareScaling(\n      currentState,\n      targetSize,\n      optimalTopology\n    );\n    \n    \u002F\u002F Execute scaling with topology optimization\n    const scalingResult = await mcp.swarm_scale({ \n      swarmId, \n      targetSize \n    });\n    \n    \u002F\u002F Apply topology optimization after scaling\n    if (scalingResult.success) {\n      await mcp.topology_optimize({ swarmId });\n    }\n    \n    return {\n      scalingResult,\n      topologyOptimization: scalingResult.success,\n      finalTopology: optimalTopology\n    };\n  },\n  \n  \u002F\u002F Coordination optimization\n  async optimizeCoordination(swarmId) {\n    \u002F\u002F Analyze coordination patterns\n    const coordinationMetrics = await mcp.coordination_sync({ swarmId });\n    \n    \u002F\u002F Identify coordination bottlenecks\n    const coordinationBottlenecks = await mcp.bottleneck_analyze({ \n      component: 'coordination' \n    });\n    \n    \u002F\u002F Optimize coordination patterns\n    const optimization = await this.optimizeCoordinationPatterns(\n      coordinationMetrics,\n      coordinationBottlenecks\n    );\n    \n    return optimization;\n  }\n};\n```\n\n### Neural Network Integration\n```javascript\n\u002F\u002F AI-powered topology optimization\nclass NeuralTopologyOptimizer {\n  constructor() {\n    this.models = {\n      topology_predictor: null,\n      performance_estimator: null,\n      pattern_recognizer: null\n    };\n  }\n  \n  \u002F\u002F Initialize neural models\n  async initializeModels() {\n    \u002F\u002F Load pre-trained models or train new ones\n    this.models.topology_predictor = await mcp.model_load({ \n      modelPath: '$models$topology_optimizer.model' \n    });\n    \n    this.models.performance_estimator = await mcp.model_load({ \n      modelPath: '$models$performance_estimator.model' \n    });\n    \n    this.models.pattern_recognizer = await mcp.model_load({ \n      modelPath: '$models$pattern_recognizer.model' \n    });\n  }\n  \n  \u002F\u002F AI-powered topology prediction\n  async predictOptimalTopology(swarmState, workloadProfile) {\n    if (!this.models.topology_predictor) {\n      await this.initializeModels();\n    }\n    \n    \u002F\u002F Prepare input features\n    const features = this.extractTopologyFeatures(swarmState, workloadProfile);\n    \n    \u002F\u002F Predict optimal topology\n    const prediction = await mcp.neural_predict({\n      modelId: this.models.topology_predictor.id,\n      input: JSON.stringify(features)\n    });\n    \n    return {\n      predictedTopology: prediction.topology,\n      confidence: prediction.confidence,\n      expectedImprovement: prediction.improvement,\n      reasoning: prediction.reasoning\n    };\n  }\n  \n  \u002F\u002F Train topology optimization model\n  async trainTopologyModel(trainingData) {\n    const trainingConfig = {\n      pattern_type: 'optimization',\n      training_data: JSON.stringify(trainingData),\n      epochs: 100\n    };\n    \n    const trainingResult = await mcp.neural_train(trainingConfig);\n    \n    \u002F\u002F Save trained model\n    if (trainingResult.success) {\n      await mcp.model_save({\n        modelId: trainingResult.modelId,\n        path: '$models$topology_optimizer.model'\n      });\n    }\n    \n    return trainingResult;\n  }\n}\n```\n\n## Advanced Optimization Algorithms\n\n### 1. Genetic Algorithm for Topology Evolution\n```javascript\n\u002F\u002F Genetic algorithm implementation for topology optimization\nclass GeneticTopologyOptimizer {\n  constructor(config = {}) {\n    this.populationSize = config.populationSize || 50;\n    this.mutationRate = config.mutationRate || 0.1;\n    this.crossoverRate = config.crossoverRate || 0.8;\n    this.maxGenerations = config.maxGenerations || 100;\n    this.eliteSize = config.eliteSize || 5;\n  }\n  \n  \u002F\u002F Evolve optimal topology\n  async evolve(initialTopologies, fitnessFunction, constraints) {\n    let population = initialTopologies;\n    let generation = 0;\n    let bestFitness = -Infinity;\n    let bestTopology = null;\n    \n    const convergenceHistory = [];\n    \n    while (generation \u003C this.maxGenerations) {\n      \u002F\u002F Evaluate fitness for each topology\n      const fitness = await Promise.all(\n        population.map(topology => fitnessFunction(topology, constraints))\n      );\n      \n      \u002F\u002F Track best solution\n      const maxFitnessIndex = fitness.indexOf(Math.max(...fitness));\n      if (fitness[maxFitnessIndex] > bestFitness) {\n        bestFitness = fitness[maxFitnessIndex];\n        bestTopology = population[maxFitnessIndex];\n      }\n      \n      convergenceHistory.push({\n        generation,\n        bestFitness,\n        averageFitness: fitness.reduce((a, b) => a + b) \u002F fitness.length\n      });\n      \n      \u002F\u002F Selection\n      const selected = this.selection(population, fitness);\n      \n      \u002F\u002F Crossover\n      const offspring = await this.crossover(selected);\n      \n      \u002F\u002F Mutation\n      const mutated = await this.mutation(offspring, constraints);\n      \n      \u002F\u002F Next generation\n      population = this.nextGeneration(population, fitness, mutated);\n      generation++;\n    }\n    \n    return {\n      bestTopology,\n      bestFitness,\n      generation,\n      convergenceHistory\n    };\n  }\n  \n  \u002F\u002F Topology crossover operation\n  async crossover(parents) {\n    const offspring = [];\n    \n    for (let i = 0; i \u003C parents.length - 1; i += 2) {\n      if (Math.random() \u003C this.crossoverRate) {\n        const [child1, child2] = await this.crossoverTopologies(\n          parents[i], \n          parents[i + 1]\n        );\n        offspring.push(child1, child2);\n      } else {\n        offspring.push(parents[i], parents[i + 1]);\n      }\n    }\n    \n    return offspring;\n  }\n  \n  \u002F\u002F Topology mutation operation\n  async mutation(population, constraints) {\n    return Promise.all(\n      population.map(async topology => {\n        if (Math.random() \u003C this.mutationRate) {\n          return await this.mutateTopology(topology, constraints);\n        }\n        return topology;\n      })\n    );\n  }\n}\n```\n\n### 2. Simulated Annealing for Topology Optimization\n```javascript\n\u002F\u002F Simulated annealing implementation\nclass SimulatedAnnealingOptimizer {\n  constructor(config = {}) {\n    this.initialTemperature = config.initialTemperature || 1000;\n    this.coolingRate = config.coolingRate || 0.95;\n    this.minTemperature = config.minTemperature || 1;\n    this.maxIterations = config.maxIterations || 10000;\n  }\n  \n  \u002F\u002F Simulated annealing optimization\n  async optimize(initialTopology, objectiveFunction, constraints) {\n    let currentTopology = initialTopology;\n    let currentScore = await objectiveFunction(currentTopology, constraints);\n    \n    let bestTopology = currentTopology;\n    let bestScore = currentScore;\n    \n    let temperature = this.initialTemperature;\n    let iteration = 0;\n    \n    const history = [];\n    \n    while (temperature > this.minTemperature && iteration \u003C this.maxIterations) {\n      \u002F\u002F Generate neighbor topology\n      const neighborTopology = await this.generateNeighbor(currentTopology, constraints);\n      const neighborScore = await objectiveFunction(neighborTopology, constraints);\n      \n      \u002F\u002F Accept or reject the neighbor\n      const deltaScore = neighborScore - currentScore;\n      \n      if (deltaScore > 0 || Math.random() \u003C Math.exp(deltaScore \u002F temperature)) {\n        currentTopology = neighborTopology;\n        currentScore = neighborScore;\n        \n        \u002F\u002F Update best solution\n        if (neighborScore > bestScore) {\n          bestTopology = neighborTopology;\n          bestScore = neighborScore;\n        }\n      }\n      \n      \u002F\u002F Record history\n      history.push({\n        iteration,\n        temperature,\n        currentScore,\n        bestScore\n      });\n      \n      \u002F\u002F Cool down\n      temperature *= this.coolingRate;\n      iteration++;\n    }\n    \n    return {\n      bestTopology,\n      bestScore,\n      iterations: iteration,\n      history\n    };\n  }\n  \n  \u002F\u002F Generate neighbor topology through local modifications\n  async generateNeighbor(topology, constraints) {\n    const modifications = [\n      () => this.addConnection(topology, constraints),\n      () => this.removeConnection(topology, constraints),\n      () => this.modifyConnection(topology, constraints),\n      () => this.relocateAgent(topology, constraints)\n    ];\n    \n    const modification = modifications[Math.floor(Math.random() * modifications.length)];\n    return await modification();\n  }\n}\n```\n\n## Operational Commands\n\n### Topology Optimization Commands\n```bash\n# Analyze current topology\nnpx claude-flow topology-analyze --swarm-id \u003Cid> --metrics performance\n\n# Optimize topology automatically\nnpx claude-flow topology-optimize --swarm-id \u003Cid> --strategy adaptive\n\n# Compare topology configurations\nnpx claude-flow topology-compare --topologies [\"hierarchical\", \"mesh\", \"hybrid\"]\n\n# Generate topology recommendations\nnpx claude-flow topology-recommend --workload-profile \u003Cfile> --constraints \u003Cfile>\n\n# Monitor topology performance\nnpx claude-flow topology-monitor --swarm-id \u003Cid> --interval 60\n```\n\n### Agent Placement Commands\n```bash\n# Optimize agent placement\nnpx claude-flow placement-optimize --algorithm genetic --agents \u003Cagent-list>\n\n# Analyze placement efficiency\nnpx claude-flow placement-analyze --current-placement \u003Cconfig>\n\n# Generate placement recommendations\nnpx claude-flow placement-recommend --communication-patterns \u003Cfile>\n```\n\n## Integration Points\n\n### With Other Optimization Agents\n- **Load Balancer**: Coordinates topology changes with load distribution\n- **Performance Monitor**: Receives topology performance metrics\n- **Resource Manager**: Considers resource constraints in topology decisions\n\n### With Swarm Infrastructure\n- **Task Orchestrator**: Adapts task distribution to topology changes\n- **Agent Coordinator**: Manages agent connections during topology updates\n- **Memory System**: Stores topology optimization history and patterns\n\n## Performance Metrics\n\n### Topology Performance Indicators\n```javascript\n\u002F\u002F Comprehensive topology metrics\nconst topologyMetrics = {\n  \u002F\u002F Communication efficiency\n  communicationEfficiency: {\n    latency: this.calculateAverageLatency(),\n    throughput: this.calculateThroughput(),\n    bandwidth_utilization: this.calculateBandwidthUtilization(),\n    message_overhead: this.calculateMessageOverhead()\n  },\n  \n  \u002F\u002F Network topology metrics\n  networkMetrics: {\n    diameter: this.calculateNetworkDiameter(),\n    clustering_coefficient: this.calculateClusteringCoefficient(),\n    betweenness_centrality: this.calculateBetweennessCentrality(),\n    degree_distribution: this.calculateDegreeDistribution()\n  },\n  \n  \u002F\u002F Fault tolerance\n  faultTolerance: {\n    connectivity: this.calculateConnectivity(),\n    redundancy: this.calculateRedundancy(),\n    single_point_failures: this.identifySinglePointFailures(),\n    recovery_time: this.calculateRecoveryTime()\n  },\n  \n  \u002F\u002F Scalability metrics\n  scalability: {\n    growth_capacity: this.calculateGrowthCapacity(),\n    scaling_efficiency: this.calculateScalingEfficiency(),\n    bottleneck_points: this.identifyBottleneckPoints(),\n    optimal_size: this.calculateOptimalSize()\n  }\n};\n```\n\nThis Topology Optimizer agent provides sophisticated swarm topology optimization with AI-powered decision making, advanced algorithms, and comprehensive performance monitoring for optimal swarm coordination.",{"name":5,"description":7},"main","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-Agent-智能体\u002FYYC3-Agent-智能体-ruflo\u002F.agents\u002Fskills\u002Fagent-topology-optimizer",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill agent-topology-optimizer",{"tool":39,"command":40},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill agent-topology-optimizer",{"tool":42,"command":43},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill agent-topology-optimizer","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Agent-智能体\u002FYYC3-Agent-智能体-ruflo\u002F.agents\u002Fskills\u002Fagent-topology-optimizer\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]