diff --git a/claude-flow-todo-api/.env.example b/claude-flow-todo-api/.env.example deleted file mode 100644 index 87c6e7f607..0000000000 --- a/claude-flow-todo-api/.env.example +++ /dev/null @@ -1,3 +0,0 @@ -JWT_SECRET=your-super-secret-jwt-key -PORT=3000 -NODE_ENV=development \ No newline at end of file diff --git a/claude-flow-todo-api/README.md b/claude-flow-todo-api/README.md deleted file mode 100644 index 19ab9794d6..0000000000 --- a/claude-flow-todo-api/README.md +++ /dev/null @@ -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. \ No newline at end of file diff --git a/claude-flow-todo-api/package.json b/claude-flow-todo-api/package.json deleted file mode 100644 index 31785d359d..0000000000 --- a/claude-flow-todo-api/package.json +++ /dev/null @@ -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" - } -} \ No newline at end of file diff --git a/flow-2-init/.claude/settings.json b/flow-2-init/.claude/settings.json deleted file mode 100644 index b3612851fb..0000000000 --- a/flow-2-init/.claude/settings.json +++ /dev/null @@ -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" - } -} \ No newline at end of file diff --git a/flow-2-init/.github/workflows/issue-108-monitor.yml b/flow-2-init/.github/workflows/issue-108-monitor.yml deleted file mode 100644 index 270a3bb1e1..0000000000 --- a/flow-2-init/.github/workflows/issue-108-monitor.yml +++ /dev/null @@ -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)\" - }" \ No newline at end of file diff --git a/flow-2-init/CLAUDE.md b/flow-2-init/CLAUDE.md deleted file mode 100644 index 7ad00e9bd8..0000000000 --- a/flow-2-init/CLAUDE.md +++ /dev/null @@ -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. \ No newline at end of file diff --git a/flow-2-init/architecture/claude-flow-v2-architecture.md b/flow-2-init/architecture/claude-flow-v2-architecture.md deleted file mode 100644 index ab21fb7ec0..0000000000 --- a/flow-2-init/architecture/claude-flow-v2-architecture.md +++ /dev/null @@ -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
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 - async start(): Promise - async stop(): Promise - async shutdown(): Promise - - // Swarm Operations - async createSwarm(config: SwarmConfig): Promise - async spawnAgent(type: AgentType, config: AgentConfig): Promise - async orchestrateTask(task: TaskDefinition): Promise - - // Coordination - async assignTask(taskId: TaskId, agentId: AgentId): Promise - async balanceLoad(): Promise - async handleFailure(agentId: AgentId, error: Error): Promise - - // 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 - async executeParallel(tasks: TaskDefinition[]): Promise - async executePipeline(pipeline: TaskPipeline): Promise - - // Claude CLI Integration - async spawnClaude(config: ClaudeConfig): Promise - async sendPrompt(instance: ClaudeInstance, prompt: string): Promise - async terminateClaude(instance: ClaudeInstance): Promise - - // Resource Management - async allocateResources(task: TaskDefinition): Promise - async releaseResources(allocation: ResourceAllocation): Promise - async monitorResources(): Promise - - // Error Handling - async handleTimeout(task: TaskDefinition): Promise - async handleError(task: TaskDefinition, error: Error): Promise - async retryTask(task: TaskDefinition, attempt: number): Promise -} -``` - -**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 - async retrieve(key: string): Promise - async search(query: MemoryQuery): Promise - async delete(key: string): Promise - - // Agent Memory - async getAgentMemory(agentId: AgentId): Promise - async shareMemory(from: AgentId, to: AgentId, key: string): Promise - async broadcastMemory(key: string, agents: AgentId[]): Promise - - // Knowledge Base - async createKnowledgeBase(name: string, domain: string): Promise - async updateKnowledge(kbId: KnowledgeBaseId, entry: KnowledgeEntry): Promise - async queryKnowledge(kbId: KnowledgeBaseId, query: string): Promise - - // Synchronization - async sync(): Promise - async backup(): Promise - async restore(backupId: BackupId): Promise -} -``` - -**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 - async createBranch(name: string, from: string): Promise - async createPullRequest(config: PRConfig): Promise - - // Workflow Automation - async createWorkflow(config: WorkflowConfig): Promise - async triggerWorkflow(workflowId: string): Promise - async monitorWorkflow(runId: string): Promise - - // Issue Management - async createIssue(config: IssueConfig): Promise - async updateIssue(issueId: string, update: IssueUpdate): Promise - async linkPRToIssue(prId: string, issueId: string): Promise - - // Code Review - async requestReview(prId: string, reviewers: string[]): Promise - async postReviewComment(prId: string, comment: ReviewComment): Promise - async approveChanges(prId: string): Promise -} -``` - -**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 - async generatePseudocode(spec: Specification): Promise - async designArchitecture(pseudo: Pseudocode): Promise - async refineImplementation(arch: Architecture): Promise - async completeProject(impl: Implementation): Promise - - // Mode Management - async activateMode(mode: SparcMode): Promise - async switchMode(from: SparcMode, to: SparcMode): Promise - async getModeCapabilities(mode: SparcMode): Promise -} -``` - -**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 - async recognizePattern(input: any): Promise - async suggestOptimization(context: Context): Promise - - // Performance Learning - async recordSuccess(task: TaskDefinition, result: TaskResult): Promise - async recordFailure(task: TaskDefinition, error: Error): Promise - async predictSuccess(task: TaskDefinition): Promise - - // Adaptive Behavior - async adaptStrategy(feedback: Feedback): Promise - async optimizeWorkflow(workflow: Workflow): Promise - async personalizeAgent(agentId: AgentId, preferences: Preferences): Promise -} -``` - -**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 = new Map() - - async getAgent(type: AgentType): Promise { - // Return available agent or spawn new one - } - - async releaseAgent(agentId: AgentId): Promise { - // 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 { - // Group related tasks for efficient execution - } -} -``` - -### 3. Memory Caching -```typescript -class MemoryCache { - private readonly cache = new LRUCache(1000) - private readonly ttl = 5 * 60 * 1000 // 5 minutes - - async get(key: string): Promise { - // Check cache before querying SharedMemory - } -} -``` - -## Integration Points - -### 1. Claude Code CLI Integration -```typescript -interface ClaudeCliIntegration { - // Process management - spawn(config: ClaudeConfig): Promise - kill(pid: number): Promise - - // Communication - sendPrompt(process: ChildProcess, prompt: string): Promise - readResponse(process: ChildProcess): Promise - - // Tool usage - executeTools(tools: ToolCall[]): Promise -} -``` - -### 2. ruv-swarm MCP Integration -```typescript -interface RuvSwarmIntegration { - // MCP communication - connect(config: McpConfig): Promise - callTool(tool: string, params: any): Promise - - // Memory operations - storeMemory(key: string, value: any): Promise - retrieveMemory(key: string): Promise - - // Neural features - trainPattern(pattern: Pattern): Promise - predictOutcome(input: any): Promise -} -``` - -### 3. GitHub API Integration -```typescript -interface GitHubApiIntegration { - // Authentication - authenticate(token: string): Promise - - // Repository operations - getRepo(owner: string, repo: string): Promise - createPR(config: PRConfig): Promise - - // Workflow management - createWorkflow(yaml: string): Promise - triggerWorkflow(id: string): Promise -} -``` - -## 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. \ No newline at end of file diff --git a/flow-2-init/claude-flow b/flow-2-init/claude-flow deleted file mode 100755 index da6c86a82b..0000000000 --- a/flow-2-init/claude-flow +++ /dev/null @@ -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); -}); \ No newline at end of file diff --git a/flow-2-init/scripts/issue-108-updater.cjs b/flow-2-init/scripts/issue-108-updater.cjs deleted file mode 100755 index fabccbbc2e..0000000000 --- a/flow-2-init/scripts/issue-108-updater.cjs +++ /dev/null @@ -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 }; \ No newline at end of file diff --git a/test-alpha5/.claude/commands/analysis/README.md b/test-alpha5/.claude/commands/analysis/README.md deleted file mode 100644 index 1eb295c1a8..0000000000 --- a/test-alpha5/.claude/commands/analysis/README.md +++ /dev/null @@ -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) diff --git a/test-alpha5/.claude/commands/analysis/bottleneck-detect.md b/test-alpha5/.claude/commands/analysis/bottleneck-detect.md deleted file mode 100644 index 0cee44d1db..0000000000 --- a/test-alpha5/.claude/commands/analysis/bottleneck-detect.md +++ /dev/null @@ -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 ` - Analyze specific swarm (default: current) -- `--time-range, -t ` - Analysis period: 1h, 24h, 7d, all (default: 1h) -- `--threshold ` - Bottleneck threshold percentage (default: 20) -- `--export, -e ` - 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 \ No newline at end of file diff --git a/test-alpha5/.claude/commands/analysis/performance-report.md b/test-alpha5/.claude/commands/analysis/performance-report.md deleted file mode 100644 index 04b8d9e9ac..0000000000 --- a/test-alpha5/.claude/commands/analysis/performance-report.md +++ /dev/null @@ -1,25 +0,0 @@ -# performance-report - -Generate comprehensive performance reports for swarm operations. - -## Usage -```bash -npx claude-flow analysis performance-report [options] -``` - -## Options -- `--format ` - Report format (json, html, markdown) -- `--include-metrics` - Include detailed metrics -- `--compare ` - 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 -``` diff --git a/test-alpha5/.claude/commands/analysis/token-usage.md b/test-alpha5/.claude/commands/analysis/token-usage.md deleted file mode 100644 index 5d6f2b9cff..0000000000 --- a/test-alpha5/.claude/commands/analysis/token-usage.md +++ /dev/null @@ -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