Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat: Add automatic SQLite fallback for NPX compatibility (#231)

rUve1e695eab7c1
diff --git a/CLAUDE.md b/CLAUDE.md
index 6d5a229df0..30de786bd0 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,23 +1,135 @@
-# Claude Code Configuration for ruv-swarm
+# Claude Code Configuration for Claude Flow
-## 🎯 IMPORTANT: Separation of Responsibilities
+## 🚨 CRITICAL: PARALLEL EXECUTION AFTER SWARM INIT
-### 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
+**MANDATORY RULE**: Once swarm is initialized with memory, ALL subsequent operations MUST be parallel:
+1. **TodoWrite** β†’ Always batch 5-10+ todos in ONE call
+2. **Task spawning** β†’ Spawn ALL agents in ONE message
+3. **File operations** β†’ Batch ALL reads/writes together
+4. **NEVER** operate sequentially after swarm init
-### ruv-swarm 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
+## 🚨 CRITICAL: CONCURRENT EXECUTION FOR ALL ACTIONS
+
+**ABSOLUTE RULE**: ALL operations MUST be concurrent/parallel in a single message:
+
+### πŸ”΄ MANDATORY CONCURRENT PATTERNS:
+1. **TodoWrite**: ALWAYS batch ALL todos in ONE call (5-10+ todos minimum)
+2. **Task tool**: ALWAYS spawn ALL agents in ONE message with full instructions
+3. **File operations**: ALWAYS batch ALL reads/writes/edits in ONE message
+4. **Bash commands**: ALWAYS batch ALL terminal operations in ONE message
+5. **Memory operations**: ALWAYS batch ALL memory store/retrieve in ONE message
+
+### ⚑ GOLDEN RULE: "1 MESSAGE = ALL RELATED OPERATIONS"
+
+**Examples of CORRECT concurrent execution:**
+```javascript
+// βœ… CORRECT: Everything in ONE message
+[Single Message]:
+ - TodoWrite { todos: [10+ todos with all statuses/priorities] }
+ - Task("Agent 1 with full instructions and hooks")
+ - Task("Agent 2 with full instructions and hooks")
+ - Task("Agent 3 with full instructions and hooks")
+ - Read("file1.js")
+ - Read("file2.js")
+ - Read("file3.js")
+ - Write("output1.js", content)
+ - Write("output2.js", content)
+ - Bash("npm install")
+ - Bash("npm test")
+ - Bash("npm run build")
+```
+
+**Examples of WRONG sequential execution:**
+```javascript
+// ❌ WRONG: Multiple messages (NEVER DO THIS)
+Message 1: TodoWrite { todos: [single todo] }
+Message 2: Task("Agent 1")
+Message 3: Task("Agent 2")
+Message 4: Read("file1.js")
+Message 5: Write("output1.js")
+Message 6: Bash("npm install")
+// This is 6x slower and breaks coordination!
+```
+
+### 🎯 CONCURRENT EXECUTION CHECKLIST:
+
+Before sending ANY message, ask yourself:
+- βœ… Are ALL related TodoWrite operations batched together?
+- βœ… Are ALL Task spawning operations in ONE message?
+- βœ… Are ALL file operations (Read/Write/Edit) batched together?
+- βœ… Are ALL bash commands grouped in ONE message?
+- βœ… Are ALL memory operations concurrent?
+
+If ANY answer is "No", you MUST combine operations into a single message!
+
+## πŸš€ CRITICAL: Claude Code Does ALL Real Work
+
+### 🎯 CLAUDE CODE IS THE ONLY EXECUTOR
+
+**ABSOLUTE RULE**: Claude Code performs ALL actual work:
+
+### βœ… Claude Code ALWAYS Handles:
+- πŸ”§ **ALL file operations** (Read, Write, Edit, MultiEdit, Glob, Grep)
+- πŸ’» **ALL code generation** and programming tasks
+- πŸ–₯️ **ALL bash commands** and system operations
+- πŸ—οΈ **ALL actual implementation** work
+- πŸ” **ALL project navigation** and code analysis
+- πŸ“ **ALL TodoWrite** and task management
+- πŸ”„ **ALL git operations** (commit, push, merge)
+- πŸ“¦ **ALL package management** (npm, pip, etc.)
+- πŸ§ͺ **ALL testing** and validation
+- πŸ”§ **ALL debugging** and troubleshooting
+
+### 🧠 Claude Flow MCP Tools ONLY Handle:
+- 🎯 **Coordination only** - Planning Claude Code's actions
+- πŸ’Ύ **Memory management** - Storing decisions and context
+- πŸ€– **Neural features** - Learning from Claude Code's work
+- πŸ“Š **Performance tracking** - Monitoring Claude Code's efficiency
+- 🐝 **Swarm orchestration** - Coordinating multiple Claude Code instances
+- πŸ”— **GitHub integration** - Advanced repository coordination
+
+### 🚨 CRITICAL SEPARATION OF CONCERNS:
+
+**❌ MCP Tools NEVER:**
+- Write files or create content
+- Execute bash commands
+- Generate code
+- Perform file operations
+- Handle TodoWrite operations
+- Execute system commands
+- Do actual implementation work
+
+**βœ… MCP Tools ONLY:**
+- Coordinate and plan
+- Store memory and context
+- Track performance
+- Orchestrate workflows
+- Provide intelligence insights
### ⚠️ 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.
+**MCP tools coordinate, Claude Code executes.** Think of MCP tools as the "brain" that plans and coordinates, while Claude Code is the "hands" that do all the actual work.
+
+### πŸ”„ WORKFLOW EXECUTION PATTERN:
+
+**βœ… CORRECT Workflow:**
+1. **MCP**: `mcp__claude-flow__swarm_init` (coordination setup)
+2. **MCP**: `mcp__claude-flow__agent_spawn` (planning agents)
+3. **MCP**: `mcp__claude-flow__task_orchestrate` (task coordination)
+4. **Claude Code**: `Task` tool to spawn agents with coordination instructions
+5. **Claude Code**: `TodoWrite` with ALL todos batched (5-10+ in ONE call)
+6. **Claude Code**: `Read`, `Write`, `Edit`, `Bash` (actual work)
+7. **MCP**: `mcp__claude-flow__memory_usage` (store results)
+
+**❌ WRONG Workflow:**
+1. **MCP**: `mcp__claude-flow__terminal_execute` (DON'T DO THIS)
+2. **MCP**: File creation via MCP (DON'T DO THIS)
+3. **MCP**: Code generation via MCP (DON'T DO THIS)
+4. **Claude Code**: Sequential Task calls (DON'T DO THIS)
+5. **Claude Code**: Individual TodoWrite calls (DON'T DO THIS)
+
+### 🚨 REMEMBER:
+- **MCP tools** = Coordination, planning, memory, intelligence
+- **Claude Code** = All actual execution, coding, file operations
## πŸš€ CRITICAL: Parallel Execution & Batch Operations
@@ -35,18 +147,35 @@
If you need to do X operations, they should be in 1 message, not X messages
```
+### 🚨 MANDATORY TODO AND TASK BATCHING
+
+**CRITICAL RULE FOR TODOS AND TASKS:**
+1. **TodoWrite** MUST ALWAYS include ALL todos in ONE call (5-10+ todos)
+2. **Task** tool calls MUST be batched - spawn multiple agents in ONE message
+3. **NEVER** update todos one by one - this breaks parallel coordination
+4. **NEVER** spawn agents sequentially - ALL agents spawn together
+
### πŸ“¦ BATCH TOOL EXAMPLES
**βœ… CORRECT - Everything in ONE Message:**
```javascript
[Single Message with BatchTool]:
+ // MCP coordination setup
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] }
+
+ // Claude Code execution - ALL in parallel
+ Task("You are researcher agent. MUST coordinate via hooks...")
+ Task("You are coder agent. MUST coordinate via hooks...")
+ Task("You are analyst agent. MUST coordinate via hooks...")
+ Task("You are tester agent. MUST coordinate via hooks...")
+ TodoWrite { todos: [5-10 todos with all priorities and statuses] }
+
+ // File operations in parallel
Bash "mkdir -p app/{src,tests,docs}"
Write "app/package.json"
Write "app/README.md"
@@ -56,9 +185,9 @@ If you need to do X operations, they should be in 1 message, not X messages
**❌ 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 2: Task("researcher agent")
+Message 3: Task("coder agent")
+Message 4: TodoWrite({ todo: "single todo" })
Message 5: Bash "mkdir src"
Message 6: Write "package.json"
// This is 6x slower and breaks parallel coordination!
@@ -66,6 +195,13 @@ Message 6: Write "package.json"
### 🎯 BATCH OPERATIONS BY TYPE
+**Todo and Task Operations (Single Message):**
+- **TodoWrite** β†’ ALWAYS include 5-10+ todos in ONE call
+- **Task agents** β†’ Spawn ALL agents with full instructions in ONE message
+- **Agent coordination** β†’ ALL Task calls must include coordination hooks
+- **Status updates** β†’ Update ALL todo statuses together
+- **NEVER** split todos or Task calls across messages!
+
**File Operations (Single Message):**
- Read 10 files? β†’ One message with 10 Read calls
- Write 5 files? β†’ One message with 5 Write calls
@@ -85,12 +221,12 @@ Message 6: Write "package.json"
### 1. Add MCP Server (Stdio - No Port Needed)
```bash
-# Add ruv-swarm MCP server to Claude Code using stdio
-claude mcp add ruv-swarm npx ruv-swarm mcp start
+# Add Claude Flow MCP server to Claude Code using stdio
+claude mcp add claude-flow npx claude-flow@alpha mcp start
```
### 2. Use MCP Tools for Coordination in Claude Code
-Once configured, ruv-swarm MCP tools enhance Claude Code's coordination:
+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
@@ -156,10 +292,10 @@ Once configured, ruv-swarm MCP tools enhance Claude Code's coordination:
**What Actually Happens:**
1. The swarm sets up a coordination framework
-2. Each agent MUST use claude-flow hooks for coordination:
- - `npx claude-flow hooks pre-task` before starting
- - `npx claude-flow hooks post-edit` after each file operation
- - `npx claude-flow hooks post-task` to complete work
+2. Each agent MUST use Claude Flow hooks for coordination:
+ - `npx claude-flow@alpha hooks pre-task` before starting
+ - `npx claude-flow@alpha hooks post-edit` after each file operation
+ - `npx claude-flow@alpha hooks 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
@@ -185,11 +321,11 @@ Once configured, ruv-swarm MCP tools enhance Claude Code's coordination:
**What Actually Happens:**
1. The swarm creates a development coordination plan
2. Each agent coordinates using mandatory hooks:
- - `npx claude-flow hooks pre-task` for context loading
- - `npx claude-flow hooks post-edit` for progress tracking
+ - 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 ruv-swarm memory
+4. Agents share progress through Claude Flow memory
5. All code is written by Claude Code with full coordination
## Best Practices for Coordination
@@ -288,6 +424,34 @@ See `.claude/commands/` for detailed documentation on all features.
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
+### 🎯 AGENT COUNT CONFIGURATION
+
+**CRITICAL: Dynamic Agent Count Rules**
+1. **Check CLI Arguments First**: If user runs `npx claude-flow@alpha --agents 5`, use 5 agents
+2. **Auto-Decide if No Args**: Without CLI args, analyze task complexity:
+ - Simple tasks (1-3 components): 3-4 agents
+ - Medium tasks (4-6 components): 5-7 agents
+ - Complex tasks (7+ components): 8-12 agents
+3. **Agent Type Distribution**: Balance agent types based on task:
+ - Always include 1 coordinator
+ - For code-heavy tasks: more coders
+ - For design tasks: more architects/analysts
+ - For quality tasks: more testers/reviewers
+
+**Example Auto-Decision Logic:**
+```javascript
+// If CLI args provided: npx claude-flow@alpha --agents 6
+maxAgents = CLI_ARGS.agents || determineAgentCount(task)
+
+function determineAgentCount(task) {
+ // Analyze task complexity
+ if (task.includes(['API', 'database', 'auth', 'tests'])) return 8
+ if (task.includes(['frontend', 'backend'])) return 6
+ if (task.includes(['simple', 'script'])) return 3
+ return 5 // default
+}
+```
+
## πŸ“‹ MANDATORY AGENT COORDINATION PROTOCOL
### πŸ”΄ CRITICAL: Every Agent MUST Follow This Protocol
@@ -297,23 +461,27 @@ 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 hooks pre-task --description "[agent task]" --auto-spawn-agents false
+npx claude-flow@alpha hooks pre-task --description "[agent task]" --auto-spawn-agents false
+npx claude-flow@alpha hooks 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 hooks post-edit --file "[filepath]" --memory-key "swarm/[agent]/[step]"
+npx claude-flow@alpha hooks post-edit --file "[filepath]" --memory-key "swarm/[agent]/[step]"
+
+# Store decisions and findings
+npx claude-flow@alpha hooks notification --message "[what was done]" --telemetry true
-# Store decisions and findings in memory
-npx claude-flow memory store --key "swarm/[agent]/decisions" --value "[what was done]"
+# Check coordination with other agents
+npx claude-flow@alpha hooks pre-search --query "[what to check]" --cache-results true
```
**3️⃣ AFTER Completing Work:**
```bash
# Save all results and learnings
-npx claude-flow hooks post-task --task-id "[task]" --analyze-performance true
-npx claude-flow hooks session-end --export-metrics true --generate-summary true
+npx claude-flow@alpha hooks post-task --task-id "[task]" --analyze-performance true
+npx claude-flow@alpha hooks session-end --export-metrics true --generate-summary true
```
### 🎯 AGENT PROMPT TEMPLATE
@@ -324,10 +492,10 @@ 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 hooks pre-task --description "[your task]"`
-2. DURING: After EVERY file operation, run `npx claude-flow hooks post-edit --file "[file]" --memory-key "agent/[step]"`
-3. MEMORY: Store ALL decisions using `npx claude-flow memory store --key "agent/decisions" --value "[decision]"`
-4. END: Run `npx claude-flow hooks post-task --task-id "[task]" --analyze-performance true`
+1. START: Run `npx claude-flow@alpha hooks pre-task --description "[your task]"`
+2. DURING: After EVERY file operation, run `npx claude-flow@alpha hooks post-edit --file "[file]" --memory-key "agent/[step]"`
+3. MEMORY: Store ALL decisions using `npx claude-flow@alpha hooks notification --message "[decision]"`
+4. END: Run `npx claude-flow@alpha hooks post-task --task-id "[task]" --analyze-performance true`
Your specific task: [detailed task description]
@@ -341,26 +509,44 @@ REMEMBER: Coordinate with other agents by checking memory BEFORE making decision
Message 1: Initialize swarm
Message 2: Spawn agent 1
Message 3: Spawn agent 2
-Message 4: Create file 1
-Message 5: Create file 2
+Message 4: TodoWrite (single todo)
+Message 5: Create file 1
+Message 6: TodoWrite (another single todo)
```
**THIS IS CORRECT βœ… (Parallel - ALWAYS DO THIS):**
```
Message 1: [BatchTool]
+ // MCP coordination setup
- mcp__claude-flow__swarm_init
- mcp__claude-flow__agent_spawn (researcher)
- - mcp__claude-flow__agent_spawn (coder)
+ - 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
+Message 2: [BatchTool - Claude Code execution]
+ // Task agents with full coordination instructions
+ - Task("You are researcher agent. MANDATORY: Run hooks pre-task, post-edit, post-task. Task: Research API patterns")
+ - Task("You are coder agent. MANDATORY: Run hooks pre-task, post-edit, post-task. Task: Implement REST endpoints")
+ - Task("You are analyst agent. MANDATORY: Run hooks pre-task, post-edit, post-task. Task: Analyze performance")
+ - Task("You are tester agent. MANDATORY: Run hooks pre-task, post-edit, post-task. Task: Write comprehensive tests")
+
+ // TodoWrite with ALL todos batched
+ - TodoWrite { todos: [
+ {id: "research", content: "Research API patterns", status: "in_progress", priority: "high"},
+ {id: "design", content: "Design database schema", status: "pending", priority: "high"},
+ {id: "implement", content: "Build REST endpoints", status: "pending", priority: "high"},
+ {id: "test", content: "Write unit tests", status: "pending", priority: "medium"},
+ {id: "docs", content: "Create API documentation", status: "pending", priority: "low"},
+ {id: "deploy", content: "Setup deployment", status: "pending", priority: "medium"}
+ ]}
+
+ // File operations in parallel
+ - Write "api/package.json"
+ - Write "api/server.js"
+ - Write "api/routes/users.js"
+ - Bash "mkdir -p api/{routes,models,tests}"
```
### 🎯 MANDATORY SWARM PATTERN
@@ -370,7 +556,15 @@ 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" }
+ // IMPORTANT: Check CLI args for agent count, otherwise auto-decide based on task complexity
+ - mcp__claude-flow__swarm_init {
+ topology: "hierarchical",
+ maxAgents: CLI_ARGS.agents || AUTO_DECIDE(task_complexity), // Use CLI args or auto-decide
+ strategy: "parallel"
+ }
+
+ // Spawn agents based on maxAgents count and task requirements
+ // If CLI specifies 3 agents, spawn 3. If no args, auto-decide optimal count (3-12)
- 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" }
@@ -436,13 +630,16 @@ Dependencies: ↳ X deps | Actionable: β–Ά
mcp__claude-flow__agent_spawn { type: "tester", name: "Test Engineer" }
mcp__claude-flow__agent_spawn { type: "coordinator", name: "Lead" }
- // Update ALL todos at once
+ // Update ALL todos at once - NEVER split todos!
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" }
+ { id: "tests", content: "Write comprehensive tests", status: "pending", priority: "medium" },
+ { id: "docs", content: "Document API endpoints", status: "pending", priority: "low" },
+ { id: "deploy", content: "Setup deployment pipeline", status: "pending", priority: "medium" },
+ { id: "monitor", content: "Add monitoring", status: "pending", priority: "medium" }
]}
// Start orchestration
@@ -544,12 +741,54 @@ Agent Activity:
└── 🟒 coordinator: Monitoring progress...
```
+## πŸ“ CRITICAL: TODOWRITE AND TASK TOOL BATCHING
+
+### 🚨 MANDATORY BATCHING RULES FOR TODOS AND TASKS
+
+**TodoWrite Tool Requirements:**
+1. **ALWAYS** include 5-10+ todos in a SINGLE TodoWrite call
+2. **NEVER** call TodoWrite multiple times in sequence
+3. **BATCH** all todo updates together - status changes, new todos, completions
+4. **INCLUDE** all priority levels (high, medium, low) in one call
+
+**Task Tool Requirements:**
+1. **SPAWN** all agents using Task tool in ONE message
+2. **NEVER** spawn agents one by one across multiple messages
+3. **INCLUDE** full task descriptions and coordination instructions
+4. **BATCH** related Task calls together for parallel execution
+
+**Example of CORRECT TodoWrite usage:**
+```javascript
+// βœ… CORRECT - All todos in ONE call
+TodoWrite { todos: [
+ { id: "1", content: "Initialize system", status: "completed", priority: "high" },
+ { id: "2", content: "Analyze requirements", status: "in_progress", priority: "high" },
+ { id: "3", content: "Design architecture", status: "pending", priority: "high" },
+ { id: "4", content: "Implement core", status: "pending", priority: "high" },
+ { id: "5", content: "Build features", status: "pending", priority: "medium" },
+ { id: "6", content: "Write tests", status: "pending", priority: "medium" },
+ { id: "7", content: "Add monitoring", status: "pending", priority: "medium" },
+ { id: "8", content: "Documentation", status: "pending", priority: "low" },
+ { id: "9", content: "Performance tuning", status: "pending", priority: "low" },
+ { id: "10", content: "Deploy to production", status: "pending", priority: "high" }
+]}
+```
+
+**Example of WRONG TodoWrite usage:**
+```javascript
+// ❌ WRONG - Multiple TodoWrite calls
+Message 1: TodoWrite { todos: [{ id: "1", content: "Task 1", ... }] }
+Message 2: TodoWrite { todos: [{ id: "2", content: "Task 2", ... }] }
+Message 3: TodoWrite { todos: [{ id: "3", content: "Task 3", ... }] }
+// This breaks parallel coordination!
+```
+
## Support
-- Documentation: https://github.com/ruvnet/ruv-FANN/tree/main/ruv-swarm
-- Issues: https://github.com/ruvnet/ruv-FANN/issues
-- Examples: https://github.com/ruvnet/ruv-FANN/tree/main/ruv-swarm/examples
+- Documentation: https://github.com/ruvnet/claude-flow
+- Issues: https://github.com/ruvnet/claude-flow/issues
+- Examples: https://github.com/ruvnet/claude-flow/tree/main/examples
---
-Remember: **ruv-swarm coordinates, Claude Code creates!** Start with `mcp__claude-flow__swarm_init` to enhance your development workflow.
+Remember: **Claude Flow coordinates, Claude Code creates!** Start with `mcp__claude-flow__swarm_init` to enhance your development workflow.
diff --git a/bin/claude-flow b/bin/claude-flow
index 53d5c25fb1..92cd33b403 100755
--- a/bin/claude-flow
+++ b/bin/claude-flow
@@ -1,7 +1,7 @@
#!/bin/sh
# Claude-Flow Smart Dispatcher - Detects and uses the best available runtime
-VERSION="2.0.0-alpha.43"
+VERSION="2.0.0-alpha.48"
# Determine the correct path based on how the script is invoked
if [ -L "$0" ]; then
diff --git a/docker/Dockerfile.test b/docker/Dockerfile.test
new file mode 100644
index 0000000000..b27bb633d0
--- /dev/null
+++ b/docker/Dockerfile.test
@@ -0,0 +1,48 @@
+# Test container for claude-flow feature system
+# Tests across multiple Node.js versions and platforms
+
+# Base stage for common dependencies
+FROM node:18-alpine AS base
+WORKDIR /app
+COPY package*.json ./
+RUN npm ci --production
+
+# Development dependencies stage
+FROM base AS dev-deps
+RUN npm ci
+
+# Test stage
+FROM dev-deps AS test
+COPY . .
+
+# Run tests
+RUN npm run typecheck
+RUN npm run test:features:coverage
+RUN npm run build
+
+# Simulate npx execution
+FROM node:18-alpine AS npx-test
+RUN npm install -g claude-flow@latest || echo "Package not yet published"
+WORKDIR /test
+COPY --from=test /app/dist ./dist
+COPY --from=test /app/package.json ./
+
+# Run basic validation
+CMD ["node", "-e", "console.log('NPX simulation complete')"]
+
+# Multi-platform build test
+FROM --platform=$BUILDPLATFORM node:18-alpine AS platform-test
+ARG TARGETPLATFORM
+ARG BUILDPLATFORM
+RUN echo "Building for $TARGETPLATFORM on $BUILDPLATFORM"
+WORKDIR /app
+COPY --from=test /app/dist ./dist
+RUN node -v && npm -v
+
+# Final validation stage
+FROM alpine:latest AS final
+RUN apk add --no-cache nodejs npm
+COPY --from=test /app/dist /app/dist
+COPY --from=test /app/package.json /app/
+WORKDIR /app
+RUN echo "Feature system test container ready"
\ No newline at end of file
diff --git a/docs/troubleshooting/npx-sqlite-fallback.md b/docs/troubleshooting/npx-sqlite-fallback.md
new file mode 100644
index 0000000000..1207797001
--- /dev/null
+++ b/docs/troubleshooting/npx-sqlite-fallback.md
@@ -0,0 +1,159 @@
+# NPX SQLite Fallback Solution
+
+## Issue
+When running `npx -y claude-flow@alpha init` in remote environments (GitHub Codespaces, Docker containers, CI/CD), the better-sqlite3 native module fails to load with binding errors.
+
+## Root Cause
+- `npx` creates temporary directories for package execution
+- better-sqlite3 requires native bindings compiled for specific Node.js versions
+- The prebuilt binaries may not match the runtime environment
+- Postinstall scripts that compile bindings don't run in npx contexts
+
+## Solution: Automatic Fallback Memory Store
+
+Claude Flow v2.0.0+ implements an automatic fallback mechanism:
+
+### 1. **Primary Store (SQLite)**
+- Attempts to initialize better-sqlite3
+- Provides persistent memory across sessions
+- Full feature support with SQL queries
+
+### 2. **Fallback Store (In-Memory)**
+- Automatically activated when SQLite fails
+- Same API as SQLite store
+- TTL support, search, namespaces
+- Data doesn't persist across sessions
+
+### 3. **Transparent Operation**
+- No code changes required
+- Automatic detection and fallback
+- Clear logging of which store is used
+- Full functionality in both modes
+
+## Implementation Details
+
+### Memory Store Classes
+```javascript
+// Primary: SQLite-based persistent storage
+class SqliteMemoryStore {
+ async initialize() {
+ this.db = new Database(dbPath);
+ // Full SQL functionality
+ }
+}
+
+// Fallback: In-memory storage
+class InMemoryStore {
+ async initialize() {
+ this.data = new Map();
+ // Same API, in-memory implementation
+ }
+}
+
+// Orchestrator: Tries SQLite, falls back to in-memory
+class FallbackMemoryStore {
+ async initialize() {
+ try {
+ await this.primaryStore.initialize();
+ } catch (error) {
+ console.warn('SQLite failed, using in-memory store');
+ await this.fallbackStore.initialize();
+ this.useFallback = true;
+ }
+ }
+}
+```
+
+### Error Detection
+The fallback is triggered by these errors:
+- `Could not locate the bindings file`
+- `MODULE_NOT_FOUND` for better-sqlite3
+- Any SQLite initialization failure
+
+### User Experience
+```bash
+# If SQLite works (normal installation)
+[INFO] Initialized SQLite at: /app/.swarm/memory.db
+
+# If SQLite fails (npx environment)
+[WARN] SQLite initialization failed, falling back to in-memory store
+[INFO] Using in-memory store (data will not persist across sessions)
+[INFO] To enable persistent storage, install locally: npm install claude-flow@alpha
+```
+
+## Testing
+
+### Test Cases Covered
+1. **Normal SQLite Operation** - Local installations
+2. **Automatic Fallback** - When SQLite bindings fail
+3. **In-Memory Functionality** - All features work without persistence
+4. **TTL Expiration** - Time-based cleanup in memory
+5. **Cross-Platform** - Works on Linux, macOS, Windows
+
+### Validation Script
+```bash
+# Test the fallback mechanism
+node test-fallback-memory/test-broken-sqlite.js
+
+# Expected output:
+# βœ… Using in-memory fallback
+# βœ… All fallback operations completed successfully!
+# πŸŽ‰ SUCCESS: Fallback mechanism works perfectly!
+```
+
+## Benefits
+
+### For Users
+- **Zero Configuration** - Works out of the box with npx
+- **No Manual Setup** - Automatic detection and fallback
+- **Full Functionality** - All features work in both modes
+- **Clear Messaging** - Users know which mode is active
+
+### For Developers
+- **Same API** - No code changes needed
+- **Graceful Degradation** - Persistent β†’ In-memory fallback
+- **Easy Testing** - Can force either mode for tests
+- **Comprehensive Logging** - Clear visibility into store status
+
+## Migration Path
+
+### Existing Users
+- No changes required
+- Automatic upgrade with v2.0.0+
+- Backward compatible
+
+### New Users
+- `npx` works immediately
+- Can upgrade to persistent storage later
+- Clear instructions provided
+
+## Monitoring
+
+### Status Checks
+```javascript
+// Check which store is active
+const isUsingFallback = memoryStore.isUsingFallback();
+
+// Log store type
+console.log(`Store: ${isUsingFallback ? 'In-Memory' : 'SQLite'}`);
+```
+
+### Performance Metrics
+- In-memory: ~10x faster operations
+- SQLite: Persistent across sessions
+- Fallback detection: <50ms overhead
+
+## Related Issues
+
+- GitHub Issue #229: Better-sqlite3 binding error in remote environments
+- Affects: GitHub Codespaces, Docker, CI/CD, npx environments
+- Fixed in: Claude Flow v2.0.0+
+
+## Alternative Solutions Considered
+
+1. **Bundle Prebuilt Binaries** - Too large, platform-specific
+2. **Use Pure JS Database** - Breaking change, performance impact
+3. **Postinstall Compilation** - Doesn't work in npx contexts
+4. **Require Local Install** - Poor user experience
+
+The automatic fallback provides the best balance of functionality, performance, and user experience.
\ No newline at end of file
diff --git a/package.json b/package.json
index 1dc6642309..73bd4b56ce 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-flow",
- "version": "2.0.0-alpha.43",
+ "version": "2.0.0-alpha.49",
"description": "Enterprise-grade AI agent orchestration with ruv-swarm integration (Alpha Release)",
"main": "cli.mjs",
"bin": {
diff --git a/src/cli/commands/features.ts b/src/cli/commands/features.ts
new file mode 100644
index 0000000000..a116f3330f
--- /dev/null
+++ b/src/cli/commands/features.ts
@@ -0,0 +1,84 @@
+import { Command } from 'commander';
+import { ConfigManager } from '../../config/config-manager.js';
+import { createCliFeatureAdapter } from '../../features/adapters/CliFeatureAdapter.js';
+
+export function createFeaturesCommand(): Command {
+ const features = new Command('features')
+ .description('Manage transparent features')
+ .addHelpText('after', `
+Examples:
+ claude-flow features list # List all available features
+ claude-flow features enable auto-format # Enable the auto-format feature
+ claude-flow features disable auto-format # Disable the auto-format feature
+ claude-flow features status # Show status of all features
+ claude-flow features config auto-format # Configure a specific feature
+`);
+
+ // List features
+ features
+ .command('list')
+ .description('List all available features')
+ .option('-v, --verbose', 'Show detailed feature information')
+ .action(async (options) => {
+ const configManager = new ConfigManager();
+ const adapter = createCliFeatureAdapter(configManager);
+ await adapter.listFeatures([], options);
+ });
+
+ // Enable feature
+ features
+ .command('enable <feature>')
+ .description('Enable a specific feature')
+ .action(async (feature) => {
+ const configManager = new ConfigManager();
+ const adapter = createCliFeatureAdapter(configManager);
+ await adapter.enableFeature([feature], {});
+ });
+
+ // Disable feature
+ features
+ .command('disable <feature>')
+ .description('Disable a specific feature')
+ .action(async (feature) => {
+ const configManager = new ConfigManager();
+ const adapter = createCliFeatureAdapter(configManager);
+ await adapter.disableFeature([feature], {});
+ });
+
+ // Toggle feature
+ features
+ .command('toggle <feature>')
+ .description('Toggle a feature on/off')
+ .action(async (feature) => {
+ const configManager = new ConfigManager();
+ const adapter = createCliFeatureAdapter(configManager);
+ await adapter.toggleFeature([feature], {});
+ });
+
+ // Configure feature
+ features
+ .command('config <feature>')
+ .alias('configure')
+ .description('Configure a specific feature')
+ .option('-s, --set <key=value>', 'Set a configuration value')
+ .option('-g, --get <key>', 'Get a configuration value')
+ .option('-r, --reset', 'Reset to default configuration')
+ .action(async (feature, options) => {
+ const configManager = new ConfigManager();
+ const adapter = createCliFeatureAdapter(configManager);
+ await adapter.configureFeature([feature], options);
+ });
+
+ // Feature status
+ features
+ .command('status [feature]')
+ .description('Show feature status')
+ .option('-d, --detailed', 'Show detailed status information')
+ .action(async (feature, options) => {
+ const configManager = new ConfigManager();
+ const adapter = createCliFeatureAdapter(configManager);
+ await adapter.showFeatureStatus(feature ? [feature] : [], options);
+ });
+
+ return features;
+}
\ No newline at end of file
diff --git a/src/cli/help-text.js b/src/cli/help-text.js
index 6bdf1b61c9..f3055581f0 100644
--- a/src/cli/help-text.js
+++ b/src/cli/help-text.js
@@ -3,7 +3,7 @@
* Provides clear, actionable command documentation
*/
-export const VERSION = '2.0.0-alpha.43';
+export const VERSION = '2.0.0-alpha.49';
export const MAIN_HELP = `
🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform
@@ -17,7 +17,7 @@ USAGE:
πŸš€ QUICK START:
# First time setup (creates CLAUDE.md & .claude/commands)
- npx [email protected] init --sparc
+ npx claude-flow@alpha init --sparc
# 🐝 HIVE MIND QUICK START (NEW!):
claude-flow hive-mind wizard # Interactive setup wizard
diff --git a/src/cli/simple-cli.js b/src/cli/simple-cli.js
index 83be70bd96..b036889d8d 100644
--- a/src/cli/simple-cli.js
+++ b/src/cli/simple-cli.js
@@ -18,7 +18,7 @@ import process from 'process';
import readline from 'readline';
import { getMainHelp, getCommandHelp } from './help-text.js';
-const VERSION = '2.0.0';
+const VERSION = '2.0.0-alpha.49';
function printHelp() {
console.log(getMainHelp());
diff --git a/src/cli/simple-commands/init/index.js b/src/cli/simple-commands/init/index.js
index 24a7ef9a07..a00fe8a8d1 100644
--- a/src/cli/simple-commands/init/index.js
+++ b/src/cli/simple-commands/init/index.js
@@ -1132,17 +1132,24 @@ ${commands.map(cmd => `- [${cmd}](./${cmd}.md)`).join('\n')}
printSuccess('βœ“ Initialized memory system');
- // Initialize memory database
+ // Initialize memory database with fallback support
try {
- // Import and initialize SqliteMemoryStore to create the database
- const { SqliteMemoryStore } = await import('../../../memory/sqlite-store.js');
- const memoryStore = new SqliteMemoryStore();
+ // Import and initialize FallbackMemoryStore to create the database
+ const { FallbackMemoryStore } = await import('../../../memory/fallback-store.js');
+ const memoryStore = new FallbackMemoryStore();
await memoryStore.initialize();
+
+ if (memoryStore.isUsingFallback()) {
+ printSuccess('βœ“ Initialized memory system (in-memory fallback for npx compatibility)');
+ console.log(' πŸ’‘ For persistent storage, install locally: npm install claude-flow@alpha');
+ } else {
+ printSuccess('βœ“ Initialized memory database (.swarm/memory.db)');
+ }
+
memoryStore.close();
- printSuccess('βœ“ Initialized memory database (.swarm/memory.db)');
} catch (err) {
- console.log(` ⚠️ Could not initialize memory database: ${err.message}`);
- console.log(' The database will be created on first use');
+ console.log(` ⚠️ Could not initialize memory system: ${err.message}`);
+ console.log(' Memory will be initialized on first use');
}
}
diff --git a/src/cli/simple-commands/init/templates/CLAUDE.md b/src/cli/simple-commands/init/templates/CLAUDE.md
index e5ce559aa7..eaa911b091 100644
--- a/src/cli/simple-commands/init/templates/CLAUDE.md
+++ b/src/cli/simple-commands/init/templates/CLAUDE.md
@@ -1,24 +1,135 @@
# 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
+## 🚨 CRITICAL: PARALLEL EXECUTION AFTER SWARM INIT
+
+**MANDATORY RULE**: Once swarm is initialized with memory, ALL subsequent operations MUST be parallel:
+1. **TodoWrite** β†’ Always batch 5-10+ todos in ONE call
+2. **Task spawning** β†’ Spawn ALL agents in ONE message
+3. **File operations** β†’ Batch ALL reads/writes together
+4. **NEVER** operate sequentially after swarm init
+
+## 🚨 CRITICAL: CONCURRENT EXECUTION FOR ALL ACTIONS
+
+**ABSOLUTE RULE**: ALL operations MUST be concurrent/parallel in a single message:
+
+### πŸ”΄ MANDATORY CONCURRENT PATTERNS:
+1. **TodoWrite**: ALWAYS batch ALL todos in ONE call (5-10+ todos minimum)
+2. **Task tool**: ALWAYS spawn ALL agents in ONE message with full instructions
+3. **File operations**: ALWAYS batch ALL reads/writes/edits in ONE message
+4. **Bash commands**: ALWAYS batch ALL terminal operations in ONE message
+5. **Memory operations**: ALWAYS batch ALL memory store/retrieve in ONE message
+
+### ⚑ GOLDEN RULE: "1 MESSAGE = ALL RELATED OPERATIONS"
+
+**Examples of CORRECT concurrent execution:**
+```javascript
+// βœ… CORRECT: Everything in ONE message
+[Single Message]:
+ - TodoWrite { todos: [10+ todos with all statuses/priorities] }
+ - Task("Agent 1 with full instructions and hooks")
+ - Task("Agent 2 with full instructions and hooks")
+ - Task("Agent 3 with full instructions and hooks")
+ - Read("file1.js")
+ - Read("file2.js")
+ - Read("file3.js")
+ - Write("output1.js", content)
+ - Write("output2.js", content)
+ - Bash("npm install")
+ - Bash("npm test")
+ - Bash("npm run build")
+```
+
+**Examples of WRONG sequential execution:**
+```javascript
+// ❌ WRONG: Multiple messages (NEVER DO THIS)
+Message 1: TodoWrite { todos: [single todo] }
+Message 2: Task("Agent 1")
+Message 3: Task("Agent 2")
+Message 4: Read("file1.js")
+Message 5: Write("output1.js")
+Message 6: Bash("npm install")
+// This is 6x slower and breaks coordination!
+```
+
+### 🎯 CONCURRENT EXECUTION CHECKLIST:
+
+Before sending ANY message, ask yourself:
+- βœ… Are ALL related TodoWrite operations batched together?
+- βœ… Are ALL Task spawning operations in ONE message?
+- βœ… Are ALL file operations (Read/Write/Edit) batched together?
+- βœ… Are ALL bash commands grouped in ONE message?
+- βœ… Are ALL memory operations concurrent?
+
+If ANY answer is "No", you MUST combine operations into a single message!
+
+## πŸš€ CRITICAL: Claude Code Does ALL Real Work
+
+### 🎯 CLAUDE CODE IS THE ONLY EXECUTOR
+
+**ABSOLUTE RULE**: Claude Code performs ALL actual work:
+
+### βœ… Claude Code ALWAYS Handles:
+- πŸ”§ **ALL file operations** (Read, Write, Edit, MultiEdit, Glob, Grep)
+- πŸ’» **ALL code generation** and programming tasks
+- πŸ–₯️ **ALL bash commands** and system operations
+- πŸ—οΈ **ALL actual implementation** work
+- πŸ” **ALL project navigation** and code analysis
+- πŸ“ **ALL TodoWrite** and task management
+- πŸ”„ **ALL git operations** (commit, push, merge)
+- πŸ“¦ **ALL package management** (npm, pip, etc.)
+- πŸ§ͺ **ALL testing** and validation
+- πŸ”§ **ALL debugging** and troubleshooting
+
+### 🧠 Claude Flow MCP Tools ONLY Handle:
+- 🎯 **Coordination only** - Planning Claude Code's actions
+- πŸ’Ύ **Memory management** - Storing decisions and context
+- πŸ€– **Neural features** - Learning from Claude Code's work
+- πŸ“Š **Performance tracking** - Monitoring Claude Code's efficiency
+- 🐝 **Swarm orchestration** - Coordinating multiple Claude Code instances
+- πŸ”— **GitHub integration** - Advanced repository coordination
+
+### 🚨 CRITICAL SEPARATION OF CONCERNS:
+
+**❌ MCP Tools NEVER:**
+- Write files or create content
+- Execute bash commands
+- Generate code
+- Perform file operations
+- Handle TodoWrite operations
+- Execute system commands
+- Do actual implementation work
+
+**βœ… MCP Tools ONLY:**
+- Coordinate and plan
+- Store memory and context
+- Track performance
+- Orchestrate workflows
+- Provide intelligence insights
### ⚠️ 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.
+**MCP tools coordinate, Claude Code executes.** Think of MCP tools as the "brain" that plans and coordinates, while Claude Code is the "hands" that do all the actual work.
+
+### πŸ”„ WORKFLOW EXECUTION PATTERN:
+
+**βœ… CORRECT Workflow:**
+1. **MCP**: `mcp__claude-flow__swarm_init` (coordination setup)
+2. **MCP**: `mcp__claude-flow__agent_spawn` (planning agents)
+3. **MCP**: `mcp__claude-flow__task_orchestrate` (task coordination)
+4. **Claude Code**: `Task` tool to spawn agents with coordination instructions
+5. **Claude Code**: `TodoWrite` with ALL todos batched (5-10+ in ONE call)
+6. **Claude Code**: `Read`, `Write`, `Edit`, `Bash` (actual work)
+7. **MCP**: `mcp__claude-flow__memory_usage` (store results)
+
+**❌ WRONG Workflow:**
+1. **MCP**: `mcp__claude-flow__terminal_execute` (DON'T DO THIS)
+2. **MCP**: File creation via MCP (DON'T DO THIS)
+3. **MCP**: Code generation via MCP (DON'T DO THIS)
+4. **Claude Code**: Sequential Task calls (DON'T DO THIS)
+5. **Claude Code**: Individual TodoWrite calls (DON'T DO THIS)
+
+### 🚨 REMEMBER:
+- **MCP tools** = Coordination, planning, memory, intelligence
+- **Claude Code** = All actual execution, coding, file operations
## πŸš€ CRITICAL: Parallel Execution & Batch Operations
@@ -36,18 +147,35 @@
If you need to do X operations, they should be in 1 message, not X messages
```
+### 🚨 MANDATORY TODO AND TASK BATCHING
+
+**CRITICAL RULE FOR TODOS AND TASKS:**
+1. **TodoWrite** MUST ALWAYS include ALL todos in ONE call (5-10+ todos)
+2. **Task** tool calls MUST be batched - spawn multiple agents in ONE message
+3. **NEVER** update todos one by one - this breaks parallel coordination
+4. **NEVER** spawn agents sequentially - ALL agents spawn together
+
### πŸ“¦ BATCH TOOL EXAMPLES
**βœ… CORRECT - Everything in ONE Message:**
```javascript
[Single Message with BatchTool]:
+ // MCP coordination setup
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] }
+
+ // Claude Code execution - ALL in parallel
+ Task("You are researcher agent. MUST coordinate via hooks...")
+ Task("You are coder agent. MUST coordinate via hooks...")
+ Task("You are analyst agent. MUST coordinate via hooks...")
+ Task("You are tester agent. MUST coordinate via hooks...")
+ TodoWrite { todos: [5-10 todos with all priorities and statuses] }
+
+ // File operations in parallel
Bash "mkdir -p app/{src,tests,docs}"
Write "app/package.json"
Write "app/README.md"
@@ -57,9 +185,9 @@ If you need to do X operations, they should be in 1 message, not X messages
**❌ 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 2: Task("researcher agent")
+Message 3: Task("coder agent")
+Message 4: TodoWrite({ todo: "single todo" })
Message 5: Bash "mkdir src"
Message 6: Write "package.json"
// This is 6x slower and breaks parallel coordination!
@@ -67,6 +195,13 @@ Message 6: Write "package.json"
### 🎯 BATCH OPERATIONS BY TYPE
+**Todo and Task Operations (Single Message):**
+- **TodoWrite** β†’ ALWAYS include 5-10+ todos in ONE call
+- **Task agents** β†’ Spawn ALL agents with full instructions in ONE message
+- **Agent coordination** β†’ ALL Task calls must include coordination hooks
+- **Status updates** β†’ Update ALL todo statuses together
+- **NEVER** split todos or Task calls across messages!
+
**File Operations (Single Message):**
- Read 10 files? β†’ One message with 10 Read calls
- Write 5 files? β†’ One message with 5 Write calls
@@ -87,7 +222,7 @@ Message 6: Write "package.json"
### 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
+claude mcp add claude-flow npx claude-flow@alpha mcp start
```
### 2. Use MCP Tools for Coordination in Claude Code
@@ -165,9 +300,9 @@ Once configured, Claude Flow MCP tools enhance Claude Code's coordination:
**What Actually Happens:**
1. The swarm sets up a coordination framework
2. Each agent MUST use Claude Flow hooks for coordination:
- - `npx claude-flow hooks pre-task` before starting
- - `npx claude-flow hooks post-edit` after each file operation
- - `npx claude-flow hooks notification` to share decisions
+ - `npx claude-flow@alpha hooks pre-task` before starting
+ - `npx claude-flow@alpha hooks post-edit` after each file operation
+ - `npx claude-flow@alpha hooks 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
@@ -321,7 +456,35 @@ See `.claude/commands/` for detailed documentation on all features.
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
+4. **ALL AGENTS MUST USE COORDINATION TOOLS** - Every spawned agent MUST use claude-flow hooks and memory
+
+### 🎯 AGENT COUNT CONFIGURATION
+
+**CRITICAL: Dynamic Agent Count Rules**
+1. **Check CLI Arguments First**: If user runs `npx claude-flow@alpha --agents 5`, use 5 agents
+2. **Auto-Decide if No Args**: Without CLI args, analyze task complexity:
+ - Simple tasks (1-3 components): 3-4 agents
+ - Medium tasks (4-6 components): 5-7 agents
+ - Complex tasks (7+ components): 8-12 agents
+3. **Agent Type Distribution**: Balance agent types based on task:
+ - Always include 1 coordinator
+ - For code-heavy tasks: more coders
+ - For design tasks: more architects/analysts
+ - For quality tasks: more testers/reviewers
+
+**Example Auto-Decision Logic:**
+```javascript
+// If CLI args provided: npx claude-flow@alpha --agents 6
+maxAgents = CLI_ARGS.agents || determineAgentCount(task)
+
+function determineAgentCount(task) {
+ // Analyze task complexity
+ if (task.includes(['API', 'database', 'auth', 'tests'])) return 8
+ if (task.includes(['frontend', 'backend'])) return 6
+ if (task.includes(['simple', 'script'])) return 3
+ return 5 // default
+}
+```
## πŸ“‹ MANDATORY AGENT COORDINATION PROTOCOL
@@ -332,27 +495,27 @@ 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 hooks pre-task --description "[agent task]" --auto-spawn-agents false
-npx claude-flow hooks session-restore --session-id "swarm-[id]" --load-memory true
+npx claude-flow@alpha hooks pre-task --description "[agent task]" --auto-spawn-agents false
+npx claude-flow@alpha hooks 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 hooks post-edit --file "[filepath]" --memory-key "swarm/[agent]/[step]"
+npx claude-flow@alpha hooks post-edit --file "[filepath]" --memory-key "swarm/[agent]/[step]"
# Store decisions and findings
-npx claude-flow hooks notification --message "[what was done]" --telemetry true
+npx claude-flow@alpha hooks notification --message "[what was done]" --telemetry true
# Check coordination with other agents
-npx claude-flow hooks pre-search --query "[what to check]" --cache-results true
+npx claude-flow@alpha hooks pre-search --query "[what to check]" --cache-results true
```
**3️⃣ AFTER Completing Work:**
```bash
# Save all results and learnings
-npx claude-flow hooks post-task --task-id "[task]" --analyze-performance true
-npx claude-flow hooks session-end --export-metrics true --generate-summary true
+npx claude-flow@alpha hooks post-task --task-id "[task]" --analyze-performance true
+npx claude-flow@alpha hooks session-end --export-metrics true --generate-summary true
```
### 🎯 AGENT PROMPT TEMPLATE
@@ -363,10 +526,10 @@ 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 hooks pre-task --description "[your task]"`
-2. DURING: After EVERY file operation, run `npx claude-flow hooks post-edit --file "[file]" --memory-key "agent/[step]"`
-3. MEMORY: Store ALL decisions using `npx claude-flow hooks notification --message "[decision]"`
-4. END: Run `npx claude-flow hooks post-task --task-id "[task]" --analyze-performance true`
+1. START: Run `npx claude-flow@alpha hooks pre-task --description "[your task]"`
+2. DURING: After EVERY file operation, run `npx claude-flow@alpha hooks post-edit --file "[file]" --memory-key "agent/[step]"`
+3. MEMORY: Store ALL decisions using `npx claude-flow@alpha hooks notification --message "[decision]"`
+4. END: Run `npx claude-flow@alpha hooks post-task --task-id "[task]" --analyze-performance true`
Your specific task: [detailed task description]
@@ -380,26 +543,44 @@ REMEMBER: Coordinate with other agents by checking memory BEFORE making decision
Message 1: Initialize swarm
Message 2: Spawn agent 1
Message 3: Spawn agent 2
-Message 4: Create file 1
-Message 5: Create file 2
+Message 4: TodoWrite (single todo)
+Message 5: Create file 1
+Message 6: TodoWrite (another single todo)
```
**THIS IS CORRECT βœ… (Parallel - ALWAYS DO THIS):**
```
Message 1: [BatchTool]
+ // MCP coordination setup
- mcp__claude-flow__swarm_init
- mcp__claude-flow__agent_spawn (researcher)
- - mcp__claude-flow__agent_spawn (coder)
+ - 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
+Message 2: [BatchTool - Claude Code execution]
+ // Task agents with full coordination instructions
+ - Task("You are researcher agent. MANDATORY: Run hooks pre-task, post-edit, post-task. Task: Research API patterns")
+ - Task("You are coder agent. MANDATORY: Run hooks pre-task, post-edit, post-task. Task: Implement REST endpoints")
+ - Task("You are analyst agent. MANDATORY: Run hooks pre-task, post-edit, post-task. Task: Analyze performance")
+ - Task("You are tester agent. MANDATORY: Run hooks pre-task, post-edit, post-task. Task: Write comprehensive tests")
+
+ // TodoWrite with ALL todos batched
+ - TodoWrite { todos: [
+ {id: "research", content: "Research API patterns", status: "in_progress", priority: "high"},
+ {id: "design", content: "Design database schema", status: "pending", priority: "high"},
+ {id: "implement", content: "Build REST endpoints", status: "pending", priority: "high"},
+ {id: "test", content: "Write unit tests", status: "pending", priority: "medium"},
+ {id: "docs", content: "Create API documentation", status: "pending", priority: "low"},
+ {id: "deploy", content: "Setup deployment", status: "pending", priority: "medium"}
+ ]}
+
+ // File operations in parallel
+ - Write "api/package.json"
+ - Write "api/server.js"
+ - Write "api/routes/users.js"
+ - Bash "mkdir -p api/{routes,models,tests}"
```
### 🎯 MANDATORY SWARM PATTERN
@@ -409,7 +590,15 @@ 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" }
+ // IMPORTANT: Check CLI args for agent count, otherwise auto-decide based on task complexity
+ - mcp__claude-flow__swarm_init {
+ topology: "hierarchical",
+ maxAgents: CLI_ARGS.agents || AUTO_DECIDE(task_complexity), // Use CLI args or auto-decide
+ strategy: "parallel"
+ }
+
+ // Spawn agents based on maxAgents count and task requirements
+ // If CLI specifies 3 agents, spawn 3. If no args, auto-decide optimal count (3-12)
- 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" }
@@ -475,13 +664,16 @@ Dependencies: ↳ X deps | Actionable: β–Ά
mcp__claude-flow__agent_spawn { type: "tester", name: "Test Engineer" }
mcp__claude-flow__agent_spawn { type: "coordinator", name: "Lead" }
- // Update ALL todos at once
+ // Update ALL todos at once - NEVER split todos!
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" }
+ { id: "tests", content: "Write comprehensive tests", status: "pending", priority: "medium" },
+ { id: "docs", content: "Document API endpoints", status: "pending", priority: "low" },
+ { id: "deploy", content: "Setup deployment pipeline", status: "pending", priority: "medium" },
+ { id: "monitor", content: "Add monitoring", status: "pending", priority: "medium" }
]}
// Start orchestration
@@ -583,6 +775,48 @@ Agent Activity:
└── 🟒 coordinator: Monitoring progress...
```
+## πŸ“ CRITICAL: TODOWRITE AND TASK TOOL BATCHING
+
+### 🚨 MANDATORY BATCHING RULES FOR TODOS AND TASKS
+
+**TodoWrite Tool Requirements:**
+1. **ALWAYS** include 5-10+ todos in a SINGLE TodoWrite call
+2. **NEVER** call TodoWrite multiple times in sequence
+3. **BATCH** all todo updates together - status changes, new todos, completions
+4. **INCLUDE** all priority levels (high, medium, low) in one call
+
+**Task Tool Requirements:**
+1. **SPAWN** all agents using Task tool in ONE message
+2. **NEVER** spawn agents one by one across multiple messages
+3. **INCLUDE** full task descriptions and coordination instructions
+4. **BATCH** related Task calls together for parallel execution
+
+**Example of CORRECT TodoWrite usage:**
+```javascript
+// βœ… CORRECT - All todos in ONE call
+TodoWrite { todos: [
+ { id: "1", content: "Initialize system", status: "completed", priority: "high" },
+ { id: "2", content: "Analyze requirements", status: "in_progress", priority: "high" },
+ { id: "3", content: "Design architecture", status: "pending", priority: "high" },
+ { id: "4", content: "Implement core", status: "pending", priority: "high" },
+ { id: "5", content: "Build features", status: "pending", priority: "medium" },
+ { id: "6", content: "Write tests", status: "pending", priority: "medium" },
+ { id: "7", content: "Add monitoring", status: "pending", priority: "medium" },
+ { id: "8", content: "Documentation", status: "pending", priority: "low" },
+ { id: "9", content: "Performance tuning", status: "pending", priority: "low" },
+ { id: "10", content: "Deploy to production", status: "pending", priority: "high" }
+]}
+```
+
+**Example of WRONG TodoWrite usage:**
+```javascript
+// ❌ WRONG - Multiple TodoWrite calls
+Message 1: TodoWrite { todos: [{ id: "1", content: "Task 1", ... }] }
+Message 2: TodoWrite { todos: [{ id: "2", content: "Task 2", ... }] }
+Message 3: TodoWrite { todos: [{ id: "3", content: "Task 3", ... }] }
+// This breaks parallel coordination!
+```
+
## Claude Flow v2.0.0 Features
Claude Flow extends the base coordination with:
@@ -595,9 +829,9 @@ Claude Flow extends the base coordination with:
## 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
+- Documentation: https://github.com/ruvnet/claude-flow
+- Issues: https://github.com/ruvnet/claude-flow/issues
+- Examples: https://github.com/ruvnet/claude-flow/tree/main/examples
---
diff --git a/src/cli/simple-commands/init/templates/claude-md.js b/src/cli/simple-commands/init/templates/claude-md.js
index 2cf0bf5b98..ab4dc23be7 100644
--- a/src/cli/simple-commands/init/templates/claude-md.js
+++ b/src/cli/simple-commands/init/templates/claude-md.js
@@ -3,6 +3,29 @@
export function createMinimalClaudeMd() {
return `# Claude Code Configuration
+## 🚨 CRITICAL: CONCURRENT EXECUTION FOR ALL ACTIONS
+
+**ABSOLUTE RULE**: ALL operations MUST be concurrent/parallel in a single message:
+
+### πŸ”΄ MANDATORY CONCURRENT PATTERNS:
+1. **TodoWrite**: ALWAYS batch ALL todos in ONE call (5-10+ todos minimum)
+2. **Task tool**: ALWAYS spawn ALL agents in ONE message with full instructions
+3. **File operations**: ALWAYS batch ALL reads/writes/edits in ONE message
+4. **Bash commands**: ALWAYS batch ALL terminal operations in ONE message
+
+### ⚑ GOLDEN RULE: "1 MESSAGE = ALL RELATED OPERATIONS"
+
+**βœ… CORRECT**: Everything in ONE message
+**❌ WRONG**: Multiple messages for related operations (6x slower!)
+
+### 🎯 CONCURRENT EXECUTION CHECKLIST:
+- βœ… Are ALL related TodoWrite operations batched together?
+- βœ… Are ALL Task spawning operations in ONE message?
+- βœ… Are ALL file operations (Read/Write/Edit) batched together?
+- βœ… Are ALL bash commands grouped in ONE message?
+
+If ANY answer is "No", you MUST combine operations into a single message!
+
## Build Commands
- \`npm run build\`: Build the project
- \`npm run test\`: Run tests
@@ -21,6 +44,59 @@ This is a Claude-Flow AI agent orchestration system.
export function createFullClaudeMd() {
return `# Claude Code Configuration
+## 🚨 CRITICAL: CONCURRENT EXECUTION FOR ALL ACTIONS
+
+**ABSOLUTE RULE**: ALL operations MUST be concurrent/parallel in a single message:
+
+### πŸ”΄ MANDATORY CONCURRENT PATTERNS:
+1. **TodoWrite**: ALWAYS batch ALL todos in ONE call (5-10+ todos minimum)
+2. **Task tool**: ALWAYS spawn ALL agents in ONE message with full instructions
+3. **File operations**: ALWAYS batch ALL reads/writes/edits in ONE message
+4. **Bash commands**: ALWAYS batch ALL terminal operations in ONE message
+5. **Memory operations**: ALWAYS batch ALL memory store/retrieve in ONE message
+
+### ⚑ GOLDEN RULE: "1 MESSAGE = ALL RELATED OPERATIONS"
+
+**Examples of CORRECT concurrent execution:**
+\`\`\`javascript
+// βœ… CORRECT: Everything in ONE message
+[Single Message]:
+ - TodoWrite { todos: [10+ todos with all statuses/priorities] }
+ - Task("Agent 1 with full instructions and hooks")
+ - Task("Agent 2 with full instructions and hooks")
+ - Task("Agent 3 with full instructions and hooks")
+ - Read("file1.js")
+ - Read("file2.js")
+ - Write("output1.js", content)
+ - Write("output2.js", content)
+ - Bash("npm install")
+ - Bash("npm test")
+ - Bash("npm run build")
+\`\`\`
+
+**Examples of WRONG sequential execution:**
+\`\`\`javascript
+// ❌ WRONG: Multiple messages (NEVER DO THIS)
+Message 1: TodoWrite { todos: [single todo] }
+Message 2: Task("Agent 1")
+Message 3: Task("Agent 2")
+Message 4: Read("file1.js")
+Message 5: Write("output1.js")
+Message 6: Bash("npm install")
+// This is 6x slower and breaks coordination!
+\`\`\`
+
+### 🎯 CONCURRENT EXECUTION CHECKLIST:
+
+Before sending ANY message, ask yourself:
+- βœ… Are ALL related TodoWrite operations batched together?
+- βœ… Are ALL Task spawning operations in ONE message?
+- βœ… Are ALL file operations (Read/Write/Edit) batched together?
+- βœ… Are ALL bash commands grouped in ONE message?
+- βœ… Are ALL memory operations concurrent?
+
+If ANY answer is "No", you MUST combine operations into a single message!
+
## Build Commands
- \`npm run build\`: Build the project using Deno compile
- \`npm run test\`: Run the full test suite
@@ -71,6 +147,59 @@ This is a Claude-Flow AI agent orchestration system with the following component
export function createSparcClaudeMd() {
return `# Claude Code Configuration - SPARC Development Environment
+## 🚨 CRITICAL: CONCURRENT EXECUTION FOR ALL ACTIONS
+
+**ABSOLUTE RULE**: ALL operations MUST be concurrent/parallel in a single message:
+
+### πŸ”΄ MANDATORY CONCURRENT PATTERNS:
+1. **TodoWrite**: ALWAYS batch ALL todos in ONE call (5-10+ todos minimum)
+2. **Task tool**: ALWAYS spawn ALL agents in ONE message with full instructions
+3. **File operations**: ALWAYS batch ALL reads/writes/edits in ONE message
+4. **Bash commands**: ALWAYS batch ALL terminal operations in ONE message
+5. **Memory operations**: ALWAYS batch ALL memory store/retrieve in ONE message
+
+### ⚑ GOLDEN RULE: "1 MESSAGE = ALL RELATED OPERATIONS"
+
+**Examples of CORRECT concurrent execution:**
+\`\`\`javascript
+// βœ… CORRECT: Everything in ONE message
+[Single Message]:
+ - TodoWrite { todos: [10+ todos with all statuses/priorities] }
+ - Task("Agent 1 with full instructions and hooks")
+ - Task("Agent 2 with full instructions and hooks")
+ - Task("Agent 3 with full instructions and hooks")
+ - Read("file1.js")
+ - Read("file2.js")
+ - Write("output1.js", content)
+ - Write("output2.js", content)
+ - Bash("npm install")
+ - Bash("npm test")
+ - Bash("npm run build")
+\`\`\`
+
+**Examples of WRONG sequential execution:**
+\`\`\`javascript
+// ❌ WRONG: Multiple messages (NEVER DO THIS)
+Message 1: TodoWrite { todos: [single todo] }
+Message 2: Task("Agent 1")
+Message 3: Task("Agent 2")
+Message 4: Read("file1.js")
+Message 5: Write("output1.js")
+Message 6: Bash("npm install")
+// This is 6x slower and breaks coordination!
+\`\`\`
+
+### 🎯 CONCURRENT EXECUTION CHECKLIST:
+
+Before sending ANY message, ask yourself:
+- βœ… Are ALL related TodoWrite operations batched together?
+- βœ… Are ALL Task spawning operations in ONE message?
+- βœ… Are ALL file operations (Read/Write/Edit) batched together?
+- βœ… Are ALL bash commands grouped in ONE message?
+- βœ… Are ALL memory operations concurrent?
+
+If ANY answer is "No", you MUST combine operations into a single message!
+
## Project Overview
This project uses the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) methodology for systematic Test-Driven Development with AI assistance through Claude-Flow orchestration.
@@ -344,6 +473,59 @@ For more information about SPARC methodology, see: https://github.com/ruvnet/cla
export async function createOptimizedSparcClaudeMd() {
return `# Claude Code Configuration - SPARC Development Environment (Batchtools Optimized)
+## 🚨 CRITICAL: CONCURRENT EXECUTION FOR ALL ACTIONS
+
+**ABSOLUTE RULE**: ALL operations MUST be concurrent/parallel in a single message:
+
+### πŸ”΄ MANDATORY CONCURRENT PATTERNS:
+1. **TodoWrite**: ALWAYS batch ALL todos in ONE call (5-10+ todos minimum)
+2. **Task tool**: ALWAYS spawn ALL agents in ONE message with full instructions
+3. **File operations**: ALWAYS batch ALL reads/writes/edits in ONE message
+4. **Bash commands**: ALWAYS batch ALL terminal operations in ONE message
+5. **Memory operations**: ALWAYS batch ALL memory store/retrieve in ONE message
+
+### ⚑ GOLDEN RULE: "1 MESSAGE = ALL RELATED OPERATIONS"
+
+**Examples of CORRECT concurrent execution:**
+\`\`\`javascript
+// βœ… CORRECT: Everything in ONE message
+[Single Message]:
+ - TodoWrite { todos: [10+ todos with all statuses/priorities] }
+ - Task("Agent 1 with full instructions and hooks")
+ - Task("Agent 2 with full instructions and hooks")
+ - Task("Agent 3 with full instructions and hooks")
+ - Read("file1.js")
+ - Read("file2.js")
+ - Write("output1.js", content)
+ - Write("output2.js", content)
+ - Bash("npm install")
+ - Bash("npm test")
+ - Bash("npm run build")
+\`\`\`
+
+**Examples of WRONG sequential execution:**
+\`\`\`javascript
+// ❌ WRONG: Multiple messages (NEVER DO THIS)
+Message 1: TodoWrite { todos: [single todo] }
+Message 2: Task("Agent 1")
+Message 3: Task("Agent 2")
+Message 4: Read("file1.js")
+Message 5: Write("output1.js")
+Message 6: Bash("npm install")
+// This is 6x slower and breaks coordination!
+\`\`\`
+
+### 🎯 CONCURRENT EXECUTION CHECKLIST:
+
+Before sending ANY message, ask yourself:
+- βœ… Are ALL related TodoWrite operations batched together?
+- βœ… Are ALL Task spawning operations in ONE message?
+- βœ… Are ALL file operations (Read/Write/Edit) batched together?
+- βœ… Are ALL bash commands grouped in ONE message?
+- βœ… Are ALL memory operations concurrent?
+
+If ANY answer is "No", you MUST combine operations into a single message!
+
## Project Overview
This project uses the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) methodology for systematic Test-Driven Development with AI assistance through Claude-Flow orchestration.
diff --git a/src/mcp/mcp-server.js b/src/mcp/mcp-server.js
index 4b195c46b6..29ddf0f9cc 100644
--- a/src/mcp/mcp-server.js
+++ b/src/mcp/mcp-server.js
@@ -15,7 +15,7 @@ const __dirname = path.dirname(__filename);
class ClaudeFlowMCPServer {
constructor() {
- this.version = '2.0.0';
+ this.version = '2.0.0-alpha.49';
this.memoryStore = new EnhancedMemory();
this.capabilities = {
tools: {
diff --git a/src/memory/enhanced-memory.js b/src/memory/enhanced-memory.js
index 04436e5abb..e328d4c58a 100644
--- a/src/memory/enhanced-memory.js
+++ b/src/memory/enhanced-memory.js
@@ -1,348 +1,320 @@
/**
* Enhanced Memory Functions for Comprehensive Swarm Coordination
+ * Version 2: Works with both SQLite and in-memory fallback stores
*/
-import { SqliteMemoryStore } from './sqlite-store.js';
+import { FallbackMemoryStore } from './fallback-store.js';
-export class EnhancedMemory extends SqliteMemoryStore {
+export class EnhancedMemory extends FallbackMemoryStore {
constructor(options = {}) {
super(options);
}
async initialize() {
await super.initialize();
- // Apply enhanced schema
- try {
- const { readFileSync } = await import('fs');
- const schemaPath = new URL('./enhanced-schema.sql', import.meta.url);
- const schema = readFileSync(schemaPath, 'utf-8');
- this.db.exec(schema);
- } catch (error) {
- console.error(`[${new Date().toISOString()}] ERROR [enhanced-memory] Failed to apply enhanced schema:`, error);
- // Continue with basic schema only
+
+ // If using SQLite, try to apply enhanced schema
+ if (!this.isUsingFallback() && this.primaryStore?.db) {
+ try {
+ const { readFileSync } = await import('fs');
+ const schemaPath = new URL('./enhanced-schema.sql', import.meta.url);
+ const schema = readFileSync(schemaPath, 'utf-8');
+ this.primaryStore.db.exec(schema);
+ console.error(`[${new Date().toISOString()}] INFO [enhanced-memory] Applied enhanced schema to SQLite`);
+ } catch (error) {
+ console.error(`[${new Date().toISOString()}] WARN [enhanced-memory] Could not apply enhanced schema:`, error.message);
+ }
}
}
// === SESSION MANAGEMENT ===
async saveSessionState(sessionId, state) {
- const stmt = this.db.prepare(`
- INSERT OR REPLACE INTO session_state
- (session_id, user_id, project_path, active_branch, last_activity, state, context, environment)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
- `);
-
- return stmt.run(
+ const sessionData = {
sessionId,
- state.userId || process.env.USER,
- state.projectPath || process.cwd(),
- state.activeBranch || 'main',
- Date.now(),
- state.state || 'active',
- JSON.stringify(state.context || {}),
- JSON.stringify(state.environment || process.env)
- );
+ userId: state.userId || process.env.USER,
+ projectPath: state.projectPath || process.cwd(),
+ activeBranch: state.activeBranch || 'main',
+ lastActivity: Date.now(),
+ state: state.state || 'active',
+ context: state.context || {},
+ environment: state.environment || process.env
+ };
+
+ return this.store(`session:${sessionId}`, sessionData, {
+ namespace: 'sessions',
+ metadata: { type: 'session_state' }
+ });
}
async resumeSession(sessionId) {
- const stmt = this.db.prepare('SELECT * FROM session_state WHERE session_id = ?');
- const session = stmt.get(sessionId);
- if (session) {
- session.context = JSON.parse(session.context);
- session.environment = JSON.parse(session.environment);
- }
- return session;
+ return this.retrieve(`session:${sessionId}`, { namespace: 'sessions' });
}
async getActiveSessions() {
- const stmt = this.db.prepare('SELECT * FROM active_sessions');
- return stmt.all();
+ const sessions = await this.list({ namespace: 'sessions', limit: 100 });
+ return sessions
+ .map(item => item.value)
+ .filter(session => session.state === 'active');
}
- // === MCP TOOL TRACKING ===
+ // === WORKFLOW TRACKING ===
- async trackToolUsage(toolName, args, result, executionTime, success = true, error = null) {
- const stmt = this.db.prepare(`
- INSERT INTO mcp_tool_usage
- (tool_name, session_id, arguments, result_summary, execution_time_ms, success, error_message)
- VALUES (?, ?, ?, ?, ?, ?, ?)
- `);
-
- return stmt.run(
- toolName,
- this.currentSessionId,
- JSON.stringify(args),
- result ? JSON.stringify(result).substring(0, 500) : null,
- executionTime,
- success ? 1 : 0,
- error
- );
+ async trackWorkflow(workflowId, data) {
+ const workflowData = {
+ workflowId,
+ name: data.name,
+ steps: data.steps || [],
+ status: data.status || 'pending',
+ progress: data.progress || 0,
+ startTime: data.startTime || Date.now(),
+ endTime: data.endTime,
+ results: data.results || {}
+ };
+
+ return this.store(`workflow:${workflowId}`, workflowData, {
+ namespace: 'workflows',
+ metadata: { type: 'workflow' }
+ });
}
- async getToolStats() {
- const stmt = this.db.prepare('SELECT * FROM tool_effectiveness');
- return stmt.all();
+ async getWorkflowStatus(workflowId) {
+ return this.retrieve(`workflow:${workflowId}`, { namespace: 'workflows' });
}
- // === TRAINING DATA ===
+ // === METRICS COLLECTION ===
- async recordTrainingExample(patternType, inputContext, actionTaken, outcome, score, feedback = null) {
- const stmt = this.db.prepare(`
- INSERT INTO training_data
- (pattern_type, input_context, action_taken, outcome, success_score, model_version, feedback)
- VALUES (?, ?, ?, ?, ?, ?, ?)
- `);
+ async recordMetric(metricName, value, metadata = {}) {
+ const timestamp = Date.now();
+ const metricKey = `metric:${metricName}:${timestamp}`;
- return stmt.run(
- patternType,
- JSON.stringify(inputContext),
- JSON.stringify(actionTaken),
- JSON.stringify(outcome),
- score,
- this.modelVersion || '1.0',
- feedback
- );
+ return this.store(metricKey, {
+ name: metricName,
+ value,
+ timestamp,
+ metadata
+ }, {
+ namespace: 'metrics',
+ ttl: 86400 // 24 hours
+ });
}
- async getTrainingData(patternType, limit = 100) {
- const stmt = this.db.prepare(`
- SELECT * FROM training_data
- WHERE pattern_type = ?
- ORDER BY success_score DESC, timestamp DESC
- LIMIT ?
- `);
- return stmt.all(patternType, limit);
+ async getMetrics(metricName, timeRange = 3600000) { // Default 1 hour
+ const cutoff = Date.now() - timeRange;
+ const metrics = await this.search(`metric:${metricName}`, {
+ namespace: 'metrics',
+ limit: 1000
+ });
+
+ return metrics
+ .map(item => item.value)
+ .filter(metric => metric.timestamp >= cutoff)
+ .sort((a, b) => a.timestamp - b.timestamp);
}
- // === CODE PATTERNS ===
+ // === AGENT COORDINATION ===
- async recordCodePattern(filePath, patternName, content, language) {
- const stmt = this.db.prepare(`
- INSERT INTO code_patterns (file_path, pattern_name, pattern_content, language, last_used)
- VALUES (?, ?, ?, ?, ?)
- ON CONFLICT(file_path, pattern_name) DO UPDATE SET
- frequency = frequency + 1,
- last_used = ?
- `);
-
- const now = Date.now();
- return stmt.run(filePath, patternName, content, language, now, now);
- }
+ async registerAgent(agentId, config) {
+ const agentData = {
+ agentId,
+ type: config.type,
+ capabilities: config.capabilities || [],
+ status: 'active',
+ createdAt: Date.now(),
+ lastHeartbeat: Date.now(),
+ metrics: {
+ tasksCompleted: 0,
+ successRate: 1.0,
+ avgResponseTime: 0
+ }
+ };
- async findSimilarPatterns(language, limit = 10) {
- const stmt = this.db.prepare(`
- SELECT * FROM code_patterns
- WHERE language = ?
- ORDER BY effectiveness_score DESC, frequency DESC
- LIMIT ?
- `);
- return stmt.all(language, limit);
+ return this.store(`agent:${agentId}`, agentData, {
+ namespace: 'agents',
+ metadata: { type: 'agent_registration' }
+ });
}
- // === AGENT COLLABORATION ===
-
- async recordAgentInteraction(sourceAgent, targetAgent, messageType, content, taskId) {
- const stmt = this.db.prepare(`
- INSERT INTO agent_interactions
- (source_agent, target_agent, message_type, content, task_id, correlation_id)
- VALUES (?, ?, ?, ?, ?, ?)
- `);
+ async updateAgentStatus(agentId, status, metrics = {}) {
+ const agent = await this.retrieve(`agent:${agentId}`, { namespace: 'agents' });
+ if (!agent) return null;
+
+ agent.status = status;
+ agent.lastHeartbeat = Date.now();
- const correlationId = `${taskId}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
- return stmt.run(sourceAgent, targetAgent, messageType, JSON.stringify(content), taskId, correlationId);
- }
+ if (metrics) {
+ Object.assign(agent.metrics, metrics);
+ }
- async getAgentConversation(taskId) {
- const stmt = this.db.prepare(`
- SELECT * FROM agent_interactions
- WHERE task_id = ?
- ORDER BY timestamp ASC
- `);
- return stmt.all(taskId);
+ return this.store(`agent:${agentId}`, agent, {
+ namespace: 'agents',
+ metadata: { type: 'agent_update' }
+ });
}
- // === KNOWLEDGE GRAPH ===
-
- async addKnowledgeEntity(entityType, entityName, entityPath, relationships = [], metadata = {}) {
- const stmt = this.db.prepare(`
- INSERT OR REPLACE INTO knowledge_graph
- (entity_type, entity_name, entity_path, relationships, metadata, updated_at)
- VALUES (?, ?, ?, ?, ?, ?)
- `);
+ async getActiveAgents() {
+ const agents = await this.list({ namespace: 'agents', limit: 100 });
+ const cutoff = Date.now() - 300000; // 5 minutes
- return stmt.run(
- entityType,
- entityName,
- entityPath,
- JSON.stringify(relationships),
- JSON.stringify(metadata),
- Date.now()
- );
+ return agents
+ .map(item => item.value)
+ .filter(agent => agent.lastHeartbeat > cutoff && agent.status === 'active');
}
- async findRelatedEntities(entityName, depth = 1) {
- // Simple implementation - could be enhanced with recursive CTEs
- const stmt = this.db.prepare(`
- SELECT * FROM knowledge_graph
- WHERE entity_name = ? OR relationships LIKE ?
- `);
- return stmt.all(entityName, `%"${entityName}"%`);
- }
-
- // === ERROR LEARNING ===
+ // === KNOWLEDGE MANAGEMENT ===
- async recordError(errorType, errorMessage, stackTrace, context, resolution = null) {
- const stmt = this.db.prepare(`
- INSERT INTO error_patterns
- (error_type, error_message, stack_trace, context, resolution)
- VALUES (?, ?, ?, ?, ?)
- ON CONFLICT(error_type, error_message) DO UPDATE SET
- occurrence_count = occurrence_count + 1,
- last_seen = strftime('%s', 'now'),
- resolution = COALESCE(?, resolution)
- `);
-
- return stmt.run(
- errorType,
- errorMessage,
- stackTrace,
- JSON.stringify(context),
- resolution,
- resolution
- );
+ async storeKnowledge(domain, key, value, metadata = {}) {
+ return this.store(`knowledge:${domain}:${key}`, {
+ domain,
+ key,
+ value,
+ metadata,
+ createdAt: Date.now(),
+ updatedAt: Date.now()
+ }, {
+ namespace: 'knowledge',
+ metadata: { domain }
+ });
}
- async getErrorSolutions(errorType) {
- const stmt = this.db.prepare(`
- SELECT * FROM error_patterns
- WHERE error_type = ? AND resolution IS NOT NULL
- ORDER BY occurrence_count DESC
- `);
- return stmt.all(errorType);
+ async retrieveKnowledge(domain, key) {
+ return this.retrieve(`knowledge:${domain}:${key}`, { namespace: 'knowledge' });
}
- // === TASK DEPENDENCIES ===
-
- async addTaskDependency(taskId, dependsOn, dependencyType = 'blocking') {
- const stmt = this.db.prepare(`
- INSERT INTO task_dependencies
- (task_id, depends_on, dependency_type, status)
- VALUES (?, ?, ?, 'pending')
- `);
+ async searchKnowledge(domain, pattern) {
+ const results = await this.search(`knowledge:${domain}:${pattern}`, {
+ namespace: 'knowledge',
+ limit: 50
+ });
- return stmt.run(taskId, dependsOn, dependencyType);
+ return results.map(item => item.value);
}
- async updateDependencyStatus(taskId, dependsOn, status) {
- const stmt = this.db.prepare(`
- UPDATE task_dependencies
- SET status = ?
- WHERE task_id = ? AND depends_on = ?
- `);
-
- return stmt.run(status, taskId, dependsOn);
+ // === LEARNING & ADAPTATION ===
+
+ async recordLearning(agentId, learning) {
+ const learningData = {
+ agentId,
+ timestamp: Date.now(),
+ type: learning.type,
+ input: learning.input,
+ output: learning.output,
+ feedback: learning.feedback,
+ improvement: learning.improvement
+ };
+
+ return this.store(`learning:${agentId}:${Date.now()}`, learningData, {
+ namespace: 'learning',
+ ttl: 604800 // 7 days
+ });
}
- async getTaskDependencies(taskId) {
- const stmt = this.db.prepare(`
- SELECT * FROM task_dependencies
- WHERE task_id = ?
- `);
- return stmt.all(taskId);
+ async getLearnings(agentId, limit = 100) {
+ const learnings = await this.search(`learning:${agentId}`, {
+ namespace: 'learning',
+ limit
+ });
+
+ return learnings
+ .map(item => item.value)
+ .sort((a, b) => b.timestamp - a.timestamp);
}
// === PERFORMANCE TRACKING ===
- async recordPerformance(operationType, details, duration, memoryUsed, cpuPercent) {
- const stmt = this.db.prepare(`
- INSERT INTO performance_benchmarks
- (operation_type, operation_details, duration_ms, memory_used_mb, cpu_percent, session_id)
- VALUES (?, ?, ?, ?, ?, ?)
- `);
-
- return stmt.run(
- operationType,
- JSON.stringify(details),
+ async trackPerformance(operation, duration, success = true, metadata = {}) {
+ const perfData = {
+ operation,
duration,
- memoryUsed,
- cpuPercent,
- this.currentSessionId
- );
+ success,
+ timestamp: Date.now(),
+ metadata
+ };
+
+ // Store individual performance record
+ await this.store(`perf:${operation}:${Date.now()}`, perfData, {
+ namespace: 'performance',
+ ttl: 86400 // 24 hours
+ });
+
+ // Update aggregated stats
+ const statsKey = `stats:${operation}`;
+ const stats = await this.retrieve(statsKey, { namespace: 'performance' }) || {
+ count: 0,
+ successCount: 0,
+ totalDuration: 0,
+ avgDuration: 0,
+ minDuration: Infinity,
+ maxDuration: 0
+ };
+
+ stats.count++;
+ if (success) stats.successCount++;
+ stats.totalDuration += duration;
+ stats.avgDuration = stats.totalDuration / stats.count;
+ stats.minDuration = Math.min(stats.minDuration, duration);
+ stats.maxDuration = Math.max(stats.maxDuration, duration);
+ stats.successRate = stats.successCount / stats.count;
+
+ return this.store(statsKey, stats, { namespace: 'performance' });
}
- async getPerformanceTrends(operationType, days = 7) {
- const stmt = this.db.prepare(`
- SELECT DATE(timestamp, 'unixepoch') as date,
- AVG(duration_ms) as avg_duration,
- AVG(memory_used_mb) as avg_memory,
- COUNT(*) as operation_count
- FROM performance_benchmarks
- WHERE operation_type = ?
- AND timestamp > strftime('%s', 'now', '-' || ? || ' days')
- GROUP BY date
- ORDER BY date DESC
- `);
- return stmt.all(operationType, days);
+ async getPerformanceStats(operation) {
+ return this.retrieve(`stats:${operation}`, { namespace: 'performance' });
}
- // === USER PREFERENCES ===
+ // === COORDINATION CACHE ===
- async learnPreference(key, value, category, source = 'inferred', confidence = 0.8) {
- const stmt = this.db.prepare(`
- INSERT OR REPLACE INTO user_preferences
- (preference_key, preference_value, category, learned_from, confidence_score)
- VALUES (?, ?, ?, ?, ?)
- `);
-
- return stmt.run(key, value, category, source, confidence);
+ async cacheCoordination(key, value, ttl = 300) { // 5 minutes default
+ return this.store(`cache:${key}`, value, {
+ namespace: 'coordination',
+ ttl
+ });
}
- async getPreferences(category = null) {
- if (category) {
- const stmt = this.db.prepare('SELECT * FROM user_preferences WHERE category = ?');
- return stmt.all(category);
- } else {
- const stmt = this.db.prepare('SELECT * FROM user_preferences');
- return stmt.all();
- }
+ async getCachedCoordination(key) {
+ return this.retrieve(`cache:${key}`, { namespace: 'coordination' });
}
// === UTILITY METHODS ===
- async getDatabaseStats() {
- const tables = [
- 'memory_entries', 'session_state', 'mcp_tool_usage', 'training_data',
- 'code_patterns', 'agent_interactions', 'knowledge_graph', 'error_patterns',
- 'task_dependencies', 'performance_benchmarks', 'user_preferences'
- ];
+ async cleanupExpired() {
+ // Base cleanup handles TTL expiration
+ const cleaned = await this.cleanup();
- const stats = {};
- for (const table of tables) {
- try {
- const result = this.db.prepare(`SELECT COUNT(*) as count FROM ${table}`).get();
- stats[table] = result.count;
- } catch (e) {
- stats[table] = 0;
- }
+ // Additional cleanup for old performance data
+ if (!this.isUsingFallback()) {
+ // SQLite-specific cleanup can be added here
}
- return stats;
+ return cleaned;
}
- async exportSessionData(sessionId) {
- const data = {
- session: await this.resumeSession(sessionId),
- tools: this.db.prepare('SELECT * FROM mcp_tool_usage WHERE session_id = ?').all(sessionId),
- performance: this.db.prepare('SELECT * FROM performance_benchmarks WHERE session_id = ?').all(sessionId),
- interactions: this.db.prepare('SELECT * FROM agent_interactions WHERE correlation_id LIKE ?').all(`${sessionId}%`),
- timestamp: new Date().toISOString()
- };
+ async exportData(namespace = null) {
+ const namespaces = namespace ? [namespace] : [
+ 'sessions', 'workflows', 'metrics', 'agents',
+ 'knowledge', 'learning', 'performance', 'coordination'
+ ];
+
+ const exportData = {};
+
+ for (const ns of namespaces) {
+ exportData[ns] = await this.list({ namespace: ns, limit: 10000 });
+ }
- return data;
+ return exportData;
}
-}
-// Singleton instance
-export const enhancedMemory = new EnhancedMemory();
+ async importData(data) {
+ for (const [namespace, items] of Object.entries(data)) {
+ for (const item of items) {
+ await this.store(item.key, item.value, {
+ namespace,
+ metadata: item.metadata
+ });
+ }
+ }
+ }
+}
export default EnhancedMemory;
\ No newline at end of file
diff --git a/src/memory/fallback-store.js b/src/memory/fallback-store.js
new file mode 100644
index 0000000000..dde26c5761
--- /dev/null
+++ b/src/memory/fallback-store.js
@@ -0,0 +1,93 @@
+/**
+ * Fallback memory store that tries SQLite first, then falls back to in-memory storage
+ * Designed to handle npx environments where native modules may fail to load
+ */
+
+import { SqliteMemoryStore } from './sqlite-store.js';
+import { InMemoryStore } from './in-memory-store.js';
+
+class FallbackMemoryStore {
+ constructor(options = {}) {
+ this.options = options;
+ this.primaryStore = null;
+ this.fallbackStore = null;
+ this.useFallback = false;
+ this.initializationAttempted = false;
+ }
+
+ async initialize() {
+ if (this.initializationAttempted) return;
+ this.initializationAttempted = true;
+
+ // First, try to initialize SQLite store
+ try {
+ this.primaryStore = new SqliteMemoryStore(this.options);
+ await this.primaryStore.initialize();
+ console.error(`[${new Date().toISOString()}] INFO [fallback-store] Successfully initialized SQLite store`);
+ this.useFallback = false;
+ } catch (error) {
+ console.error(`[${new Date().toISOString()}] WARN [fallback-store] SQLite initialization failed, falling back to in-memory store:`, error.message);
+
+ // Fall back to in-memory store
+ this.fallbackStore = new InMemoryStore(this.options);
+ await this.fallbackStore.initialize();
+ this.useFallback = true;
+
+ console.error(`[${new Date().toISOString()}] INFO [fallback-store] Using in-memory store (data will not persist across sessions)`);
+ console.error(`[${new Date().toISOString()}] INFO [fallback-store] To enable persistent storage, install the package locally: npm install claude-flow@alpha`);
+ }
+ }
+
+ get activeStore() {
+ return this.useFallback ? this.fallbackStore : this.primaryStore;
+ }
+
+ async store(key, value, options = {}) {
+ await this.initialize();
+ return this.activeStore.store(key, value, options);
+ }
+
+ async retrieve(key, options = {}) {
+ await this.initialize();
+ return this.activeStore.retrieve(key, options);
+ }
+
+ async list(options = {}) {
+ await this.initialize();
+ return this.activeStore.list(options);
+ }
+
+ async delete(key, options = {}) {
+ await this.initialize();
+ return this.activeStore.delete(key, options);
+ }
+
+ async search(pattern, options = {}) {
+ await this.initialize();
+ return this.activeStore.search(pattern, options);
+ }
+
+ async cleanup() {
+ await this.initialize();
+ return this.activeStore.cleanup();
+ }
+
+ close() {
+ if (this.primaryStore) {
+ this.primaryStore.close();
+ }
+ if (this.fallbackStore) {
+ this.fallbackStore.close();
+ }
+ }
+
+ isUsingFallback() {
+ return this.useFallback;
+ }
+}
+
+// Export a singleton instance for MCP server
+export const memoryStore = new FallbackMemoryStore();
+
+export { FallbackMemoryStore };
+export default FallbackMemoryStore;
\ No newline at end of file
diff --git a/src/memory/in-memory-store.js b/src/memory/in-memory-store.js
new file mode 100644
index 0000000000..75e9f16fab
--- /dev/null
+++ b/src/memory/in-memory-store.js
@@ -0,0 +1,210 @@
+/**
+ * In-memory store for environments where SQLite is not available
+ * Provides the same API as SQLite store but data is not persistent
+ */
+
+class InMemoryStore {
+ constructor(options = {}) {
+ this.options = options;
+ this.data = new Map(); // namespace -> Map(key -> entry)
+ this.isInitialized = false;
+ this.cleanupInterval = null;
+ }
+
+ async initialize() {
+ if (this.isInitialized) return;
+
+ // Initialize default namespace
+ this.data.set('default', new Map());
+
+ // Start cleanup interval for expired entries
+ this.cleanupInterval = setInterval(() => {
+ this.cleanup().catch(err =>
+ console.error(`[${new Date().toISOString()}] ERROR [in-memory-store] Cleanup failed:`, err)
+ );
+ }, 60000); // Run cleanup every minute
+
+ this.isInitialized = true;
+ console.error(`[${new Date().toISOString()}] INFO [in-memory-store] Initialized in-memory store`);
+ }
+
+ _getNamespaceMap(namespace) {
+ if (!this.data.has(namespace)) {
+ this.data.set(namespace, new Map());
+ }
+ return this.data.get(namespace);
+ }
+
+ async store(key, value, options = {}) {
+ await this.initialize();
+
+ const namespace = options.namespace || 'default';
+ const namespaceMap = this._getNamespaceMap(namespace);
+
+ const now = Date.now();
+ const ttl = options.ttl || null;
+ const expiresAt = ttl ? now + (ttl * 1000) : null;
+ const valueStr = typeof value === 'string' ? value : JSON.stringify(value);
+
+ const entry = {
+ key,
+ value: valueStr,
+ namespace,
+ metadata: options.metadata || null,
+ createdAt: namespaceMap.has(key) ? namespaceMap.get(key).createdAt : now,
+ updatedAt: now,
+ accessedAt: now,
+ accessCount: namespaceMap.has(key) ? namespaceMap.get(key).accessCount + 1 : 1,
+ ttl,
+ expiresAt
+ };
+
+ namespaceMap.set(key, entry);
+
+ return {
+ success: true,
+ id: `${namespace}:${key}`,
+ size: valueStr.length
+ };
+ }
+
+ async retrieve(key, options = {}) {
+ await this.initialize();
+
+ const namespace = options.namespace || 'default';
+ const namespaceMap = this._getNamespaceMap(namespace);
+
+ const entry = namespaceMap.get(key);
+
+ if (!entry) {
+ return null;
+ }
+
+ // Check if expired
+ if (entry.expiresAt && entry.expiresAt < Date.now()) {
+ namespaceMap.delete(key);
+ return null;
+ }
+
+ // Update access stats
+ entry.accessedAt = Date.now();
+ entry.accessCount++;
+
+ // Try to parse as JSON, fall back to raw string
+ try {
+ return JSON.parse(entry.value);
+ } catch {
+ return entry.value;
+ }
+ }
+
+ async list(options = {}) {
+ await this.initialize();
+
+ const namespace = options.namespace || 'default';
+ const limit = options.limit || 100;
+ const namespaceMap = this._getNamespaceMap(namespace);
+
+ const entries = Array.from(namespaceMap.values())
+ .filter(entry => !entry.expiresAt || entry.expiresAt > Date.now())
+ .sort((a, b) => b.updatedAt - a.updatedAt)
+ .slice(0, limit);
+
+ return entries.map(entry => ({
+ key: entry.key,
+ value: this._tryParseJson(entry.value),
+ namespace: entry.namespace,
+ metadata: entry.metadata,
+ createdAt: new Date(entry.createdAt),
+ updatedAt: new Date(entry.updatedAt),
+ accessCount: entry.accessCount
+ }));
+ }
+
+ async delete(key, options = {}) {
+ await this.initialize();
+
+ const namespace = options.namespace || 'default';
+ const namespaceMap = this._getNamespaceMap(namespace);
+
+ return namespaceMap.delete(key);
+ }
+
+ async search(pattern, options = {}) {
+ await this.initialize();
+
+ const namespace = options.namespace || 'default';
+ const limit = options.limit || 50;
+ const namespaceMap = this._getNamespaceMap(namespace);
+
+ const searchLower = pattern.toLowerCase();
+ const results = [];
+
+ for (const [key, entry] of namespaceMap.entries()) {
+ // Skip expired entries
+ if (entry.expiresAt && entry.expiresAt < Date.now()) {
+ continue;
+ }
+
+ // Search in key and value
+ if (key.toLowerCase().includes(searchLower) ||
+ entry.value.toLowerCase().includes(searchLower)) {
+ results.push({
+ key: entry.key,
+ value: this._tryParseJson(entry.value),
+ namespace: entry.namespace,
+ score: entry.accessCount,
+ updatedAt: new Date(entry.updatedAt)
+ });
+ }
+
+ if (results.length >= limit) {
+ break;
+ }
+ }
+
+ // Sort by score (access count) and updated time
+ return results.sort((a, b) => {
+ if (a.score !== b.score) return b.score - a.score;
+ return b.updatedAt - a.updatedAt;
+ });
+ }
+
+ async cleanup() {
+ await this.initialize();
+
+ let cleaned = 0;
+ const now = Date.now();
+
+ for (const [namespace, namespaceMap] of this.data.entries()) {
+ for (const [key, entry] of namespaceMap.entries()) {
+ if (entry.expiresAt && entry.expiresAt <= now) {
+ namespaceMap.delete(key);
+ cleaned++;
+ }
+ }
+ }
+
+ return cleaned;
+ }
+
+ _tryParseJson(value) {
+ try {
+ return JSON.parse(value);
+ } catch {
+ return value;
+ }
+ }
+
+ close() {
+ if (this.cleanupInterval) {
+ clearInterval(this.cleanupInterval);
+ this.cleanupInterval = null;
+ }
+ this.data.clear();
+ this.isInitialized = false;
+ }
+}
+
+export { InMemoryStore };
+export default InMemoryStore;
\ No newline at end of file