This commit is contained in:
rUv committed 2025-06-10 23:33:22 +00:00
1 parent bee340c997
commit effc3bd829
11 files changed
+1397 -3

No files matched your search

+25 -2
View File
@@ -138,6 +138,8 @@ Comprehensive documentation is available to help you get the most out of Claude-
- **[Terminal Management](./docs/08-terminal-management.md)** - Terminal pooling and sessions
- **[Troubleshooting](./docs/09-troubleshooting.md)** - Common issues and solutions
- **[Advanced Usage](./docs/10-advanced-usage.md)** - Power user features
- **[Claude Spawning](./docs/11-claude-spawning.md)** - Spawning Claude instances
- **[Swarm Mode](./docs/12-swarm.md)** - Self-orchestrating agent swarms 🐝
- **[CLI Reference](./docs/cli-reference.md)** - Complete command documentation
## 💡 **Quick Start Guide**
@@ -189,7 +191,28 @@ npx claude-flow claude spawn "fix payment bug" --tools "View,Edit,Bash" --no-per
npx claude-flow claude batch examples/claude-workflow.json --dry-run
```
### 6. **Monitor System Status**
### 6. **Claude Swarm Mode** 🐝 🆕
```bash
# Create self-orchestrating agent swarms
npx claude-flow swarm "Build a complete e-commerce platform"
# Research-focused swarm
npx claude-flow swarm "Research cloud architecture best practices" \
--strategy research --research --max-agents 8
# Development swarm with review
npx claude-flow swarm "Refactor authentication system" \
--strategy development --review --parallel
# Complex project with coordinator
npx claude-flow swarm "Migrate monolithic app to microservices" \
--coordinator --max-depth 4 --timeout 120
# Preview swarm configuration
npx claude-flow swarm "Create mobile app" --dry-run --verbose
```
### 7. **Monitor System Status**
```bash
# Check system health
npx claude-flow status
@@ -477,7 +500,7 @@ claude-flow task workflow example-workflow.json
## Development
### Prerequisites
- Deno 1.38+ or Node.js 16+
- Deno 1.38+ or Node.js 16+ (Install Deno: https://deno.land/#installation)
- Git
### Setup
BIN
View File
Binary file not shown.
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
# Claude-Flow Swarm Mode Wrapper
# This script wraps the swarm demo to work with the installed Deno
# Find deno in the path
DENO_PATH=$(which deno 2>/dev/null || echo "/home/codespace/.deno/bin/deno")
if [ ! -x "$DENO_PATH" ]; then
echo "Error: Deno is not installed or not in PATH"
echo "Please install Deno first: https://deno.land/#installation"
exit 1
fi
# Get the directory of this script
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SWARM_DEMO="$SCRIPT_DIR/../swarm-demo.ts"
# Run the swarm demo with all arguments
exec "$DENO_PATH" run --allow-all "$SWARM_DEMO" "$@"
+303
View File
@@ -0,0 +1,303 @@
# Swarm Mode - Self-Orchestrating Agent Networks
## Overview
Swarm mode enables Claude to act as a master orchestrator, automatically spawning and coordinating multiple specialized sub-agents to achieve complex objectives. This advanced feature allows for autonomous, self-organizing AI teams that can tackle large-scale projects.
## Key Concepts
### Master Orchestrator
The primary Claude instance that:
- Analyzes objectives and creates execution plans
- Spawns specialized agents as needed
- Manages task dependencies and coordination
- Monitors progress and adjusts strategies
- Synthesizes results from all agents
### Agent Types
- **Researcher**: Information gathering, web research, analysis
- **Developer**: Code implementation, testing, debugging
- **Analyst**: Data analysis, pattern recognition, insights
- **Reviewer**: Code review, quality assurance, validation
- **Coordinator**: Sub-task coordination, dependency management
### Orchestration Strategies
- **Auto**: Automatically determine the best approach
- **Research**: Focus on research and information gathering
- **Development**: Focus on implementation and coding
- **Analysis**: Focus on analysis and insights
## Command Usage
### Basic Syntax
```bash
claude-flow swarm <objective> [options]
```
### Options
| Option | Short | Description | Default |
|--------|-------|-------------|---------|
| `--strategy` | `-s` | Orchestration strategy (auto, research, development, analysis) | `auto` |
| `--max-agents` | | Maximum number of agents to spawn | `5` |
| `--max-depth` | | Maximum delegation depth | `3` |
| `--research` | | Enable research capabilities for all agents | `false` |
| `--parallel` | | Enable parallel execution | `false` |
| `--memory-namespace` | | Shared memory namespace | `swarm` |
| `--timeout` | | Swarm timeout in minutes | `60` |
| `--review` | | Enable peer review between agents | `false` |
| `--coordinator` | | Spawn dedicated coordinator agent | `false` |
| `--config` | `-c` | MCP config file | |
| `--verbose` | `-v` | Enable verbose output | `false` |
| `--dry-run` | `-d` | Preview swarm configuration | `false` |
## Examples
### Basic Swarm
```bash
claude-flow swarm "Build a complete e-commerce platform with React and Node.js"
```
### Research-Focused Swarm
```bash
claude-flow swarm "Research and document best practices for microservices architecture" \
--strategy research \
--research \
--max-agents 8
```
### Development Swarm with Review
```bash
claude-flow swarm "Refactor the authentication system with modern security practices" \
--strategy development \
--review \
--parallel \
--max-agents 6
```
### Complex Project with Coordinator
```bash
claude-flow swarm "Migrate monolithic application to microservices" \
--coordinator \
--max-depth 4 \
--timeout 120 \
--review
```
### Dry Run to Preview
```bash
claude-flow swarm "Create mobile app" --dry-run --verbose
```
## How It Works
### 1. Objective Analysis
The master orchestrator receives the objective and:
- Breaks it down into major components
- Identifies required skills and resources
- Determines optimal agent composition
- Creates a hierarchical task structure
### 2. Agent Spawning
Based on the analysis, the orchestrator:
- Spawns specialized agents with appropriate tools
- Assigns specific responsibilities to each agent
- Sets up communication channels
- Establishes task dependencies
### 3. Task Distribution
The orchestrator manages work distribution:
- Assigns tasks based on agent capabilities
- Monitors workload balance
- Handles task handoffs
- Manages parallel execution when enabled
### 4. Coordination & Communication
Throughout execution:
- Agents share discoveries via memory namespace
- Progress updates flow to the orchestrator
- Dependencies are automatically managed
- Peer reviews occur if enabled
### 5. Result Synthesis
As tasks complete:
- Results are collected and validated
- The orchestrator synthesizes findings
- Final deliverables are assembled
- Summary report is generated
## Memory Coordination
All agents in a swarm share a memory namespace, enabling:
- **Knowledge Sharing**: Discoveries are immediately available to all agents
- **Duplicate Prevention**: Agents avoid redundant work
- **Context Building**: Each agent builds on others' findings
- **Progress Tracking**: Centralized view of swarm progress
## Advanced Features
### Delegation Depth
The `--max-depth` option controls how many levels of sub-agents can be created:
- Depth 1: Only the master orchestrator
- Depth 2: Master can spawn agents
- Depth 3: Agents can spawn sub-agents
- Depth 4+: Deep hierarchical structures
### Peer Review
When `--review` is enabled:
- Agents review each other's work
- Quality checks occur automatically
- Feedback loops improve outputs
- Final results have higher quality
### Parallel Execution
With `--parallel` flag:
- Independent tasks run simultaneously
- Resource utilization is maximized
- Total execution time is reduced
- Coordination overhead increases
### Dedicated Coordinator
The `--coordinator` option:
- Spawns a specialized coordination agent
- Handles complex dependency management
- Optimizes resource allocation
- Manages inter-agent communication
## Best Practices
### 1. Clear Objectives
- Be specific about desired outcomes
- Include success criteria
- Mention any constraints or requirements
### 2. Strategy Selection
- Use `auto` for general tasks
- Choose `research` for information-heavy projects
- Select `development` for coding tasks
- Pick `analysis` for data-centric work
### 3. Resource Management
- Start with default agent limits
- Increase `--max-agents` for complex projects
- Monitor system resources during execution
- Use `--timeout` to prevent runaway swarms
### 4. Review Process
- Enable `--review` for critical projects
- Allow extra time for review cycles
- Consider peer review for quality assurance
### 5. Memory Namespace
- Use project-specific namespaces
- Clean up namespaces after completion
- Share namespaces across related swarms
## Monitoring Swarms
During execution, the master orchestrator provides regular status updates:
```
[SWARM STATUS]
- Active Agents: 4/6
- Tasks Completed: 12/20
- Current Phase: Implementation
- Next Actions:
- Complete user authentication module
- Begin integration testing
- Review API documentation
```
## Integration with Claude-Flow
Swarm mode integrates seamlessly with other Claude-Flow features:
- Uses the same persistence layer
- Shares terminal pool resources
- Leverages MCP tools
- Coordinates through EventBus
## Troubleshooting
### Common Issues
1. **"Claude command not found"**
- Ensure Claude CLI is installed
- Check PATH environment variable
2. **"Maximum agents reached"**
- Increase `--max-agents` limit
- Simplify objective into phases
3. **"Timeout exceeded"**
- Extend timeout with `--timeout`
- Break objective into smaller parts
4. **"Memory namespace conflict"**
- Use unique namespace per swarm
- Clean up old namespaces
### Debug Mode
Use `--verbose` for detailed logging:
```bash
claude-flow swarm "debug task" --verbose --dry-run
```
## Example Workflows
### Full Stack Application
```bash
claude-flow swarm "Create a full-stack task management app with React, Node.js, PostgreSQL" \
--strategy development \
--max-agents 8 \
--parallel \
--review \
--coordinator
```
### Research Project
```bash
claude-flow swarm "Research and compare top 10 JavaScript frameworks for enterprise applications" \
--strategy research \
--research \
--max-agents 10 \
--memory-namespace "js-frameworks"
```
### Code Migration
```bash
claude-flow swarm "Migrate legacy jQuery application to modern React with TypeScript" \
--strategy development \
--review \
--max-depth 4 \
--timeout 180
```
## Security Considerations
- Swarms inherit orchestrator's permissions
- Each agent runs with specified tools only
- Memory namespaces provide isolation
- No external data access without `--research`
## Performance Tips
1. Use `--parallel` for independent tasks
2. Limit `--max-depth` to reduce overhead
3. Set appropriate `--timeout` values
4. Monitor system resources during execution
5. Use focused strategies over `auto`
## Future Enhancements
Planned improvements for swarm mode:
- Visual swarm monitoring dashboard
- Dynamic agent scaling
- Cross-swarm coordination
- Swarm templates and presets
- Performance analytics
## Conclusion
Swarm mode represents the pinnacle of AI agent orchestration, enabling autonomous teams of specialized agents to tackle complex objectives. By leveraging Claude's intelligence for both execution and coordination, swarms can achieve results that would be difficult or impossible for a single agent.
Start with simple swarms and gradually increase complexity as you become familiar with the patterns and best practices. The self-organizing nature of swarms means they can often surprise you with creative solutions and efficient execution strategies.
+4 -1
View File
@@ -4,7 +4,8 @@
"description": "Advanced AI agent orchestration system for Claude Code",
"main": "src/cli/main.ts",
"bin": {
"claude-flow": "./bin/claude-flow"
"claude-flow": "./bin/claude-flow",
"claude-flow-swarm": "./bin/claude-flow-swarm"
},
"scripts": {
"postinstall": "node scripts/install.js",
@@ -36,7 +37,9 @@
},
"files": [
"bin/claude-flow",
"bin/claude-flow-swarm",
"src/",
"swarm-demo.ts",
"scripts/install.js",
"README.md",
"LICENSE",
+74
View File
@@ -0,0 +1,74 @@
# Claude-Flow Swarm Mode Demo
This is a working demonstration of the swarm mode feature that bypasses the Cliffy import issues in the current version.
## Usage
```bash
# Direct usage
./swarm-demo.ts <objective> [options]
# Using claude-flow wrapper
./bin/claude-flow swarm <objective> [options]
# Or if installed globally
claude-flow swarm <objective> [options]
```
## Options
- `--dry-run, -d` - Preview swarm configuration without executing
- `--max-agents <n>` - Maximum number of agents (default: 5)
- `--strategy <s>` - Strategy: auto, research, development, analysis
- `--coordinator` - Spawn dedicated coordinator agent
- `--research` - Enable research capabilities for all agents
- `--parallel` - Enable parallel execution
- `--review` - Enable peer review between agents
- `--verbose, -v` - Show verbose output
## Examples
```bash
# Basic swarm
./bin/claude-flow swarm "Build a REST API"
# Complex migration with coordinator
./bin/claude-flow swarm "Migrate monolithic app to microservices" \
--coordinator --max-agents 10 --review
# Research swarm
./bin/claude-flow swarm "Research best practices for cloud architecture" \
--strategy research --research --max-agents 8
# Development swarm with parallel execution
./bin/claude-flow swarm "Implement user authentication system" \
--strategy development --parallel --review
# Preview configuration
./bin/claude-flow swarm "Create mobile app" --dry-run --verbose
```
## Requirements
- Claude CLI must be installed and available in PATH
- Deno runtime (for running the scripts)
## How It Works
1. The swarm demo script creates an orchestration prompt for Claude
2. Claude acts as the master orchestrator
3. The master analyzes the objective and creates an execution plan
4. It then coordinates the spawning and management of sub-agents
5. Each agent works on specific tasks while sharing knowledge
6. Results are synthesized and presented
## Troubleshooting
If you get "Claude CLI not found", ensure:
1. Claude desktop app is installed
2. The `claude` command is available in your PATH
3. You can test with: `which claude`
## Note
This is a temporary solution while the main CLI is being updated to resolve the import assertion deprecation warnings. The functionality is identical to the integrated swarm command.
+92
View File
@@ -0,0 +1,92 @@
#!/bin/bash
# Integration test for Claude-Flow Swarm Mode
echo "Claude-Flow Swarm Mode Integration Test"
echo "======================================="
echo
# Test 1: Binary exists
echo "Test 1: Checking binary files..."
if [ -f "./bin/claude-flow" ]; then
echo "✅ claude-flow binary found"
else
echo "❌ claude-flow binary not found"
exit 1
fi
if [ -f "./bin/claude-flow-swarm" ]; then
echo "✅ claude-flow-swarm wrapper found"
else
echo "❌ claude-flow-swarm wrapper not found"
exit 1
fi
# Test 2: Help command
echo -e "\nTest 2: Testing help command..."
if ./bin/claude-flow help swarm | grep -q "Claude Swarm Mode"; then
echo "✅ Swarm help command works"
else
echo "❌ Swarm help command failed"
exit 1
fi
# Test 3: Swarm listed in main help
echo -e "\nTest 3: Checking swarm in main help..."
if ./bin/claude-flow --help | grep -q "swarm"; then
echo "✅ Swarm command listed in main help"
else
echo "❌ Swarm command not listed in main help"
exit 1
fi
# Test 4: Standalone swarm dry-run
echo -e "\nTest 4: Testing standalone swarm dry-run..."
if ./bin/claude-flow-swarm "Test objective" --dry-run | grep -q "DRY RUN"; then
echo "✅ Standalone swarm dry-run works"
else
echo "❌ Standalone swarm dry-run failed"
exit 1
fi
# Test 5: Complex swarm configuration
echo -e "\nTest 5: Testing complex swarm configuration..."
OUTPUT=$(./bin/claude-flow-swarm "Complex test" --strategy research --max-agents 10 --coordinator --review --parallel --dry-run)
if echo "$OUTPUT" | grep -q "Strategy: research" && \
echo "$OUTPUT" | grep -q "Max Agents: 10" && \
echo "$OUTPUT" | grep -q "Coordinator: true" && \
echo "$OUTPUT" | grep -q "Review Mode: true" && \
echo "$OUTPUT" | grep -q "Parallel: true"; then
echo "✅ Complex swarm configuration works"
else
echo "❌ Complex swarm configuration failed"
echo "Output: $OUTPUT"
exit 1
fi
# Test 6: Check documentation files
echo -e "\nTest 6: Checking documentation..."
if [ -f "./docs/12-swarm.md" ]; then
echo "✅ Swarm documentation found"
else
echo "❌ Swarm documentation not found"
exit 1
fi
# Test 7: Check swarm demo script
echo -e "\nTest 7: Checking swarm demo script..."
if [ -f "./swarm-demo.ts" ]; then
echo "✅ swarm-demo.ts found"
else
echo "❌ swarm-demo.ts not found"
exit 1
fi
echo -e "\n======================================="
echo "✅ All integration tests passed!"
echo
echo "Swarm mode is ready to use:"
echo " 1. ./bin/claude-flow swarm \"Your objective\" [options]"
echo " 2. ./bin/claude-flow-swarm \"Your objective\" [options]"
echo " 3. npx claude-flow swarm \"Your objective\" [options]"
echo
echo "For more info: ./bin/claude-flow help swarm"
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env -S deno run --allow-all
/**
* Test script for Claude Swarm Mode functionality
*/
import { colors } from 'https://deno.land/x/cliffy@v1.0.0-rc.3/ansi/colors.ts';
async function runTest(name: string, command: string[], expectedPatterns: string[]): Promise<boolean> {
console.log(colors.blue(`\nTesting: ${name}`));
console.log(colors.gray(`Command: ${command.join(' ')}`));
try {
const cmd = new Deno.Command(command[0], {
args: command.slice(1),
stdout: 'piped',
stderr: 'piped',
});
const { code, stdout, stderr } = await cmd.output();
const output = new TextDecoder().decode(stdout);
const errorOutput = new TextDecoder().decode(stderr);
if (code !== 0 && !name.includes("dry-run")) {
console.log(colors.red(`❌ Command failed with code ${code}`));
if (errorOutput) {
console.log(colors.red(`Error: ${errorOutput}`));
}
return false;
}
// Check for expected patterns in output
let allPatternsFound = true;
for (const pattern of expectedPatterns) {
if (!output.includes(pattern)) {
console.log(colors.red(`❌ Expected pattern not found: "${pattern}"`));
allPatternsFound = false;
}
}
if (allPatternsFound) {
console.log(colors.green(`✅ Test passed`));
return true;
} else {
console.log(colors.red(`❌ Test failed`));
console.log(colors.gray(`Output: ${output.substring(0, 200)}...`));
return false;
}
} catch (error) {
console.log(colors.red(`❌ Error running test: ${(error as Error).message}`));
return false;
}
}
async function main() {
console.log(colors.bold('Claude-Flow Swarm Mode Test Suite'));
console.log('='.repeat(50));
const tests = [
{
name: "Swarm demo dry-run",
command: ["./swarm-demo.ts", "Build a REST API", "--dry-run"],
patterns: ["DRY RUN", "Swarm ID:", "Objective: Build a REST API"],
},
{
name: "CLI swarm command dry-run",
command: ["deno", "run", "--allow-all", "./src/cli/main.ts", "swarm", "Test objective", "--dry-run"],
patterns: ["DRY RUN", "Swarm ID:", "Objective: Test objective"],
},
{
name: "CLI swarm help",
command: ["deno", "run", "--allow-all", "./src/cli/main.ts", "help", "swarm"],
patterns: ["Claude Swarm Mode", "self-orchestrating Claude agent swarms"],
},
{
name: "Swarm with research strategy",
command: ["./swarm-demo.ts", "Research test", "--strategy", "research", "--dry-run"],
patterns: ["Strategy: research", "DRY RUN"],
},
{
name: "Swarm with all options",
command: [
"./swarm-demo.ts",
"Complex task",
"--max-agents", "10",
"--max-depth", "4",
"--research",
"--parallel",
"--review",
"--coordinator",
"--dry-run"
],
patterns: [
"Max Agents: 10",
"Max Depth: 4",
"Research: true",
"Parallel: true",
"Review Mode: true",
"Coordinator: true"
],
},
];
let passedTests = 0;
let failedTests = 0;
for (const test of tests) {
const passed = await runTest(test.name, test.command, test.patterns);
if (passed) {
passedTests++;
} else {
failedTests++;
}
}
console.log('\n' + '='.repeat(50));
console.log(colors.bold('Test Summary:'));
console.log(colors.green(`✅ Passed: ${passedTests}`));
console.log(colors.red(`❌ Failed: ${failedTests}`));
console.log(colors.blue(`📊 Total: ${tests.length}`));
if (failedTests === 0) {
console.log(colors.green('\n🎉 All tests passed!'));
} else {
console.log(colors.red('\n⚠️ Some tests failed'));
}
// Additional manual test instructions
console.log('\n' + colors.bold('Manual Testing Instructions:'));
console.log('1. Test with actual Claude CLI (if available):');
console.log(' ./swarm-demo.ts "Build a simple calculator"');
console.log(' ./bin/claude-flow swarm "Create a REST API"');
console.log('\n2. Test various strategies:');
console.log(' ./swarm-demo.ts "Research best practices" --strategy research');
console.log(' ./swarm-demo.ts "Implement feature" --strategy development');
console.log('\n3. Test complex scenarios:');
console.log(' ./swarm-demo.ts "Migrate to microservices" --coordinator --review --parallel');
}
if (import.meta.main) {
await main();
}
+107
View File
@@ -7,6 +7,7 @@ import { MemoryManager } from "../../memory/manager.ts";
import { EventBus } from "../../core/event-bus.ts";
import { Logger } from "../../core/logger.ts";
import { JsonPersistenceManager } from "../../core/json-persistence.ts";
import { swarmAction } from "./swarm.ts";
let orchestrator: Orchestrator | null = null;
let configManager: ConfigManager | null = null;
@@ -993,6 +994,84 @@ export function setupCommands(cli: CLI): void {
},
});
// Swarm command
cli.command({
name: "swarm",
description: "Create self-orchestrating Claude agent swarms",
options: [
{
name: "strategy",
short: "s",
description: "Orchestration strategy (auto, research, development, analysis)",
type: "string",
default: "auto",
},
{
name: "max-agents",
description: "Maximum number of agents to spawn",
type: "number",
default: 5,
},
{
name: "max-depth",
description: "Maximum delegation depth",
type: "number",
default: 3,
},
{
name: "research",
description: "Enable research capabilities for all agents",
type: "boolean",
},
{
name: "parallel",
description: "Enable parallel execution",
type: "boolean",
},
{
name: "memory-namespace",
description: "Shared memory namespace",
type: "string",
default: "swarm",
},
{
name: "timeout",
description: "Swarm timeout in minutes",
type: "number",
default: 60,
},
{
name: "review",
description: "Enable peer review between agents",
type: "boolean",
},
{
name: "coordinator",
description: "Spawn dedicated coordinator agent",
type: "boolean",
},
{
name: "config",
short: "c",
description: "MCP config file",
type: "string",
},
{
name: "verbose",
short: "v",
description: "Enable verbose output",
type: "boolean",
},
{
name: "dry-run",
short: "d",
description: "Preview swarm configuration",
type: "boolean",
},
],
action: swarmAction,
});
// Help command
cli.command({
name: "help",
@@ -1027,6 +1106,34 @@ export function setupCommands(cli: CLI): void {
console.log(` ${blue("claude-flow claude batch")} workflow.json --dry-run`);
console.log();
console.log("For more information, see: https://github.com/ruvnet/claude-code-flow/docs/11-claude-spawning.md");
} else if (command === "swarm") {
console.log(bold(blue("Claude Swarm Mode")));
console.log();
console.log("Create self-orchestrating Claude agent swarms to tackle complex objectives.");
console.log();
console.log(bold("Usage:"));
console.log(" claude-flow swarm <objective> [options]");
console.log();
console.log(bold("Options:"));
console.log(" -s, --strategy <s> Orchestration strategy (auto, research, development, analysis)");
console.log(" --max-agents <n> Maximum number of agents (default: 5)");
console.log(" --max-depth <n> Maximum delegation depth (default: 3)");
console.log(" --research Enable research capabilities for all agents");
console.log(" --parallel Enable parallel execution");
console.log(" --memory-namespace <ns> Shared memory namespace (default: swarm)");
console.log(" --timeout <minutes> Swarm timeout in minutes (default: 60)");
console.log(" --review Enable peer review between agents");
console.log(" --coordinator Spawn dedicated coordinator agent");
console.log(" -c, --config <file> MCP config file");
console.log(" -v, --verbose Enable verbose output");
console.log(" -d, --dry-run Preview swarm configuration");
console.log();
console.log(bold("Examples:"));
console.log(` ${blue("claude-flow swarm")} "Build a REST API"`);
console.log(` ${blue("claude-flow swarm")} "Research cloud architecture" --strategy research --research`);
console.log(` ${blue("claude-flow swarm")} "Migrate app to microservices" --coordinator --review`);
console.log();
console.log("For more information, see: https://github.com/ruvnet/claude-code-flow/docs/12-swarm.md");
} else {
// Show general help
cli.showHelp();
+266
View File
@@ -0,0 +1,266 @@
/**
* Claude Swarm Mode - Self-orchestrating agent swarms
*/
import { generateId } from '../../utils/helpers.ts';
import { success, error, warning, info } from "../cli-core.ts";
import type { CommandContext } from "../cli-core.ts";
export async function swarmAction(ctx: CommandContext) {
// Get the objective from args
const objective = ctx.args.join(' ');
if (!objective) {
error("Usage: swarm <objective>");
console.log("\nExamples:");
console.log(' claude-flow swarm "Build a REST API"');
console.log(' claude-flow swarm "Research cloud architecture" --strategy research --research');
return;
}
const options = {
strategy: ctx.flags.strategy as string || 'auto',
maxAgents: ctx.flags.maxAgents as number || ctx.flags['max-agents'] as number || 5,
maxDepth: ctx.flags.maxDepth as number || ctx.flags['max-depth'] as number || 3,
research: ctx.flags.research as boolean || false,
parallel: ctx.flags.parallel as boolean || false,
memoryNamespace: ctx.flags.memoryNamespace as string || ctx.flags['memory-namespace'] as string || 'swarm',
timeout: ctx.flags.timeout as number || 60,
review: ctx.flags.review as boolean || false,
coordinator: ctx.flags.coordinator as boolean || false,
config: ctx.flags.config as string || ctx.flags.c as string,
verbose: ctx.flags.verbose as boolean || ctx.flags.v as boolean || false,
dryRun: ctx.flags.dryRun as boolean || ctx.flags['dry-run'] as boolean || ctx.flags.d as boolean || false,
};
const swarmId = generateId('swarm');
if (options.dryRun) {
warning('DRY RUN - Swarm Configuration:');
console.log(`Swarm ID: ${swarmId}`);
console.log(`Objective: ${objective}`);
console.log(`Strategy: ${options.strategy}`);
console.log(`Max Agents: ${options.maxAgents}`);
console.log(`Max Depth: ${options.maxDepth}`);
console.log(`Research: ${options.research}`);
console.log(`Parallel: ${options.parallel}`);
console.log(`Review Mode: ${options.review}`);
console.log(`Coordinator: ${options.coordinator}`);
console.log(`Memory Namespace: ${options.memoryNamespace}`);
console.log(`Timeout: ${options.timeout} minutes`);
return;
}
success(`🐝 Initializing Claude Swarm: ${swarmId}`);
console.log(`📋 Objective: ${objective}`);
// Build the orchestration prompt
const orchestrationPrompt = buildOrchestrationPrompt(objective, options);
// Spawn the master orchestrator
info('🎯 Spawning Master Orchestrator...');
const orchestratorTask = {
id: `${swarmId}-orchestrator`,
description: orchestrationPrompt,
tools: buildOrchestratorTools(options),
config: options.config,
environment: {
CLAUDE_SWARM_ID: swarmId,
CLAUDE_SWARM_MODE: 'orchestrator',
CLAUDE_SWARM_OBJECTIVE: objective,
CLAUDE_SWARM_STRATEGY: options.strategy,
CLAUDE_SWARM_MAX_AGENTS: options.maxAgents.toString(),
CLAUDE_SWARM_MAX_DEPTH: options.maxDepth.toString(),
CLAUDE_SWARM_MEMORY_NS: options.memoryNamespace,
}
};
if (options.verbose) {
console.log('Orchestrator configuration:');
console.log(JSON.stringify(orchestratorTask, null, 2));
}
// Check if Claude CLI is available
try {
const checkClaude = new Deno.Command('which', { args: ['claude'] });
const checkResult = await checkClaude.output();
if (!checkResult.success) {
throw new Error('Claude CLI not found in PATH');
}
} catch (err) {
error('Claude CLI not found!');
console.log('Make sure Claude desktop app is installed and the claude command is available in your PATH');
console.log('You can test with: which claude');
return;
}
// Spawn the master orchestrator using Deno.Command
try {
// Build Claude command arguments
const claudeArgs = [orchestrationPrompt];
claudeArgs.push('--allowedTools', orchestratorTask.tools);
if (orchestratorTask.config) {
claudeArgs.push('--mcp-config', orchestratorTask.config);
}
if (options.verbose) {
claudeArgs.push('--verbose');
}
// Show progress
console.log('Launching orchestrator with Claude...');
// Create the command
const command = new Deno.Command('claude', {
args: claudeArgs,
stdin: 'piped',
stdout: 'inherit',
stderr: 'inherit',
env: {
...Deno.env.toObject(),
...orchestratorTask.environment,
},
});
// Spawn the process
const process = command.spawn();
success('✅ Master Orchestrator spawned successfully');
info('🚀 Swarm is now active and self-orchestrating...');
// Set up timeout if specified
let timeoutId: number | undefined;
if (options.timeout > 0) {
timeoutId = setTimeout(() => {
warning(`⏰ Swarm timeout reached (${options.timeout} minutes)`);
process.kill("SIGTERM");
}, options.timeout * 60 * 1000);
}
// Wait for the orchestrator to complete
const status = await process.status;
if (timeoutId) {
clearTimeout(timeoutId);
}
if (status.success) {
success(`✅ Swarm ${swarmId} completed successfully`);
} else {
error(`Swarm ${swarmId} exited with code ${status.code}`);
}
} catch (err) {
error(`Failed to spawn orchestrator: ${(err as Error).message}`);
console.log('Make sure Claude CLI is installed and available in your PATH');
}
}
function buildOrchestrationPrompt(objective: string, options: any): string {
const strategies = {
auto: 'Automatically determine the best approach',
research: 'Focus on research and information gathering',
development: 'Focus on implementation and coding',
analysis: 'Focus on analysis and insights'
};
return `
# Claude Swarm Orchestration Task
You are the Master Orchestrator for a Claude agent swarm. Your objective is to coordinate multiple specialized agents to achieve the following goal:
**OBJECTIVE**: ${objective}
## Orchestration Parameters:
- Strategy: ${strategies[options.strategy as keyof typeof strategies] || strategies.auto}
- Maximum Agents: ${options.maxAgents}
- Maximum Delegation Depth: ${options.maxDepth}
- Parallel Execution: ${options.parallel ? 'Enabled' : 'Disabled'}
- Peer Review: ${options.review ? 'Enabled' : 'Disabled'}
- Research Capabilities: ${options.research ? 'Enabled' : 'Disabled'}
## Your Responsibilities:
1. **Task Decomposition**: Break down the objective into subtasks
2. **Agent Spawning**: Create specialized agents for each subtask
3. **Resource Allocation**: Assign appropriate tools and permissions
4. **Coordination**: Manage dependencies and communication
5. **Quality Control**: ${options.review ? 'Implement peer review processes' : 'Monitor task quality'}
6. **Progress Tracking**: Monitor and report on swarm progress
## Available Agent Types:
- **Researcher**: Information gathering, web research, analysis
- **Developer**: Code implementation, testing, debugging
- **Analyst**: Data analysis, pattern recognition, insights
- **Reviewer**: Code review, quality assurance, validation
- **Coordinator**: Sub-task coordination, dependency management
## Swarm Execution Process:
1. Analyze the objective and create a detailed execution plan
2. Identify required agent types and their responsibilities
3. Spawn agents with appropriate configurations using:
\`\`\`
claude-flow agent spawn <type> --name "<name>" --task "<specific task>"
\`\`\`
4. Create tasks and assign them to agents:
\`\`\`
claude-flow task create <type> "<description>" --assign-to <agent-id>
\`\`\`
5. Monitor progress and adjust as needed
6. ${options.review ? 'Implement peer review cycles between agents' : 'Validate outputs'}
7. Synthesize results and report completion
## Memory Coordination:
All agents share the memory namespace: "${options.memoryNamespace}"
Use this for:
- Sharing discoveries and insights
- Avoiding duplicate work
- Building on each other's findings
- Maintaining context across the swarm
## Special Instructions:
${options.coordinator ? '- Spawn a dedicated coordinator agent for complex subtasks' : ''}
${options.research ? '- All agents should have research capabilities enabled' : ''}
${options.parallel ? '- Maximize parallel execution where dependencies allow' : ''}
${options.maxDepth > 1 ? `- Agents can delegate to sub-agents up to depth ${options.maxDepth}` : ''}
## Output Format:
Provide regular status updates in this format:
\`\`\`
[SWARM STATUS]
- Active Agents: X/Y
- Tasks Completed: X/Y
- Current Phase: <phase>
- Next Actions: <list>
\`\`\`
Begin by analyzing the objective and presenting your execution plan.
`;
}
function buildOrchestratorTools(options: any): string {
const tools = [
'View',
'Edit',
'Replace',
'GlobTool',
'GrepTool',
'LS',
'Bash',
'dispatch_agent'
];
if (options.research) {
tools.push('WebFetchTool');
}
if (options.parallel) {
tools.push('BatchTool');
}
return tools.join(',');
}
Executable
+365
View File
@@ -0,0 +1,365 @@
#!/usr/bin/env -S deno run --allow-all
/**
* Claude Swarm Mode Demo - Standalone script bypassing Cliffy issues
*/
import { colors } from 'https://deno.land/x/cliffy@v1.0.0-rc.3/ansi/colors.ts';
import { generateId } from './src/utils/helpers.ts';
const VERSION = "1.0.2";
// Parse command line arguments manually
function parseArgs(): { objective: string; options: any } {
const args = Deno.args;
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
showHelp();
Deno.exit(0);
}
// Find where flags start
let objectiveEndIndex = args.length;
for (let i = 0; i < args.length; i++) {
if (args[i].startsWith('-')) {
objectiveEndIndex = i;
break;
}
}
const objective = args.slice(0, objectiveEndIndex).join(' ');
if (!objective) {
console.error(colors.red('Error: No objective provided'));
showHelp();
Deno.exit(1);
}
// Parse options
const options: any = {
strategy: 'auto',
maxAgents: 5,
maxDepth: 3,
research: false,
parallel: false,
memoryNamespace: 'swarm',
timeout: 60,
review: false,
coordinator: false,
verbose: false,
dryRun: false,
};
for (let i = objectiveEndIndex; i < args.length; i++) {
const arg = args[i];
switch (arg) {
case '--strategy':
case '-s':
options.strategy = args[++i] || 'auto';
break;
case '--max-agents':
options.maxAgents = parseInt(args[++i]) || 5;
break;
case '--max-depth':
options.maxDepth = parseInt(args[++i]) || 3;
break;
case '--research':
options.research = true;
break;
case '--parallel':
options.parallel = true;
break;
case '--memory-namespace':
options.memoryNamespace = args[++i] || 'swarm';
break;
case '--timeout':
options.timeout = parseInt(args[++i]) || 60;
break;
case '--review':
options.review = true;
break;
case '--coordinator':
options.coordinator = true;
break;
case '--config':
case '-c':
options.config = args[++i];
break;
case '--verbose':
case '-v':
options.verbose = true;
break;
case '--dry-run':
case '-d':
options.dryRun = true;
break;
}
}
return { objective, options };
}
function showHelp() {
console.log(colors.bold('Claude-Flow Swarm Mode Demo'));
console.log();
console.log('Usage: ./swarm-demo.ts <objective> [options]');
console.log();
console.log('Options:');
console.log(' -s, --strategy <s> Orchestration strategy (auto, research, development, analysis)');
console.log(' --max-agents <n> Maximum number of agents (default: 5)');
console.log(' --max-depth <n> Maximum delegation depth (default: 3)');
console.log(' --research Enable research capabilities for all agents');
console.log(' --parallel Enable parallel execution');
console.log(' --memory-namespace <ns> Shared memory namespace (default: swarm)');
console.log(' --timeout <minutes> Swarm timeout in minutes (default: 60)');
console.log(' --review Enable peer review between agents');
console.log(' --coordinator Spawn dedicated coordinator agent');
console.log(' -c, --config <file> MCP config file');
console.log(' -v, --verbose Enable verbose output');
console.log(' -d, --dry-run Preview swarm configuration');
console.log();
console.log('Examples:');
console.log(' ./swarm-demo.ts "Build a REST API"');
console.log(' ./swarm-demo.ts "Research cloud architecture" --strategy research --research');
console.log(' ./swarm-demo.ts "Migrate app to microservices" --coordinator --review');
}
function buildOrchestrationPrompt(objective: string, options: any): string {
const strategies = {
auto: 'Automatically determine the best approach',
research: 'Focus on research and information gathering',
development: 'Focus on implementation and coding',
analysis: 'Focus on analysis and insights'
};
return `
# Claude Swarm Orchestration Task
You are the Master Orchestrator for a Claude agent swarm. Your objective is to coordinate multiple specialized agents to achieve the following goal:
**OBJECTIVE**: ${objective}
## Orchestration Parameters:
- Strategy: ${strategies[options.strategy as keyof typeof strategies] || strategies.auto}
- Maximum Agents: ${options.maxAgents}
- Maximum Delegation Depth: ${options.maxDepth}
- Parallel Execution: ${options.parallel ? 'Enabled' : 'Disabled'}
- Peer Review: ${options.review ? 'Enabled' : 'Disabled'}
- Research Capabilities: ${options.research ? 'Enabled' : 'Disabled'}
## Your Responsibilities:
1. **Task Decomposition**: Break down the objective into subtasks
2. **Agent Spawning**: Create specialized agents for each subtask
3. **Resource Allocation**: Assign appropriate tools and permissions
4. **Coordination**: Manage dependencies and communication
5. **Quality Control**: ${options.review ? 'Implement peer review processes' : 'Monitor task quality'}
6. **Progress Tracking**: Monitor and report on swarm progress
## Available Agent Types:
- **Researcher**: Information gathering, web research, analysis
- **Developer**: Code implementation, testing, debugging
- **Analyst**: Data analysis, pattern recognition, insights
- **Reviewer**: Code review, quality assurance, validation
- **Coordinator**: Sub-task coordination, dependency management
## Swarm Execution Process:
1. Analyze the objective and create a detailed execution plan
2. Identify required agent types and their responsibilities
3. Spawn agents with appropriate configurations using:
\`\`\`
claude-flow agent spawn <type> --name "<name>" --task "<specific task>"
\`\`\`
4. Create tasks and assign them to agents:
\`\`\`
claude-flow task create <type> "<description>" --assign-to <agent-id>
\`\`\`
5. Monitor progress and adjust as needed
6. ${options.review ? 'Implement peer review cycles between agents' : 'Validate outputs'}
7. Synthesize results and report completion
## Memory Coordination:
All agents share the memory namespace: "${options.memoryNamespace}"
Use this for:
- Sharing discoveries and insights
- Avoiding duplicate work
- Building on each other's findings
- Maintaining context across the swarm
## Special Instructions:
${options.coordinator ? '- Spawn a dedicated coordinator agent for complex subtasks' : ''}
${options.research ? '- All agents should have research capabilities enabled' : ''}
${options.parallel ? '- Maximize parallel execution where dependencies allow' : ''}
${options.maxDepth > 1 ? `- Agents can delegate to sub-agents up to depth ${options.maxDepth}` : ''}
## Output Format:
Provide regular status updates in this format:
\`\`\`
[SWARM STATUS]
- Active Agents: X/Y
- Tasks Completed: X/Y
- Current Phase: <phase>
- Next Actions: <list>
\`\`\`
Begin by analyzing the objective and presenting your execution plan.
`;
}
function buildOrchestratorTools(options: any): string {
const tools = [
'View',
'Edit',
'Replace',
'GlobTool',
'GrepTool',
'LS',
'Bash',
'dispatch_agent'
];
if (options.research) {
tools.push('WebFetchTool');
}
if (options.parallel) {
tools.push('BatchTool');
}
return tools.join(',');
}
async function main() {
const { objective, options } = parseArgs();
const swarmId = generateId('swarm');
if (options.dryRun) {
console.log(colors.yellow('DRY RUN - Swarm Configuration:'));
console.log(`Swarm ID: ${swarmId}`);
console.log(`Objective: ${objective}`);
console.log(`Strategy: ${options.strategy}`);
console.log(`Max Agents: ${options.maxAgents}`);
console.log(`Max Depth: ${options.maxDepth}`);
console.log(`Research: ${options.research}`);
console.log(`Parallel: ${options.parallel}`);
console.log(`Review Mode: ${options.review}`);
console.log(`Coordinator: ${options.coordinator}`);
console.log(`Memory Namespace: ${options.memoryNamespace}`);
console.log(`Timeout: ${options.timeout} minutes`);
return;
}
console.log(colors.green(`🐝 Initializing Claude Swarm: ${swarmId}`));
console.log(colors.cyan(`📋 Objective: ${objective}`));
// Build the orchestration prompt
const orchestrationPrompt = buildOrchestrationPrompt(objective, options);
// Spawn the master orchestrator
console.log(colors.blue('🎯 Spawning Master Orchestrator...'));
const orchestratorTask = {
id: `${swarmId}-orchestrator`,
description: orchestrationPrompt,
tools: buildOrchestratorTools(options),
config: options.config,
environment: {
CLAUDE_SWARM_ID: swarmId,
CLAUDE_SWARM_MODE: 'orchestrator',
CLAUDE_SWARM_OBJECTIVE: objective,
CLAUDE_SWARM_STRATEGY: options.strategy,
CLAUDE_SWARM_MAX_AGENTS: options.maxAgents.toString(),
CLAUDE_SWARM_MAX_DEPTH: options.maxDepth.toString(),
CLAUDE_SWARM_MEMORY_NS: options.memoryNamespace,
}
};
if (options.verbose) {
console.log(colors.gray('Orchestrator configuration:'));
console.log(JSON.stringify(orchestratorTask, null, 2));
}
// Check if Claude CLI is available
try {
const checkClaude = new Deno.Command('which', { args: ['claude'] });
const checkResult = await checkClaude.output();
if (!checkResult.success) {
throw new Error('Claude CLI not found in PATH');
}
} catch (error) {
console.error(colors.red('❌ Claude CLI not found!'));
console.error(colors.yellow('Make sure Claude desktop app is installed and the claude command is available in your PATH'));
console.error(colors.yellow('You can test with: which claude'));
Deno.exit(1);
}
// Spawn the master orchestrator using Deno.Command
try {
// Build Claude command arguments
const claudeArgs = [orchestrationPrompt];
claudeArgs.push('--allowedTools', orchestratorTask.tools);
if (orchestratorTask.config) {
claudeArgs.push('--mcp-config', orchestratorTask.config);
}
if (options.verbose) {
claudeArgs.push('--verbose');
}
// Show progress
console.log(colors.gray('Launching orchestrator with Claude...'));
// Create the command
const command = new Deno.Command('claude', {
args: claudeArgs,
stdin: 'piped',
stdout: 'inherit',
stderr: 'inherit',
env: {
...Deno.env.toObject(),
...orchestratorTask.environment,
},
});
// Spawn the process
const process = command.spawn();
console.log(colors.green('✅ Master Orchestrator spawned successfully'));
console.log(colors.blue('🚀 Swarm is now active and self-orchestrating...'));
// Set up timeout if specified
let timeoutId: number | undefined;
if (options.timeout > 0) {
timeoutId = setTimeout(() => {
console.log(colors.yellow(`\n⏰ Swarm timeout reached (${options.timeout} minutes)`));
process.kill("SIGTERM");
}, options.timeout * 60 * 1000);
}
// Wait for the orchestrator to complete
const status = await process.status;
if (timeoutId) {
clearTimeout(timeoutId);
}
if (status.success) {
console.log(colors.green(`\n✅ Swarm ${swarmId} completed successfully`));
} else {
console.log(colors.red(`\n❌ Swarm ${swarmId} exited with code ${status.code}`));
}
} catch (error) {
console.error(colors.red('❌ Failed to spawn orchestrator:'), (error as Error).message);
console.error(colors.yellow('Make sure Claude CLI is installed and available in your PATH'));
}
}
// Run the demo
if (import.meta.main) {
await main();
}