[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EE3APZ820DJM6AQDAFN0SR":3,"skill-same:01M7EE3APZ820DJM6AQDAFN0SR":46},{"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":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7EE3APZ820DJM6AQDAFN0SR","agent-topology-optimizer",null,"Agent skill for topology-optimizer - invoke with $agent-topology-optimizer","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fagent-topology-optimizer-ruflo-main\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","d69096e239f2a89aabc2cd078c47664a9d3b1e11","04-安全渗透\u002Fagent-topology-optimizer-ruflo-main",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill agent-topology-optimizer",{"tool":38,"command":39},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill agent-topology-optimizer",{"tool":41,"command":42},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill agent-topology-optimizer","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fagent-topology-optimizer-ruflo-main\u002FSKILL.md",true,[],[47,55,60,67,74,81],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":54},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":56,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":54},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":54},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":54},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":54},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":54},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]