chore: clean up test directories and development artifacts

- Remove obsolete test-alpha5 directory and generated files
- Remove claude-flow-todo-api test directory
- Remove flow-2-init test directory
- Remove test-es-module-fix directory
- Clean up development artifacts from testing phases

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
rUvandClaude committed 2025-07-08 15:48:18 +00:00
1 parent 29800626c9
commit e89851a5ff
58 files changed
-4116

No files matched your search

-3
View File
@@ -1,3 +0,0 @@
JWT_SECRET=your-super-secret-jwt-key
PORT=3000
NODE_ENV=development
-31
View File
@@ -1,31 +0,0 @@
# Claude Flow Todo API
A simple RESTful API for managing todos, built using Claude Flow Swarm orchestration.
## Features
- User registration and authentication
- JWT-based authentication
- CRUD operations for todos
- Input validation
- SQLite database
## Quick Start
1. Copy `.env.example` to `.env` and update values
2. Install dependencies: `npm install`
3. Run the server: `npm start`
4. Run tests: `npm test`
## API Endpoints
### Authentication
- POST /api/auth/register - Register new user
- POST /api/auth/login - Login user
### Todos
- GET /api/todos - Get all todos (authenticated)
- POST /api/todos - Create new todo (authenticated)
- PUT /api/todos/:id - Update todo (authenticated)
- DELETE /api/todos/:id - Delete todo (authenticated)
## Built with Claude Flow Swarm
This project was created using Claude Flow's swarm orchestration with 5 specialized agents working in parallel.
-24
View File
@@ -1,24 +0,0 @@
{
"name": "claude-flow-todo-api",
"version": "1.0.0",
"description": "A simple Todo API built with Claude Flow Swarm",
"main": "src/server.js",
"scripts": {
"start": "node src/server.js",
"dev": "nodemon src/server.js",
"test": "jest --coverage"
},
"dependencies": {
"express": "^4.18.2",
"sqlite3": "^5.1.6",
"bcryptjs": "^2.4.3",
"jsonwebtoken": "^9.0.2",
"express-validator": "^7.0.1",
"dotenv": "^16.3.1"
},
"devDependencies": {
"jest": "^29.7.0",
"supertest": "^6.3.3",
"nodemon": "^3.0.2"
}
}
-114
View File
@@ -1,114 +0,0 @@
{
"env": {
"CLAUDE_FLOW_AUTO_COMMIT": "false",
"CLAUDE_FLOW_AUTO_PUSH": "false",
"CLAUDE_FLOW_HOOKS_ENABLED": "true",
"CLAUDE_FLOW_TELEMETRY_ENABLED": "true",
"CLAUDE_FLOW_REMOTE_EXECUTION": "true",
"CLAUDE_FLOW_GITHUB_INTEGRATION": "true"
},
"permissions": {
"allow": [
"Bash(npx claude-flow *)",
"Bash(npm run lint)",
"Bash(npm run test:*)",
"Bash(npm test *)",
"Bash(git status)",
"Bash(git diff *)",
"Bash(git log *)",
"Bash(git add *)",
"Bash(git commit *)",
"Bash(git push)",
"Bash(git config *)",
"Bash(gh *)",
"Bash(node *)",
"Bash(which *)",
"Bash(pwd)",
"Bash(ls *)"
],
"deny": [
"Bash(rm -rf /)",
"Bash(curl * | bash)",
"Bash(wget * | sh)",
"Bash(eval *)"
]
},
"hooks": {
"preEdit": {
"enabled": true,
"actions": [
"auto-assign-agents",
"validate-syntax",
"load-context"
]
},
"postEdit": {
"enabled": true,
"actions": [
"format-code",
"update-memory",
"train-neural",
"analyze-performance"
]
},
"preCommand": {
"enabled": true,
"actions": [
"validate-safety",
"prepare-resources",
"optimize-execution"
]
},
"postCommand": {
"enabled": true,
"actions": [
"track-metrics",
"store-results",
"update-telemetry"
]
},
"sessionEnd": {
"enabled": true,
"actions": [
"generate-summary",
"persist-state",
"export-metrics"
]
}
},
"mcpServers": {
"claude-flow": {
"command": "npx",
"args": [
"claude-flow",
"mcp",
"start"
],
"env": {
"CLAUDE_FLOW_HOOKS_ENABLED": "true",
"CLAUDE_FLOW_TELEMETRY_ENABLED": "true",
"CLAUDE_FLOW_REMOTE_READY": "true",
"CLAUDE_FLOW_GITHUB_INTEGRATION": "true"
}
}
},
"includeCoAuthoredBy": true,
"features": {
"autoTopologySelection": true,
"parallelExecution": true,
"neuralTraining": true,
"bottleneckAnalysis": true,
"smartAutoSpawning": true,
"selfHealingWorkflows": true,
"crossSessionMemory": true,
"githubIntegration": true
},
"performance": {
"maxAgents": 10,
"defaultTopology": "hierarchical",
"executionStrategy": "parallel",
"tokenOptimization": true,
"cacheEnabled": true,
"telemetryLevel": "detailed"
}
}
-151
View File
@@ -1,151 +0,0 @@
name: Issue 108 Monitoring and Updates
on:
issues:
types: [opened, edited, closed, reopened]
issue_comment:
types: [created, edited, deleted]
pull_request:
types: [opened, closed, merged, synchronize]
push:
branches: [claude-flow-v2.0.0, main]
jobs:
monitor-issue-108:
runs-on: ubuntu-latest
if: github.event.issue.number == 108 || contains(github.event.pull_request.title, 'Issue 108') || contains(github.event.commits[0].message, 'Issue 108')
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: |
npm install -g @anthropic/claude-code
npm install -g ruv-swarm
- name: Initialize swarm coordination
run: |
npx ruv-swarm init hierarchical 3 --claude
npx ruv-swarm agent spawn coordinator --name "GitHub Monitor"
npx ruv-swarm agent spawn analyst --name "Issue Tracker"
npx ruv-swarm agent spawn researcher --name "Change Detector"
- name: Update issue status
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# Get current issue data
ISSUE_DATA=$(gh issue view 108 --json title,body,state,assignees,labels,comments)
# Create swarm memory entry
npx ruv-swarm memory store "issue_108_update" "{
\"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
\"trigger\": \"${{ github.event_name }}\",
\"issue_data\": $ISSUE_DATA,
\"commit_sha\": \"${{ github.sha }}\",
\"branch\": \"${{ github.ref_name }}\",
\"actor\": \"${{ github.actor }}\"
}"
# Analyze changes and update issue
npx ruv-swarm task orchestrate "Analyze changes and update issue 108 with progress" \
--strategy adaptive --priority high
- name: Add progress comment
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# Get swarm status
SWARM_STATUS=$(npx ruv-swarm status --json)
# Create progress update comment
gh issue comment 108 --body "🚀 Swarm Progress Update - $(date -u +%Y-%m-%d\ %H:%M:%S\ UTC)
## 📊 Current Status
### 🔴 Event Triggered
- **Action**: ${{ github.event_name }}
- **Branch**: ${{ github.ref_name }}
- **Commit**: ${{ github.sha }}
- **Actor**: ${{ github.actor }}
### 🎯 Swarm Coordination Status
- **Active Swarms**: $(echo '$SWARM_STATUS' | jq -r '.active_swarms')
- **Coordinated Agents**: $(echo '$SWARM_STATUS' | jq -r '.total_agents')
- **Last Update**: $(date -u +%Y-%m-%dT%H:%M:%SZ)
### 📈 Metrics
- **Memory Usage**: $(npx ruv-swarm memory usage --summary)
- **Neural Networks**: $(npx ruv-swarm neural status --summary)
- **Task Queue**: $(npx ruv-swarm task status --summary)
### 📝 Next Steps
- Monitor build status changes
- Track TypeScript error resolution
- Coordinate with development swarm
- Update progress metrics
---
🤖 *Automated update by Issue 108 Monitor*"
coordinate-with-other-swarms:
runs-on: ubuntu-latest
if: github.event_name == 'push' || github.event_name == 'pull_request'
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Cross-swarm coordination
run: |
# Initialize coordination swarm
npx ruv-swarm init mesh 5 --claude
# Spawn coordination agents
npx ruv-swarm agent spawn coordinator --name "Cross-Swarm Coordinator"
npx ruv-swarm agent spawn analyst --name "Build Status Tracker"
npx ruv-swarm agent spawn researcher --name "Change Analyzer"
npx ruv-swarm agent spawn coder --name "Integration Validator"
# Share knowledge across swarms
npx ruv-swarm memory store "cross_swarm_update" "{
\"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
\"repository\": \"${{ github.repository }}\",
\"event\": \"${{ github.event_name }}\",
\"ref\": \"${{ github.ref }}\",
\"sha\": \"${{ github.sha }}\",
\"changes\": \"$(git diff --name-only HEAD~1 HEAD | head -10)\",
\"issue_108_status\": \"monitoring\",
\"coordination_active\": true
}"
# Orchestrate cross-swarm coordination
npx ruv-swarm task orchestrate "Coordinate with other swarms and update issue 108" \
--strategy parallel --priority medium
- name: Neural pattern learning
run: |
# Train neural patterns based on changes
npx ruv-swarm neural train --iterations 5 --pattern adaptive
# Update cognitive patterns
npx ruv-swarm neural patterns --update convergent
# Store learning results
npx ruv-swarm memory store "neural_learning" "{
\"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
\"learning_session\": \"issue_108_coordination\",
\"patterns_updated\": [\"adaptive\", \"convergent\"],
\"performance_metrics\": \"$(npx ruv-swarm benchmark --quick)\"
}"
-604
View File
@@ -1,604 +0,0 @@
# Claude Code Configuration for Claude Flow
## 🚀 IMPORTANT: Claude Flow AI-Driven Development
### Claude Code Handles:
- ✅ **ALL file operations** (Read, Write, Edit, MultiEdit)
- ✅ **ALL code generation** and development tasks
- ✅ **ALL bash commands** and system operations
- ✅ **ALL actual implementation** work
- ✅ **Project navigation** and code analysis
### Claude Flow MCP Tools Handle:
- 🧠 **Coordination only** - Orchestrating Claude Code's actions
- 💾 **Memory management** - Persistent state across sessions
- 🤖 **Neural features** - Cognitive patterns and learning
- 📊 **Performance tracking** - Monitoring and metrics
- 🐝 **Swarm orchestration** - Multi-agent coordination
- 🔗 **GitHub integration** - Advanced repository management
### ⚠️ Key Principle:
**MCP tools DO NOT create content or write code.** They coordinate and enhance Claude Code's native capabilities. Think of them as an orchestration layer that helps Claude Code work more efficiently.
## 🚀 CRITICAL: Parallel Execution & Batch Operations
### 🚨 MANDATORY RULE #1: BATCH EVERYTHING
**When using swarms, you MUST use BatchTool for ALL operations:**
1. **NEVER** send multiple messages for related operations
2. **ALWAYS** combine multiple tool calls in ONE message
3. **PARALLEL** execution is MANDATORY, not optional
### ⚡ THE GOLDEN RULE OF SWARMS
```
If you need to do X operations, they should be in 1 message, not X messages
```
### 📦 BATCH TOOL EXAMPLES
**✅ CORRECT - Everything in ONE Message:**
```javascript
[Single Message with BatchTool]:
mcp__claude-flow__swarm_init { topology: "mesh", maxAgents: 6 }
mcp__claude-flow__agent_spawn { type: "researcher" }
mcp__claude-flow__agent_spawn { type: "coder" }
mcp__claude-flow__agent_spawn { type: "analyst" }
mcp__claude-flow__agent_spawn { type: "tester" }
mcp__claude-flow__agent_spawn { type: "coordinator" }
TodoWrite { todos: [todo1, todo2, todo3, todo4, todo5] }
Bash "mkdir -p app/{src,tests,docs}"
Write "app/package.json"
Write "app/README.md"
Write "app/src/index.js"
```
**❌ WRONG - Multiple Messages (NEVER DO THIS):**
```javascript
Message 1: mcp__claude-flow__swarm_init
Message 2: mcp__claude-flow__agent_spawn
Message 3: mcp__claude-flow__agent_spawn
Message 4: TodoWrite (one todo)
Message 5: Bash "mkdir src"
Message 6: Write "package.json"
// This is 6x slower and breaks parallel coordination!
```
### 🎯 BATCH OPERATIONS BY TYPE
**File Operations (Single Message):**
- Read 10 files? → One message with 10 Read calls
- Write 5 files? → One message with 5 Write calls
- Edit 1 file many times? → One MultiEdit call
**Swarm Operations (Single Message):**
- Need 8 agents? → One message with swarm_init + 8 agent_spawn calls
- Multiple memories? → One message with all memory_usage calls
- Task + monitoring? → One message with task_orchestrate + swarm_monitor
**Command Operations (Single Message):**
- Multiple directories? → One message with all mkdir commands
- Install + test + lint? → One message with all npm commands
- Git operations? → One message with all git commands
## 🚀 Quick Setup (Stdio MCP - Recommended)
### 1. Add MCP Server (Stdio - No Port Needed)
```bash
# Add Claude Flow MCP server to Claude Code using stdio
claude mcp add claude-flow npx claude-flow mcp start
```
### 2. Use MCP Tools for Coordination in Claude Code
Once configured, Claude Flow MCP tools enhance Claude Code's coordination:
**Initialize a swarm:**
- Use the `mcp__claude-flow__swarm_init` tool to set up coordination topology
- Choose: mesh, hierarchical, ring, or star
- This creates a coordination framework for Claude Code's work
**Spawn agents:**
- Use `mcp__claude-flow__agent_spawn` tool to create specialized coordinators
- Agent types represent different thinking patterns, not actual coders
- They help Claude Code approach problems from different angles
**Orchestrate tasks:**
- Use `mcp__claude-flow__task_orchestrate` tool to coordinate complex workflows
- This breaks down tasks for Claude Code to execute systematically
- The agents don't write code - they coordinate Claude Code's actions
## Available MCP Tools for Coordination
### Coordination Tools:
- `mcp__claude-flow__swarm_init` - Set up coordination topology for Claude Code
- `mcp__claude-flow__agent_spawn` - Create cognitive patterns to guide Claude Code
- `mcp__claude-flow__task_orchestrate` - Break down and coordinate complex tasks
### Monitoring Tools:
- `mcp__claude-flow__swarm_status` - Monitor coordination effectiveness
- `mcp__claude-flow__agent_list` - View active cognitive patterns
- `mcp__claude-flow__agent_metrics` - Track coordination performance
- `mcp__claude-flow__task_status` - Check workflow progress
- `mcp__claude-flow__task_results` - Review coordination outcomes
### Memory & Neural Tools:
- `mcp__claude-flow__memory_usage` - Persistent memory across sessions
- `mcp__claude-flow__neural_status` - Neural pattern effectiveness
- `mcp__claude-flow__neural_train` - Improve coordination patterns
- `mcp__claude-flow__neural_patterns` - Analyze thinking approaches
### GitHub Integration Tools (NEW!):
- `mcp__claude-flow__github_swarm` - Create specialized GitHub management swarms
- `mcp__claude-flow__repo_analyze` - Deep repository analysis with AI
- `mcp__claude-flow__pr_enhance` - AI-powered pull request improvements
- `mcp__claude-flow__issue_triage` - Intelligent issue classification
- `mcp__claude-flow__code_review` - Automated code review with swarms
### System Tools:
- `mcp__claude-flow__benchmark_run` - Measure coordination efficiency
- `mcp__claude-flow__features_detect` - Available capabilities
- `mcp__claude-flow__swarm_monitor` - Real-time coordination tracking
## Workflow Examples (Coordination-Focused)
### Research Coordination Example
**Context:** Claude Code needs to research a complex topic systematically
**Step 1:** Set up research coordination
- Tool: `mcp__claude-flow__swarm_init`
- Parameters: `{"topology": "mesh", "maxAgents": 5, "strategy": "balanced"}`
- Result: Creates a mesh topology for comprehensive exploration
**Step 2:** Define research perspectives
- Tool: `mcp__claude-flow__agent_spawn`
- Parameters: `{"type": "researcher", "name": "Literature Review"}`
- Tool: `mcp__claude-flow__agent_spawn`
- Parameters: `{"type": "analyst", "name": "Data Analysis"}`
- Result: Different cognitive patterns for Claude Code to use
**Step 3:** Coordinate research execution
- Tool: `mcp__claude-flow__task_orchestrate`
- Parameters: `{"task": "Research neural architecture search papers", "strategy": "adaptive"}`
- Result: Claude Code systematically searches, reads, and analyzes papers
**What Actually Happens:**
1. The swarm sets up a coordination framework
2. Each agent MUST use Claude Flow hooks for coordination:
- `npx claude-flow hook pre-task` before starting
- `npx claude-flow hook post-edit` after each file operation
- `npx claude-flow hook notification` to share decisions
3. Claude Code uses its native Read, WebSearch, and Task tools
4. The swarm coordinates through shared memory and hooks
5. Results are synthesized by Claude Code with full coordination history
### Development Coordination Example
**Context:** Claude Code needs to build a complex system with multiple components
**Step 1:** Set up development coordination
- Tool: `mcp__claude-flow__swarm_init`
- Parameters: `{"topology": "hierarchical", "maxAgents": 8, "strategy": "specialized"}`
- Result: Hierarchical structure for organized development
**Step 2:** Define development perspectives
- Tool: `mcp__claude-flow__agent_spawn`
- Parameters: `{"type": "architect", "name": "System Design"}`
- Result: Architectural thinking pattern for Claude Code
**Step 3:** Coordinate implementation
- Tool: `mcp__claude-flow__task_orchestrate`
- Parameters: `{"task": "Implement user authentication with JWT", "strategy": "parallel"}`
- Result: Claude Code implements features using its native tools
**What Actually Happens:**
1. The swarm creates a development coordination plan
2. Each agent coordinates using mandatory hooks:
- Pre-task hooks for context loading
- Post-edit hooks for progress tracking
- Memory storage for cross-agent coordination
3. Claude Code uses Write, Edit, Bash tools for implementation
4. Agents share progress through Claude Flow memory
5. All code is written by Claude Code with full coordination
### GitHub Repository Management Example (NEW!)
**Context:** Claude Code needs to manage a complex GitHub repository
**Step 1:** Initialize GitHub swarm
- Tool: `mcp__claude-flow__github_swarm`
- Parameters: `{"repository": "owner/repo", "agents": 5, "focus": "maintenance"}`
- Result: Specialized swarm for repository management
**Step 2:** Analyze repository health
- Tool: `mcp__claude-flow__repo_analyze`
- Parameters: `{"deep": true, "include": ["issues", "prs", "code"]}`
- Result: Comprehensive repository analysis
**Step 3:** Enhance pull requests
- Tool: `mcp__claude-flow__pr_enhance`
- Parameters: `{"pr_number": 123, "add_tests": true, "improve_docs": true}`
- Result: AI-powered PR improvements
## Best Practices for Coordination
### ✅ DO:
- Use MCP tools to coordinate Claude Code's approach to complex tasks
- Let the swarm break down problems into manageable pieces
- Use memory tools to maintain context across sessions
- Monitor coordination effectiveness with status tools
- Train neural patterns for better coordination over time
- Leverage GitHub tools for repository management
### ❌ DON'T:
- Expect agents to write code (Claude Code does all implementation)
- Use MCP tools for file operations (use Claude Code's native tools)
- Try to make agents execute bash commands (Claude Code handles this)
- Confuse coordination with execution (MCP coordinates, Claude executes)
## Memory and Persistence
The swarm provides persistent memory that helps Claude Code:
- Remember project context across sessions
- Track decisions and rationale
- Maintain consistency in large projects
- Learn from previous coordination patterns
- Store GitHub workflow preferences
## Performance Benefits
When using Claude Flow coordination with Claude Code:
- **84.8% SWE-Bench solve rate** - Better problem-solving through coordination
- **32.3% token reduction** - Efficient task breakdown reduces redundancy
- **2.8-4.4x speed improvement** - Parallel coordination strategies
- **27+ neural models** - Diverse cognitive approaches
- **GitHub automation** - Streamlined repository management
## Claude Code Hooks Integration
Claude Flow includes powerful hooks that automate coordination:
### Pre-Operation Hooks
- **Auto-assign agents** before file edits based on file type
- **Validate commands** before execution for safety
- **Prepare resources** automatically for complex operations
- **Optimize topology** based on task complexity analysis
- **Cache searches** for improved performance
- **GitHub context** loading for repository operations
### Post-Operation Hooks
- **Auto-format code** using language-specific formatters
- **Train neural patterns** from successful operations
- **Update memory** with operation context
- **Analyze performance** and identify bottlenecks
- **Track token usage** for efficiency metrics
- **Sync GitHub** state for consistency
### Session Management
- **Generate summaries** at session end
- **Persist state** across Claude Code sessions
- **Track metrics** for continuous improvement
- **Restore previous** session context automatically
- **Export workflows** for reuse
### Advanced Features (v2.0.0!)
- **🚀 Automatic Topology Selection** - Optimal swarm structure for each task
- **⚡ Parallel Execution** - 2.8-4.4x speed improvements
- **🧠 Neural Training** - Continuous learning from operations
- **📊 Bottleneck Analysis** - Real-time performance optimization
- **🤖 Smart Auto-Spawning** - Zero manual agent management
- **🛡️ Self-Healing Workflows** - Automatic error recovery
- **💾 Cross-Session Memory** - Persistent learning & context
- **🔗 GitHub Integration** - Repository-aware swarms
### Configuration
Hooks are pre-configured in `.claude/settings.json`. Key features:
- Automatic agent assignment for different file types
- Code formatting on save
- Neural pattern learning from edits
- Session state persistence
- Performance tracking and optimization
- Intelligent caching and token reduction
- GitHub workflow automation
See `.claude/commands/` for detailed documentation on all features.
## Integration Tips
1. **Start Simple**: Begin with basic swarm init and single agent
2. **Scale Gradually**: Add more agents as task complexity increases
3. **Use Memory**: Store important decisions and context
4. **Monitor Progress**: Regular status checks ensure effective coordination
5. **Train Patterns**: Let neural agents learn from successful coordinations
6. **Enable Hooks**: Use the pre-configured hooks for automation
7. **GitHub First**: Use GitHub tools for repository management
## 🧠 SWARM ORCHESTRATION PATTERN
### You are the SWARM ORCHESTRATOR. **IMMEDIATELY SPAWN AGENTS IN PARALLEL** to execute tasks
### 🚨 CRITICAL INSTRUCTION: You are the SWARM ORCHESTRATOR
**MANDATORY**: When using swarms, you MUST:
1. **SPAWN ALL AGENTS IN ONE BATCH** - Use multiple tool calls in a SINGLE message
2. **EXECUTE TASKS IN PARALLEL** - Never wait for one task before starting another
3. **USE BATCHTOOL FOR EVERYTHING** - Multiple operations = Single message with multiple tools
4. **ALL AGENTS MUST USE COORDINATION TOOLS** - Every spawned agent MUST use Claude Flow hooks and memory
## 📋 MANDATORY AGENT COORDINATION PROTOCOL
### 🔴 CRITICAL: Every Agent MUST Follow This Protocol
When you spawn an agent using the Task tool, that agent MUST:
**1️⃣ BEFORE Starting Work:**
```bash
# Check previous work and load context
npx claude-flow hook pre-task --description "[agent task]" --auto-spawn-agents false
npx claude-flow hook session-restore --session-id "swarm-[id]" --load-memory true
```
**2️⃣ DURING Work (After EVERY Major Step):**
```bash
# Store progress in memory after each file operation
npx claude-flow hook post-edit --file "[filepath]" --memory-key "swarm/[agent]/[step]"
# Store decisions and findings
npx claude-flow hook notification --message "[what was done]" --telemetry true
# Check coordination with other agents
npx claude-flow hook pre-search --query "[what to check]" --cache-results true
```
**3️⃣ AFTER Completing Work:**
```bash
# Save all results and learnings
npx claude-flow hook post-task --task-id "[task]" --analyze-performance true
npx claude-flow hook session-end --export-metrics true --generate-summary true
```
### 🎯 AGENT PROMPT TEMPLATE
When spawning agents, ALWAYS include these coordination instructions:
```
You are the [Agent Type] agent in a coordinated swarm.
MANDATORY COORDINATION:
1. START: Run `npx claude-flow hook pre-task --description "[your task]"`
2. DURING: After EVERY file operation, run `npx claude-flow hook post-edit --file "[file]" --memory-key "agent/[step]"`
3. MEMORY: Store ALL decisions using `npx claude-flow hook notification --message "[decision]"`
4. END: Run `npx claude-flow hook post-task --task-id "[task]" --analyze-performance true`
Your specific task: [detailed task description]
REMEMBER: Coordinate with other agents by checking memory BEFORE making decisions!
```
### ⚡ PARALLEL EXECUTION IS MANDATORY
**THIS IS WRONG ❌ (Sequential - NEVER DO THIS):**
```
Message 1: Initialize swarm
Message 2: Spawn agent 1
Message 3: Spawn agent 2
Message 4: Create file 1
Message 5: Create file 2
```
**THIS IS CORRECT ✅ (Parallel - ALWAYS DO THIS):**
```
Message 1: [BatchTool]
- mcp__claude-flow__swarm_init
- mcp__claude-flow__agent_spawn (researcher)
- mcp__claude-flow__agent_spawn (coder)
- mcp__claude-flow__agent_spawn (analyst)
- mcp__claude-flow__agent_spawn (tester)
- mcp__claude-flow__agent_spawn (coordinator)
Message 2: [BatchTool]
- Write file1.js
- Write file2.js
- Write file3.js
- Bash mkdir commands
- TodoWrite updates
```
### 🎯 MANDATORY SWARM PATTERN
When given ANY complex task with swarms:
```
STEP 1: IMMEDIATE PARALLEL SPAWN (Single Message!)
[BatchTool]:
- mcp__claude-flow__swarm_init { topology: "hierarchical", maxAgents: 8, strategy: "parallel" }
- mcp__claude-flow__agent_spawn { type: "architect", name: "System Designer" }
- mcp__claude-flow__agent_spawn { type: "coder", name: "API Developer" }
- mcp__claude-flow__agent_spawn { type: "coder", name: "Frontend Dev" }
- mcp__claude-flow__agent_spawn { type: "analyst", name: "DB Designer" }
- mcp__claude-flow__agent_spawn { type: "tester", name: "QA Engineer" }
- mcp__claude-flow__agent_spawn { type: "researcher", name: "Tech Lead" }
- mcp__claude-flow__agent_spawn { type: "coordinator", name: "PM" }
- TodoWrite { todos: [multiple todos at once] }
STEP 2: PARALLEL TASK EXECUTION (Single Message!)
[BatchTool]:
- mcp__claude-flow__task_orchestrate { task: "main task", strategy: "parallel" }
- mcp__claude-flow__memory_usage { action: "store", key: "init", value: {...} }
- Multiple Read operations
- Multiple Write operations
- Multiple Bash commands
STEP 3: CONTINUE PARALLEL WORK (Never Sequential!)
```
### 📊 VISUAL TASK TRACKING FORMAT
Use this format when displaying task progress:
```
📊 Progress Overview
├── Total Tasks: X
├── ✅ Completed: X (X%)
├── 🔄 In Progress: X (X%)
├── ⭕ Todo: X (X%)
└── ❌ Blocked: X (X%)
📋 Todo (X)
└── 🔴 001: [Task description] [PRIORITY] ▶
🔄 In progress (X)
├── 🟡 002: [Task description] ↳ X deps ▶
└── 🔴 003: [Task description] [PRIORITY] ▶
✅ Completed (X)
├── ✅ 004: [Task description]
└── ... (more completed tasks)
Priority indicators: 🔴 HIGH/CRITICAL, 🟡 MEDIUM, 🟢 LOW
Dependencies: ↳ X deps | Actionable: ▶
```
### 🎯 REAL EXAMPLE: Full-Stack App Development
**Task**: "Build a complete REST API with authentication, database, and tests"
**🚨 MANDATORY APPROACH - Everything in Parallel:**
```javascript
// ✅ CORRECT: SINGLE MESSAGE with ALL operations
[BatchTool - Message 1]:
// Initialize and spawn ALL agents at once
mcp__claude-flow__swarm_init { topology: "hierarchical", maxAgents: 8, strategy: "parallel" }
mcp__claude-flow__agent_spawn { type: "architect", name: "System Designer" }
mcp__claude-flow__agent_spawn { type: "coder", name: "API Developer" }
mcp__claude-flow__agent_spawn { type: "coder", name: "Auth Expert" }
mcp__claude-flow__agent_spawn { type: "analyst", name: "DB Designer" }
mcp__claude-flow__agent_spawn { type: "tester", name: "Test Engineer" }
mcp__claude-flow__agent_spawn { type: "coordinator", name: "Lead" }
// Update ALL todos at once
TodoWrite { todos: [
{ id: "design", content: "Design API architecture", status: "in_progress", priority: "high" },
{ id: "auth", content: "Implement authentication", status: "pending", priority: "high" },
{ id: "db", content: "Design database schema", status: "pending", priority: "high" },
{ id: "api", content: "Build REST endpoints", status: "pending", priority: "high" },
{ id: "tests", content: "Write comprehensive tests", status: "pending", priority: "medium" }
]}
// Start orchestration
mcp__claude-flow__task_orchestrate { task: "Build REST API", strategy: "parallel" }
// Store initial memory
mcp__claude-flow__memory_usage { action: "store", key: "project/init", value: { started: Date.now() } }
[BatchTool - Message 2]:
// Create ALL directories at once
Bash("mkdir -p test-app/{src,tests,docs,config}")
Bash("mkdir -p test-app/src/{models,routes,middleware,services}")
Bash("mkdir -p test-app/tests/{unit,integration}")
// Write ALL base files at once
Write("test-app/package.json", packageJsonContent)
Write("test-app/.env.example", envContent)
Write("test-app/README.md", readmeContent)
Write("test-app/src/server.js", serverContent)
Write("test-app/src/config/database.js", dbConfigContent)
[BatchTool - Message 3]:
// Read multiple files for context
Read("test-app/package.json")
Read("test-app/src/server.js")
Read("test-app/.env.example")
// Run multiple commands
Bash("cd test-app && npm install")
Bash("cd test-app && npm run lint")
Bash("cd test-app && npm test")
```
### 🚫 NEVER DO THIS (Sequential = WRONG):
```javascript
// ❌ WRONG: Multiple messages, one operation each
Message 1: mcp__claude-flow__swarm_init
Message 2: mcp__claude-flow__agent_spawn (just one agent)
Message 3: mcp__claude-flow__agent_spawn (another agent)
Message 4: TodoWrite (single todo)
Message 5: Write (single file)
// This is 5x slower and wastes swarm coordination!
```
### 🔄 MEMORY COORDINATION PATTERN
Every agent coordination step MUST use memory:
```
// After each major decision or implementation
mcp__claude-flow__memory_usage
action: "store"
key: "swarm-{id}/agent-{name}/{step}"
value: {
timestamp: Date.now(),
decision: "what was decided",
implementation: "what was built",
nextSteps: ["step1", "step2"],
dependencies: ["dep1", "dep2"]
}
// To retrieve coordination data
mcp__claude-flow__memory_usage
action: "retrieve"
key: "swarm-{id}/agent-{name}/{step}"
// To check all swarm progress
mcp__claude-flow__memory_usage
action: "list"
pattern: "swarm-{id}/*"
```
### ⚡ PERFORMANCE TIPS
1. **Batch Everything**: Never operate on single files when multiple are needed
2. **Parallel First**: Always think "what can run simultaneously?"
3. **Memory is Key**: Use memory for ALL cross-agent coordination
4. **Monitor Progress**: Use mcp__claude-flow__swarm_monitor for real-time tracking
5. **Auto-Optimize**: Let hooks handle topology and agent selection
### 🎨 VISUAL SWARM STATUS
When showing swarm status, use this format:
```
🐝 Swarm Status: ACTIVE
├── 🏗️ Topology: hierarchical
├── 👥 Agents: 6/8 active
├── ⚡ Mode: parallel execution
├── 📊 Tasks: 12 total (4 complete, 6 in-progress, 2 pending)
└── 🧠 Memory: 15 coordination points stored
Agent Activity:
├── 🟢 architect: Designing database schema...
├── 🟢 coder-1: Implementing auth endpoints...
├── 🟢 coder-2: Building user CRUD operations...
├── 🟢 analyst: Optimizing query performance...
├── 🟡 tester: Waiting for auth completion...
└── 🟢 coordinator: Monitoring progress...
```
## Claude Flow v2.0.0 Features
Claude Flow extends the base coordination with:
- **🔗 GitHub Integration** - Deep repository management
- **🎯 Project Templates** - Quick-start for common projects
- **📊 Advanced Analytics** - Detailed performance insights
- **🤖 Custom Agent Types** - Domain-specific coordinators
- **🔄 Workflow Automation** - Reusable task sequences
- **🛡️ Enhanced Security** - Safer command execution
## Support
- Documentation: https://github.com/Ejb503/claude-flow
- Issues: https://github.com/Ejb503/claude-flow/issues
- Examples: https://github.com/Ejb503/claude-flow/tree/main/examples
---
Remember: **Claude Flow coordinates, Claude Code creates!** Start with `mcp__claude-flow__swarm_init` to enhance your development workflow.
@@ -1,669 +0,0 @@
# Claude Flow v2.0.0 Architecture Design
## Executive Summary
Claude Flow v2.0.0 represents a complete integration of Claude Code CLI with ruv-swarm orchestration capabilities, creating a powerful autonomous development system. This architecture enables parallel execution, intelligent task coordination, and seamless GitHub workflow integration.
## Architecture Overview
```mermaid
graph TB
subgraph "Claude Code CLI Layer"
CC[Claude Code CLI]
CCTools[Native Tools<br/>Read/Write/Edit/Bash]
CCMemory[File Operations]
end
subgraph "Claude Flow Integration Layer"
SC[SwarmCoordinator]
TE[TaskExecutor]
SM[SharedMemory]
AT[Agent Types]
end
subgraph "ruv-swarm MCP Layer"
RS[ruv-swarm MCP Server]
RSTools[MCP Tools]
RSMemory[Persistent Memory]
RSNeural[Neural Features]
end
subgraph "External Systems"
GH[GitHub API]
FS[File System]
WEB[Web Services]
end
CC --> SC
SC --> TE
SC --> SM
SC --> AT
SC --> RS
TE --> CC
SM --> RSMemory
CC --> CCTools
CCTools --> FS
SC --> GH
RSTools --> RSMemory
RSTools --> RSNeural
```
## Core Components
### 1. SwarmCoordinator (Full Implementation)
The SwarmCoordinator is the central orchestration component that manages the entire swarm lifecycle.
```typescript
interface SwarmCoordinator {
// Lifecycle Management
async initialize(config: SwarmConfig): Promise<void>
async start(): Promise<void>
async stop(): Promise<void>
async shutdown(): Promise<void>
// Swarm Operations
async createSwarm(config: SwarmConfig): Promise<SwarmId>
async spawnAgent(type: AgentType, config: AgentConfig): Promise<AgentId>
async orchestrateTask(task: TaskDefinition): Promise<TaskResult>
// Coordination
async assignTask(taskId: TaskId, agentId: AgentId): Promise<void>
async balanceLoad(): Promise<void>
async handleFailure(agentId: AgentId, error: Error): Promise<void>
// Monitoring
getSwarmStatus(): SwarmStatus
getAgentMetrics(agentId: AgentId): AgentMetrics
getTaskProgress(taskId: TaskId): TaskProgress
}
```
**Key Features:**
- **Dynamic Agent Spawning**: Automatically spawn Claude CLI instances based on workload
- **Intelligent Task Assignment**: Match tasks to agents based on capabilities and performance
- **Load Balancing**: Distribute work evenly across available agents
- **Failure Recovery**: Automatic retry and reassignment of failed tasks
- **Real-time Monitoring**: Track swarm health, progress, and performance
### 2. TaskExecutor (Parallel Execution Engine)
The TaskExecutor manages the actual execution of tasks using Claude CLI instances.
```typescript
interface TaskExecutor {
// Task Execution
async executeTask(task: TaskDefinition, agent: AgentState): Promise<TaskResult>
async executeParallel(tasks: TaskDefinition[]): Promise<TaskResult[]>
async executePipeline(pipeline: TaskPipeline): Promise<PipelineResult>
// Claude CLI Integration
async spawnClaude(config: ClaudeConfig): Promise<ClaudeInstance>
async sendPrompt(instance: ClaudeInstance, prompt: string): Promise<string>
async terminateClaude(instance: ClaudeInstance): Promise<void>
// Resource Management
async allocateResources(task: TaskDefinition): Promise<ResourceAllocation>
async releaseResources(allocation: ResourceAllocation): Promise<void>
async monitorResources(): Promise<ResourceMetrics>
// Error Handling
async handleTimeout(task: TaskDefinition): Promise<void>
async handleError(task: TaskDefinition, error: Error): Promise<void>
async retryTask(task: TaskDefinition, attempt: number): Promise<TaskResult>
}
```
**Key Features:**
- **Parallel Execution**: Run multiple Claude instances simultaneously
- **Resource Pooling**: Maintain a pool of Claude instances for quick task assignment
- **Timeout Management**: Enforce task timeouts and handle long-running operations
- **Error Recovery**: Automatic retry with exponential backoff
- **Progress Tracking**: Real-time updates on task execution status
### 3. SharedMemory System
The SharedMemory system enables coordination and knowledge sharing between agents.
```typescript
interface SharedMemory {
// Memory Operations
async store(key: string, value: any, metadata?: MemoryMetadata): Promise<void>
async retrieve(key: string): Promise<any>
async search(query: MemoryQuery): Promise<MemoryEntry[]>
async delete(key: string): Promise<void>
// Agent Memory
async getAgentMemory(agentId: AgentId): Promise<AgentMemory>
async shareMemory(from: AgentId, to: AgentId, key: string): Promise<void>
async broadcastMemory(key: string, agents: AgentId[]): Promise<void>
// Knowledge Base
async createKnowledgeBase(name: string, domain: string): Promise<KnowledgeBaseId>
async updateKnowledge(kbId: KnowledgeBaseId, entry: KnowledgeEntry): Promise<void>
async queryKnowledge(kbId: KnowledgeBaseId, query: string): Promise<KnowledgeEntry[]>
// Synchronization
async sync(): Promise<void>
async backup(): Promise<BackupId>
async restore(backupId: BackupId): Promise<void>
}
```
**Key Features:**
- **Distributed Memory**: Share state across all agents in the swarm
- **Knowledge Persistence**: Store learnings and insights for future use
- **Efficient Retrieval**: Fast search and retrieval of relevant information
- **Memory Partitioning**: Separate memory spaces for different contexts
- **Automatic Synchronization**: Keep memory consistent across the swarm
### 4. Agent Type System
A comprehensive agent type system with specialized capabilities.
```typescript
enum AgentType {
COORDINATOR = 'coordinator', // Orchestrates other agents
RESEARCHER = 'researcher', // Gathers information
DEVELOPER = 'developer', // Writes code
ANALYZER = 'analyzer', // Analyzes data/code
REVIEWER = 'reviewer', // Reviews work
TESTER = 'tester', // Tests functionality
DOCUMENTER = 'documenter', // Creates documentation
MONITOR = 'monitor', // Monitors system
SPECIALIST = 'specialist' // Domain-specific
}
interface AgentCapabilities {
// Core Capabilities
primarySkills: string[]
secondarySkills: string[]
tools: ToolType[]
// Performance Characteristics
speed: number // 1-10 scale
accuracy: number // 1-10 scale
creativity: number // 1-10 scale
reliability: number // 1-10 scale
// Resource Requirements
memoryRequired: number
cpuRequired: number
maxConcurrentTasks: number
}
```
**Agent Specializations:**
1. **Coordinator**: High-level orchestration, task decomposition
2. **Researcher**: Web search, documentation analysis, fact gathering
3. **Developer**: Code generation, implementation, refactoring
4. **Analyzer**: Code analysis, performance profiling, security scanning
5. **Reviewer**: Code review, quality assurance, best practices
6. **Tester**: Test creation, execution, coverage analysis
7. **Documenter**: API docs, user guides, technical writing
8. **Monitor**: System monitoring, performance tracking, alerting
9. **Specialist**: Domain-specific tasks (e.g., DevOps, Security, ML)
### 5. GitHub Workflow Integration
Deep integration with GitHub for automated workflow management.
```typescript
interface GitHubIntegration {
// Repository Management
async analyzeRepository(repo: string): Promise<RepoAnalysis>
async createBranch(name: string, from: string): Promise<void>
async createPullRequest(config: PRConfig): Promise<PullRequest>
// Workflow Automation
async createWorkflow(config: WorkflowConfig): Promise<void>
async triggerWorkflow(workflowId: string): Promise<WorkflowRun>
async monitorWorkflow(runId: string): Promise<WorkflowStatus>
// Issue Management
async createIssue(config: IssueConfig): Promise<Issue>
async updateIssue(issueId: string, update: IssueUpdate): Promise<void>
async linkPRToIssue(prId: string, issueId: string): Promise<void>
// Code Review
async requestReview(prId: string, reviewers: string[]): Promise<void>
async postReviewComment(prId: string, comment: ReviewComment): Promise<void>
async approveChanges(prId: string): Promise<void>
}
```
**GitHub Features:**
- **Automated PR Creation**: Create PRs with proper descriptions and labels
- **Issue Tracking**: Update issues automatically as work progresses
- **Workflow Generation**: Create GitHub Actions workflows programmatically
- **Review Coordination**: Manage multi-reviewer processes
- **Release Management**: Automate release preparation and deployment
### 6. SPARC Methodology Support
Full support for SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) methodology.
```typescript
interface SparcSupport {
// SPARC Phases
async executeSpecification(objective: string): Promise<Specification>
async generatePseudocode(spec: Specification): Promise<Pseudocode>
async designArchitecture(pseudo: Pseudocode): Promise<Architecture>
async refineImplementation(arch: Architecture): Promise<Implementation>
async completeProject(impl: Implementation): Promise<CompletedProject>
// Mode Management
async activateMode(mode: SparcMode): Promise<void>
async switchMode(from: SparcMode, to: SparcMode): Promise<void>
async getModeCapabilities(mode: SparcMode): Promise<ModeCapabilities>
}
```
**SPARC Modes:**
1. **Specification Mode**: Requirements gathering and analysis
2. **Pseudocode Mode**: High-level algorithm design
3. **Architecture Mode**: System design and structure
4. **Refinement Mode**: Iterative improvement
5. **Completion Mode**: Final implementation and testing
### 7. Neural Network Features
Advanced neural network capabilities for learning and adaptation.
```typescript
interface NeuralFeatures {
// Pattern Recognition
async learnPattern(pattern: Pattern): Promise<void>
async recognizePattern(input: any): Promise<Pattern[]>
async suggestOptimization(context: Context): Promise<Optimization[]>
// Performance Learning
async recordSuccess(task: TaskDefinition, result: TaskResult): Promise<void>
async recordFailure(task: TaskDefinition, error: Error): Promise<void>
async predictSuccess(task: TaskDefinition): Promise<number>
// Adaptive Behavior
async adaptStrategy(feedback: Feedback): Promise<void>
async optimizeWorkflow(workflow: Workflow): Promise<OptimizedWorkflow>
async personalizeAgent(agentId: AgentId, preferences: Preferences): Promise<void>
}
```
**Neural Capabilities:**
- **Pattern Learning**: Learn from successful task completions
- **Failure Prediction**: Anticipate potential issues
- **Workflow Optimization**: Continuously improve processes
- **Adaptive Strategies**: Adjust approach based on results
- **Performance Prediction**: Estimate task completion times
## Implementation Architecture
### Directory Structure
```
/workspaces/claude-code-flow/
├── src/
│ ├── coordination/
│ │ ├── swarm-coordinator.ts # Main coordinator
│ │ ├── task-executor.ts # Task execution engine
│ │ ├── load-balancer.ts # Load balancing
│ │ ├── agent-manager.ts # Agent lifecycle
│ │ └── workflow-engine.ts # Workflow execution
│ ├── memory/
│ │ ├── shared-memory.ts # Shared memory system
│ │ ├── knowledge-base.ts # Knowledge management
│ │ ├── memory-sync.ts # Synchronization
│ │ └── cache-manager.ts # Performance caching
│ ├── agents/
│ │ ├── agent-factory.ts # Agent creation
│ │ ├── agent-types/ # Type implementations
│ │ ├── capabilities.ts # Capability definitions
│ │ └── agent-pool.ts # Agent pooling
│ ├── github/
│ │ ├── workflow-generator.ts # GitHub Actions
│ │ ├── pr-manager.ts # PR automation
│ │ ├── issue-tracker.ts # Issue management
│ │ └── release-manager.ts # Release automation
│ ├── sparc/
│ │ ├── sparc-engine.ts # SPARC methodology
│ │ ├── mode-manager.ts # Mode switching
│ │ ├── phase-executor.ts # Phase execution
│ │ └── sparc-templates/ # Phase templates
│ └── neural/
│ ├── pattern-recognition.ts # Pattern learning
│ ├── performance-predictor.ts # Success prediction
│ ├── workflow-optimizer.ts # Optimization
│ └── adaptive-strategy.ts # Strategy adaptation
```
### Communication Flow
```mermaid
sequenceDiagram
participant User
participant CLI as Claude CLI
participant SC as SwarmCoordinator
participant TE as TaskExecutor
participant Agent
participant Memory
participant GitHub
User->>CLI: claude-flow swarm init
CLI->>SC: Initialize swarm
SC->>Memory: Load configuration
SC->>SC: Create swarm topology
User->>CLI: Execute task
CLI->>SC: Orchestrate task
SC->>SC: Decompose task
SC->>TE: Assign to executor
TE->>Agent: Spawn Claude instance
Agent->>Agent: Execute task
Agent->>Memory: Store results
Agent->>TE: Return results
TE->>SC: Task complete
SC->>GitHub: Update issue/PR
SC->>User: Report completion
```
### Data Flow
```mermaid
graph LR
subgraph "Input"
U[User Input]
G[GitHub Events]
F[File Changes]
end
subgraph "Processing"
SC[SwarmCoordinator]
TE[TaskExecutor]
A[Agents]
M[Memory]
end
subgraph "Output"
Code[Generated Code]
PR[Pull Requests]
Docs[Documentation]
Tests[Test Results]
end
U --> SC
G --> SC
F --> SC
SC --> TE
TE --> A
A <--> M
A --> Code
A --> PR
A --> Docs
A --> Tests
```
## Key Design Decisions
### 1. Separation of Concerns
- **Claude Code CLI**: Handles all file operations and code generation
- **ruv-swarm MCP**: Provides coordination and memory capabilities
- **Claude Flow**: Integrates both systems seamlessly
### 2. Parallel Execution Strategy
- Use process pooling for Claude CLI instances
- Implement work-stealing for load balancing
- Enable pipeline parallelism for dependent tasks
### 3. Memory Architecture
- Hierarchical memory structure for efficient retrieval
- Separate memory spaces for different contexts
- Automatic garbage collection for old entries
### 4. Error Handling
- Circuit breakers for failing agents
- Exponential backoff for retries
- Graceful degradation under load
### 5. Security Considerations
- Sandboxed execution environments
- API key management
- Rate limiting for external services
## Performance Optimizations
### 1. Agent Pooling
```typescript
class AgentPool {
private readonly minAgents = 2
private readonly maxAgents = 10
private agents: Map<AgentId, AgentInstance> = new Map()
async getAgent(type: AgentType): Promise<AgentInstance> {
// Return available agent or spawn new one
}
async releaseAgent(agentId: AgentId): Promise<void> {
// Return agent to pool for reuse
}
}
```
### 2. Task Batching
```typescript
class TaskBatcher {
private readonly batchSize = 5
private readonly batchTimeout = 1000 // ms
async batchTasks(tasks: TaskDefinition[]): Promise<TaskBatch[]> {
// Group related tasks for efficient execution
}
}
```
### 3. Memory Caching
```typescript
class MemoryCache {
private readonly cache = new LRUCache<string, any>(1000)
private readonly ttl = 5 * 60 * 1000 // 5 minutes
async get(key: string): Promise<any> {
// Check cache before querying SharedMemory
}
}
```
## Integration Points
### 1. Claude Code CLI Integration
```typescript
interface ClaudeCliIntegration {
// Process management
spawn(config: ClaudeConfig): Promise<ChildProcess>
kill(pid: number): Promise<void>
// Communication
sendPrompt(process: ChildProcess, prompt: string): Promise<void>
readResponse(process: ChildProcess): Promise<string>
// Tool usage
executeTools(tools: ToolCall[]): Promise<ToolResults>
}
```
### 2. ruv-swarm MCP Integration
```typescript
interface RuvSwarmIntegration {
// MCP communication
connect(config: McpConfig): Promise<McpClient>
callTool(tool: string, params: any): Promise<any>
// Memory operations
storeMemory(key: string, value: any): Promise<void>
retrieveMemory(key: string): Promise<any>
// Neural features
trainPattern(pattern: Pattern): Promise<void>
predictOutcome(input: any): Promise<Prediction>
}
```
### 3. GitHub API Integration
```typescript
interface GitHubApiIntegration {
// Authentication
authenticate(token: string): Promise<void>
// Repository operations
getRepo(owner: string, repo: string): Promise<Repository>
createPR(config: PRConfig): Promise<PullRequest>
// Workflow management
createWorkflow(yaml: string): Promise<void>
triggerWorkflow(id: string): Promise<WorkflowRun>
}
```
## Deployment Architecture
### 1. Local Development
```yaml
# docker-compose.yml
version: '3.8'
services:
claude-flow:
build: .
volumes:
- ./workspace:/workspace
- ~/.claude:/root/.claude
environment:
- CLAUDE_API_KEY=${CLAUDE_API_KEY}
- GITHUB_TOKEN=${GITHUB_TOKEN}
ruv-swarm:
image: ruv-swarm:latest
ports:
- "3000:3000"
volumes:
- ./memory:/data/memory
```
### 2. CI/CD Integration
```yaml
# .github/workflows/claude-flow.yml
name: Claude Flow CI/CD
on:
push:
branches: [main]
pull_request:
types: [opened, synchronize]
jobs:
claude-flow:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run Claude Flow
run: |
npx claude-flow swarm init --topology hierarchical
npx claude-flow swarm spawn developer analyzer tester
npx claude-flow task orchestrate "Review and test PR"
```
### 3. Production Deployment
```typescript
interface ProductionConfig {
// Scaling
autoScale: {
minAgents: 5,
maxAgents: 50,
scaleUpThreshold: 0.8,
scaleDownThreshold: 0.2
}
// Monitoring
monitoring: {
enableMetrics: true,
enableTracing: true,
enableLogging: true,
alertThresholds: {
errorRate: 0.05,
latency: 5000,
cpuUsage: 0.9
}
}
// Security
security: {
enableAuth: true,
enableEncryption: true,
apiRateLimit: 1000,
maxConcurrentUsers: 100
}
}
```
## Migration Strategy
### Phase 1: Core Infrastructure (Week 1-2)
1. Implement enhanced SwarmCoordinator
2. Integrate TaskExecutor with Claude CLI
3. Set up SharedMemory system
4. Create agent type definitions
### Phase 2: Integration (Week 3-4)
1. Connect Claude Code CLI with swarm system
2. Implement ruv-swarm MCP integration
3. Set up GitHub workflow automation
4. Create SPARC methodology support
### Phase 3: Advanced Features (Week 5-6)
1. Implement neural network features
2. Add performance optimizations
3. Create monitoring and analytics
4. Set up production deployment
### Phase 4: Testing & Documentation (Week 7-8)
1. Comprehensive testing suite
2. Performance benchmarking
3. Documentation and examples
4. User guides and tutorials
## Success Metrics
### Performance Metrics
- **Task Throughput**: >100 tasks/hour
- **Parallel Efficiency**: >80% CPU utilization
- **Memory Usage**: <2GB per swarm
- **Response Time**: <500ms for task assignment
### Quality Metrics
- **Success Rate**: >95% task completion
- **Error Recovery**: >90% automatic recovery
- **Code Quality**: >80% test coverage
- **Documentation**: 100% API coverage
### User Metrics
- **Setup Time**: <5 minutes
- **Learning Curve**: <1 hour to productivity
- **User Satisfaction**: >4.5/5 rating
- **Community Adoption**: >1000 users in 3 months
## Conclusion
Claude Flow v2.0.0 architecture provides a robust, scalable, and intelligent system for autonomous development. By combining Claude Code CLI's powerful capabilities with ruv-swarm's orchestration features, we create a system that can handle complex development tasks with minimal human intervention.
The architecture prioritizes:
- **Scalability**: Handle projects of any size
- **Reliability**: Automatic error recovery and failover
- **Performance**: Parallel execution and optimization
- **Usability**: Simple commands, powerful results
- **Extensibility**: Easy to add new capabilities
This design positions Claude Flow as the premier autonomous development platform, enabling developers to focus on high-level objectives while the system handles implementation details.
-34
View File
@@ -1,34 +0,0 @@
#!/usr/bin/env node
/**
* Claude Flow CLI - AI-Driven Development Toolkit
*
* This is the main entry point for the Claude Flow command-line interface.
* It provides powerful AI coordination capabilities for Claude Code.
*/
const { spawn } = require('child_process');
const path = require('path');
// Resolve the actual CLI path
const cliPath = path.resolve(__dirname, 'dist', 'index.js');
// Forward all arguments to the actual CLI
const child = spawn(process.execPath, [cliPath, ...process.argv.slice(2)], {
stdio: 'inherit',
env: {
...process.env,
CLAUDE_FLOW_CLI: 'true'
}
});
// Forward the exit code
child.on('exit', (code) => {
process.exit(code);
});
// Handle errors
child.on('error', (err) => {
console.error('Failed to start Claude Flow:', err);
process.exit(1);
});
-277
View File
@@ -1,277 +0,0 @@
#!/usr/bin/env node
/**
* Issue 108 Automated Update Script
* Coordinates with other swarms and updates issue 108 based on changes
*/
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
class Issue108Coordinator {
constructor() {
this.swarmId = null;
this.agents = [];
this.issueNumber = 108;
this.monitorInterval = 30000; // 30 seconds
}
async initialize() {
console.log('🚀 Initializing Issue 108 Coordinator...');
try {
// Initialize swarm
const swarmResult = execSync('npx ruv-swarm init hierarchical 4 --claude', { encoding: 'utf8' });
this.swarmId = JSON.parse(swarmResult).id;
// Spawn specialized agents
const agents = [
{ type: 'coordinator', name: 'Issue Coordinator' },
{ type: 'analyst', name: 'Progress Tracker' },
{ type: 'researcher', name: 'Repository Monitor' },
{ type: 'coder', name: 'Integration Agent' }
];
for (const agent of agents) {
const result = execSync(`npx ruv-swarm agent spawn ${agent.type} --name "${agent.name}"`, { encoding: 'utf8' });
this.agents.push(JSON.parse(result).agent);
}
console.log(`✅ Swarm initialized with ${this.agents.length} agents`);
// Initialize DAA for cross-swarm coordination
execSync('npx ruv-swarm daa init --coordination --learning --persistence disk', { encoding: 'utf8' });
} catch (error) {
console.error('❌ Initialization failed:', error.message);
throw error;
}
}
async monitorChanges() {
console.log('🔍 Starting change monitoring...');
setInterval(async () => {
try {
await this.checkForUpdates();
} catch (error) {
console.error('⚠️ Monitoring error:', error.message);
}
}, this.monitorInterval);
}
async checkForUpdates() {
try {
// Get current issue status
const issueData = execSync(`gh issue view ${this.issueNumber} --json title,body,state,assignees,labels,comments,updatedAt`, { encoding: 'utf8' });
const issue = JSON.parse(issueData);
// Get repository changes
const changes = this.getRecentChanges();
// Store in swarm memory
const memoryData = {
timestamp: new Date().toISOString(),
issue: issue,
changes: changes,
swarm_id: this.swarmId,
coordination_active: true
};
execSync(`npx ruv-swarm memory store "issue_108_status" '${JSON.stringify(memoryData)}'`, { encoding: 'utf8' });
// Check if update is needed
if (this.shouldUpdateIssue(changes)) {
await this.updateIssue(changes);
}
// Coordinate with other swarms
await this.coordinateWithOtherSwarms();
} catch (error) {
console.error('❌ Update check failed:', error.message);
}
}
getRecentChanges() {
try {
const gitChanges = execSync('git log --oneline --since="1 hour ago" --max-count=10', { encoding: 'utf8' });
const diffStat = execSync('git diff --stat HEAD~1 HEAD', { encoding: 'utf8' });
return {
recent_commits: gitChanges.trim().split('\n').filter(line => line.trim()),
diff_stat: diffStat.trim(),
timestamp: new Date().toISOString()
};
} catch (error) {
console.warn('⚠️ Git changes check failed:', error.message);
return { recent_commits: [], diff_stat: '', timestamp: new Date().toISOString() };
}
}
shouldUpdateIssue(changes) {
// Update if there are recent commits or significant changes
return changes.recent_commits.length > 0 ||
changes.diff_stat.length > 0 ||
this.hasSignificantChanges(changes);
}
hasSignificantChanges(changes) {
const significantPatterns = [
'claude-flow',
'issue 108',
'typescript',
'swarm',
'fix',
'update',
'v2.0.0'
];
return changes.recent_commits.some(commit =>
significantPatterns.some(pattern =>
commit.toLowerCase().includes(pattern.toLowerCase())
)
);
}
async updateIssue(changes) {
console.log('📝 Updating issue 108...');
try {
// Orchestrate update task
const taskResult = execSync(`npx ruv-swarm task orchestrate "Update issue 108 with latest changes" --strategy adaptive --priority high`, { encoding: 'utf8' });
const task = JSON.parse(taskResult);
// Generate update comment
const updateComment = this.generateUpdateComment(changes, task);
// Post comment to issue
execSync(`gh issue comment ${this.issueNumber} --body "${updateComment}"`, { encoding: 'utf8' });
console.log('✅ Issue 108 updated successfully');
} catch (error) {
console.error('❌ Issue update failed:', error.message);
}
}
generateUpdateComment(changes, task) {
const timestamp = new Date().toISOString();
return `🚀 Swarm Progress Update - ${timestamp}
## 📊 Current Status
### 🔴 Recent Changes Detected
${changes.recent_commits.map(commit => `- ${commit}`).join('\n')}
### 🎯 Swarm Coordination Status
- **Task ID**: ${task.taskId}
- **Assigned Agents**: ${task.assigned_agents?.length || 0}
- **Strategy**: ${task.strategy}
- **Priority**: ${task.priority}
### 📈 Metrics
- **Swarm Memory**: $(npx ruv-swarm memory usage --summary)
- **Neural Networks**: Active
- **Cross-Swarm Coordination**: Enabled
### 📝 Next Steps
- Continue monitoring repository changes
- Coordinate with development swarm
- Update progress metrics as changes occur
---
🤖 *Automated update by Issue 108 Coordinator*`.replace(/\n/g, '\\n').replace(/"/g, '\\"');
}
async coordinateWithOtherSwarms() {
try {
// Check for other active swarms
const swarmStatus = execSync('npx ruv-swarm status --json', { encoding: 'utf8' });
const status = JSON.parse(swarmStatus);
if (status.active_swarms > 1) {
console.log(`🔗 Coordinating with ${status.active_swarms - 1} other swarms...`);
// Share knowledge across swarms
for (const agent of this.agents) {
if (agent.type === 'coordinator') {
const knowledgeData = {
source: 'issue_108_coordinator',
timestamp: new Date().toISOString(),
issue_status: 'monitoring',
coordination_active: true,
swarm_id: this.swarmId
};
execSync(`npx ruv-swarm daa knowledge-share --source-agent ${agent.id} --knowledge-domain issue_108 --knowledge-content '${JSON.stringify(knowledgeData)}'`, { encoding: 'utf8' });
}
}
}
} catch (error) {
console.warn('⚠️ Cross-swarm coordination warning:', error.message);
}
}
async shutdown() {
console.log('🛑 Shutting down Issue 108 Coordinator...');
try {
// Save final state
const finalState = {
timestamp: new Date().toISOString(),
swarm_id: this.swarmId,
agents: this.agents,
status: 'shutdown',
coordination_active: false
};
execSync(`npx ruv-swarm memory store "issue_108_final_state" '${JSON.stringify(finalState)}'`, { encoding: 'utf8' });
console.log('✅ Shutdown complete');
} catch (error) {
console.error('❌ Shutdown error:', error.message);
}
}
}
// Main execution
async function main() {
const coordinator = new Issue108Coordinator();
try {
await coordinator.initialize();
// Handle graceful shutdown
process.on('SIGINT', async () => {
await coordinator.shutdown();
process.exit(0);
});
process.on('SIGTERM', async () => {
await coordinator.shutdown();
process.exit(0);
});
// Start monitoring
await coordinator.monitorChanges();
// Keep the process running
console.log('📡 Issue 108 Coordinator is running. Press Ctrl+C to stop.');
} catch (error) {
console.error('💥 Fatal error:', error);
process.exit(1);
}
}
// Run if called directly
if (require.main === module) {
main().catch(console.error);
}
module.exports = { Issue108Coordinator };
@@ -1,9 +0,0 @@
# Analysis Commands
Commands for analysis operations in Claude Flow.
## Available Commands
- [bottleneck-detect](./bottleneck-detect.md)
- [token-usage](./token-usage.md)
- [performance-report](./performance-report.md)
@@ -1,150 +0,0 @@
# bottleneck detect
Analyze performance bottlenecks in swarm operations and suggest optimizations.
## Usage
```bash
npx claude-flow bottleneck detect [options]
```
## Options
- `--swarm-id, -s <id>` - Analyze specific swarm (default: current)
- `--time-range, -t <range>` - Analysis period: 1h, 24h, 7d, all (default: 1h)
- `--threshold <percent>` - Bottleneck threshold percentage (default: 20)
- `--export, -e <file>` - Export analysis to file
- `--fix` - Apply automatic optimizations
## Examples
### Basic bottleneck detection
```bash
npx claude-flow bottleneck detect
```
### Analyze specific swarm
```bash
npx claude-flow bottleneck detect --swarm-id swarm-123
```
### Last 24 hours with export
```bash
npx claude-flow bottleneck detect -t 24h -e bottlenecks.json
```
### Auto-fix detected issues
```bash
npx claude-flow bottleneck detect --fix --threshold 15
```
## Metrics Analyzed
### Communication Bottlenecks
- Message queue delays
- Agent response times
- Coordination overhead
- Memory access patterns
### Processing Bottlenecks
- Task completion times
- Agent utilization rates
- Parallel execution efficiency
- Resource contention
### Memory Bottlenecks
- Cache hit rates
- Memory access patterns
- Storage I/O performance
- Neural pattern loading
### Network Bottlenecks
- API call latency
- MCP communication delays
- External service timeouts
- Concurrent request limits
## Output Format
```
🔍 Bottleneck Analysis Report
━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Summary
├── Time Range: Last 1 hour
├── Agents Analyzed: 6
├── Tasks Processed: 42
└── Critical Issues: 2
🚨 Critical Bottlenecks
1. Agent Communication (35% impact)
└── coordinator → coder-1 messages delayed by 2.3s avg
2. Memory Access (28% impact)
└── Neural pattern loading taking 1.8s per access
⚠️ Warning Bottlenecks
1. Task Queue (18% impact)
└── 5 tasks waiting > 10s for assignment
💡 Recommendations
1. Switch to hierarchical topology (est. 40% improvement)
2. Enable memory caching (est. 25% improvement)
3. Increase agent concurrency to 8 (est. 20% improvement)
✅ Quick Fixes Available
Run with --fix to apply:
- Enable smart caching
- Optimize message routing
- Adjust agent priorities
```
## Automatic Fixes
When using `--fix`, the following optimizations may be applied:
1. **Topology Optimization**
- Switch to more efficient topology
- Adjust communication patterns
- Reduce coordination overhead
2. **Caching Enhancement**
- Enable memory caching
- Optimize cache strategies
- Preload common patterns
3. **Concurrency Tuning**
- Adjust agent counts
- Optimize parallel execution
- Balance workload distribution
4. **Priority Adjustment**
- Reorder task queues
- Prioritize critical paths
- Reduce wait times
## Performance Impact
Typical improvements after bottleneck resolution:
- **Communication**: 30-50% faster message delivery
- **Processing**: 20-40% reduced task completion time
- **Memory**: 40-60% fewer cache misses
- **Overall**: 25-45% performance improvement
## Integration with Claude Code
```javascript
// Check for bottlenecks in Claude Code
mcp__claude-flow__bottleneck_detect {
timeRange: "1h",
threshold: 20,
autoFix: false
}
```
## See Also
- `performance report` - Detailed performance analysis
- `token usage` - Token optimization analysis
- `swarm monitor` - Real-time monitoring
- `cache manage` - Cache optimization
@@ -1,25 +0,0 @@
# performance-report
Generate comprehensive performance reports for swarm operations.
## Usage
```bash
npx claude-flow analysis performance-report [options]
```
## Options
- `--format <type>` - Report format (json, html, markdown)
- `--include-metrics` - Include detailed metrics
- `--compare <id>` - Compare with previous swarm
## Examples
```bash
# Generate HTML report
npx claude-flow analysis performance-report --format html
# Compare swarms
npx claude-flow analysis performance-report --compare swarm-123
# Full metrics report
npx claude-flow analysis performance-report --include-metrics --format markdown
```
@@ -1,25 +0,0 @@
# token-usage
Analyze token usage patterns and optimize for efficiency.
## Usage
```bash
npx claude-flow analysis token-usage [options]
```
## Options
- `--period <time>` - Analysis period (1h, 24h, 7d, 30d)
- `--by-agent` - Break down by agent
- `--by-operation` - Break down by operation type
## Examples
```bash
# Last 24 hours token usage
npx claude-flow analysis token-usage --period 24h
# By agent breakdown
npx claude-flow analysis token-usage --by-agent
# Export detailed report
npx claude-flow analysis token-usage --period 7d --export tokens.csv
```
@@ -1,9 +0,0 @@
# Automation Commands
Commands for automation operations in Claude Flow.
## Available Commands
- [auto-agent](./auto-agent.md)
- [smart-spawn](./smart-spawn.md)
- [workflow-select](./workflow-select.md)
@@ -1,112 +0,0 @@
# auto agent
Automatically spawn and manage agents based on task requirements.
## Usage
```bash
npx claude-flow auto agent [options]
```
## Options
- `--task, -t <description>` - Task description for agent analysis
- `--max-agents, -m <number>` - Maximum agents to spawn (default: auto)
- `--min-agents <number>` - Minimum agents required (default: 1)
- `--strategy, -s <type>` - Selection strategy: optimal, minimal, balanced
- `--no-spawn` - Analyze only, don't spawn agents
## Examples
### Basic auto-spawning
```bash
npx claude-flow auto agent --task "Build a REST API with authentication"
```
### Constrained spawning
```bash
npx claude-flow auto agent -t "Debug performance issue" --max-agents 3
```
### Analysis only
```bash
npx claude-flow auto agent -t "Refactor codebase" --no-spawn
```
### Minimal strategy
```bash
npx claude-flow auto agent -t "Fix bug in login" -s minimal
```
## How It Works
1. **Task Analysis**
- Parses task description
- Identifies required skills
- Estimates complexity
- Determines parallelization opportunities
2. **Agent Selection**
- Matches skills to agent types
- Considers task dependencies
- Optimizes for efficiency
- Respects constraints
3. **Topology Selection**
- Chooses optimal swarm structure
- Configures communication patterns
- Sets up coordination rules
- Enables monitoring
4. **Automatic Spawning**
- Creates selected agents
- Assigns specific roles
- Distributes subtasks
- Initiates coordination
## Agent Types Selected
- **Architect**: System design, architecture decisions
- **Coder**: Implementation, code generation
- **Tester**: Test creation, quality assurance
- **Analyst**: Performance, optimization
- **Researcher**: Documentation, best practices
- **Coordinator**: Task management, progress tracking
## Strategies
### Optimal
- Maximum efficiency
- May spawn more agents
- Best for complex tasks
- Highest resource usage
### Minimal
- Minimum viable agents
- Conservative approach
- Good for simple tasks
- Lowest resource usage
### Balanced
- Middle ground
- Adaptive to complexity
- Default strategy
- Good performance/resource ratio
## Integration with Claude Code
```javascript
// In Claude Code after auto-spawning
mcp__claude-flow__auto_agent {
task: "Build authentication system",
strategy: "balanced",
maxAgents: 6
}
```
## See Also
- `agent spawn` - Manual agent creation
- `swarm init` - Initialize swarm manually
- `smart spawn` - Intelligent agent spawning
- `workflow select` - Choose predefined workflows
@@ -1,25 +0,0 @@
# smart-spawn
Intelligently spawn agents based on workload analysis.
## Usage
```bash
npx claude-flow automation smart-spawn [options]
```
## Options
- `--analyze` - Analyze before spawning
- `--threshold <n>` - Spawn threshold
- `--topology <type>` - Preferred topology
## Examples
```bash
# Smart spawn with analysis
npx claude-flow automation smart-spawn --analyze
# Set spawn threshold
npx claude-flow automation smart-spawn --threshold 5
# Force topology
npx claude-flow automation smart-spawn --topology hierarchical
```
@@ -1,25 +0,0 @@
# workflow-select
Automatically select optimal workflow based on task type.
## Usage
```bash
npx claude-flow automation workflow-select [options]
```
## Options
- `--task <description>` - Task description
- `--constraints <list>` - Workflow constraints
- `--preview` - Preview without executing
## Examples
```bash
# Select workflow for task
npx claude-flow automation workflow-select --task "Deploy to production"
# With constraints
npx claude-flow automation workflow-select --constraints "no-downtime,rollback"
# Preview mode
npx claude-flow automation workflow-select --task "Database migration" --preview
```
@@ -1,9 +0,0 @@
# Coordination Commands
Commands for coordination operations in Claude Flow.
## Available Commands
- [swarm-init](./swarm-init.md)
- [agent-spawn](./agent-spawn.md)
- [task-orchestrate](./task-orchestrate.md)
@@ -1,25 +0,0 @@
# agent-spawn
Spawn a new agent in the current swarm.
## Usage
```bash
npx claude-flow agent spawn [options]
```
## Options
- `--type <type>` - Agent type (coder, researcher, analyst, tester, coordinator)
- `--name <name>` - Custom agent name
- `--skills <list>` - Specific skills (comma-separated)
## Examples
```bash
# Spawn coder agent
npx claude-flow agent spawn --type coder
# With custom name
npx claude-flow agent spawn --type researcher --name "API Expert"
# With specific skills
npx claude-flow agent spawn --type coder --skills "python,fastapi,testing"
```
@@ -1,76 +0,0 @@
# swarm init
Initialize a Claude Flow swarm with specified topology and configuration.
## Usage
```bash
npx claude-flow swarm init [options]
```
## Options
- `--topology, -t <type>` - Swarm topology: mesh, hierarchical, ring, star (default: hierarchical)
- `--max-agents, -m <number>` - Maximum number of agents (default: 8)
- `--strategy, -s <type>` - Execution strategy: balanced, parallel, sequential (default: parallel)
- `--auto-spawn` - Automatically spawn agents based on task complexity
- `--memory` - Enable cross-session memory persistence
- `--github` - Enable GitHub integration features
## Examples
### Basic initialization
```bash
npx claude-flow swarm init
```
### Mesh topology for research
```bash
npx claude-flow swarm init --topology mesh --max-agents 5 --strategy balanced
```
### Hierarchical for development
```bash
npx claude-flow swarm init --topology hierarchical --max-agents 10 --strategy parallel --auto-spawn
```
### GitHub-focused swarm
```bash
npx claude-flow swarm init --topology star --github --memory
```
## Topologies
### Mesh
- All agents connect to all others
- Best for: Research, exploration, brainstorming
- Communication: High overhead, maximum information sharing
### Hierarchical
- Tree structure with clear command chain
- Best for: Development, structured tasks, large projects
- Communication: Efficient, clear responsibilities
### Ring
- Agents connect in a circle
- Best for: Pipeline processing, sequential workflows
- Communication: Low overhead, ordered processing
### Star
- Central coordinator with satellite agents
- Best for: Simple tasks, centralized control
- Communication: Minimal overhead, clear coordination
## Integration with Claude Code
Once initialized, use MCP tools in Claude Code:
```javascript
mcp__claude-flow__swarm_init { topology: "hierarchical", maxAgents: 8 }
```
## See Also
- `agent spawn` - Create swarm agents
- `task orchestrate` - Coordinate task execution
- `swarm status` - Check swarm state
- `swarm monitor` - Real-time monitoring
@@ -1,25 +0,0 @@
# task-orchestrate
Orchestrate complex tasks across the swarm.
## Usage
```bash
npx claude-flow task orchestrate [options]
```
## Options
- `--task <description>` - Task description
- `--strategy <type>` - Orchestration strategy
- `--priority <level>` - Task priority (low, medium, high, critical)
## Examples
```bash
# Orchestrate development task
npx claude-flow task orchestrate --task "Implement user authentication"
# High priority task
npx claude-flow task orchestrate --task "Fix production bug" --priority critical
# With specific strategy
npx claude-flow task orchestrate --task "Refactor codebase" --strategy parallel
```
@@ -1,11 +0,0 @@
# Github Commands
Commands for github operations in Claude Flow.
## Available Commands
- [github-swarm](./github-swarm.md)
- [repo-analyze](./repo-analyze.md)
- [pr-enhance](./pr-enhance.md)
- [issue-triage](./issue-triage.md)
- [code-review](./code-review.md)
@@ -1,25 +0,0 @@
# code-review
Automated code review with swarm intelligence.
## Usage
```bash
npx claude-flow github code-review [options]
```
## Options
- `--pr-number <n>` - Pull request to review
- `--focus <areas>` - Review focus (security, performance, style)
- `--suggest-fixes` - Suggest code fixes
## Examples
```bash
# Review PR
npx claude-flow github code-review --pr-number 456
# Security focus
npx claude-flow github code-review --pr-number 456 --focus security
# With fix suggestions
npx claude-flow github code-review --pr-number 456 --suggest-fixes
```
@@ -1,108 +0,0 @@
# github swarm
Create a specialized swarm for GitHub repository management.
## Usage
```bash
npx claude-flow github swarm [options]
```
## Options
- `--repository, -r <owner/repo>` - Target GitHub repository
- `--agents, -a <number>` - Number of specialized agents (default: 5)
- `--focus, -f <type>` - Focus area: maintenance, development, review, triage
- `--auto-pr` - Enable automatic pull request enhancements
- `--issue-labels` - Auto-categorize and label issues
- `--code-review` - Enable AI-powered code reviews
## Examples
### Basic GitHub swarm
```bash
npx claude-flow github swarm --repository owner/repo
```
### Maintenance-focused swarm
```bash
npx claude-flow github swarm -r owner/repo -f maintenance --issue-labels
```
### Development swarm with PR automation
```bash
npx claude-flow github swarm -r owner/repo -f development --auto-pr --code-review
```
### Full-featured triage swarm
```bash
npx claude-flow github swarm -r owner/repo -a 8 -f triage --issue-labels --auto-pr
```
## Agent Types
### Issue Triager
- Analyzes and categorizes issues
- Suggests labels and priorities
- Identifies duplicates and related issues
### PR Reviewer
- Reviews code changes
- Suggests improvements
- Checks for best practices
### Documentation Agent
- Updates README files
- Creates API documentation
- Maintains changelog
### Test Agent
- Identifies missing tests
- Suggests test cases
- Validates test coverage
### Security Agent
- Scans for vulnerabilities
- Reviews dependencies
- Suggests security improvements
## Workflows
### Issue Triage Workflow
1. Scan all open issues
2. Categorize by type and priority
3. Apply appropriate labels
4. Suggest assignees
5. Link related issues
### PR Enhancement Workflow
1. Analyze PR changes
2. Suggest missing tests
3. Improve documentation
4. Format code consistently
5. Add helpful comments
### Repository Health Check
1. Analyze code quality metrics
2. Review dependency status
3. Check test coverage
4. Assess documentation completeness
5. Generate health report
## Integration with Claude Code
Use in Claude Code with MCP tools:
```javascript
mcp__claude-flow__github_swarm {
repository: "owner/repo",
agents: 6,
focus: "maintenance"
}
```
## See Also
- `repo analyze` - Deep repository analysis
- `pr enhance` - Enhance pull requests
- `issue triage` - Intelligent issue management
- `code review` - Automated reviews
@@ -1,25 +0,0 @@
# issue-triage
Intelligent issue classification and triage.
## Usage
```bash
npx claude-flow github issue-triage [options]
```
## Options
- `--repository <owner/repo>` - Target repository
- `--auto-label` - Automatically apply labels
- `--assign` - Auto-assign to team members
## Examples
```bash
# Triage issues
npx claude-flow github issue-triage --repository myorg/myrepo
# With auto-labeling
npx claude-flow github issue-triage --repository myorg/myrepo --auto-label
# Full automation
npx claude-flow github issue-triage --repository myorg/myrepo --auto-label --assign
```
@@ -1,26 +0,0 @@
# pr-enhance
AI-powered pull request enhancements.
## Usage
```bash
npx claude-flow github pr-enhance [options]
```
## Options
- `--pr-number <n>` - Pull request number
- `--add-tests` - Add missing tests
- `--improve-docs` - Improve documentation
- `--check-security` - Security review
## Examples
```bash
# Enhance PR
npx claude-flow github pr-enhance --pr-number 123
# Add tests
npx claude-flow github pr-enhance --pr-number 123 --add-tests
# Full enhancement
npx claude-flow github pr-enhance --pr-number 123 --add-tests --improve-docs
```
@@ -1,25 +0,0 @@
# repo-analyze
Deep analysis of GitHub repository with AI insights.
## Usage
```bash
npx claude-flow github repo-analyze [options]
```
## Options
- `--repository <owner/repo>` - Repository to analyze
- `--deep` - Enable deep analysis
- `--include <areas>` - Include specific areas (issues, prs, code, commits)
## Examples
```bash
# Basic analysis
npx claude-flow github repo-analyze --repository myorg/myrepo
# Deep analysis
npx claude-flow github repo-analyze --repository myorg/myrepo --deep
# Specific areas
npx claude-flow github repo-analyze --repository myorg/myrepo --include issues,prs
```
@@ -1,11 +0,0 @@
# Hooks Commands
Commands for hooks operations in Claude Flow.
## Available Commands
- [pre-task](./pre-task.md)
- [post-task](./post-task.md)
- [pre-edit](./pre-edit.md)
- [post-edit](./post-edit.md)
- [session-end](./session-end.md)
@@ -1,25 +0,0 @@
# post-edit
Hook executed after file edits.
## Usage
```bash
npx claude-flow hook post-edit [options]
```
## Options
- `--file <path>` - Edited file
- `--memory-key <key>` - Memory storage key
- `--format` - Auto-format code
## Examples
```bash
# Post-edit hook
npx claude-flow hook post-edit --file src/api.js
# Store in memory
npx claude-flow hook post-edit --file src/api.js --memory-key "api-changes"
# With formatting
npx claude-flow hook post-edit --file src/api.js --format
```
@@ -1,25 +0,0 @@
# post-task
Hook executed after task completion.
## Usage
```bash
npx claude-flow hook post-task [options]
```
## Options
- `--task-id <id>` - Task identifier
- `--analyze-performance` - Analyze task performance
- `--update-memory` - Update swarm memory
## Examples
```bash
# Basic post-task
npx claude-flow hook post-task --task-id task-123
# With performance analysis
npx claude-flow hook post-task --task-id task-123 --analyze-performance
# Update memory
npx claude-flow hook post-task --task-id task-123 --update-memory
```
@@ -1,25 +0,0 @@
# pre-edit
Hook executed before file edits.
## Usage
```bash
npx claude-flow hook pre-edit [options]
```
## Options
- `--file <path>` - File to be edited
- `--validate-syntax` - Validate syntax before edit
- `--backup` - Create backup
## Examples
```bash
# Pre-edit hook
npx claude-flow hook pre-edit --file src/api.js
# With validation
npx claude-flow hook pre-edit --file src/api.js --validate-syntax
# Create backup
npx claude-flow hook pre-edit --file src/api.js --backup
```
@@ -1,100 +0,0 @@
# hook pre-task
Execute pre-task preparations and context loading.
## Usage
```bash
npx claude-flow hook pre-task [options]
```
## Options
- `--description, -d <text>` - Task description for context
- `--auto-spawn-agents` - Automatically spawn required agents (default: true)
- `--load-memory` - Load relevant memory from previous sessions
- `--optimize-topology` - Select optimal swarm topology
- `--estimate-complexity` - Analyze task complexity
## Examples
### Basic pre-task hook
```bash
npx claude-flow hook pre-task --description "Implement user authentication"
```
### With memory loading
```bash
npx claude-flow hook pre-task -d "Continue API development" --load-memory
```
### Manual agent control
```bash
npx claude-flow hook pre-task -d "Debug issue #123" --auto-spawn-agents false
```
### Full optimization
```bash
npx claude-flow hook pre-task -d "Refactor codebase" --optimize-topology --estimate-complexity
```
## Features
### Auto Agent Assignment
- Analyzes task requirements
- Determines needed agent types
- Spawns agents automatically
- Configures agent parameters
### Memory Loading
- Retrieves relevant past decisions
- Loads previous task contexts
- Restores agent configurations
- Maintains continuity
### Topology Optimization
- Analyzes task structure
- Selects best swarm topology
- Configures communication patterns
- Optimizes for performance
### Complexity Estimation
- Evaluates task difficulty
- Estimates time requirements
- Suggests agent count
- Identifies dependencies
## Integration
This hook is automatically called by Claude Code when:
- Starting a new task
- Resuming work after a break
- Switching between projects
- Beginning complex operations
Manual usage in agents:
```bash
# In agent coordination
npx claude-flow hook pre-task --description "Your task here"
```
## Output
Returns JSON with:
```json
{
"continue": true,
"topology": "hierarchical",
"agentsSpawned": 5,
"complexity": "medium",
"estimatedMinutes": 30,
"memoryLoaded": true
}
```
## See Also
- `hook post-task` - Post-task cleanup
- `agent spawn` - Manual agent creation
- `memory usage` - Memory management
- `swarm init` - Swarm initialization
@@ -1,25 +0,0 @@
# session-end
Hook executed at session end.
## Usage
```bash
npx claude-flow hook session-end [options]
```
## Options
- `--export-metrics` - Export session metrics
- `--generate-summary` - Generate session summary
- `--persist-state` - Save session state
## Examples
```bash
# End session
npx claude-flow hook session-end
# Export metrics
npx claude-flow hook session-end --export-metrics
# Full closure
npx claude-flow hook session-end --export-metrics --generate-summary --persist-state
```
@@ -1,9 +0,0 @@
# Memory Commands
Commands for memory operations in Claude Flow.
## Available Commands
- [memory-usage](./memory-usage.md)
- [memory-persist](./memory-persist.md)
- [memory-search](./memory-search.md)
@@ -1,25 +0,0 @@
# memory-persist
Persist memory across sessions.
## Usage
```bash
npx claude-flow memory persist [options]
```
## Options
- `--export <file>` - Export to file
- `--import <file>` - Import from file
- `--compress` - Compress memory data
## Examples
```bash
# Export memory
npx claude-flow memory persist --export memory-backup.json
# Import memory
npx claude-flow memory persist --import memory-backup.json
# Compressed export
npx claude-flow memory persist --export memory.gz --compress
```
@@ -1,25 +0,0 @@
# memory-search
Search through stored memory.
## Usage
```bash
npx claude-flow memory search [options]
```
## Options
- `--query <text>` - Search query
- `--pattern <regex>` - Pattern matching
- `--limit <n>` - Result limit
## Examples
```bash
# Search memory
npx claude-flow memory search --query "authentication"
# Pattern search
npx claude-flow memory search --pattern "api-.*"
# Limited results
npx claude-flow memory search --query "config" --limit 10
```
@@ -1,25 +0,0 @@
# memory-usage
Manage persistent memory storage.
## Usage
```bash
npx claude-flow memory usage [options]
```
## Options
- `--action <type>` - Action (store, retrieve, list, clear)
- `--key <key>` - Memory key
- `--value <data>` - Data to store (JSON)
## Examples
```bash
# Store memory
npx claude-flow memory usage --action store --key "project-config" --value '{"api": "v2"}'
# Retrieve memory
npx claude-flow memory usage --action retrieve --key "project-config"
# List all keys
npx claude-flow memory usage --action list
```
@@ -1,9 +0,0 @@
# Monitoring Commands
Commands for monitoring operations in Claude Flow.
## Available Commands
- [swarm-monitor](./swarm-monitor.md)
- [agent-metrics](./agent-metrics.md)
- [real-time-view](./real-time-view.md)
@@ -1,25 +0,0 @@
# agent-metrics
View agent performance metrics.
## Usage
```bash
npx claude-flow agent metrics [options]
```
## Options
- `--agent-id <id>` - Specific agent
- `--period <time>` - Time period
- `--format <type>` - Output format
## Examples
```bash
# All agents metrics
npx claude-flow agent metrics
# Specific agent
npx claude-flow agent metrics --agent-id agent-001
# Last hour
npx claude-flow agent metrics --period 1h
```
@@ -1,25 +0,0 @@
# real-time-view
Real-time view of swarm activity.
## Usage
```bash
npx claude-flow monitoring real-time-view [options]
```
## Options
- `--filter <type>` - Filter view
- `--highlight <pattern>` - Highlight pattern
- `--tail <n>` - Show last N events
## Examples
```bash
# Start real-time view
npx claude-flow monitoring real-time-view
# Filter errors
npx claude-flow monitoring real-time-view --filter errors
# Highlight pattern
npx claude-flow monitoring real-time-view --highlight "API"
```
@@ -1,25 +0,0 @@
# swarm-monitor
Real-time swarm monitoring.
## Usage
```bash
npx claude-flow swarm monitor [options]
```
## Options
- `--interval <ms>` - Update interval
- `--metrics` - Show detailed metrics
- `--export` - Export monitoring data
## Examples
```bash
# Start monitoring
npx claude-flow swarm monitor
# Custom interval
npx claude-flow swarm monitor --interval 5000
# With metrics
npx claude-flow swarm monitor --metrics
```
@@ -1,9 +0,0 @@
# Optimization Commands
Commands for optimization operations in Claude Flow.
## Available Commands
- [topology-optimize](./topology-optimize.md)
- [parallel-execute](./parallel-execute.md)
- [cache-manage](./cache-manage.md)
@@ -1,25 +0,0 @@
# cache-manage
Manage operation cache for performance.
## Usage
```bash
npx claude-flow optimization cache-manage [options]
```
## Options
- `--action <type>` - Action (view, clear, optimize)
- `--max-size <mb>` - Maximum cache size
- `--ttl <seconds>` - Time to live
## Examples
```bash
# View cache stats
npx claude-flow optimization cache-manage --action view
# Clear cache
npx claude-flow optimization cache-manage --action clear
# Set limits
npx claude-flow optimization cache-manage --max-size 100 --ttl 3600
```
@@ -1,25 +0,0 @@
# parallel-execute
Execute tasks in parallel for maximum efficiency.
## Usage
```bash
npx claude-flow optimization parallel-execute [options]
```
## Options
- `--tasks <file>` - Task list file
- `--max-parallel <n>` - Maximum parallel tasks
- `--strategy <type>` - Execution strategy
## Examples
```bash
# Execute task list
npx claude-flow optimization parallel-execute --tasks tasks.json
# Limit parallelism
npx claude-flow optimization parallel-execute --tasks tasks.json --max-parallel 5
# Custom strategy
npx claude-flow optimization parallel-execute --strategy adaptive
```
@@ -1,25 +0,0 @@
# topology-optimize
Optimize swarm topology for current workload.
## Usage
```bash
npx claude-flow optimization topology-optimize [options]
```
## Options
- `--analyze-first` - Analyze before optimizing
- `--target <metric>` - Optimization target
- `--apply` - Apply optimizations
## Examples
```bash
# Analyze and suggest
npx claude-flow optimization topology-optimize --analyze-first
# Optimize for speed
npx claude-flow optimization topology-optimize --target speed
# Apply changes
npx claude-flow optimization topology-optimize --target efficiency --apply
```
@@ -1,9 +0,0 @@
# Training Commands
Commands for training operations in Claude Flow.
## Available Commands
- [neural-train](./neural-train.md)
- [pattern-learn](./pattern-learn.md)
- [model-update](./model-update.md)
@@ -1,25 +0,0 @@
# model-update
Update neural models with new data.
## Usage
```bash
npx claude-flow training model-update [options]
```
## Options
- `--model <name>` - Model to update
- `--incremental` - Incremental update
- `--validate` - Validate after update
## Examples
```bash
# Update all models
npx claude-flow training model-update
# Specific model
npx claude-flow training model-update --model agent-selector
# Incremental with validation
npx claude-flow training model-update --incremental --validate
```
@@ -1,25 +0,0 @@
# neural-train
Train neural patterns from operations.
## Usage
```bash
npx claude-flow training neural-train [options]
```
## Options
- `--data <source>` - Training data source
- `--model <name>` - Target model
- `--epochs <n>` - Training epochs
## Examples
```bash
# Train from recent ops
npx claude-flow training neural-train --data recent
# Specific model
npx claude-flow training neural-train --model task-predictor
# Custom epochs
npx claude-flow training neural-train --epochs 100
```
@@ -1,25 +0,0 @@
# pattern-learn
Learn patterns from successful operations.
## Usage
```bash
npx claude-flow training pattern-learn [options]
```
## Options
- `--source <type>` - Pattern source
- `--threshold <score>` - Success threshold
- `--save <name>` - Save pattern set
## Examples
```bash
# Learn from all ops
npx claude-flow training pattern-learn
# High success only
npx claude-flow training pattern-learn --threshold 0.9
# Save patterns
npx claude-flow training pattern-learn --save optimal-patterns
```
@@ -1,9 +0,0 @@
# Workflows Commands
Commands for workflows operations in Claude Flow.
## Available Commands
- [workflow-create](./workflow-create.md)
- [workflow-execute](./workflow-execute.md)
- [workflow-export](./workflow-export.md)
@@ -1,25 +0,0 @@
# workflow-create
Create reusable workflow templates.
## Usage
```bash
npx claude-flow workflow create [options]
```
## Options
- `--name <name>` - Workflow name
- `--from-history` - Create from history
- `--interactive` - Interactive creation
## Examples
```bash
# Create workflow
npx claude-flow workflow create --name "deploy-api"
# From history
npx claude-flow workflow create --name "test-suite" --from-history
# Interactive mode
npx claude-flow workflow create --interactive
```
@@ -1,25 +0,0 @@
# workflow-execute
Execute saved workflows.
## Usage
```bash
npx claude-flow workflow execute [options]
```
## Options
- `--name <name>` - Workflow name
- `--params <json>` - Workflow parameters
- `--dry-run` - Preview execution
## Examples
```bash
# Execute workflow
npx claude-flow workflow execute --name "deploy-api"
# With parameters
npx claude-flow workflow execute --name "test-suite" --params '{"env": "staging"}'
# Dry run
npx claude-flow workflow execute --name "deploy-api" --dry-run
```
@@ -1,25 +0,0 @@
# workflow-export
Export workflows for sharing.
## Usage
```bash
npx claude-flow workflow export [options]
```
## Options
- `--name <name>` - Workflow to export
- `--format <type>` - Export format
- `--include-history` - Include execution history
## Examples
```bash
# Export workflow
npx claude-flow workflow export --name "deploy-api"
# As YAML
npx claude-flow workflow export --name "test-suite" --format yaml
# With history
npx claude-flow workflow export --name "deploy-api" --include-history
```
-103
View File
@@ -1,103 +0,0 @@
{
"env": {
"CLAUDE_FLOW_AUTO_COMMIT": "false",
"CLAUDE_FLOW_AUTO_PUSH": "false",
"CLAUDE_FLOW_HOOKS_ENABLED": "true",
"CLAUDE_FLOW_TELEMETRY_ENABLED": "true",
"CLAUDE_FLOW_REMOTE_EXECUTION": "true",
"CLAUDE_FLOW_GITHUB_INTEGRATION": "true"
},
"permissions": {
"allow": [
"Bash(npx claude-flow *)",
"Bash(npm run lint)",
"Bash(npm run test:*)",
"Bash(npm test *)",
"Bash(git status)",
"Bash(git diff *)",
"Bash(git log *)",
"Bash(git add *)",
"Bash(git commit *)",
"Bash(git push)",
"Bash(git config *)",
"Bash(gh *)",
"Bash(node *)",
"Bash(which *)",
"Bash(pwd)",
"Bash(ls *)"
],
"deny": [
"Bash(rm -rf /)",
"Bash(curl * | bash)",
"Bash(wget * | sh)",
"Bash(eval *)"
]
},
"hooks": {
"preEditHook": {
"command": "npx",
"args": ["claude-flow", "hook", "pre-edit", "--file", "${file}", "--auto-assign-agents", "true", "--load-context", "true"],
"alwaysRun": false,
"outputFormat": "json"
},
"postEditHook": {
"command": "npx",
"args": ["claude-flow", "hook", "post-edit", "--file", "${file}", "--format", "true", "--update-memory", "true", "--train-neural", "true"],
"alwaysRun": true,
"outputFormat": "json"
},
"preCommandHook": {
"command": "npx",
"args": ["claude-flow", "hook", "pre-command", "--command", "${command}", "--validate-safety", "true", "--prepare-resources", "true"],
"alwaysRun": false,
"outputFormat": "json"
},
"postCommandHook": {
"command": "npx",
"args": ["claude-flow", "hook", "post-command", "--command", "${command}", "--track-metrics", "true", "--store-results", "true"],
"alwaysRun": false,
"outputFormat": "json"
},
"sessionEndHook": {
"command": "npx",
"args": ["claude-flow", "hook", "session-end", "--generate-summary", "true", "--persist-state", "true", "--export-metrics", "true"],
"alwaysRun": true,
"outputFormat": "json"
}
},
"mcpServers": {
"claude-flow": {
"command": "npx",
"args": [
"claude-flow",
"mcp",
"start"
],
"env": {
"CLAUDE_FLOW_HOOKS_ENABLED": "true",
"CLAUDE_FLOW_TELEMETRY_ENABLED": "true",
"CLAUDE_FLOW_REMOTE_READY": "true",
"CLAUDE_FLOW_GITHUB_INTEGRATION": "true"
}
}
},
"includeCoAuthoredBy": true,
"features": {
"autoTopologySelection": true,
"parallelExecution": true,
"neuralTraining": true,
"bottleneckAnalysis": true,
"smartAutoSpawning": true,
"selfHealingWorkflows": true,
"crossSessionMemory": true,
"githubIntegration": true
},
"performance": {
"maxAgents": 10,
"defaultTopology": "hierarchical",
"executionStrategy": "parallel",
"tokenOptimization": true,
"cacheEnabled": true,
"telemetryLevel": "detailed"
}
}
-604
View File
@@ -1,604 +0,0 @@
# Claude Code Configuration for Claude Flow
## 🚀 IMPORTANT: Claude Flow AI-Driven Development
### Claude Code Handles:
- ✅ **ALL file operations** (Read, Write, Edit, MultiEdit)
- ✅ **ALL code generation** and development tasks
- ✅ **ALL bash commands** and system operations
- ✅ **ALL actual implementation** work
- ✅ **Project navigation** and code analysis
### Claude Flow MCP Tools Handle:
- 🧠 **Coordination only** - Orchestrating Claude Code's actions
- 💾 **Memory management** - Persistent state across sessions
- 🤖 **Neural features** - Cognitive patterns and learning
- 📊 **Performance tracking** - Monitoring and metrics
- 🐝 **Swarm orchestration** - Multi-agent coordination
- 🔗 **GitHub integration** - Advanced repository management
### ⚠️ Key Principle:
**MCP tools DO NOT create content or write code.** They coordinate and enhance Claude Code's native capabilities. Think of them as an orchestration layer that helps Claude Code work more efficiently.
## 🚀 CRITICAL: Parallel Execution & Batch Operations
### 🚨 MANDATORY RULE #1: BATCH EVERYTHING
**When using swarms, you MUST use BatchTool for ALL operations:**
1. **NEVER** send multiple messages for related operations
2. **ALWAYS** combine multiple tool calls in ONE message
3. **PARALLEL** execution is MANDATORY, not optional
### ⚡ THE GOLDEN RULE OF SWARMS
```
If you need to do X operations, they should be in 1 message, not X messages
```
### 📦 BATCH TOOL EXAMPLES
**✅ CORRECT - Everything in ONE Message:**
```javascript
[Single Message with BatchTool]:
mcp__claude-flow__swarm_init { topology: "mesh", maxAgents: 6 }
mcp__claude-flow__agent_spawn { type: "researcher" }
mcp__claude-flow__agent_spawn { type: "coder" }
mcp__claude-flow__agent_spawn { type: "analyst" }
mcp__claude-flow__agent_spawn { type: "tester" }
mcp__claude-flow__agent_spawn { type: "coordinator" }
TodoWrite { todos: [todo1, todo2, todo3, todo4, todo5] }
Bash "mkdir -p app/{src,tests,docs}"
Write "app/package.json"
Write "app/README.md"
Write "app/src/index.js"
```
**❌ WRONG - Multiple Messages (NEVER DO THIS):**
```javascript
Message 1: mcp__claude-flow__swarm_init
Message 2: mcp__claude-flow__agent_spawn
Message 3: mcp__claude-flow__agent_spawn
Message 4: TodoWrite (one todo)
Message 5: Bash "mkdir src"
Message 6: Write "package.json"
// This is 6x slower and breaks parallel coordination!
```
### 🎯 BATCH OPERATIONS BY TYPE
**File Operations (Single Message):**
- Read 10 files? → One message with 10 Read calls
- Write 5 files? → One message with 5 Write calls
- Edit 1 file many times? → One MultiEdit call
**Swarm Operations (Single Message):**
- Need 8 agents? → One message with swarm_init + 8 agent_spawn calls
- Multiple memories? → One message with all memory_usage calls
- Task + monitoring? → One message with task_orchestrate + swarm_monitor
**Command Operations (Single Message):**
- Multiple directories? → One message with all mkdir commands
- Install + test + lint? → One message with all npm commands
- Git operations? → One message with all git commands
## 🚀 Quick Setup (Stdio MCP - Recommended)
### 1. Add MCP Server (Stdio - No Port Needed)
```bash
# Add Claude Flow MCP server to Claude Code using stdio
claude mcp add claude-flow npx claude-flow mcp start
```
### 2. Use MCP Tools for Coordination in Claude Code
Once configured, Claude Flow MCP tools enhance Claude Code's coordination:
**Initialize a swarm:**
- Use the `mcp__claude-flow__swarm_init` tool to set up coordination topology
- Choose: mesh, hierarchical, ring, or star
- This creates a coordination framework for Claude Code's work
**Spawn agents:**
- Use `mcp__claude-flow__agent_spawn` tool to create specialized coordinators
- Agent types represent different thinking patterns, not actual coders
- They help Claude Code approach problems from different angles
**Orchestrate tasks:**
- Use `mcp__claude-flow__task_orchestrate` tool to coordinate complex workflows
- This breaks down tasks for Claude Code to execute systematically
- The agents don't write code - they coordinate Claude Code's actions
## Available MCP Tools for Coordination
### Coordination Tools:
- `mcp__claude-flow__swarm_init` - Set up coordination topology for Claude Code
- `mcp__claude-flow__agent_spawn` - Create cognitive patterns to guide Claude Code
- `mcp__claude-flow__task_orchestrate` - Break down and coordinate complex tasks
### Monitoring Tools:
- `mcp__claude-flow__swarm_status` - Monitor coordination effectiveness
- `mcp__claude-flow__agent_list` - View active cognitive patterns
- `mcp__claude-flow__agent_metrics` - Track coordination performance
- `mcp__claude-flow__task_status` - Check workflow progress
- `mcp__claude-flow__task_results` - Review coordination outcomes
### Memory & Neural Tools:
- `mcp__claude-flow__memory_usage` - Persistent memory across sessions
- `mcp__claude-flow__neural_status` - Neural pattern effectiveness
- `mcp__claude-flow__neural_train` - Improve coordination patterns
- `mcp__claude-flow__neural_patterns` - Analyze thinking approaches
### GitHub Integration Tools (NEW!):
- `mcp__claude-flow__github_swarm` - Create specialized GitHub management swarms
- `mcp__claude-flow__repo_analyze` - Deep repository analysis with AI
- `mcp__claude-flow__pr_enhance` - AI-powered pull request improvements
- `mcp__claude-flow__issue_triage` - Intelligent issue classification
- `mcp__claude-flow__code_review` - Automated code review with swarms
### System Tools:
- `mcp__claude-flow__benchmark_run` - Measure coordination efficiency
- `mcp__claude-flow__features_detect` - Available capabilities
- `mcp__claude-flow__swarm_monitor` - Real-time coordination tracking
## Workflow Examples (Coordination-Focused)
### Research Coordination Example
**Context:** Claude Code needs to research a complex topic systematically
**Step 1:** Set up research coordination
- Tool: `mcp__claude-flow__swarm_init`
- Parameters: `{"topology": "mesh", "maxAgents": 5, "strategy": "balanced"}`
- Result: Creates a mesh topology for comprehensive exploration
**Step 2:** Define research perspectives
- Tool: `mcp__claude-flow__agent_spawn`
- Parameters: `{"type": "researcher", "name": "Literature Review"}`
- Tool: `mcp__claude-flow__agent_spawn`
- Parameters: `{"type": "analyst", "name": "Data Analysis"}`
- Result: Different cognitive patterns for Claude Code to use
**Step 3:** Coordinate research execution
- Tool: `mcp__claude-flow__task_orchestrate`
- Parameters: `{"task": "Research neural architecture search papers", "strategy": "adaptive"}`
- Result: Claude Code systematically searches, reads, and analyzes papers
**What Actually Happens:**
1. The swarm sets up a coordination framework
2. Each agent MUST use Claude Flow hooks for coordination:
- `npx claude-flow hook pre-task` before starting
- `npx claude-flow hook post-edit` after each file operation
- `npx claude-flow hook notification` to share decisions
3. Claude Code uses its native Read, WebSearch, and Task tools
4. The swarm coordinates through shared memory and hooks
5. Results are synthesized by Claude Code with full coordination history
### Development Coordination Example
**Context:** Claude Code needs to build a complex system with multiple components
**Step 1:** Set up development coordination
- Tool: `mcp__claude-flow__swarm_init`
- Parameters: `{"topology": "hierarchical", "maxAgents": 8, "strategy": "specialized"}`
- Result: Hierarchical structure for organized development
**Step 2:** Define development perspectives
- Tool: `mcp__claude-flow__agent_spawn`
- Parameters: `{"type": "architect", "name": "System Design"}`
- Result: Architectural thinking pattern for Claude Code
**Step 3:** Coordinate implementation
- Tool: `mcp__claude-flow__task_orchestrate`
- Parameters: `{"task": "Implement user authentication with JWT", "strategy": "parallel"}`
- Result: Claude Code implements features using its native tools
**What Actually Happens:**
1. The swarm creates a development coordination plan
2. Each agent coordinates using mandatory hooks:
- Pre-task hooks for context loading
- Post-edit hooks for progress tracking
- Memory storage for cross-agent coordination
3. Claude Code uses Write, Edit, Bash tools for implementation
4. Agents share progress through Claude Flow memory
5. All code is written by Claude Code with full coordination
### GitHub Repository Management Example (NEW!)
**Context:** Claude Code needs to manage a complex GitHub repository
**Step 1:** Initialize GitHub swarm
- Tool: `mcp__claude-flow__github_swarm`
- Parameters: `{"repository": "owner/repo", "agents": 5, "focus": "maintenance"}`
- Result: Specialized swarm for repository management
**Step 2:** Analyze repository health
- Tool: `mcp__claude-flow__repo_analyze`
- Parameters: `{"deep": true, "include": ["issues", "prs", "code"]}`
- Result: Comprehensive repository analysis
**Step 3:** Enhance pull requests
- Tool: `mcp__claude-flow__pr_enhance`
- Parameters: `{"pr_number": 123, "add_tests": true, "improve_docs": true}`
- Result: AI-powered PR improvements
## Best Practices for Coordination
### ✅ DO:
- Use MCP tools to coordinate Claude Code's approach to complex tasks
- Let the swarm break down problems into manageable pieces
- Use memory tools to maintain context across sessions
- Monitor coordination effectiveness with status tools
- Train neural patterns for better coordination over time
- Leverage GitHub tools for repository management
### ❌ DON'T:
- Expect agents to write code (Claude Code does all implementation)
- Use MCP tools for file operations (use Claude Code's native tools)
- Try to make agents execute bash commands (Claude Code handles this)
- Confuse coordination with execution (MCP coordinates, Claude executes)
## Memory and Persistence
The swarm provides persistent memory that helps Claude Code:
- Remember project context across sessions
- Track decisions and rationale
- Maintain consistency in large projects
- Learn from previous coordination patterns
- Store GitHub workflow preferences
## Performance Benefits
When using Claude Flow coordination with Claude Code:
- **84.8% SWE-Bench solve rate** - Better problem-solving through coordination
- **32.3% token reduction** - Efficient task breakdown reduces redundancy
- **2.8-4.4x speed improvement** - Parallel coordination strategies
- **27+ neural models** - Diverse cognitive approaches
- **GitHub automation** - Streamlined repository management
## Claude Code Hooks Integration
Claude Flow includes powerful hooks that automate coordination:
### Pre-Operation Hooks
- **Auto-assign agents** before file edits based on file type
- **Validate commands** before execution for safety
- **Prepare resources** automatically for complex operations
- **Optimize topology** based on task complexity analysis
- **Cache searches** for improved performance
- **GitHub context** loading for repository operations
### Post-Operation Hooks
- **Auto-format code** using language-specific formatters
- **Train neural patterns** from successful operations
- **Update memory** with operation context
- **Analyze performance** and identify bottlenecks
- **Track token usage** for efficiency metrics
- **Sync GitHub** state for consistency
### Session Management
- **Generate summaries** at session end
- **Persist state** across Claude Code sessions
- **Track metrics** for continuous improvement
- **Restore previous** session context automatically
- **Export workflows** for reuse
### Advanced Features (v2.0.0!)
- **🚀 Automatic Topology Selection** - Optimal swarm structure for each task
- **⚡ Parallel Execution** - 2.8-4.4x speed improvements
- **🧠 Neural Training** - Continuous learning from operations
- **📊 Bottleneck Analysis** - Real-time performance optimization
- **🤖 Smart Auto-Spawning** - Zero manual agent management
- **🛡️ Self-Healing Workflows** - Automatic error recovery
- **💾 Cross-Session Memory** - Persistent learning & context
- **🔗 GitHub Integration** - Repository-aware swarms
### Configuration
Hooks are pre-configured in `.claude/settings.json`. Key features:
- Automatic agent assignment for different file types
- Code formatting on save
- Neural pattern learning from edits
- Session state persistence
- Performance tracking and optimization
- Intelligent caching and token reduction
- GitHub workflow automation
See `.claude/commands/` for detailed documentation on all features.
## Integration Tips
1. **Start Simple**: Begin with basic swarm init and single agent
2. **Scale Gradually**: Add more agents as task complexity increases
3. **Use Memory**: Store important decisions and context
4. **Monitor Progress**: Regular status checks ensure effective coordination
5. **Train Patterns**: Let neural agents learn from successful coordinations
6. **Enable Hooks**: Use the pre-configured hooks for automation
7. **GitHub First**: Use GitHub tools for repository management
## 🧠 SWARM ORCHESTRATION PATTERN
### You are the SWARM ORCHESTRATOR. **IMMEDIATELY SPAWN AGENTS IN PARALLEL** to execute tasks
### 🚨 CRITICAL INSTRUCTION: You are the SWARM ORCHESTRATOR
**MANDATORY**: When using swarms, you MUST:
1. **SPAWN ALL AGENTS IN ONE BATCH** - Use multiple tool calls in a SINGLE message
2. **EXECUTE TASKS IN PARALLEL** - Never wait for one task before starting another
3. **USE BATCHTOOL FOR EVERYTHING** - Multiple operations = Single message with multiple tools
4. **ALL AGENTS MUST USE COORDINATION TOOLS** - Every spawned agent MUST use Claude Flow hooks and memory
## 📋 MANDATORY AGENT COORDINATION PROTOCOL
### 🔴 CRITICAL: Every Agent MUST Follow This Protocol
When you spawn an agent using the Task tool, that agent MUST:
**1️⃣ BEFORE Starting Work:**
```bash
# Check previous work and load context
npx claude-flow hook pre-task --description "[agent task]" --auto-spawn-agents false
npx claude-flow hook session-restore --session-id "swarm-[id]" --load-memory true
```
**2️⃣ DURING Work (After EVERY Major Step):**
```bash
# Store progress in memory after each file operation
npx claude-flow hook post-edit --file "[filepath]" --memory-key "swarm/[agent]/[step]"
# Store decisions and findings
npx claude-flow hook notification --message "[what was done]" --telemetry true
# Check coordination with other agents
npx claude-flow hook pre-search --query "[what to check]" --cache-results true
```
**3️⃣ AFTER Completing Work:**
```bash
# Save all results and learnings
npx claude-flow hook post-task --task-id "[task]" --analyze-performance true
npx claude-flow hook session-end --export-metrics true --generate-summary true
```
### 🎯 AGENT PROMPT TEMPLATE
When spawning agents, ALWAYS include these coordination instructions:
```
You are the [Agent Type] agent in a coordinated swarm.
MANDATORY COORDINATION:
1. START: Run `npx claude-flow hook pre-task --description "[your task]"`
2. DURING: After EVERY file operation, run `npx claude-flow hook post-edit --file "[file]" --memory-key "agent/[step]"`
3. MEMORY: Store ALL decisions using `npx claude-flow hook notification --message "[decision]"`
4. END: Run `npx claude-flow hook post-task --task-id "[task]" --analyze-performance true`
Your specific task: [detailed task description]
REMEMBER: Coordinate with other agents by checking memory BEFORE making decisions!
```
### ⚡ PARALLEL EXECUTION IS MANDATORY
**THIS IS WRONG ❌ (Sequential - NEVER DO THIS):**
```
Message 1: Initialize swarm
Message 2: Spawn agent 1
Message 3: Spawn agent 2
Message 4: Create file 1
Message 5: Create file 2
```
**THIS IS CORRECT ✅ (Parallel - ALWAYS DO THIS):**
```
Message 1: [BatchTool]
- mcp__claude-flow__swarm_init
- mcp__claude-flow__agent_spawn (researcher)
- mcp__claude-flow__agent_spawn (coder)
- mcp__claude-flow__agent_spawn (analyst)
- mcp__claude-flow__agent_spawn (tester)
- mcp__claude-flow__agent_spawn (coordinator)
Message 2: [BatchTool]
- Write file1.js
- Write file2.js
- Write file3.js
- Bash mkdir commands
- TodoWrite updates
```
### 🎯 MANDATORY SWARM PATTERN
When given ANY complex task with swarms:
```
STEP 1: IMMEDIATE PARALLEL SPAWN (Single Message!)
[BatchTool]:
- mcp__claude-flow__swarm_init { topology: "hierarchical", maxAgents: 8, strategy: "parallel" }
- mcp__claude-flow__agent_spawn { type: "architect", name: "System Designer" }
- mcp__claude-flow__agent_spawn { type: "coder", name: "API Developer" }
- mcp__claude-flow__agent_spawn { type: "coder", name: "Frontend Dev" }
- mcp__claude-flow__agent_spawn { type: "analyst", name: "DB Designer" }
- mcp__claude-flow__agent_spawn { type: "tester", name: "QA Engineer" }
- mcp__claude-flow__agent_spawn { type: "researcher", name: "Tech Lead" }
- mcp__claude-flow__agent_spawn { type: "coordinator", name: "PM" }
- TodoWrite { todos: [multiple todos at once] }
STEP 2: PARALLEL TASK EXECUTION (Single Message!)
[BatchTool]:
- mcp__claude-flow__task_orchestrate { task: "main task", strategy: "parallel" }
- mcp__claude-flow__memory_usage { action: "store", key: "init", value: {...} }
- Multiple Read operations
- Multiple Write operations
- Multiple Bash commands
STEP 3: CONTINUE PARALLEL WORK (Never Sequential!)
```
### 📊 VISUAL TASK TRACKING FORMAT
Use this format when displaying task progress:
```
📊 Progress Overview
├── Total Tasks: X
├── ✅ Completed: X (X%)
├── 🔄 In Progress: X (X%)
├── ⭕ Todo: X (X%)
└── ❌ Blocked: X (X%)
📋 Todo (X)
└── 🔴 001: [Task description] [PRIORITY] ▶
🔄 In progress (X)
├── 🟡 002: [Task description] ↳ X deps ▶
└── 🔴 003: [Task description] [PRIORITY] ▶
✅ Completed (X)
├── ✅ 004: [Task description]
└── ... (more completed tasks)
Priority indicators: 🔴 HIGH/CRITICAL, 🟡 MEDIUM, 🟢 LOW
Dependencies: ↳ X deps | Actionable: ▶
```
### 🎯 REAL EXAMPLE: Full-Stack App Development
**Task**: "Build a complete REST API with authentication, database, and tests"
**🚨 MANDATORY APPROACH - Everything in Parallel:**
```javascript
// ✅ CORRECT: SINGLE MESSAGE with ALL operations
[BatchTool - Message 1]:
// Initialize and spawn ALL agents at once
mcp__claude-flow__swarm_init { topology: "hierarchical", maxAgents: 8, strategy: "parallel" }
mcp__claude-flow__agent_spawn { type: "architect", name: "System Designer" }
mcp__claude-flow__agent_spawn { type: "coder", name: "API Developer" }
mcp__claude-flow__agent_spawn { type: "coder", name: "Auth Expert" }
mcp__claude-flow__agent_spawn { type: "analyst", name: "DB Designer" }
mcp__claude-flow__agent_spawn { type: "tester", name: "Test Engineer" }
mcp__claude-flow__agent_spawn { type: "coordinator", name: "Lead" }
// Update ALL todos at once
TodoWrite { todos: [
{ id: "design", content: "Design API architecture", status: "in_progress", priority: "high" },
{ id: "auth", content: "Implement authentication", status: "pending", priority: "high" },
{ id: "db", content: "Design database schema", status: "pending", priority: "high" },
{ id: "api", content: "Build REST endpoints", status: "pending", priority: "high" },
{ id: "tests", content: "Write comprehensive tests", status: "pending", priority: "medium" }
]}
// Start orchestration
mcp__claude-flow__task_orchestrate { task: "Build REST API", strategy: "parallel" }
// Store initial memory
mcp__claude-flow__memory_usage { action: "store", key: "project/init", value: { started: Date.now() } }
[BatchTool - Message 2]:
// Create ALL directories at once
Bash("mkdir -p test-app/{src,tests,docs,config}")
Bash("mkdir -p test-app/src/{models,routes,middleware,services}")
Bash("mkdir -p test-app/tests/{unit,integration}")
// Write ALL base files at once
Write("test-app/package.json", packageJsonContent)
Write("test-app/.env.example", envContent)
Write("test-app/README.md", readmeContent)
Write("test-app/src/server.js", serverContent)
Write("test-app/src/config/database.js", dbConfigContent)
[BatchTool - Message 3]:
// Read multiple files for context
Read("test-app/package.json")
Read("test-app/src/server.js")
Read("test-app/.env.example")
// Run multiple commands
Bash("cd test-app && npm install")
Bash("cd test-app && npm run lint")
Bash("cd test-app && npm test")
```
### 🚫 NEVER DO THIS (Sequential = WRONG):
```javascript
// ❌ WRONG: Multiple messages, one operation each
Message 1: mcp__claude-flow__swarm_init
Message 2: mcp__claude-flow__agent_spawn (just one agent)
Message 3: mcp__claude-flow__agent_spawn (another agent)
Message 4: TodoWrite (single todo)
Message 5: Write (single file)
// This is 5x slower and wastes swarm coordination!
```
### 🔄 MEMORY COORDINATION PATTERN
Every agent coordination step MUST use memory:
```
// After each major decision or implementation
mcp__claude-flow__memory_usage
action: "store"
key: "swarm-{id}/agent-{name}/{step}"
value: {
timestamp: Date.now(),
decision: "what was decided",
implementation: "what was built",
nextSteps: ["step1", "step2"],
dependencies: ["dep1", "dep2"]
}
// To retrieve coordination data
mcp__claude-flow__memory_usage
action: "retrieve"
key: "swarm-{id}/agent-{name}/{step}"
// To check all swarm progress
mcp__claude-flow__memory_usage
action: "list"
pattern: "swarm-{id}/*"
```
### ⚡ PERFORMANCE TIPS
1. **Batch Everything**: Never operate on single files when multiple are needed
2. **Parallel First**: Always think "what can run simultaneously?"
3. **Memory is Key**: Use memory for ALL cross-agent coordination
4. **Monitor Progress**: Use mcp__claude-flow__swarm_monitor for real-time tracking
5. **Auto-Optimize**: Let hooks handle topology and agent selection
### 🎨 VISUAL SWARM STATUS
When showing swarm status, use this format:
```
🐝 Swarm Status: ACTIVE
├── 🏗️ Topology: hierarchical
├── 👥 Agents: 6/8 active
├── ⚡ Mode: parallel execution
├── 📊 Tasks: 12 total (4 complete, 6 in-progress, 2 pending)
└── 🧠 Memory: 15 coordination points stored
Agent Activity:
├── 🟢 architect: Designing database schema...
├── 🟢 coder-1: Implementing auth endpoints...
├── 🟢 coder-2: Building user CRUD operations...
├── 🟢 analyst: Optimizing query performance...
├── 🟡 tester: Waiting for auth completion...
└── 🟢 coordinator: Monitoring progress...
```
## Claude Flow v2.0.0 Features
Claude Flow extends the base coordination with:
- **🔗 GitHub Integration** - Deep repository management
- **🎯 Project Templates** - Quick-start for common projects
- **📊 Advanced Analytics** - Detailed performance insights
- **🤖 Custom Agent Types** - Domain-specific coordinators
- **🔄 Workflow Automation** - Reusable task sequences
- **🛡️ Enhanced Security** - Safer command execution
## Support
- Documentation: https://github.com/Ejb503/claude-flow
- Issues: https://github.com/Ejb503/claude-flow/issues
- Examples: https://github.com/Ejb503/claude-flow/tree/main/examples
---
Remember: **Claude Flow coordinates, Claude Code creates!** Start with `mcp__claude-flow__swarm_init` to enhance your development workflow.
-34
View File
@@ -1,34 +0,0 @@
#!/usr/bin/env node
/**
* Claude Flow CLI - AI-Driven Development Toolkit
*
* This is the main entry point for the Claude Flow command-line interface.
* It provides powerful AI coordination capabilities for Claude Code.
*/
const { spawn } = require('child_process');
const path = require('path');
// Resolve the actual CLI path
const cliPath = path.resolve(__dirname, 'dist', 'index.js');
// Forward all arguments to the actual CLI
const child = spawn(process.execPath, [cliPath, ...process.argv.slice(2)], {
stdio: 'inherit',
env: {
...process.env,
CLAUDE_FLOW_CLI: 'true'
}
});
// Forward the exit code
child.on('exit', (code) => {
process.exit(code);
});
// Handle errors
child.on('error', (err) => {
console.error('Failed to start Claude Flow:', err);
process.exit(1);
});
-48
View File
@@ -1,48 +0,0 @@
#!/bin/bash
echo "Testing claude-flow@alpha ES Module Fix in Docker"
echo "================================================="
# Create test directory
TEST_DIR="docker-es-module-test"
mkdir -p $TEST_DIR
# Create Dockerfile
cat > $TEST_DIR/Dockerfile << 'EOF'
FROM node:22-slim
# Install git (needed for some npm operations)
RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/*
# Create test directory
WORKDIR /app
# Create ES module project
RUN echo '{"name": "test-es-module", "version": "1.0.0", "type": "module", "description": "Test ES module project"}' > package.json
# Install latest alpha version
RUN npm install claude-flow@alpha
# Run claude-flow init
RUN npx claude-flow init
# List files to verify wrapper was created
RUN ls -la
# Test the wrapper
CMD ["./claude-flow", "--version"]
EOF
# Build and run the Docker container
echo "Building Docker image..."
docker build -t claude-flow-es-test $TEST_DIR
echo ""
echo "Running Docker container..."
docker run --rm claude-flow-es-test
# Cleanup
rm -rf $TEST_DIR
echo ""
echo "Docker test complete!"
-54
View File
@@ -1,54 +0,0 @@
#!/bin/bash
echo "Testing claude-flow ES Module Fix"
echo "================================="
# Create test directory
TEST_DIR="es-module-test"
mkdir -p $TEST_DIR
# Create package.json with ES module
cat > $TEST_DIR/package.json << 'EOF'
{
"name": "test-es-module",
"version": "1.0.0",
"type": "module",
"description": "Test ES module project"
}
EOF
# Test npx directly
echo "Testing with npx claude-flow@alpha..."
cd $TEST_DIR
npx claude-flow@alpha init
# Check if wrapper was created
if [ -f "./claude-flow" ]; then
echo "✓ Wrapper created successfully"
# Check wrapper content
echo ""
echo "Wrapper content (first 20 lines):"
head -20 ./claude-flow
# Test execution
echo ""
echo "Testing wrapper execution..."
./claude-flow --version
RESULT=$?
if [ $RESULT -eq 0 ]; then
echo "✓ Wrapper executed successfully!"
else
echo "✗ Wrapper failed with exit code: $RESULT"
fi
else
echo "✗ Wrapper not created"
fi
# Cleanup
cd ..
rm -rf $TEST_DIR
echo ""
echo "Test complete!"