ruv-swarm
Version:
High-performance neural network swarm orchestration in WebAssembly
561 lines (456 loc) ⢠13.2 kB
JavaScript
/**
* Advanced command documentation for enhanced swarm optimization
*/
import fs from 'fs/promises';
import path from 'path';
class AdvancedCommandsGenerator {
constructor(options = {}) {
this.workingDir = options.workingDir || process.cwd();
}
/**
* Generate advanced optimization command documentation
*/
async generateAdvancedCommands() {
const commandsDir = path.join(this.workingDir, '.claude', 'commands');
// Create subdirectories
const subdirs = ['optimization', 'analysis', 'training', 'automation'];
for (const subdir of subdirs) {
await fs.mkdir(path.join(commandsDir, subdir), { recursive: true });
}
const commands = {
// Optimization commands
'optimization/auto-topology.md': {
title: 'Automatic Topology Selection',
content: `
Automatically select the optimal swarm topology based on task complexity analysis.
The system analyzes your task description to determine:
- Complexity level (simple/medium/complex)
- Required agent types
- Estimated duration
- Resource requirements
### 2. Topology Selection
Based on analysis, it selects:
- **Star**: For simple, centralized tasks
- **Mesh**: For medium complexity with flexibility needs
- **Hierarchical**: For complex tasks requiring structure
- **Ring**: For sequential processing workflows
### 3. Example Usage
**Simple Task:**
\`\`\`
Tool: mcp__ruv-swarm__task_orchestrate
Parameters: {"task": "Fix typo in README.md"}
Result: Automatically uses star topology with single agent
\`\`\`
**Complex Task:**
\`\`\`
Tool: mcp__ruv-swarm__task_orchestrate
Parameters: {"task": "Refactor authentication system with JWT, add tests, update documentation"}
Result: Automatically uses hierarchical topology with architect, coder, and tester agents
\`\`\`
- šÆ Optimal performance for each task type
- š¤ Automatic agent assignment
- ā” Reduced setup time
- š Better resource utilization
The pre-task hook automatically handles topology selection:
\`\`\`json
{
"command": "npx ruv-swarm hook pre-task --auto-spawn-agents --optimize-topology"
}
\`\`\``,
},
'optimization/parallel-execution.md': {
title: 'Parallel Task Execution',
content: `
Execute independent subtasks in parallel for maximum efficiency.
\`\`\`
Tool: mcp__ruv-swarm__task_orchestrate
Parameters: {
"task": "Build complete REST API with auth, CRUD operations, and tests",
"strategy": "parallel",
"maxAgents": 8
}
\`\`\`
The system automatically:
- Identifies independent components
- Assigns specialized agents
- Executes in parallel where possible
- Synchronizes at dependency points
For the REST API task:
- **Agent 1 (Architect)**: Design API structure
- **Agent 2-3 (Coders)**: Implement auth & CRUD in parallel
- **Agent 4 (Tester)**: Write tests as features complete
- **Agent 5 (Documenter)**: Update docs continuously
- š 2.8-4.4x faster execution
- šŖ Optimal CPU utilization
- š Automatic load balancing
- š Linear scalability with agents
\`\`\`
Tool: mcp__ruv-swarm__swarm_monitor
Parameters: {"interval": 1, "duration": 10}
\`\`\`
Watch real-time parallel execution progress!`,
},
// Analysis commands
'analysis/performance-bottlenecks.md': {
title: 'Performance Bottleneck Analysis',
content: `
Identify and resolve performance bottlenecks in your development workflow.
The post-task hook automatically analyzes:
- Execution time vs. complexity
- Agent utilization rates
- Resource constraints
- Operation patterns
**Time Bottlenecks:**
- Tasks taking > 5 minutes
- Sequential operations that could parallelize
- Redundant file operations
**Coordination Bottlenecks:**
- Single agent for complex tasks
- Unbalanced agent workloads
- Poor topology selection
**Resource Bottlenecks:**
- High operation count (> 100)
- Memory constraints
- I/O limitations
### 3. Improvement Suggestions
\`\`\`
Tool: mcp__ruv-swarm__task_results
Parameters: {"taskId": "task-123", "format": "detailed"}
Result includes:
{
"bottlenecks": [
{
"type": "coordination",
"severity": "high",
"description": "Single agent used for complex task",
"recommendation": "Spawn specialized agents for parallel work"
}
],
"improvements": [
{
"area": "execution_time",
"suggestion": "Use parallel task execution",
"expectedImprovement": "30-50% time reduction"
}
]
}
\`\`\`
The system learns from each task to prevent future bottlenecks!`,
},
'analysis/token-efficiency.md': {
title: 'Token Usage Optimization',
content: `
Reduce token consumption while maintaining quality through intelligent coordination.
- Search results cached for 5 minutes
- File content cached during session
- Pattern recognition reduces redundant searches
- Agents share context automatically
- Avoid duplicate file reads
- Batch related operations
\`\`\`bash
npx ruv-swarm hook session-end --export-metrics
{
"metrics": {
"tokensSaved": 15420,
"operations": 45,
"efficiency": "343 tokens/operation"
}
}
\`\`\`
1. **Use Task tool** for complex searches
2. **Enable caching** in pre-search hooks
3. **Batch operations** when possible
4. **Review session summaries** for insights
- š 32.3% average token reduction
- šÆ More focused operations
- š Intelligent result reuse
- š Cumulative improvements`,
},
// Training commands
'training/neural-patterns.md': {
title: 'Neural Pattern Training',
content: `
Continuously improve coordination through neural network learning.
Every successful operation trains the neural networks:
- Edit patterns for different file types
- Search strategies that find results faster
- Task decomposition approaches
- Agent coordination patterns
\`\`\`
Tool: mcp__ruv-swarm__neural_train
Parameters: {"iterations": 20}
\`\`\`
**Cognitive Patterns:**
- Convergent: Focused problem-solving
- Divergent: Creative exploration
- Lateral: Alternative approaches
- Systems: Holistic thinking
- Critical: Analytical evaluation
- Abstract: High-level design
\`\`\`
Tool: mcp__ruv-swarm__neural_status
Result: {
"patterns": {
"convergent": 0.92,
"divergent": 0.87,
"lateral": 0.85
},
"improvement": "5.3% since last session",
"confidence": 0.89
}
\`\`\`
- š§ Learns your coding style
- š Improves with each use
- šÆ Better task predictions
- ā” Faster coordination`,
},
'training/specialization.md': {
title: 'Agent Specialization Training',
content: `
Train agents to become experts in specific domains for better performance.
Agents automatically specialize based on file extensions:
- **.js/.ts**: Modern JavaScript patterns
- **.py**: Pythonic idioms
- **.go**: Go best practices
- **.rs**: Rust safety patterns
\`\`\`
Tool: mcp__ruv-swarm__agent_spawn
Parameters: {
"type": "coder",
"capabilities": ["react", "typescript", "testing"]
}
\`\`\`
The system trains through:
- Successful edit operations
- Code review patterns
- Error fix approaches
- Performance optimizations
\`\`\`
Tool: mcp__ruv-swarm__agent_list
Parameters: {"filter": "active"}
Result shows expertise levels:
{
"agents": [
{
"id": "coder-123",
"specializations": {
"javascript": 0.95,
"react": 0.88,
"testing": 0.82
}
}
]
}
\`\`\`
Agents share learnings across sessions for cumulative expertise!`,
},
// Automation commands
'automation/smart-agents.md': {
title: 'Smart Agent Auto-Spawning',
content: `
Automatically spawn the right agents at the right time without manual intervention.
When editing files, agents auto-spawn:
- **JavaScript/TypeScript**: Coder agent
- **Markdown**: Researcher agent
- **JSON/YAML**: Analyst agent
- **Multiple files**: Coordinator agent
\`\`\`
Simple task: "Fix typo"
ā Single coordinator agent
Complex task: "Implement OAuth with Google"
ā Architect + Coder + Tester + Researcher
\`\`\`
The system monitors workload and spawns additional agents when:
- Task queue grows
- Complexity increases
- Parallel opportunities exist
Already enabled in settings.json:
\`\`\`json
{
"hooks": [{
"matcher": "^Task$",
"command": "npx ruv-swarm hook pre-task --auto-spawn-agents"
}]
}
\`\`\`
- š¤ Zero manual agent management
- šÆ Perfect agent selection
- š Dynamic scaling
- š¾ Resource efficiency`,
},
'automation/self-healing.md': {
title: 'Self-Healing Workflows',
content: `
Automatically detect and recover from errors without interrupting your flow.
Monitors for:
- Failed commands
- Syntax errors
- Missing dependencies
- Broken tests
**Missing Dependencies:**
\`\`\`
Error: Cannot find module 'express'
ā Automatically runs: npm install express
ā Retries original command
\`\`\`
**Syntax Errors:**
\`\`\`
Error: Unexpected token
ā Analyzes error location
ā Suggests fix through analyzer agent
ā Applies fix with confirmation
\`\`\`
**Test Failures:**
\`\`\`
Test failed: "user authentication"
ā Spawns debugger agent
ā Analyzes failure cause
ā Implements fix
ā Re-runs tests
\`\`\`
Each recovery improves future prevention:
- Patterns saved to knowledge base
- Similar errors prevented proactively
- Recovery strategies optimized
\`\`\`json
{
"PostToolUse": [{
"matcher": "^Bash$",
"command": "npx ruv-swarm hook post-bash --exit-code '\${tool.result.exitCode}' --auto-recover"
}]
}
\`\`\`
- š”ļø Resilient workflows
- š Automatic recovery
- š Learns from errors
- ā±ļø Saves debugging time`,
},
'automation/session-memory.md': {
title: 'Cross-Session Memory',
content: `
Maintain context and learnings across Claude Code sessions for continuous improvement.
At session end, automatically saves:
- Active agents and specializations
- Task history and patterns
- Performance metrics
- Neural network weights
- Knowledge base updates
\`\`\`bash
claude "Continue where we left off"
npx ruv-swarm hook session-restore --session-id "sess-123"
\`\`\`
**Project Memory:**
- File relationships
- Common edit patterns
- Testing approaches
- Build configurations
**Agent Memory:**
- Specialization levels
- Task success rates
- Optimization strategies
- Error patterns
**Performance Memory:**
- Bottleneck history
- Optimization results
- Token usage patterns
- Efficiency trends
\`\`\`bash
ls .ruv-swarm/
rm .ruv-swarm/session-*.json
export RUV_SWARM_MEMORY_PERSIST=false
\`\`\`
- š§ Contextual awareness
- š Cumulative learning
- ā” Faster task completion
- šÆ Personalized optimization`,
},
};
const createdFiles = [];
// Generate command files
for (const [filepath, config] of Object.entries(commands)) {
const content = config.content || this.generateCommandContent(config);
const filePath = path.join(commandsDir, filepath);
await fs.writeFile(filePath, content);
createdFiles.push(filepath);
}
return { files: createdFiles, success: true };
}
generateCommandContent(config) {
return `
${config.description || 'Advanced swarm optimization capability'}
${config.usage || 'See main documentation for details'}
${config.benefits || '- Improved performance\n- Automated workflows\n- Intelligent coordination'}
`;
}
}
export { AdvancedCommandsGenerator };