mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-24 14:16:34 +09:00
feat: Implement system monitoring, SPARC commands, and task management features
- Added `monitor.js` for system monitoring commands with options for current metrics and continuous monitoring. - Introduced `sparc.js` for SPARC development mode commands, including modes listing, mode info, task execution, and TDD workflow. - Created `status.js` for system status reporting with detailed information and JSON output options. - Developed `task.js` for task management commands, including task creation, listing, status checking, cancellation, and workflow execution. - Added utility functions in `utils.js` for shared CLI functionalities, including command validation, file handling, and environment variable management.
This commit is contained in:
1 parent
de90d3644c
commit
8115c6fa3d
21 files changed
+4528
-929
No files matched your search
@@ -23,8 +23,9 @@
|
||||
|
||||
- **🚀 10x Faster Development**: Parallel AI agent execution with intelligent task distribution
|
||||
- **🧠 Persistent Memory**: Agents learn and share knowledge across sessions
|
||||
- **⚡ SPARC Methodology**: Systematic development with Specification → Pseudocode → Architecture → Refinement → Completion
|
||||
- **🔄 Zero Configuration**: Works out-of-the-box with sensible defaults
|
||||
- **⚡ VSCode Native**: Seamless integration with your favorite IDE
|
||||
- **🤖 VSCode Native**: Seamless integration with your favorite IDE
|
||||
- **🔒 Enterprise Ready**: Production-grade security, monitoring, and scaling
|
||||
- **🌐 MCP Compatible**: Full Model Context Protocol support for tool integration
|
||||
|
||||
@@ -32,9 +33,14 @@
|
||||
|
||||
```bash
|
||||
# 🚀 Get started in 30 seconds
|
||||
npx claude-flow init
|
||||
npx claude-flow init --sparc
|
||||
npx claude-flow start
|
||||
|
||||
# ⚡ SPARC Development Workflow
|
||||
npx claude-flow sparc modes # List development modes
|
||||
npx claude-flow sparc tdd "user auth" # Run TDD workflow
|
||||
npx claude-flow sparc run architect "design API" # Architecture mode
|
||||
|
||||
# 🤖 Spawn a research team
|
||||
npx claude-flow agent spawn researcher --name "Senior Researcher"
|
||||
npx claude-flow agent spawn analyst --name "Data Analyst"
|
||||
@@ -67,8 +73,8 @@ Advanced CRDT-based memory system with SQLite performance and Markdown readabili
|
||||
</td>
|
||||
<td width="33%" align="center">
|
||||
|
||||
### ⚡ **Enhanced Claude Integration**
|
||||
Spawn Claude instances with comprehensive Claude-Flow guidance, teaching them to use memory, coordination, and system commands effectively.
|
||||
### ⚡ **SPARC Development**
|
||||
Systematic AI-assisted development using Specification → Pseudocode → Architecture → Refinement → Completion methodology with 16+ specialized modes.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
@@ -145,12 +151,14 @@ Comprehensive documentation is available to help you get the most out of Claude-
|
||||
|
||||
### 1. **Initialize Claude Code Integration**
|
||||
```bash
|
||||
npx claude-flow init
|
||||
npx claude-flow init --sparc
|
||||
```
|
||||
This creates:
|
||||
- `CLAUDE.md` - Claude Code configuration
|
||||
- `CLAUDE.md` - SPARC-enhanced Claude Code configuration
|
||||
- `memory-bank.md` - Memory system documentation
|
||||
- `coordination.md` - Agent coordination documentation
|
||||
- `.roomodes` - SPARC development mode configurations
|
||||
- `.roo/` - SPARC templates and workflows
|
||||
- Memory folder structure with placeholders
|
||||
|
||||
### 2. **Start the Orchestrator**
|
||||
@@ -237,6 +245,50 @@ npx claude-flow monitor
|
||||
npx claude-flow mcp tools
|
||||
```
|
||||
|
||||
## 🚀 **SPARC Development Methodology**
|
||||
|
||||
Claude-Flow integrates the **SPARC** (Specification, Pseudocode, Architecture, Refinement, Completion) methodology for systematic AI-assisted development:
|
||||
|
||||
### **Available SPARC Modes**
|
||||
```bash
|
||||
# List all development modes
|
||||
npx claude-flow sparc modes
|
||||
|
||||
# Key modes include:
|
||||
# 🏗️ architect - System design and architecture
|
||||
# 🧠 code - Clean, modular implementation
|
||||
# 🧪 tdd - Test-driven development
|
||||
# 🛡️ security-review - Security analysis
|
||||
# 📚 docs-writer - Documentation creation
|
||||
# 🔗 integration - System integration
|
||||
```
|
||||
|
||||
### **SPARC Workflow**
|
||||
```bash
|
||||
# 1. Specification - Define requirements
|
||||
npx claude-flow sparc run spec-pseudocode "user authentication system"
|
||||
|
||||
# 2. Architecture - Design system structure
|
||||
npx claude-flow sparc run architect "auth service architecture"
|
||||
|
||||
# 3. Refinement - TDD implementation
|
||||
npx claude-flow sparc tdd "implement JWT authentication"
|
||||
|
||||
# 4. Integration - Connect components
|
||||
npx claude-flow sparc run integration "auth with user management"
|
||||
|
||||
# 5. Completion - Documentation and validation
|
||||
npx claude-flow sparc run docs-writer "authentication API docs"
|
||||
```
|
||||
|
||||
### **SPARC Features**
|
||||
- **16+ Specialized AI Modes** for different development phases
|
||||
- **Memory Persistence** across SPARC sessions with namespaced storage
|
||||
- **TDD Enforcement** with Red-Green-Refactor cycle automation
|
||||
- **Modular Design** with <500 line file constraints
|
||||
- **Environment Safety** preventing credential exposure
|
||||
- **Quality Gates** with automated code analysis and security review
|
||||
|
||||
## Architecture
|
||||
|
||||
Claude-Flow uses a modular architecture with the following components:
|
||||
@@ -396,6 +448,18 @@ npx claude-flow monitor [options]
|
||||
-f, --focus <component> Focus on specific component
|
||||
```
|
||||
|
||||
#### `sparc` - SPARC Development Methodology 🆕
|
||||
```bash
|
||||
npx claude-flow sparc <subcommand>
|
||||
modes [--verbose] List available SPARC development modes
|
||||
info <mode> Show detailed mode information
|
||||
run <mode> "<task>" Execute specific SPARC mode
|
||||
tdd "<feature>" Run full TDD workflow
|
||||
--namespace <ns> Use custom memory namespace
|
||||
--dry-run Show configuration without executing
|
||||
--verbose Show detailed output
|
||||
```
|
||||
|
||||
#### `claude` - Spawn Claude Instances with Enhanced Guidance 🆕
|
||||
```bash
|
||||
npx claude-flow claude <subcommand>
|
||||
@@ -493,6 +557,27 @@ npx claude-flow agent spawn coordinator --name "Tech Lead"
|
||||
npx claude-flow workflow development-pipeline.json --watch
|
||||
```
|
||||
|
||||
**SPARC Development Workflow:**
|
||||
```bash
|
||||
# Initialize SPARC environment
|
||||
npx claude-flow init --sparc
|
||||
|
||||
# Complete feature development using SPARC methodology
|
||||
npx claude-flow sparc run spec-pseudocode "user authentication system"
|
||||
npx claude-flow sparc run architect "JWT auth service design"
|
||||
npx claude-flow sparc tdd "implement secure authentication"
|
||||
npx claude-flow sparc run security-review "auth vulnerability scan"
|
||||
npx claude-flow sparc run integration "connect auth to user service"
|
||||
|
||||
# TDD-focused development
|
||||
npx claude-flow sparc tdd "payment processing system"
|
||||
npx claude-flow sparc tdd "real-time notifications"
|
||||
|
||||
# Architecture and design
|
||||
npx claude-flow sparc run architect "microservices architecture"
|
||||
npx claude-flow sparc run docs-writer "API documentation"
|
||||
```
|
||||
|
||||
**Enhanced Claude Spawn Examples:**
|
||||
```bash
|
||||
# Backend API development with high test coverage
|
||||
@@ -627,7 +712,7 @@ Claude-Flow seamlessly integrates with Claude Code through the `CLAUDE.md` file
|
||||
- **Build Command Integration**: All build/test commands are available to Claude
|
||||
- **Memory Persistence**: Claude remembers context across sessions
|
||||
- **Enhanced Guidance**: Spawned Claude instances receive detailed Claude-Flow instructions
|
||||
- **SPARC Methodology**: Built-in support for structured AI development
|
||||
- **SPARC Methodology**: Built-in support for systematic development with 16+ specialized AI modes
|
||||
|
||||
Use with Claude Code:
|
||||
```bash
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
// note to AI never remove this script from the repository bin directory
|
||||
|
||||
const { spawn } = require('child_process');
|
||||
const path = require('path');
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
This file serves as persistent memory storage for Claude across sessions.
|
||||
|
||||
## Session Information
|
||||
- **Current Session**: Started 2025-06-11T03:45:46.289Z
|
||||
- **Current Session**: Started 2025-06-11T16:25:44.812Z
|
||||
- **Project Phase**: [Development/Testing/Production]
|
||||
- **Active Tasks**: [List current tasks]
|
||||
|
||||
|
||||
@@ -1,76 +1,5 @@
|
||||
{
|
||||
"agents": [
|
||||
{
|
||||
"id": "agent-1749613592964-g0npi8ni4",
|
||||
"type": "researcher",
|
||||
"name": "Research Bot",
|
||||
"status": "active",
|
||||
"capabilities": [
|
||||
"web-search",
|
||||
"information-gathering",
|
||||
"analysis"
|
||||
],
|
||||
"systemPrompt": "You are a research agent specialized in gathering and analyzing information.",
|
||||
"maxConcurrentTasks": 5,
|
||||
"priority": 1,
|
||||
"createdAt": 1749613592964
|
||||
},
|
||||
{
|
||||
"id": "agent-1749613632456-gtndy9ddl",
|
||||
"type": "implementer",
|
||||
"name": "Code Developer",
|
||||
"status": "active",
|
||||
"capabilities": [
|
||||
"code-generation",
|
||||
"file-manipulation",
|
||||
"testing"
|
||||
],
|
||||
"systemPrompt": "You are an implementation agent focused on writing code and creating solutions.",
|
||||
"maxConcurrentTasks": 5,
|
||||
"priority": 7,
|
||||
"createdAt": 1749613632456
|
||||
},
|
||||
{
|
||||
"id": "agent-1749614777174-96e2hdm1c",
|
||||
"type": "researcher",
|
||||
"name": "Test Researcher",
|
||||
"status": "active",
|
||||
"capabilities": [
|
||||
"research",
|
||||
"web-search"
|
||||
],
|
||||
"systemPrompt": "You are a research agent",
|
||||
"maxConcurrentTasks": 5,
|
||||
"priority": 1,
|
||||
"createdAt": 1749614777174
|
||||
}
|
||||
],
|
||||
"tasks": [
|
||||
{
|
||||
"id": "task-1749613648853-m04joqfqj",
|
||||
"type": "implementation",
|
||||
"description": "Build authentication module",
|
||||
"status": "pending",
|
||||
"priority": 9,
|
||||
"dependencies": [
|
||||
"task-1749613600902-dfn3e8u8c"
|
||||
],
|
||||
"metadata": {},
|
||||
"progress": 0,
|
||||
"createdAt": 1749613648853
|
||||
},
|
||||
{
|
||||
"id": "task-1749613600902-dfn3e8u8c",
|
||||
"type": "research",
|
||||
"description": "Analyze authentication patterns",
|
||||
"status": "assigned",
|
||||
"priority": 8,
|
||||
"dependencies": [],
|
||||
"metadata": {},
|
||||
"progress": 0,
|
||||
"createdAt": 1749613600902,
|
||||
"assignedAgent": "agent-1749613592964-g0npi8ni4"
|
||||
}
|
||||
],
|
||||
"lastUpdated": 1749614777174
|
||||
"agents": [],
|
||||
"tasks": [],
|
||||
"lastUpdated": 1749659144815
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "==========================================
|
||||
|
||||
Claude-Flow REPL Demo
|
||||
|
||||
==========================================
|
||||
|
||||
The REPL is now fully functional! Here's what you can do:
|
||||
|
||||
1. Start the REPL:
|
||||
$ claude-flow repl
|
||||
|
||||
2. Available commands:
|
||||
- help : Show all commands
|
||||
- status : Show system status
|
||||
- clear : Clear screen
|
||||
- history : Show command history
|
||||
- exit : Exit REPL
|
||||
|
||||
3. Agent Management:
|
||||
- agent spawn <type> [name]
|
||||
- agent list
|
||||
- agent info <id>
|
||||
- agent terminate <id>
|
||||
|
||||
4. Task Management:
|
||||
- task create <type> <description>
|
||||
- task list
|
||||
- task assign <task-id> <agent-id>
|
||||
- task status <id>
|
||||
|
||||
5. Memory Operations:
|
||||
- memory store <key> <value>
|
||||
- memory get <key>
|
||||
- memory list
|
||||
- memory clear
|
||||
|
||||
6. Terminal Sessions:
|
||||
- terminal create [name]
|
||||
- terminal list
|
||||
- terminal exec <command>
|
||||
- terminal attach <id>
|
||||
- terminal detach
|
||||
|
||||
7. Special Features:
|
||||
- !<command> : Execute shell command
|
||||
- /<search> : Search command history
|
||||
|
||||
==========================================
|
||||
|
||||
Starting interactive REPL now...
|
||||
"
|
||||
|
||||
# Start the REPL
|
||||
./bin/claude-flow repl
|
||||
@@ -0,0 +1,213 @@
|
||||
// command-registry.js - Extensible command registration system
|
||||
import { initCommand } from './simple-commands/init.js';
|
||||
import { memoryCommand } from './simple-commands/memory.js';
|
||||
import { sparcCommand } from './simple-commands/sparc.js';
|
||||
import { agentCommand } from './simple-commands/agent.js';
|
||||
import { taskCommand } from './simple-commands/task.js';
|
||||
import { configCommand } from './simple-commands/config.js';
|
||||
import { statusCommand } from './simple-commands/status.js';
|
||||
import { mcpCommand } from './simple-commands/mcp.js';
|
||||
import { monitorCommand } from './simple-commands/monitor.js';
|
||||
|
||||
// Command registry for extensible CLI
|
||||
export const commandRegistry = new Map();
|
||||
|
||||
// Register core commands
|
||||
export function registerCoreCommands() {
|
||||
commandRegistry.set('init', {
|
||||
handler: initCommand,
|
||||
description: 'Initialize Claude Code integration files',
|
||||
usage: 'init [--force] [--minimal] [--sparc]',
|
||||
examples: [
|
||||
'init --sparc',
|
||||
'init --force --minimal',
|
||||
'init --sparc --force'
|
||||
]
|
||||
});
|
||||
|
||||
commandRegistry.set('memory', {
|
||||
handler: memoryCommand,
|
||||
description: 'Memory management operations',
|
||||
usage: 'memory <subcommand> [options]',
|
||||
examples: [
|
||||
'memory store key "value"',
|
||||
'memory query search_term',
|
||||
'memory stats',
|
||||
'memory export backup.json'
|
||||
]
|
||||
});
|
||||
|
||||
commandRegistry.set('sparc', {
|
||||
handler: sparcCommand,
|
||||
description: 'SPARC development mode operations',
|
||||
usage: 'sparc <subcommand> [options]',
|
||||
examples: [
|
||||
'sparc modes',
|
||||
'sparc run code "implement feature"',
|
||||
'sparc tdd "feature description"',
|
||||
'sparc info architect'
|
||||
]
|
||||
});
|
||||
|
||||
commandRegistry.set('agent', {
|
||||
handler: agentCommand,
|
||||
description: 'Manage AI agents and hierarchies',
|
||||
usage: 'agent <subcommand> [options]',
|
||||
examples: [
|
||||
'agent spawn researcher --name "DataBot"',
|
||||
'agent list --verbose',
|
||||
'agent hierarchy create enterprise',
|
||||
'agent ecosystem status'
|
||||
]
|
||||
});
|
||||
|
||||
commandRegistry.set('task', {
|
||||
handler: taskCommand,
|
||||
description: 'Manage tasks and workflows',
|
||||
usage: 'task <subcommand> [options]',
|
||||
examples: [
|
||||
'task create research "Market analysis"',
|
||||
'task list --filter running',
|
||||
'task workflow examples/dev-flow.json',
|
||||
'task coordination status'
|
||||
]
|
||||
});
|
||||
|
||||
commandRegistry.set('config', {
|
||||
handler: configCommand,
|
||||
description: 'Manage system configuration',
|
||||
usage: 'config <subcommand> [options]',
|
||||
examples: [
|
||||
'config init',
|
||||
'config set terminal.poolSize 15',
|
||||
'config get orchestrator.maxConcurrentTasks',
|
||||
'config validate'
|
||||
]
|
||||
});
|
||||
|
||||
commandRegistry.set('status', {
|
||||
handler: statusCommand,
|
||||
description: 'Show system status and health',
|
||||
usage: 'status [--verbose] [--json]',
|
||||
examples: [
|
||||
'status',
|
||||
'status --verbose',
|
||||
'status --json'
|
||||
]
|
||||
});
|
||||
|
||||
commandRegistry.set('mcp', {
|
||||
handler: mcpCommand,
|
||||
description: 'Manage MCP server and tools',
|
||||
usage: 'mcp <subcommand> [options]',
|
||||
examples: [
|
||||
'mcp status',
|
||||
'mcp start --port 8080',
|
||||
'mcp tools --verbose',
|
||||
'mcp auth setup'
|
||||
]
|
||||
});
|
||||
|
||||
commandRegistry.set('monitor', {
|
||||
handler: monitorCommand,
|
||||
description: 'Real-time system monitoring',
|
||||
usage: 'monitor [--watch] [--interval <ms>]',
|
||||
examples: [
|
||||
'monitor',
|
||||
'monitor --watch',
|
||||
'monitor --interval 1000 --watch',
|
||||
'monitor --format json'
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
// Register a new command
|
||||
export function registerCommand(name, command) {
|
||||
if (commandRegistry.has(name)) {
|
||||
console.warn(`Command '${name}' already exists and will be overwritten`);
|
||||
}
|
||||
|
||||
commandRegistry.set(name, {
|
||||
handler: command.handler,
|
||||
description: command.description || 'No description available',
|
||||
usage: command.usage || `${name} [options]`,
|
||||
examples: command.examples || [],
|
||||
hidden: command.hidden || false
|
||||
});
|
||||
}
|
||||
|
||||
// Get command handler
|
||||
export function getCommand(name) {
|
||||
return commandRegistry.get(name);
|
||||
}
|
||||
|
||||
// List all registered commands
|
||||
export function listCommands(includeHidden = false) {
|
||||
const commands = [];
|
||||
for (const [name, command] of commandRegistry.entries()) {
|
||||
if (includeHidden || !command.hidden) {
|
||||
commands.push({
|
||||
name,
|
||||
...command
|
||||
});
|
||||
}
|
||||
}
|
||||
return commands.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
// Check if command exists
|
||||
export function hasCommand(name) {
|
||||
return commandRegistry.has(name);
|
||||
}
|
||||
|
||||
// Execute a command
|
||||
export async function executeCommand(name, subArgs, flags) {
|
||||
const command = commandRegistry.get(name);
|
||||
if (!command) {
|
||||
throw new Error(`Unknown command: ${name}`);
|
||||
}
|
||||
|
||||
try {
|
||||
await command.handler(subArgs, flags);
|
||||
} catch (err) {
|
||||
throw new Error(`Command '${name}' failed: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to show command help
|
||||
export function showCommandHelp(name) {
|
||||
const command = commandRegistry.get(name);
|
||||
if (!command) {
|
||||
console.log(`Unknown command: ${name}`);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Command: ${name}`);
|
||||
console.log(`Description: ${command.description}`);
|
||||
console.log(`Usage: ${command.usage}`);
|
||||
|
||||
if (command.examples.length > 0) {
|
||||
console.log('\nExamples:');
|
||||
for (const example of command.examples) {
|
||||
console.log(` claude-flow ${example}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to show all commands
|
||||
export function showAllCommands() {
|
||||
const commands = listCommands();
|
||||
|
||||
console.log('Available commands:');
|
||||
console.log();
|
||||
|
||||
for (const command of commands) {
|
||||
console.log(` ${command.name.padEnd(12)} ${command.description}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
console.log('Use "claude-flow help <command>" for detailed usage information');
|
||||
}
|
||||
|
||||
// Initialize the command registry
|
||||
registerCoreCommands();
|
||||
@@ -9,6 +9,7 @@ import { Logger } from "../../core/logger.ts";
|
||||
import { JsonPersistenceManager } from "../../core/json-persistence.ts";
|
||||
import { swarmAction } from "./swarm.ts";
|
||||
import { SimpleMemoryManager } from "./memory.ts";
|
||||
import { sparcAction } from "./sparc.ts";
|
||||
|
||||
let orchestrator: Orchestrator | null = null;
|
||||
let configManager: ConfigManager | null = null;
|
||||
@@ -1351,6 +1352,51 @@ Now, please proceed with the task: ${task}`;
|
||||
action: swarmAction,
|
||||
});
|
||||
|
||||
// SPARC command
|
||||
cli.command({
|
||||
name: "sparc",
|
||||
description: "SPARC-based TDD development with specialized modes",
|
||||
options: [
|
||||
{
|
||||
name: "namespace",
|
||||
short: "n",
|
||||
description: "Memory namespace for this session",
|
||||
type: "string",
|
||||
default: "sparc",
|
||||
},
|
||||
{
|
||||
name: "no-permissions",
|
||||
description: "Skip permission prompts",
|
||||
type: "boolean",
|
||||
},
|
||||
{
|
||||
name: "config",
|
||||
short: "c",
|
||||
description: "MCP configuration file",
|
||||
type: "string",
|
||||
},
|
||||
{
|
||||
name: "verbose",
|
||||
short: "v",
|
||||
description: "Enable verbose output",
|
||||
type: "boolean",
|
||||
},
|
||||
{
|
||||
name: "dry-run",
|
||||
short: "d",
|
||||
description: "Preview what would be executed",
|
||||
type: "boolean",
|
||||
},
|
||||
{
|
||||
name: "sequential",
|
||||
description: "Wait between workflow steps",
|
||||
type: "boolean",
|
||||
default: true,
|
||||
},
|
||||
],
|
||||
action: sparcAction,
|
||||
});
|
||||
|
||||
// Swarm UI command (convenience wrapper)
|
||||
cli.command({
|
||||
name: "swarm-ui",
|
||||
@@ -1507,6 +1553,44 @@ Now, please proceed with the task: ${task}`;
|
||||
console.log("For more information, see:");
|
||||
console.log(" - https://github.com/ruvnet/claude-code-flow/docs/12-swarm.md");
|
||||
console.log(" - https://github.com/ruvnet/claude-code-flow/SWARM_TTY_SOLUTION.md");
|
||||
} else if (command === "sparc") {
|
||||
console.log(bold(blue("SPARC Development Mode")));
|
||||
console.log();
|
||||
console.log("SPARC (Specification, Pseudocode, Architecture, Refinement, Completion)");
|
||||
console.log("TDD-based development with specialized AI modes from .roomodes configuration.");
|
||||
console.log();
|
||||
console.log(bold("Subcommands:"));
|
||||
console.log(" modes List all available SPARC modes");
|
||||
console.log(" info <mode> Show detailed information about a mode");
|
||||
console.log(" run <mode> <task> Execute a task using a specific SPARC mode");
|
||||
console.log(" tdd <task> Run full TDD workflow using SPARC methodology");
|
||||
console.log(" workflow <file> Execute a custom SPARC workflow from JSON file");
|
||||
console.log();
|
||||
console.log(bold("Common Modes:"));
|
||||
console.log(" spec-pseudocode Create specifications and pseudocode");
|
||||
console.log(" architect Design system architecture");
|
||||
console.log(" code Implement code solutions");
|
||||
console.log(" tdd Test-driven development");
|
||||
console.log(" debug Debug and troubleshoot issues");
|
||||
console.log(" security-review Security analysis and review");
|
||||
console.log(" docs-writer Documentation creation");
|
||||
console.log(" integration System integration and testing");
|
||||
console.log();
|
||||
console.log(bold("Options:"));
|
||||
console.log(" -n, --namespace <ns> Memory namespace for this session");
|
||||
console.log(" --no-permissions Skip permission prompts");
|
||||
console.log(" -c, --config <file> MCP configuration file");
|
||||
console.log(" -v, --verbose Enable verbose output");
|
||||
console.log(" -d, --dry-run Preview what would be executed");
|
||||
console.log(" --sequential Wait between workflow steps (default: true)");
|
||||
console.log();
|
||||
console.log(bold("Examples:"));
|
||||
console.log(` ${blue("claude-flow sparc modes")} # List all modes`);
|
||||
console.log(` ${blue("claude-flow sparc run code")} "implement user auth" # Run specific mode`);
|
||||
console.log(` ${blue("claude-flow sparc tdd")} "payment processing system" # Full TDD workflow`);
|
||||
console.log(` ${blue("claude-flow sparc workflow")} project-workflow.json # Custom workflow`);
|
||||
console.log();
|
||||
console.log("For more information, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md");
|
||||
} else {
|
||||
// Show general help
|
||||
cli.showHelp();
|
||||
|
||||
@@ -0,0 +1,514 @@
|
||||
import { success, error, warning, info } from "../cli-core.ts";
|
||||
import type { CommandContext } from "../cli-core.ts";
|
||||
import { blue, yellow, green, magenta, cyan } from "https://deno.land/std@0.224.0/fmt/colors.ts";
|
||||
|
||||
interface SparcMode {
|
||||
slug: string;
|
||||
name: string;
|
||||
roleDefinition: string;
|
||||
customInstructions: string;
|
||||
groups: string[];
|
||||
source: string;
|
||||
}
|
||||
|
||||
interface SparcConfig {
|
||||
customModes: SparcMode[];
|
||||
}
|
||||
|
||||
let sparcConfig: SparcConfig | null = null;
|
||||
|
||||
async function loadSparcConfig(): Promise<SparcConfig> {
|
||||
if (sparcConfig) {
|
||||
return sparcConfig;
|
||||
}
|
||||
|
||||
try {
|
||||
const configPath = ".roomodes";
|
||||
const content = await Deno.readTextFile(configPath);
|
||||
sparcConfig = JSON.parse(content);
|
||||
return sparcConfig!;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to load SPARC configuration: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function sparcAction(ctx: CommandContext): Promise<void> {
|
||||
const subcommand = ctx.args[0];
|
||||
|
||||
switch (subcommand) {
|
||||
case "modes":
|
||||
await listSparcModes(ctx);
|
||||
break;
|
||||
case "info":
|
||||
await showModeInfo(ctx);
|
||||
break;
|
||||
case "run":
|
||||
await runSparcMode(ctx);
|
||||
break;
|
||||
case "tdd":
|
||||
await runTddFlow(ctx);
|
||||
break;
|
||||
case "workflow":
|
||||
await runSparcWorkflow(ctx);
|
||||
break;
|
||||
default:
|
||||
await showSparcHelp();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
async function listSparcModes(ctx: CommandContext): Promise<void> {
|
||||
try {
|
||||
const config = await loadSparcConfig();
|
||||
const verbose = ctx.flags.verbose as boolean;
|
||||
|
||||
success("Available SPARC Modes:");
|
||||
console.log();
|
||||
|
||||
for (const mode of config.customModes) {
|
||||
console.log(`${cyan("•")} ${green(mode.name)} ${blue(`(${mode.slug})`)}`);
|
||||
if (verbose) {
|
||||
console.log(` ${mode.roleDefinition}`);
|
||||
console.log(` Tools: ${mode.groups.join(", ")}`);
|
||||
console.log();
|
||||
}
|
||||
}
|
||||
|
||||
if (!verbose) {
|
||||
console.log();
|
||||
info("Use --verbose for detailed descriptions");
|
||||
}
|
||||
} catch (err) {
|
||||
error(`Failed to list SPARC modes: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showModeInfo(ctx: CommandContext): Promise<void> {
|
||||
const modeSlug = ctx.args[1];
|
||||
if (!modeSlug) {
|
||||
error("Usage: sparc info <mode-slug>");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await loadSparcConfig();
|
||||
const mode = config.customModes.find(m => m.slug === modeSlug);
|
||||
|
||||
if (!mode) {
|
||||
error(`Mode not found: ${modeSlug}`);
|
||||
console.log("Available modes:");
|
||||
for (const m of config.customModes) {
|
||||
console.log(` ${m.slug} - ${m.name}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
success(`SPARC Mode: ${mode.name}`);
|
||||
console.log();
|
||||
console.log(blue("Role Definition:"));
|
||||
console.log(mode.roleDefinition);
|
||||
console.log();
|
||||
console.log(blue("Custom Instructions:"));
|
||||
console.log(mode.customInstructions);
|
||||
console.log();
|
||||
console.log(blue("Tool Groups:"));
|
||||
console.log(mode.groups.join(", "));
|
||||
console.log();
|
||||
console.log(blue("Source:"));
|
||||
console.log(mode.source);
|
||||
|
||||
} catch (err) {
|
||||
error(`Failed to show mode info: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runSparcMode(ctx: CommandContext): Promise<void> {
|
||||
const modeSlug = ctx.args[1];
|
||||
const taskDescription = ctx.args.slice(2).join(" ");
|
||||
|
||||
if (!modeSlug || !taskDescription) {
|
||||
error("Usage: sparc run <mode-slug> <task-description>");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await loadSparcConfig();
|
||||
const mode = config.customModes.find(m => m.slug === modeSlug);
|
||||
|
||||
if (!mode) {
|
||||
error(`Mode not found: ${modeSlug}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Build the enhanced task prompt using SPARC methodology
|
||||
const enhancedTask = buildSparcPrompt(mode, taskDescription, ctx.flags);
|
||||
const instanceId = `sparc-${modeSlug}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
|
||||
// Build tools based on mode groups
|
||||
const tools = buildToolsFromGroups(mode.groups);
|
||||
|
||||
if (ctx.flags.dryRun || ctx.flags["dry-run"]) {
|
||||
warning("DRY RUN - SPARC Mode Configuration:");
|
||||
console.log(`Mode: ${mode.name} (${mode.slug})`);
|
||||
console.log(`Instance ID: ${instanceId}`);
|
||||
console.log(`Tools: ${tools}`);
|
||||
console.log(`Task: ${taskDescription}`);
|
||||
console.log();
|
||||
console.log("Enhanced prompt preview:");
|
||||
console.log(enhancedTask.substring(0, 300) + "...");
|
||||
return;
|
||||
}
|
||||
|
||||
success(`Starting SPARC mode: ${mode.name}`);
|
||||
console.log(`📝 Instance ID: ${instanceId}`);
|
||||
console.log(`🎯 Mode: ${mode.slug}`);
|
||||
console.log(`🔧 Tools: ${tools}`);
|
||||
console.log(`📋 Task: ${taskDescription}`);
|
||||
console.log();
|
||||
|
||||
// Execute Claude with SPARC configuration
|
||||
await executeClaudeWithSparc(enhancedTask, tools, instanceId, ctx.flags);
|
||||
|
||||
} catch (err) {
|
||||
error(`Failed to run SPARC mode: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runTddFlow(ctx: CommandContext): Promise<void> {
|
||||
const taskDescription = ctx.args.slice(1).join(" ");
|
||||
|
||||
if (!taskDescription) {
|
||||
error("Usage: sparc tdd <task-description>");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await loadSparcConfig();
|
||||
|
||||
// Build TDD workflow using SPARC methodology
|
||||
const workflow = [
|
||||
{ mode: "spec-pseudocode", phase: "Specification", description: `Create detailed spec and pseudocode for: ${taskDescription}` },
|
||||
{ mode: "tdd", phase: "Red", description: `Write failing tests for: ${taskDescription}` },
|
||||
{ mode: "code", phase: "Green", description: `Implement minimal code to pass tests for: ${taskDescription}` },
|
||||
{ mode: "refinement-optimization-mode", phase: "Refactor", description: `Refactor and optimize implementation for: ${taskDescription}` },
|
||||
{ mode: "integration", phase: "Integration", description: `Integrate and verify complete solution for: ${taskDescription}` }
|
||||
];
|
||||
|
||||
if (ctx.flags.dryRun || ctx.flags["dry-run"]) {
|
||||
warning("DRY RUN - TDD Workflow:");
|
||||
for (const step of workflow) {
|
||||
console.log(`${cyan(step.phase)}: ${step.mode} - ${step.description}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
success("Starting SPARC TDD Workflow");
|
||||
console.log("Following Test-Driven Development with SPARC methodology");
|
||||
console.log();
|
||||
|
||||
for (let i = 0; i < workflow.length; i++) {
|
||||
const step = workflow[i];
|
||||
const mode = config.customModes.find(m => m.slug === step.mode);
|
||||
|
||||
if (!mode) {
|
||||
warning(`Mode not found: ${step.mode}, skipping step`);
|
||||
continue;
|
||||
}
|
||||
|
||||
info(`Phase ${i + 1}/5: ${step.phase} (${mode.name})`);
|
||||
console.log(`📋 ${step.description}`);
|
||||
console.log();
|
||||
|
||||
const enhancedTask = buildSparcPrompt(mode, step.description, {
|
||||
...ctx.flags,
|
||||
tddPhase: step.phase,
|
||||
workflowStep: i + 1,
|
||||
totalSteps: workflow.length
|
||||
});
|
||||
|
||||
const tools = buildToolsFromGroups(mode.groups);
|
||||
const instanceId = `sparc-tdd-${step.phase.toLowerCase()}-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`;
|
||||
|
||||
await executeClaudeWithSparc(enhancedTask, tools, instanceId, ctx.flags);
|
||||
|
||||
// Store phase completion in memory for next step
|
||||
if (ctx.flags.sequential !== false) {
|
||||
console.log("Phase completed. Press Enter to continue to next phase, or Ctrl+C to stop...");
|
||||
await new Promise<void>((resolve) => {
|
||||
const decoder = new TextDecoder();
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
Deno.stdin.read(new Uint8Array(1)).then(() => resolve());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
success("SPARC TDD Workflow completed!");
|
||||
|
||||
} catch (err) {
|
||||
error(`Failed to run TDD flow: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runSparcWorkflow(ctx: CommandContext): Promise<void> {
|
||||
const workflowFile = ctx.args[1];
|
||||
|
||||
if (!workflowFile) {
|
||||
error("Usage: sparc workflow <workflow-file.json>");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const workflowContent = await Deno.readTextFile(workflowFile);
|
||||
const workflow = JSON.parse(workflowContent);
|
||||
|
||||
if (!workflow.steps || !Array.isArray(workflow.steps)) {
|
||||
error("Invalid workflow file: missing 'steps' array");
|
||||
return;
|
||||
}
|
||||
|
||||
const config = await loadSparcConfig();
|
||||
|
||||
success(`Loading SPARC workflow: ${workflow.name || "Unnamed"}`);
|
||||
console.log(`📋 Steps: ${workflow.steps.length}`);
|
||||
console.log(`📝 Description: ${workflow.description || "No description"}`);
|
||||
console.log();
|
||||
|
||||
if (ctx.flags.dryRun || ctx.flags["dry-run"]) {
|
||||
warning("DRY RUN - Workflow Steps:");
|
||||
for (let i = 0; i < workflow.steps.length; i++) {
|
||||
const step = workflow.steps[i];
|
||||
console.log(`${i + 1}. ${cyan(step.mode)} - ${step.description || step.task}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < workflow.steps.length; i++) {
|
||||
const step = workflow.steps[i];
|
||||
const mode = config.customModes.find(m => m.slug === step.mode);
|
||||
|
||||
if (!mode) {
|
||||
warning(`Mode not found: ${step.mode}, skipping step ${i + 1}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
info(`Step ${i + 1}/${workflow.steps.length}: ${mode.name}`);
|
||||
console.log(`📋 ${step.description || step.task}`);
|
||||
console.log();
|
||||
|
||||
const enhancedTask = buildSparcPrompt(mode, step.description || step.task, {
|
||||
...ctx.flags,
|
||||
workflowStep: i + 1,
|
||||
totalSteps: workflow.steps.length,
|
||||
workflowName: workflow.name
|
||||
});
|
||||
|
||||
const tools = buildToolsFromGroups(mode.groups);
|
||||
const instanceId = `sparc-workflow-${i + 1}-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`;
|
||||
|
||||
await executeClaudeWithSparc(enhancedTask, tools, instanceId, ctx.flags);
|
||||
|
||||
if (workflow.sequential !== false && i < workflow.steps.length - 1) {
|
||||
console.log("Step completed. Press Enter to continue, or Ctrl+C to stop...");
|
||||
await new Promise<void>((resolve) => {
|
||||
Deno.stdin.read(new Uint8Array(1)).then(() => resolve());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
success("SPARC workflow completed!");
|
||||
|
||||
} catch (err) {
|
||||
error(`Failed to run workflow: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function buildSparcPrompt(mode: SparcMode, taskDescription: string, flags: any): string {
|
||||
const memoryNamespace = flags.namespace || mode.slug || "default";
|
||||
|
||||
return `# SPARC Development Mode: ${mode.name}
|
||||
|
||||
## Your Role
|
||||
${mode.roleDefinition}
|
||||
|
||||
## Your Task
|
||||
${taskDescription}
|
||||
|
||||
## Mode-Specific Instructions
|
||||
${mode.customInstructions}
|
||||
|
||||
## SPARC Development Environment
|
||||
|
||||
You are working within the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) methodology using claude-flow orchestration features.
|
||||
|
||||
### Available Development Tools
|
||||
- **Memory Persistence**: Use \`npx claude-flow memory store <key> "<value>"\` to save progress and findings
|
||||
- **Memory Retrieval**: Use \`npx claude-flow memory query <search>\` to access previous work
|
||||
- **Namespace**: Your work is stored in the "${memoryNamespace}" namespace
|
||||
|
||||
### SPARC Methodology Integration
|
||||
${flags.tddPhase ? `
|
||||
**Current TDD Phase**: ${flags.tddPhase}
|
||||
- Follow the Red-Green-Refactor cycle
|
||||
- Store test results and refactoring notes in memory
|
||||
` : ''}
|
||||
|
||||
${flags.workflowStep ? `
|
||||
**Workflow Progress**: Step ${flags.workflowStep} of ${flags.totalSteps}
|
||||
- Review previous steps: \`npx claude-flow memory query previous_steps\`
|
||||
- Store this step's output: \`npx claude-flow memory store step_${flags.workflowStep}_output "<results>"\`
|
||||
` : ''}
|
||||
|
||||
### Best Practices
|
||||
1. **Modular Development**: Keep all files under 500 lines
|
||||
2. **Environment Safety**: Never hardcode secrets or environment values
|
||||
3. **Memory Usage**: Store key findings and decisions in memory for future reference
|
||||
4. **Tool Integration**: Use \`new_task\` for subtasks and \`attempt_completion\` when finished
|
||||
|
||||
### Memory Commands Examples
|
||||
\`\`\`bash
|
||||
# Store your progress
|
||||
npx claude-flow memory store ${memoryNamespace}_progress "Current status and findings"
|
||||
|
||||
# Check for previous work
|
||||
npx claude-flow memory query ${memoryNamespace}
|
||||
|
||||
# Store phase-specific results
|
||||
npx claude-flow memory store ${memoryNamespace}_${flags.tddPhase || 'results'} "Phase output and decisions"
|
||||
\`\`\`
|
||||
|
||||
### Integration with Other SPARC Modes
|
||||
When working with other SPARC modes, use memory to:
|
||||
- Share findings with spec-pseudocode mode
|
||||
- Pass requirements to architect mode
|
||||
- Coordinate with code and tdd modes
|
||||
- Communicate results to integration mode
|
||||
|
||||
Now proceed with your task following the SPARC methodology and your specific role instructions.`;
|
||||
}
|
||||
|
||||
function buildToolsFromGroups(groups: string[]): string {
|
||||
const toolMappings: Record<string, string[]> = {
|
||||
read: ["View", "LS", "GlobTool", "GrepTool"],
|
||||
edit: ["Edit", "Replace", "MultiEdit", "Write"],
|
||||
browser: ["WebFetch"],
|
||||
mcp: ["mcp_tools"],
|
||||
command: ["Bash", "Terminal"]
|
||||
};
|
||||
|
||||
const tools = new Set<string>();
|
||||
|
||||
// Always include basic tools
|
||||
tools.add("View");
|
||||
tools.add("Edit");
|
||||
tools.add("Bash");
|
||||
|
||||
for (const group of groups) {
|
||||
if (Array.isArray(group)) {
|
||||
// Handle nested group definitions
|
||||
const groupName = group[0];
|
||||
if (toolMappings[groupName]) {
|
||||
toolMappings[groupName].forEach(tool => tools.add(tool));
|
||||
}
|
||||
} else if (toolMappings[group]) {
|
||||
toolMappings[group].forEach(tool => tools.add(tool));
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(tools).join(",");
|
||||
}
|
||||
|
||||
async function executeClaudeWithSparc(
|
||||
enhancedTask: string,
|
||||
tools: string,
|
||||
instanceId: string,
|
||||
flags: any
|
||||
): Promise<void> {
|
||||
const claudeArgs = [enhancedTask];
|
||||
claudeArgs.push("--allowedTools", tools);
|
||||
|
||||
if (flags.noPermissions || flags["no-permissions"]) {
|
||||
claudeArgs.push("--dangerously-skip-permissions");
|
||||
}
|
||||
|
||||
if (flags.config) {
|
||||
claudeArgs.push("--mcp-config", flags.config);
|
||||
}
|
||||
|
||||
if (flags.verbose) {
|
||||
claudeArgs.push("--verbose");
|
||||
}
|
||||
|
||||
try {
|
||||
const command = new Deno.Command("claude", {
|
||||
args: claudeArgs,
|
||||
env: {
|
||||
...Deno.env.toObject(),
|
||||
CLAUDE_INSTANCE_ID: instanceId,
|
||||
CLAUDE_SPARC_MODE: "true",
|
||||
CLAUDE_FLOW_MEMORY_ENABLED: "true",
|
||||
CLAUDE_FLOW_MEMORY_NAMESPACE: flags.namespace || "sparc",
|
||||
},
|
||||
stdin: "inherit",
|
||||
stdout: "inherit",
|
||||
stderr: "inherit",
|
||||
});
|
||||
|
||||
const child = command.spawn();
|
||||
const status = await child.status;
|
||||
|
||||
if (status.success) {
|
||||
success(`SPARC instance ${instanceId} completed successfully`);
|
||||
} else {
|
||||
error(`SPARC instance ${instanceId} exited with code ${status.code}`);
|
||||
}
|
||||
} catch (err) {
|
||||
error(`Failed to execute Claude: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showSparcHelp(): Promise<void> {
|
||||
console.log(`${cyan("SPARC")} - ${green("Specification, Pseudocode, Architecture, Refinement, Completion")}`);
|
||||
console.log();
|
||||
console.log("SPARC development methodology with TDD and multi-agent coordination.");
|
||||
console.log();
|
||||
console.log(blue("Commands:"));
|
||||
console.log(" modes List all available SPARC modes");
|
||||
console.log(" info <mode> Show detailed information about a mode");
|
||||
console.log(" run <mode> <task> Execute a task using a specific SPARC mode");
|
||||
console.log(" tdd <task> Run full TDD workflow using SPARC methodology");
|
||||
console.log(" workflow <file> Execute a custom SPARC workflow from JSON file");
|
||||
console.log();
|
||||
console.log(blue("Common Modes:"));
|
||||
console.log(" spec-pseudocode Create specifications and pseudocode");
|
||||
console.log(" architect Design system architecture");
|
||||
console.log(" code Implement code solutions");
|
||||
console.log(" tdd Test-driven development");
|
||||
console.log(" debug Debug and troubleshoot issues");
|
||||
console.log(" security-review Security analysis and review");
|
||||
console.log(" docs-writer Documentation creation");
|
||||
console.log(" integration System integration and testing");
|
||||
console.log();
|
||||
console.log(blue("Options:"));
|
||||
console.log(" --namespace <ns> Memory namespace for this session");
|
||||
console.log(" --no-permissions Skip permission prompts");
|
||||
console.log(" --config <file> MCP configuration file");
|
||||
console.log(" --verbose Enable verbose output");
|
||||
console.log(" --dry-run Preview what would be executed");
|
||||
console.log(" --sequential Wait between workflow steps (default: true)");
|
||||
console.log();
|
||||
console.log(blue("Examples:"));
|
||||
console.log(` ${yellow("claude-flow sparc modes")} # List all modes`);
|
||||
console.log(` ${yellow("claude-flow sparc run code")} "implement user auth" # Run specific mode`);
|
||||
console.log(` ${yellow("claude-flow sparc tdd")} "payment processing system" # Full TDD workflow`);
|
||||
console.log(` ${yellow("claude-flow sparc workflow")} project-workflow.json # Custom workflow`);
|
||||
console.log();
|
||||
console.log(blue("TDD Workflow:"));
|
||||
console.log(" 1. Specification - Define requirements and create pseudocode");
|
||||
console.log(" 2. Red Phase - Write failing tests");
|
||||
console.log(" 3. Green Phase - Implement minimal code to pass tests");
|
||||
console.log(" 4. Refactor Phase - Optimize and clean up code");
|
||||
console.log(" 5. Integration - Verify complete solution");
|
||||
console.log();
|
||||
console.log("For more information: https://github.com/ruvnet/claude-code-flow/docs/sparc.md");
|
||||
}
|
||||
+532
-665
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,211 @@
|
||||
// agent.js - Agent management commands
|
||||
import { printSuccess, printError, printWarning } from '../utils.js';
|
||||
|
||||
export async function agentCommand(subArgs, flags) {
|
||||
const agentCmd = subArgs[0];
|
||||
|
||||
switch (agentCmd) {
|
||||
case 'spawn':
|
||||
await spawnAgent(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'list':
|
||||
await listAgents(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'hierarchy':
|
||||
await manageHierarchy(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'network':
|
||||
await manageNetwork(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'ecosystem':
|
||||
await manageEcosystem(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'provision':
|
||||
await provisionAgent(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'terminate':
|
||||
await terminateAgent(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'info':
|
||||
await showAgentInfo(subArgs, flags);
|
||||
break;
|
||||
|
||||
default:
|
||||
showAgentHelp();
|
||||
}
|
||||
}
|
||||
|
||||
async function spawnAgent(subArgs, flags) {
|
||||
const agentType = subArgs[1] || 'general';
|
||||
const agentName = getFlag(subArgs, '--name') || flags.name || `agent-${Date.now()}`;
|
||||
|
||||
printSuccess(`Spawning ${agentType} agent: ${agentName}`);
|
||||
console.log('🤖 Agent would be created with the following configuration:');
|
||||
console.log(` Type: ${agentType}`);
|
||||
console.log(` Name: ${agentName}`);
|
||||
console.log(' Capabilities: Research, Analysis, Code Generation');
|
||||
console.log(' Status: Ready');
|
||||
console.log('\n📋 Note: Full agent spawning requires orchestrator to be running');
|
||||
}
|
||||
|
||||
async function listAgents(subArgs, flags) {
|
||||
printSuccess('Active agents:');
|
||||
console.log('📋 No agents currently active (orchestrator not running)');
|
||||
console.log('\nTo create agents:');
|
||||
console.log(' claude-flow agent spawn researcher --name "ResearchBot"');
|
||||
console.log(' claude-flow agent spawn coder --name "CodeBot"');
|
||||
console.log(' claude-flow agent spawn analyst --name "DataBot"');
|
||||
}
|
||||
|
||||
async function manageHierarchy(subArgs, flags) {
|
||||
const hierarchyCmd = subArgs[1];
|
||||
|
||||
switch (hierarchyCmd) {
|
||||
case 'create':
|
||||
const hierarchyType = subArgs[2] || 'basic';
|
||||
printSuccess(`Creating ${hierarchyType} agent hierarchy`);
|
||||
console.log('🏗️ Hierarchy structure would include:');
|
||||
console.log(' - Coordinator Agent (manages workflow)');
|
||||
console.log(' - Specialist Agents (domain-specific tasks)');
|
||||
console.log(' - Worker Agents (execution tasks)');
|
||||
break;
|
||||
|
||||
case 'show':
|
||||
printSuccess('Current agent hierarchy:');
|
||||
console.log('📊 No hierarchy configured (orchestrator not running)');
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log('Hierarchy commands: create, show');
|
||||
console.log('Examples:');
|
||||
console.log(' claude-flow agent hierarchy create enterprise');
|
||||
console.log(' claude-flow agent hierarchy show');
|
||||
}
|
||||
}
|
||||
|
||||
async function manageNetwork(subArgs, flags) {
|
||||
const networkCmd = subArgs[1];
|
||||
|
||||
switch (networkCmd) {
|
||||
case 'topology':
|
||||
printSuccess('Agent network topology:');
|
||||
console.log('🌐 Network visualization would show agent connections');
|
||||
break;
|
||||
|
||||
case 'metrics':
|
||||
printSuccess('Network performance metrics:');
|
||||
console.log('📈 Communication latency, throughput, reliability stats');
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log('Network commands: topology, metrics');
|
||||
}
|
||||
}
|
||||
|
||||
async function manageEcosystem(subArgs, flags) {
|
||||
const ecosystemCmd = subArgs[1];
|
||||
|
||||
switch (ecosystemCmd) {
|
||||
case 'status':
|
||||
printSuccess('Agent ecosystem status:');
|
||||
console.log('🌱 Ecosystem health: Not running');
|
||||
console.log(' Active Agents: 0');
|
||||
console.log(' Resource Usage: 0%');
|
||||
console.log(' Task Queue: Empty');
|
||||
break;
|
||||
|
||||
case 'optimize':
|
||||
printSuccess('Optimizing agent ecosystem...');
|
||||
console.log('⚡ Optimization would include:');
|
||||
console.log(' - Load balancing across agents');
|
||||
console.log(' - Resource allocation optimization');
|
||||
console.log(' - Communication path optimization');
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log('Ecosystem commands: status, optimize');
|
||||
}
|
||||
}
|
||||
|
||||
async function provisionAgent(subArgs, flags) {
|
||||
const provision = subArgs[1];
|
||||
|
||||
if (!provision) {
|
||||
printError('Usage: agent provision <count>');
|
||||
return;
|
||||
}
|
||||
|
||||
const count = parseInt(provision);
|
||||
if (isNaN(count) || count < 1) {
|
||||
printError('Count must be a positive number');
|
||||
return;
|
||||
}
|
||||
|
||||
printSuccess(`Provisioning ${count} agents...`);
|
||||
console.log('🚀 Auto-provisioning would create:');
|
||||
for (let i = 1; i <= count; i++) {
|
||||
console.log(` Agent ${i}: Type=general, Status=provisioning`);
|
||||
}
|
||||
}
|
||||
|
||||
async function terminateAgent(subArgs, flags) {
|
||||
const agentId = subArgs[1];
|
||||
|
||||
if (!agentId) {
|
||||
printError('Usage: agent terminate <agent-id>');
|
||||
return;
|
||||
}
|
||||
|
||||
printSuccess(`Terminating agent: ${agentId}`);
|
||||
console.log('🛑 Agent would be gracefully shut down');
|
||||
}
|
||||
|
||||
async function showAgentInfo(subArgs, flags) {
|
||||
const agentId = subArgs[1];
|
||||
|
||||
if (!agentId) {
|
||||
printError('Usage: agent info <agent-id>');
|
||||
return;
|
||||
}
|
||||
|
||||
printSuccess(`Agent information: ${agentId}`);
|
||||
console.log('📊 Agent details would include:');
|
||||
console.log(' Status, capabilities, current tasks, performance metrics');
|
||||
}
|
||||
|
||||
function getFlag(args, flagName) {
|
||||
const index = args.indexOf(flagName);
|
||||
return index !== -1 && index + 1 < args.length ? args[index + 1] : null;
|
||||
}
|
||||
|
||||
function showAgentHelp() {
|
||||
console.log('Agent commands:');
|
||||
console.log(' spawn <type> [--name <name>] Create new agent');
|
||||
console.log(' list [--verbose] List active agents');
|
||||
console.log(' terminate <id> Stop specific agent');
|
||||
console.log(' info <id> Show agent details');
|
||||
console.log(' hierarchy <create|show> Manage agent hierarchies');
|
||||
console.log(' network <topology|metrics> Agent network operations');
|
||||
console.log(' ecosystem <status|optimize> Ecosystem management');
|
||||
console.log(' provision <count> Auto-provision agents');
|
||||
console.log();
|
||||
console.log('Agent Types:');
|
||||
console.log(' researcher Research and information gathering');
|
||||
console.log(' coder Code development and analysis');
|
||||
console.log(' analyst Data analysis and insights');
|
||||
console.log(' coordinator Task coordination and management');
|
||||
console.log(' general Multi-purpose agent');
|
||||
console.log();
|
||||
console.log('Examples:');
|
||||
console.log(' claude-flow agent spawn researcher --name "DataBot"');
|
||||
console.log(' claude-flow agent list --verbose');
|
||||
console.log(' claude-flow agent hierarchy create enterprise');
|
||||
console.log(' claude-flow agent ecosystem status');
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
// config.js - Configuration management commands
|
||||
import { printSuccess, printError, printWarning, readJsonFile, writeJsonFile } from '../utils.js';
|
||||
|
||||
export async function configCommand(subArgs, flags) {
|
||||
const configCmd = subArgs[0];
|
||||
|
||||
switch (configCmd) {
|
||||
case 'init':
|
||||
await initConfig(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'show':
|
||||
await showConfig(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'get':
|
||||
await getConfigValue(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'set':
|
||||
await setConfigValue(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'validate':
|
||||
await validateConfig(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'reset':
|
||||
await resetConfig(subArgs, flags);
|
||||
break;
|
||||
|
||||
default:
|
||||
showConfigHelp();
|
||||
}
|
||||
}
|
||||
|
||||
async function initConfig(subArgs, flags) {
|
||||
const force = subArgs.includes('--force') || subArgs.includes('-f');
|
||||
const configFile = 'claude-flow.config.json';
|
||||
|
||||
try {
|
||||
// Check if config already exists
|
||||
const exists = await fileExists(configFile);
|
||||
if (exists && !force) {
|
||||
printWarning('Configuration file already exists');
|
||||
console.log('Use --force to overwrite existing configuration');
|
||||
return;
|
||||
}
|
||||
|
||||
printSuccess('Initializing Claude-Flow configuration...');
|
||||
|
||||
// Create default configuration
|
||||
const defaultConfig = {
|
||||
version: "1.0.30",
|
||||
terminal: {
|
||||
poolSize: 10,
|
||||
recycleAfter: 20,
|
||||
healthCheckInterval: 30000,
|
||||
type: "auto"
|
||||
},
|
||||
orchestrator: {
|
||||
maxConcurrentTasks: 10,
|
||||
taskTimeout: 300000,
|
||||
defaultPriority: 5
|
||||
},
|
||||
memory: {
|
||||
backend: "json",
|
||||
path: "./memory/claude-flow-data.json",
|
||||
cacheSize: 1000,
|
||||
indexing: true
|
||||
},
|
||||
agents: {
|
||||
maxAgents: 20,
|
||||
defaultCapabilities: ["research", "code", "terminal"],
|
||||
resourceLimits: {
|
||||
memory: "1GB",
|
||||
cpu: "50%"
|
||||
}
|
||||
},
|
||||
mcp: {
|
||||
port: 3000,
|
||||
host: "localhost",
|
||||
timeout: 30000
|
||||
},
|
||||
logging: {
|
||||
level: "info",
|
||||
file: "./claude-flow.log",
|
||||
maxSize: "10MB",
|
||||
maxFiles: 5
|
||||
}
|
||||
};
|
||||
|
||||
await writeJsonFile(configFile, defaultConfig);
|
||||
console.log(`✓ Created ${configFile}`);
|
||||
console.log('✓ Default settings configured');
|
||||
console.log('\nNext steps:');
|
||||
console.log('1. Review settings: claude-flow config show');
|
||||
console.log('2. Customize values: claude-flow config set <key> <value>');
|
||||
console.log('3. Validate config: claude-flow config validate');
|
||||
|
||||
} catch (err) {
|
||||
printError(`Failed to initialize configuration: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showConfig(subArgs, flags) {
|
||||
const configFile = 'claude-flow.config.json';
|
||||
const format = getFlag(subArgs, '--format') || 'pretty';
|
||||
|
||||
try {
|
||||
const config = await readJsonFile(configFile);
|
||||
|
||||
printSuccess('Current configuration:');
|
||||
|
||||
if (format === 'json') {
|
||||
console.log(JSON.stringify(config, null, 2));
|
||||
} else {
|
||||
// Pretty format
|
||||
console.log('\n📋 System Configuration:');
|
||||
console.log(` Version: ${config.version || 'unknown'}`);
|
||||
console.log('\n🖥️ Terminal Pool:');
|
||||
console.log(` Pool Size: ${config.terminal?.poolSize || 10}`);
|
||||
console.log(` Recycle After: ${config.terminal?.recycleAfter || 20} commands`);
|
||||
console.log(` Health Check: ${config.terminal?.healthCheckInterval || 30000}ms`);
|
||||
console.log('\n🎭 Orchestrator:');
|
||||
console.log(` Max Concurrent Tasks: ${config.orchestrator?.maxConcurrentTasks || 10}`);
|
||||
console.log(` Task Timeout: ${config.orchestrator?.taskTimeout || 300000}ms`);
|
||||
console.log('\n💾 Memory:');
|
||||
console.log(` Backend: ${config.memory?.backend || 'json'}`);
|
||||
console.log(` Path: ${config.memory?.path || './memory/claude-flow-data.json'}`);
|
||||
console.log('\n🤖 Agents:');
|
||||
console.log(` Max Agents: ${config.agents?.maxAgents || 20}`);
|
||||
console.log(` Resource Limits: ${JSON.stringify(config.agents?.resourceLimits || {})}`);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
printError('Configuration file not found');
|
||||
console.log('Run "claude-flow config init" to create default configuration');
|
||||
}
|
||||
}
|
||||
|
||||
async function getConfigValue(subArgs, flags) {
|
||||
const key = subArgs[1];
|
||||
const configFile = 'claude-flow.config.json';
|
||||
|
||||
if (!key) {
|
||||
printError('Usage: config get <key>');
|
||||
console.log('Examples:');
|
||||
console.log(' claude-flow config get terminal.poolSize');
|
||||
console.log(' claude-flow config get orchestrator.maxConcurrentTasks');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await readJsonFile(configFile);
|
||||
const value = getNestedValue(config, key);
|
||||
|
||||
if (value !== undefined) {
|
||||
console.log(`${key}: ${JSON.stringify(value)}`);
|
||||
} else {
|
||||
printWarning(`Configuration key '${key}' not found`);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
printError('Configuration file not found');
|
||||
console.log('Run "claude-flow config init" to create configuration');
|
||||
}
|
||||
}
|
||||
|
||||
async function setConfigValue(subArgs, flags) {
|
||||
const key = subArgs[1];
|
||||
const value = subArgs[2];
|
||||
const configFile = 'claude-flow.config.json';
|
||||
|
||||
if (!key || value === undefined) {
|
||||
printError('Usage: config set <key> <value>');
|
||||
console.log('Examples:');
|
||||
console.log(' claude-flow config set terminal.poolSize 15');
|
||||
console.log(' claude-flow config set orchestrator.taskTimeout 600000');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
let config = await readJsonFile(configFile, {});
|
||||
|
||||
// Parse value appropriately
|
||||
let parsedValue = value;
|
||||
if (value === 'true') parsedValue = true;
|
||||
else if (value === 'false') parsedValue = false;
|
||||
else if (!isNaN(value) && value.trim() !== '') parsedValue = Number(value);
|
||||
|
||||
// Set nested value
|
||||
setNestedValue(config, key, parsedValue);
|
||||
|
||||
await writeJsonFile(configFile, config);
|
||||
printSuccess(`Set ${key} = ${JSON.stringify(parsedValue)}`);
|
||||
|
||||
} catch (err) {
|
||||
printError(`Failed to set configuration: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function validateConfig(subArgs, flags) {
|
||||
const configFile = 'claude-flow.config.json';
|
||||
|
||||
try {
|
||||
const config = await readJsonFile(configFile);
|
||||
|
||||
printSuccess('Validating configuration...');
|
||||
|
||||
const errors = [];
|
||||
const warnings = [];
|
||||
|
||||
// Validate required sections
|
||||
const requiredSections = ['terminal', 'orchestrator', 'memory'];
|
||||
for (const section of requiredSections) {
|
||||
if (!config[section]) {
|
||||
errors.push(`Missing required section: ${section}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate specific values
|
||||
if (config.terminal?.poolSize && (config.terminal.poolSize < 1 || config.terminal.poolSize > 100)) {
|
||||
warnings.push('Terminal pool size should be between 1 and 100');
|
||||
}
|
||||
|
||||
if (config.orchestrator?.maxConcurrentTasks && config.orchestrator.maxConcurrentTasks < 1) {
|
||||
errors.push('Max concurrent tasks must be at least 1');
|
||||
}
|
||||
|
||||
if (config.agents?.maxAgents && config.agents.maxAgents < 1) {
|
||||
errors.push('Max agents must be at least 1');
|
||||
}
|
||||
|
||||
// Report results
|
||||
if (errors.length === 0 && warnings.length === 0) {
|
||||
printSuccess('✅ Configuration is valid');
|
||||
} else {
|
||||
if (errors.length > 0) {
|
||||
printError(`Found ${errors.length} error(s):`);
|
||||
errors.forEach(error => console.log(` ❌ ${error}`));
|
||||
}
|
||||
|
||||
if (warnings.length > 0) {
|
||||
printWarning(`Found ${warnings.length} warning(s):`);
|
||||
warnings.forEach(warning => console.log(` ⚠️ ${warning}`));
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
printError('Configuration file not found or invalid');
|
||||
console.log('Run "claude-flow config init" to create valid configuration');
|
||||
}
|
||||
}
|
||||
|
||||
async function resetConfig(subArgs, flags) {
|
||||
const force = subArgs.includes('--force') || subArgs.includes('-f');
|
||||
|
||||
if (!force) {
|
||||
printWarning('This will reset configuration to defaults');
|
||||
console.log('Use --force to confirm reset');
|
||||
return;
|
||||
}
|
||||
|
||||
await initConfig(['--force'], flags);
|
||||
printSuccess('Configuration reset to defaults');
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
function getNestedValue(obj, path) {
|
||||
return path.split('.').reduce((current, key) => current?.[key], obj);
|
||||
}
|
||||
|
||||
function setNestedValue(obj, path, value) {
|
||||
const keys = path.split('.');
|
||||
const last = keys.pop();
|
||||
const target = keys.reduce((current, key) => {
|
||||
if (!current[key]) current[key] = {};
|
||||
return current[key];
|
||||
}, obj);
|
||||
target[last] = value;
|
||||
}
|
||||
|
||||
function getFlag(args, flagName) {
|
||||
const index = args.indexOf(flagName);
|
||||
return index !== -1 && index + 1 < args.length ? args[index + 1] : null;
|
||||
}
|
||||
|
||||
async function fileExists(path) {
|
||||
try {
|
||||
await Deno.stat(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function showConfigHelp() {
|
||||
console.log('Configuration commands:');
|
||||
console.log(' init [--force] Create default configuration');
|
||||
console.log(' show [--format json] Display current configuration');
|
||||
console.log(' get <key> Get configuration value');
|
||||
console.log(' set <key> <value> Set configuration value');
|
||||
console.log(' validate Validate configuration');
|
||||
console.log(' reset --force Reset to defaults');
|
||||
console.log();
|
||||
console.log('Configuration Keys:');
|
||||
console.log(' terminal.poolSize Terminal pool size');
|
||||
console.log(' terminal.recycleAfter Commands before recycle');
|
||||
console.log(' orchestrator.maxConcurrentTasks Max parallel tasks');
|
||||
console.log(' orchestrator.taskTimeout Task timeout in ms');
|
||||
console.log(' memory.backend Memory storage backend');
|
||||
console.log(' memory.path Memory database path');
|
||||
console.log(' agents.maxAgents Maximum number of agents');
|
||||
console.log();
|
||||
console.log('Examples:');
|
||||
console.log(' claude-flow config init');
|
||||
console.log(' claude-flow config set terminal.poolSize 15');
|
||||
console.log(' claude-flow config get orchestrator.maxConcurrentTasks');
|
||||
console.log(' claude-flow config validate');
|
||||
}
|
||||
@@ -0,0 +1,908 @@
|
||||
// init.js - Initialize Claude Code integration files
|
||||
import { printSuccess, printError, printWarning } from '../utils.js';
|
||||
|
||||
export async function initCommand(subArgs, flags) {
|
||||
// Parse init options
|
||||
const initForce = subArgs.includes('--force') || subArgs.includes('-f') || flags.force;
|
||||
const initMinimal = subArgs.includes('--minimal') || subArgs.includes('-m') || flags.minimal;
|
||||
const initSparc = subArgs.includes('--sparc') || subArgs.includes('-s') || flags.sparc;
|
||||
|
||||
try {
|
||||
printSuccess('Initializing Claude Code integration files...');
|
||||
|
||||
// Check if files already exist
|
||||
const files = ['CLAUDE.md', 'memory-bank.md', 'coordination.md'];
|
||||
const existingFiles = [];
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
await Deno.stat(file);
|
||||
existingFiles.push(file);
|
||||
} catch {
|
||||
// File doesn't exist, which is what we want
|
||||
}
|
||||
}
|
||||
|
||||
if (existingFiles.length > 0 && !initForce) {
|
||||
printWarning(`The following files already exist: ${existingFiles.join(', ')}`);
|
||||
console.log('Use --force to overwrite existing files');
|
||||
return;
|
||||
}
|
||||
|
||||
// Create CLAUDE.md
|
||||
const claudeMd = initSparc ? createSparcClaudeMd() :
|
||||
initMinimal ? createMinimalClaudeMd() : createFullClaudeMd();
|
||||
await Deno.writeTextFile('CLAUDE.md', claudeMd);
|
||||
console.log(` ✓ Created CLAUDE.md${initSparc ? ' (SPARC-enhanced)' : ''}`);
|
||||
|
||||
// Create memory-bank.md
|
||||
const memoryBankMd = initMinimal ? createMinimalMemoryBankMd() : createFullMemoryBankMd();
|
||||
await Deno.writeTextFile('memory-bank.md', memoryBankMd);
|
||||
console.log(' ✓ Created memory-bank.md');
|
||||
|
||||
// Create coordination.md
|
||||
const coordinationMd = initMinimal ? createMinimalCoordinationMd() : createFullCoordinationMd();
|
||||
await Deno.writeTextFile('coordination.md', coordinationMd);
|
||||
console.log(' ✓ Created coordination.md');
|
||||
|
||||
// Create directory structure
|
||||
const directories = [
|
||||
'memory',
|
||||
'memory/agents',
|
||||
'memory/sessions',
|
||||
'coordination',
|
||||
'coordination/memory_bank',
|
||||
'coordination/subtasks',
|
||||
'coordination/orchestration'
|
||||
];
|
||||
|
||||
for (const dir of directories) {
|
||||
try {
|
||||
await Deno.mkdir(dir, { recursive: true });
|
||||
console.log(` ✓ Created ${dir}/ directory`);
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create placeholder files for memory directories
|
||||
const agentsReadme = createAgentsReadme();
|
||||
await Deno.writeTextFile('memory/agents/README.md', agentsReadme);
|
||||
console.log(' ✓ Created memory/agents/README.md');
|
||||
|
||||
const sessionsReadme = createSessionsReadme();
|
||||
await Deno.writeTextFile('memory/sessions/README.md', sessionsReadme);
|
||||
console.log(' ✓ Created memory/sessions/README.md');
|
||||
|
||||
// Initialize persistence database
|
||||
const initialData = {
|
||||
agents: [],
|
||||
tasks: [],
|
||||
lastUpdated: Date.now()
|
||||
};
|
||||
await Deno.writeTextFile('memory/claude-flow-data.json', JSON.stringify(initialData, null, 2));
|
||||
console.log(' ✓ Created memory/claude-flow-data.json (persistence database)');
|
||||
|
||||
// SPARC initialization
|
||||
if (initSparc) {
|
||||
console.log('\n🚀 Initializing SPARC development environment...');
|
||||
|
||||
// Check if create-sparc exists and run it
|
||||
try {
|
||||
const createSparcCommand = new Deno.Command('npx', {
|
||||
args: ['-y', 'create-sparc', 'init', '--force'],
|
||||
stdout: 'inherit',
|
||||
stderr: 'inherit',
|
||||
});
|
||||
|
||||
console.log(' 🔄 Running: npx -y create-sparc init --force');
|
||||
const createSparcResult = await createSparcCommand.output();
|
||||
|
||||
if (createSparcResult.success) {
|
||||
console.log(' ✅ SPARC environment initialized successfully');
|
||||
} else {
|
||||
printWarning('create-sparc failed, creating basic SPARC structure manually...');
|
||||
|
||||
// Fallback: create basic SPARC structure manually
|
||||
await createSparcStructureManually();
|
||||
}
|
||||
} catch (err) {
|
||||
printWarning('create-sparc not available, creating basic SPARC structure manually...');
|
||||
|
||||
// Fallback: create basic SPARC structure manually
|
||||
await createSparcStructureManually();
|
||||
}
|
||||
}
|
||||
|
||||
printSuccess('Claude Code integration files initialized successfully!');
|
||||
console.log('\nNext steps:');
|
||||
console.log('1. Review and customize the generated files for your project');
|
||||
console.log('2. Run \'npx claude-flow start\' to begin the orchestration system');
|
||||
console.log('3. Use \'claude --dangerously-skip-permissions\' for unattended operation');
|
||||
if (initSparc) {
|
||||
console.log('4. Explore SPARC modes with \'npx claude-flow sparc modes\'');
|
||||
console.log('5. Try TDD workflow with \'npx claude-flow sparc tdd "your task"\'');
|
||||
}
|
||||
console.log('\nNote: Persistence database initialized at memory/claude-flow-data.json');
|
||||
if (initSparc) {
|
||||
console.log('Note: SPARC development environment available in .roo/ directory');
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
printError(`Failed to initialize files: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to create SPARC structure manually
|
||||
async function createSparcStructureManually() {
|
||||
try {
|
||||
// Create .roo directory structure
|
||||
const rooDirectories = [
|
||||
'.roo',
|
||||
'.roo/templates',
|
||||
'.roo/workflows',
|
||||
'.roo/modes',
|
||||
'.roo/configs'
|
||||
];
|
||||
|
||||
for (const dir of rooDirectories) {
|
||||
try {
|
||||
await Deno.mkdir(dir, { recursive: true });
|
||||
console.log(` ✓ Created ${dir}/`);
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create .roomodes file (copy from existing if available, or create basic version)
|
||||
let roomodesContent;
|
||||
try {
|
||||
// Check if .roomodes already exists and read it
|
||||
roomodesContent = await Deno.readTextFile('.roomodes');
|
||||
console.log(' ✓ Using existing .roomodes configuration');
|
||||
} catch {
|
||||
// Create basic .roomodes configuration
|
||||
roomodesContent = createBasicRoomodesConfig();
|
||||
await Deno.writeTextFile('.roomodes', roomodesContent);
|
||||
console.log(' ✓ Created .roomodes configuration');
|
||||
}
|
||||
|
||||
// Create basic workflow templates
|
||||
const basicWorkflow = createBasicSparcWorkflow();
|
||||
await Deno.writeTextFile('.roo/workflows/basic-tdd.json', basicWorkflow);
|
||||
console.log(' ✓ Created .roo/workflows/basic-tdd.json');
|
||||
|
||||
// Create README for .roo directory
|
||||
const rooReadme = createRooReadme();
|
||||
await Deno.writeTextFile('.roo/README.md', rooReadme);
|
||||
console.log(' ✓ Created .roo/README.md');
|
||||
|
||||
console.log(' ✅ Basic SPARC structure created successfully');
|
||||
|
||||
} catch (err) {
|
||||
console.log(` ❌ Failed to create SPARC structure: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Template creation functions
|
||||
function createMinimalClaudeMd() {
|
||||
return `# Claude Code Configuration
|
||||
|
||||
## Build Commands
|
||||
- \`npm run build\`: Build the project
|
||||
- \`npm run test\`: Run tests
|
||||
- \`npm run lint\`: Run linter
|
||||
|
||||
## Code Style
|
||||
- Use TypeScript/ES modules
|
||||
- Follow project conventions
|
||||
- Run typecheck before committing
|
||||
|
||||
## Project Info
|
||||
This is a Claude-Flow AI agent orchestration system.
|
||||
`;
|
||||
}
|
||||
|
||||
function createFullClaudeMd() {
|
||||
return `# Claude Code Configuration
|
||||
|
||||
## Build Commands
|
||||
- \`npm run build\`: Build the project using Deno compile
|
||||
- \`npm run test\`: Run the full test suite
|
||||
- \`npm run lint\`: Run ESLint and format checks
|
||||
- \`npm run typecheck\`: Run TypeScript type checking
|
||||
- \`npx claude-flow start\`: Start the orchestration system
|
||||
- \`npx claude-flow --help\`: Show all available commands
|
||||
|
||||
## Code Style Preferences
|
||||
- Use ES modules (import/export) syntax, not CommonJS (require)
|
||||
- Destructure imports when possible (e.g., \`import { foo } from 'bar'\`)
|
||||
- Use TypeScript for all new code
|
||||
- Follow existing naming conventions (camelCase for variables, PascalCase for classes)
|
||||
- Add JSDoc comments for public APIs
|
||||
- Use async/await instead of Promise chains
|
||||
- Prefer const/let over var
|
||||
|
||||
## Workflow Guidelines
|
||||
- Always run typecheck after making code changes
|
||||
- Run tests before committing changes
|
||||
- Use meaningful commit messages following conventional commits
|
||||
- Create feature branches for new functionality
|
||||
- Ensure all tests pass before merging
|
||||
|
||||
## Project Architecture
|
||||
This is a Claude-Flow AI agent orchestration system with the following components:
|
||||
- **CLI Interface**: Command-line tools for managing the system
|
||||
- **Orchestrator**: Core engine for coordinating agents and tasks
|
||||
- **Memory System**: Persistent storage and retrieval of information
|
||||
- **Terminal Management**: Automated terminal session handling
|
||||
- **MCP Integration**: Model Context Protocol server for Claude integration
|
||||
- **Agent Coordination**: Multi-agent task distribution and management
|
||||
|
||||
## Important Notes
|
||||
- Use \`claude --dangerously-skip-permissions\` for unattended operation
|
||||
- The system supports both daemon and interactive modes
|
||||
- Memory persistence is handled automatically
|
||||
- All components are event-driven for scalability
|
||||
|
||||
## Debugging
|
||||
- Check logs in \`./claude-flow.log\`
|
||||
- Use \`npx claude-flow status\` to check system health
|
||||
- Monitor with \`npx claude-flow monitor\` for real-time updates
|
||||
- Verbose output available with \`--verbose\` flag on most commands
|
||||
`;
|
||||
}
|
||||
|
||||
function createSparcClaudeMd() {
|
||||
return `# Claude Code Configuration - SPARC Development Environment
|
||||
|
||||
## 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.
|
||||
|
||||
## SPARC Development Commands
|
||||
|
||||
### Core SPARC Commands
|
||||
- \`npx claude-flow sparc modes\`: List all available SPARC development modes
|
||||
- \`npx claude-flow sparc run <mode> "<task>"\`: Execute specific SPARC mode for a task
|
||||
- \`npx claude-flow sparc tdd "<feature>"\`: Run complete TDD workflow using SPARC methodology
|
||||
- \`npx claude-flow sparc info <mode>\`: Get detailed information about a specific mode
|
||||
|
||||
### Standard Build Commands
|
||||
- \`npm run build\`: Build the project
|
||||
- \`npm run test\`: Run the test suite
|
||||
- \`npm run lint\`: Run linter and format checks
|
||||
- \`npm run typecheck\`: Run TypeScript type checking
|
||||
|
||||
## SPARC Methodology Workflow
|
||||
|
||||
### 1. Specification Phase
|
||||
\`\`\`bash
|
||||
# Create detailed specifications and requirements
|
||||
npx claude-flow sparc run spec-pseudocode "Define user authentication requirements"
|
||||
\`\`\`
|
||||
- Define clear functional requirements
|
||||
- Document edge cases and constraints
|
||||
- Create user stories and acceptance criteria
|
||||
- Establish non-functional requirements
|
||||
|
||||
### 2. Pseudocode Phase
|
||||
\`\`\`bash
|
||||
# Develop algorithmic logic and data flows
|
||||
npx claude-flow sparc run spec-pseudocode "Create authentication flow pseudocode"
|
||||
\`\`\`
|
||||
- Break down complex logic into steps
|
||||
- Define data structures and interfaces
|
||||
- Plan error handling and edge cases
|
||||
- Create modular, testable components
|
||||
|
||||
### 3. Architecture Phase
|
||||
\`\`\`bash
|
||||
# Design system architecture and component structure
|
||||
npx claude-flow sparc run architect "Design authentication service architecture"
|
||||
\`\`\`
|
||||
- Create system diagrams and component relationships
|
||||
- Define API contracts and interfaces
|
||||
- Plan database schemas and data flows
|
||||
- Establish security and scalability patterns
|
||||
|
||||
### 4. Refinement Phase (TDD Implementation)
|
||||
\`\`\`bash
|
||||
# Execute Test-Driven Development cycle
|
||||
npx claude-flow sparc tdd "implement user authentication system"
|
||||
\`\`\`
|
||||
|
||||
**TDD Cycle:**
|
||||
1. **Red**: Write failing tests first
|
||||
2. **Green**: Implement minimal code to pass tests
|
||||
3. **Refactor**: Optimize and clean up code
|
||||
4. **Repeat**: Continue until feature is complete
|
||||
|
||||
### 5. Completion Phase
|
||||
\`\`\`bash
|
||||
# Integration, documentation, and validation
|
||||
npx claude-flow sparc run integration "integrate authentication with user management"
|
||||
\`\`\`
|
||||
- Integrate all components
|
||||
- Perform end-to-end testing
|
||||
- Create comprehensive documentation
|
||||
- Validate against original requirements
|
||||
|
||||
## SPARC Mode Reference
|
||||
|
||||
### Development Modes
|
||||
- **\`architect\`**: System design and architecture planning
|
||||
- **\`code\`**: Clean, modular code implementation
|
||||
- **\`tdd\`**: Test-driven development and testing
|
||||
- **\`spec-pseudocode\`**: Requirements and algorithmic planning
|
||||
- **\`integration\`**: System integration and coordination
|
||||
|
||||
### Quality Assurance Modes
|
||||
- **\`debug\`**: Troubleshooting and bug resolution
|
||||
- **\`security-review\`**: Security analysis and vulnerability assessment
|
||||
- **\`refinement-optimization-mode\`**: Performance optimization and refactoring
|
||||
|
||||
### Support Modes
|
||||
- **\`docs-writer\`**: Documentation creation and maintenance
|
||||
- **\`devops\`**: Deployment and infrastructure management
|
||||
- **\`mcp\`**: External service integration
|
||||
|
||||
## Code Style and Best Practices
|
||||
|
||||
### SPARC Development Principles
|
||||
- **Modular Design**: Keep files under 500 lines, break into logical components
|
||||
- **Environment Safety**: Never hardcode secrets or environment-specific values
|
||||
- **Test-First**: Always write tests before implementation (Red-Green-Refactor)
|
||||
- **Clean Architecture**: Separate concerns, use dependency injection
|
||||
- **Documentation**: Maintain clear, up-to-date documentation
|
||||
|
||||
### Coding Standards
|
||||
- Use TypeScript for type safety and better tooling
|
||||
- Follow consistent naming conventions (camelCase for variables, PascalCase for classes)
|
||||
- Implement proper error handling and logging
|
||||
- Use async/await for asynchronous operations
|
||||
- Prefer composition over inheritance
|
||||
|
||||
### Memory and State Management
|
||||
- Use claude-flow memory system for persistent state across sessions
|
||||
- Store progress and findings using namespaced keys
|
||||
- Query previous work before starting new tasks
|
||||
- Export/import memory for backup and sharing
|
||||
|
||||
## SPARC Memory Integration
|
||||
|
||||
### Memory Commands for SPARC Development
|
||||
\`\`\`bash
|
||||
# Store project specifications
|
||||
npx claude-flow memory store spec_auth "User authentication requirements and constraints"
|
||||
|
||||
# Store architectural decisions
|
||||
npx claude-flow memory store arch_decisions "Database schema and API design choices"
|
||||
|
||||
# Store test results and coverage
|
||||
npx claude-flow memory store test_coverage "Authentication module: 95% coverage, all tests passing"
|
||||
|
||||
# Query previous work
|
||||
npx claude-flow memory query auth_implementation
|
||||
|
||||
# Export project memory
|
||||
npx claude-flow memory export project_backup.json
|
||||
\`\`\`
|
||||
|
||||
### Memory Namespaces
|
||||
- **\`spec\`**: Requirements and specifications
|
||||
- **\`arch\`**: Architecture and design decisions
|
||||
- **\`impl\`**: Implementation notes and code patterns
|
||||
- **\`test\`**: Test results and coverage reports
|
||||
- **\`debug\`**: Bug reports and resolution notes
|
||||
|
||||
## Workflow Examples
|
||||
|
||||
### Feature Development Workflow
|
||||
\`\`\`bash
|
||||
# 1. Start with specification
|
||||
npx claude-flow sparc run spec-pseudocode "User profile management feature"
|
||||
|
||||
# 2. Design architecture
|
||||
npx claude-flow sparc run architect "Profile service architecture with data validation"
|
||||
|
||||
# 3. Implement with TDD
|
||||
npx claude-flow sparc tdd "user profile CRUD operations"
|
||||
|
||||
# 4. Security review
|
||||
npx claude-flow sparc run security-review "profile data access and validation"
|
||||
|
||||
# 5. Integration testing
|
||||
npx claude-flow sparc run integration "profile service with authentication system"
|
||||
|
||||
# 6. Documentation
|
||||
npx claude-flow sparc run docs-writer "profile service API documentation"
|
||||
\`\`\`
|
||||
|
||||
### Bug Fix Workflow
|
||||
\`\`\`bash
|
||||
# 1. Debug and analyze
|
||||
npx claude-flow sparc run debug "authentication token expiration issue"
|
||||
|
||||
# 2. Write regression tests
|
||||
npx claude-flow sparc run tdd "token refresh mechanism tests"
|
||||
|
||||
# 3. Implement fix
|
||||
npx claude-flow sparc run code "fix token refresh in authentication service"
|
||||
|
||||
# 4. Security review
|
||||
npx claude-flow sparc run security-review "token handling security implications"
|
||||
\`\`\`
|
||||
|
||||
## Configuration Files
|
||||
|
||||
### SPARC Configuration
|
||||
- **\`.roomodes\`**: SPARC mode definitions and configurations
|
||||
- **\`.roo/\`**: Templates, workflows, and mode-specific rules
|
||||
|
||||
### Claude-Flow Configuration
|
||||
- **\`memory/\`**: Persistent memory and session data
|
||||
- **\`coordination/\`**: Multi-agent coordination settings
|
||||
|
||||
## Git Workflow Integration
|
||||
|
||||
### Commit Strategy with SPARC
|
||||
- **Specification commits**: After completing requirements analysis
|
||||
- **Architecture commits**: After design phase completion
|
||||
- **TDD commits**: After each Red-Green-Refactor cycle
|
||||
- **Integration commits**: After successful component integration
|
||||
- **Documentation commits**: After completing documentation updates
|
||||
|
||||
### Branch Strategy
|
||||
- **\`feature/sparc-<feature-name>\`**: Feature development with SPARC methodology
|
||||
- **\`hotfix/sparc-<issue>\`**: Bug fixes using SPARC debugging workflow
|
||||
- **\`refactor/sparc-<component>\`**: Refactoring using optimization mode
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common SPARC Issues
|
||||
- **Mode not found**: Check \`.roomodes\` file exists and is valid JSON
|
||||
- **Memory persistence**: Ensure \`memory/\` directory has write permissions
|
||||
- **Tool access**: Verify required tools are available for the selected mode
|
||||
- **Namespace conflicts**: Use unique memory namespaces for different features
|
||||
|
||||
### Debug Commands
|
||||
\`\`\`bash
|
||||
# Check SPARC configuration
|
||||
npx claude-flow sparc modes
|
||||
|
||||
# Verify memory system
|
||||
npx claude-flow memory stats
|
||||
|
||||
# Check system status
|
||||
npx claude-flow status
|
||||
|
||||
# View detailed mode information
|
||||
npx claude-flow sparc info <mode-name>
|
||||
\`\`\`
|
||||
|
||||
## Project Architecture
|
||||
|
||||
This SPARC-enabled project follows a systematic development approach:
|
||||
- **Clear separation of concerns** through modular design
|
||||
- **Test-driven development** ensuring reliability and maintainability
|
||||
- **Iterative refinement** for continuous improvement
|
||||
- **Comprehensive documentation** for team collaboration
|
||||
- **AI-assisted development** through specialized SPARC modes
|
||||
|
||||
## Important Notes
|
||||
|
||||
- Always run tests before committing (\`npm run test\`)
|
||||
- Use SPARC memory system to maintain context across sessions
|
||||
- Follow the Red-Green-Refactor cycle during TDD phases
|
||||
- Document architectural decisions in memory for future reference
|
||||
- Regular security reviews for any authentication or data handling code
|
||||
|
||||
For more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md
|
||||
`;
|
||||
}
|
||||
|
||||
function createMinimalMemoryBankMd() {
|
||||
return `# Memory Bank
|
||||
|
||||
## Quick Reference
|
||||
- Project uses SQLite for memory persistence
|
||||
- Memory is organized by namespaces
|
||||
- Query with \`npx claude-flow memory query <search>\`
|
||||
|
||||
## Storage Location
|
||||
- Database: \`./memory/claude-flow-data.json\`
|
||||
- Sessions: \`./memory/sessions/\`
|
||||
`;
|
||||
}
|
||||
|
||||
function createFullMemoryBankMd() {
|
||||
return `# Memory Bank Configuration
|
||||
|
||||
## Overview
|
||||
The Claude-Flow memory system provides persistent storage and intelligent retrieval of information across agent sessions. It uses a hybrid approach combining SQL databases with semantic search capabilities.
|
||||
|
||||
## Storage Backends
|
||||
- **Primary**: JSON database (\`./memory/claude-flow-data.json\`)
|
||||
- **Sessions**: File-based storage in \`./memory/sessions/\`
|
||||
- **Cache**: In-memory cache for frequently accessed data
|
||||
|
||||
## Memory Organization
|
||||
- **Namespaces**: Logical groupings of related information
|
||||
- **Sessions**: Time-bound conversation contexts
|
||||
- **Indexing**: Automatic content indexing for fast retrieval
|
||||
- **Replication**: Optional distributed storage support
|
||||
|
||||
## Commands
|
||||
- \`npx claude-flow memory query <search>\`: Search stored information
|
||||
- \`npx claude-flow memory stats\`: Show memory usage statistics
|
||||
- \`npx claude-flow memory export <file>\`: Export memory to file
|
||||
- \`npx claude-flow memory import <file>\`: Import memory from file
|
||||
|
||||
## Configuration
|
||||
Memory settings are configured in \`claude-flow.config.json\`:
|
||||
\`\`\`json
|
||||
{
|
||||
"memory": {
|
||||
"backend": "json",
|
||||
"path": "./memory/claude-flow-data.json",
|
||||
"cacheSize": 1000,
|
||||
"indexing": true,
|
||||
"namespaces": ["default", "agents", "tasks", "sessions"],
|
||||
"retentionPolicy": {
|
||||
"sessions": "30d",
|
||||
"tasks": "90d",
|
||||
"agents": "permanent"
|
||||
}
|
||||
}
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
## Best Practices
|
||||
- Use descriptive namespaces for different data types
|
||||
- Regular memory exports for backup purposes
|
||||
- Monitor memory usage with stats command
|
||||
- Clean up old sessions periodically
|
||||
|
||||
## Memory Types
|
||||
- **Episodic**: Conversation and interaction history
|
||||
- **Semantic**: Factual knowledge and relationships
|
||||
- **Procedural**: Task patterns and workflows
|
||||
- **Meta**: System configuration and preferences
|
||||
|
||||
## Integration Notes
|
||||
- Memory is automatically synchronized across agents
|
||||
- Search supports both exact match and semantic similarity
|
||||
- Memory contents are private to your local instance
|
||||
- No data is sent to external services without explicit commands
|
||||
`;
|
||||
}
|
||||
|
||||
function createMinimalCoordinationMd() {
|
||||
return `# Agent Coordination
|
||||
|
||||
## Quick Commands
|
||||
- \`npx claude-flow agent spawn <type>\`: Create new agent
|
||||
- \`npx claude-flow agent list\`: Show active agents
|
||||
- \`npx claude-flow task create <type> <description>\`: Create task
|
||||
|
||||
## Agent Types
|
||||
- researcher, coder, analyst, coordinator, general
|
||||
`;
|
||||
}
|
||||
|
||||
function createFullCoordinationMd() {
|
||||
return `# Agent Coordination System
|
||||
|
||||
## Overview
|
||||
The Claude-Flow coordination system manages multiple AI agents working together on complex tasks. It provides intelligent task distribution, resource management, and inter-agent communication.
|
||||
|
||||
## Agent Types and Capabilities
|
||||
- **Researcher**: Web search, information gathering, knowledge synthesis
|
||||
- **Coder**: Code analysis, development, debugging, testing
|
||||
- **Analyst**: Data processing, pattern recognition, insights generation
|
||||
- **Coordinator**: Task planning, resource allocation, workflow management
|
||||
- **General**: Multi-purpose agent with balanced capabilities
|
||||
|
||||
## Task Management
|
||||
- **Priority Levels**: 1 (lowest) to 10 (highest)
|
||||
- **Dependencies**: Tasks can depend on completion of other tasks
|
||||
- **Parallel Execution**: Independent tasks run concurrently
|
||||
- **Load Balancing**: Automatic distribution based on agent capacity
|
||||
|
||||
## Coordination Commands
|
||||
\`\`\`bash
|
||||
# Agent Management
|
||||
npx claude-flow agent spawn <type> --name <name> --priority <1-10>
|
||||
npx claude-flow agent list
|
||||
npx claude-flow agent info <agent-id>
|
||||
npx claude-flow agent terminate <agent-id>
|
||||
|
||||
# Task Management
|
||||
npx claude-flow task create <type> <description> --priority <1-10> --deps <task-ids>
|
||||
npx claude-flow task list --verbose
|
||||
npx claude-flow task status <task-id>
|
||||
npx claude-flow task cancel <task-id>
|
||||
|
||||
# System Monitoring
|
||||
npx claude-flow status --verbose
|
||||
npx claude-flow monitor --interval 5000
|
||||
\`\`\`
|
||||
|
||||
## Workflow Execution
|
||||
Workflows are defined in JSON format and can orchestrate complex multi-agent operations:
|
||||
\`\`\`bash
|
||||
npx claude-flow workflow examples/research-workflow.json
|
||||
npx claude-flow workflow examples/development-config.json --async
|
||||
\`\`\`
|
||||
|
||||
## Advanced Features
|
||||
- **Circuit Breakers**: Automatic failure handling and recovery
|
||||
- **Work Stealing**: Dynamic load redistribution for efficiency
|
||||
- **Resource Limits**: Memory and CPU usage constraints
|
||||
- **Metrics Collection**: Performance monitoring and optimization
|
||||
|
||||
## Configuration
|
||||
Coordination settings in \`claude-flow.config.json\`:
|
||||
\`\`\`json
|
||||
{
|
||||
"orchestrator": {
|
||||
"maxConcurrentTasks": 10,
|
||||
"taskTimeout": 300000,
|
||||
"defaultPriority": 5
|
||||
},
|
||||
"agents": {
|
||||
"maxAgents": 20,
|
||||
"defaultCapabilities": ["research", "code", "terminal"],
|
||||
"resourceLimits": {
|
||||
"memory": "1GB",
|
||||
"cpu": "50%"
|
||||
}
|
||||
}
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
## Communication Patterns
|
||||
- **Direct Messaging**: Agent-to-agent communication
|
||||
- **Event Broadcasting**: System-wide notifications
|
||||
- **Shared Memory**: Common information access
|
||||
- **Task Handoff**: Seamless work transfer between agents
|
||||
|
||||
## Best Practices
|
||||
- Start with general agents and specialize as needed
|
||||
- Use descriptive task names and clear requirements
|
||||
- Monitor system resources during heavy workloads
|
||||
- Implement proper error handling in workflows
|
||||
- Regular cleanup of completed tasks and inactive agents
|
||||
|
||||
## Troubleshooting
|
||||
- Check agent health with \`npx claude-flow status\`
|
||||
- View detailed logs with \`npx claude-flow monitor\`
|
||||
- Restart stuck agents with terminate/spawn cycle
|
||||
- Use \`--verbose\` flags for detailed diagnostic information
|
||||
`;
|
||||
}
|
||||
|
||||
function createAgentsReadme() {
|
||||
return `# Agent Memory Storage
|
||||
|
||||
## Purpose
|
||||
This directory stores agent-specific memory data, configurations, and persistent state information for individual Claude agents in the orchestration system.
|
||||
|
||||
## Structure
|
||||
Each agent gets its own subdirectory for isolated memory storage:
|
||||
|
||||
\`\`\`
|
||||
memory/agents/
|
||||
├── agent_001/
|
||||
│ ├── state.json # Agent state and configuration
|
||||
│ ├── knowledge.md # Agent-specific knowledge base
|
||||
│ ├── tasks.json # Completed and active tasks
|
||||
│ └── calibration.json # Agent-specific calibrations
|
||||
├── agent_002/
|
||||
│ └── ...
|
||||
└── shared/
|
||||
├── common_knowledge.md # Shared knowledge across agents
|
||||
└── global_config.json # Global agent configurations
|
||||
\`\`\`
|
||||
|
||||
## Usage Guidelines
|
||||
1. **Agent Isolation**: Each agent should only read/write to its own directory
|
||||
2. **Shared Resources**: Use the \`shared/\` directory for cross-agent information
|
||||
3. **State Persistence**: Update state.json whenever agent status changes
|
||||
4. **Knowledge Sharing**: Document discoveries in knowledge.md files
|
||||
5. **Cleanup**: Remove directories for terminated agents periodically
|
||||
|
||||
## Last Updated
|
||||
${new Date().toISOString()}
|
||||
`;
|
||||
}
|
||||
|
||||
function createSessionsReadme() {
|
||||
return `# Session Memory Storage
|
||||
|
||||
## Purpose
|
||||
This directory stores session-based memory data, conversation history, and contextual information for development sessions using the Claude-Flow orchestration system.
|
||||
|
||||
## Structure
|
||||
Sessions are organized by date and session ID for easy retrieval:
|
||||
|
||||
\`\`\`
|
||||
memory/sessions/
|
||||
├── 2024-01-10/
|
||||
│ ├── session_001/
|
||||
│ │ ├── metadata.json # Session metadata and configuration
|
||||
│ │ ├── conversation.md # Full conversation history
|
||||
│ │ ├── decisions.md # Key decisions and rationale
|
||||
│ │ ├── artifacts/ # Generated files and outputs
|
||||
│ │ └── coordination_state/ # Coordination system snapshots
|
||||
│ └── ...
|
||||
└── shared/
|
||||
├── patterns.md # Common session patterns
|
||||
└── templates/ # Session template files
|
||||
\`\`\`
|
||||
|
||||
## Usage Guidelines
|
||||
1. **Session Isolation**: Each session gets its own directory
|
||||
2. **Metadata Completeness**: Always fill out session metadata
|
||||
3. **Conversation Logging**: Document all significant interactions
|
||||
4. **Artifact Organization**: Structure generated files clearly
|
||||
5. **State Preservation**: Snapshot coordination state regularly
|
||||
|
||||
## Last Updated
|
||||
${new Date().toISOString()}
|
||||
`;
|
||||
}
|
||||
|
||||
function createBasicRoomodesConfig() {
|
||||
return JSON.stringify({
|
||||
"customModes": [
|
||||
{
|
||||
"slug": "architect",
|
||||
"name": "🏗️ Architect",
|
||||
"roleDefinition": "You design scalable, secure, and modular architectures based on functional specs and user needs. You define responsibilities across services, APIs, and components.",
|
||||
"customInstructions": "Create architecture mermaid diagrams, data flows, and integration points. Ensure no part of the design includes secrets or hardcoded env values. Emphasize modular boundaries and maintain extensibility.",
|
||||
"groups": ["read", "edit"],
|
||||
"source": "project"
|
||||
},
|
||||
{
|
||||
"slug": "code",
|
||||
"name": "🧠 Auto-Coder",
|
||||
"roleDefinition": "You write clean, efficient, modular code based on pseudocode and architecture. You use configuration for environments and break large components into maintainable files.",
|
||||
"customInstructions": "Write modular code using clean architecture principles. Never hardcode secrets or environment values. Split code into files < 500 lines. Use config files or environment abstractions. Use `new_task` for subtasks and finish with `attempt_completion`.",
|
||||
"groups": ["read", "edit", "browser", "mcp", "command"],
|
||||
"source": "project"
|
||||
},
|
||||
{
|
||||
"slug": "tdd",
|
||||
"name": "🧪 Tester (TDD)",
|
||||
"roleDefinition": "You implement Test-Driven Development (TDD, London School), writing tests first and refactoring after minimal implementation passes.",
|
||||
"customInstructions": "Write failing tests first. Implement only enough code to pass. Refactor after green. Ensure tests do not hardcode secrets. Keep files < 500 lines.",
|
||||
"groups": ["read", "edit", "browser", "mcp", "command"],
|
||||
"source": "project"
|
||||
},
|
||||
{
|
||||
"slug": "spec-pseudocode",
|
||||
"name": "📋 Specification Writer",
|
||||
"roleDefinition": "You capture full project context—functional requirements, edge cases, constraints—and translate that into modular pseudocode with TDD anchors.",
|
||||
"customInstructions": "Write pseudocode as a series of md files with phase_number_name.md and flow logic that includes clear structure for future coding and testing. Split complex logic across modules.",
|
||||
"groups": ["read", "edit"],
|
||||
"source": "project"
|
||||
},
|
||||
{
|
||||
"slug": "integration",
|
||||
"name": "🔗 System Integrator",
|
||||
"roleDefinition": "You merge the outputs of all modes into a working, tested, production-ready system. You ensure consistency, cohesion, and modularity.",
|
||||
"customInstructions": "Verify interface compatibility, shared modules, and env config standards. Split integration logic across domains as needed. Use `new_task` for preflight testing.",
|
||||
"groups": ["read", "edit", "browser", "mcp", "command"],
|
||||
"source": "project"
|
||||
},
|
||||
{
|
||||
"slug": "debug",
|
||||
"name": "🪲 Debugger",
|
||||
"roleDefinition": "You troubleshoot runtime bugs, logic errors, or integration failures by tracing, inspecting, and analyzing behavior.",
|
||||
"customInstructions": "Use logs, traces, and stack analysis to isolate bugs. Avoid changing env configuration directly. Keep fixes modular.",
|
||||
"groups": ["read", "edit", "browser", "mcp", "command"],
|
||||
"source": "project"
|
||||
}
|
||||
]
|
||||
}, null, 2);
|
||||
}
|
||||
|
||||
function createBasicSparcWorkflow() {
|
||||
return JSON.stringify({
|
||||
"name": "Basic TDD Workflow",
|
||||
"description": "A simple SPARC-based TDD workflow for development",
|
||||
"sequential": true,
|
||||
"steps": [
|
||||
{
|
||||
"mode": "spec-pseudocode",
|
||||
"description": "Create detailed specifications and pseudocode",
|
||||
"phase": "specification"
|
||||
},
|
||||
{
|
||||
"mode": "tdd",
|
||||
"description": "Write failing tests (Red phase)",
|
||||
"phase": "red"
|
||||
},
|
||||
{
|
||||
"mode": "code",
|
||||
"description": "Implement minimal code to pass tests (Green phase)",
|
||||
"phase": "green"
|
||||
},
|
||||
{
|
||||
"mode": "tdd",
|
||||
"description": "Refactor and optimize (Refactor phase)",
|
||||
"phase": "refactor"
|
||||
},
|
||||
{
|
||||
"mode": "integration",
|
||||
"description": "Integrate and verify complete solution",
|
||||
"phase": "integration"
|
||||
}
|
||||
]
|
||||
}, null, 2);
|
||||
}
|
||||
|
||||
function createRooReadme() {
|
||||
return `# .roo Directory - SPARC Development Environment
|
||||
|
||||
This directory contains the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) development environment configuration and templates.
|
||||
|
||||
## Directory Structure
|
||||
|
||||
\`\`\`
|
||||
.roo/
|
||||
├── README.md # This file
|
||||
├── templates/ # Template files for common patterns
|
||||
├── workflows/ # Predefined SPARC workflows
|
||||
│ └── basic-tdd.json # Basic TDD workflow
|
||||
├── modes/ # Custom mode definitions (optional)
|
||||
└── configs/ # Configuration files
|
||||
\`\`\`
|
||||
|
||||
## SPARC Methodology
|
||||
|
||||
SPARC is a systematic approach to software development:
|
||||
|
||||
1. **Specification**: Define clear requirements and constraints
|
||||
2. **Pseudocode**: Create detailed logic flows and algorithms
|
||||
3. **Architecture**: Design system structure and components
|
||||
4. **Refinement**: Implement, test, and optimize using TDD
|
||||
5. **Completion**: Integrate, document, and validate
|
||||
|
||||
## Usage with Claude-Flow
|
||||
|
||||
Use the claude-flow SPARC commands to leverage this environment:
|
||||
|
||||
\`\`\`bash
|
||||
# List available modes
|
||||
claude-flow sparc modes
|
||||
|
||||
# Run specific mode
|
||||
claude-flow sparc run code "implement user authentication"
|
||||
|
||||
# Execute full TDD workflow
|
||||
claude-flow sparc tdd "payment processing system"
|
||||
|
||||
# Use custom workflow
|
||||
claude-flow sparc workflow .roo/workflows/basic-tdd.json
|
||||
\`\`\`
|
||||
|
||||
## Configuration
|
||||
|
||||
The main configuration is in \`.roomodes\` at the project root. This directory provides additional templates and workflows to support the SPARC development process.
|
||||
|
||||
## Customization
|
||||
|
||||
You can customize this environment by:
|
||||
- Adding new workflow templates to \`workflows/\`
|
||||
- Creating mode-specific templates in \`templates/\`
|
||||
- Adding project-specific configurations in \`configs/\`
|
||||
|
||||
For more information, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
// mcp.js - MCP server management commands
|
||||
import { printSuccess, printError, printWarning } from '../utils.js';
|
||||
|
||||
export async function mcpCommand(subArgs, flags) {
|
||||
const mcpCmd = subArgs[0];
|
||||
|
||||
switch (mcpCmd) {
|
||||
case 'status':
|
||||
await showMcpStatus(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'start':
|
||||
await startMcpServer(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'stop':
|
||||
await stopMcpServer(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'tools':
|
||||
await listMcpTools(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'auth':
|
||||
await manageMcpAuth(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'config':
|
||||
await showMcpConfig(subArgs, flags);
|
||||
break;
|
||||
|
||||
default:
|
||||
showMcpHelp();
|
||||
}
|
||||
}
|
||||
|
||||
async function showMcpStatus(subArgs, flags) {
|
||||
printSuccess('MCP Server Status:');
|
||||
console.log('🌐 Status: Stopped (orchestrator not running)');
|
||||
console.log('🔧 Configuration: Default settings');
|
||||
console.log('🔌 Connections: 0 active');
|
||||
console.log('📡 Tools: Ready to load');
|
||||
console.log('🔐 Authentication: Not configured');
|
||||
}
|
||||
|
||||
async function startMcpServer(subArgs, flags) {
|
||||
const port = getFlag(subArgs, '--port') || flags.port || 3000;
|
||||
const host = getFlag(subArgs, '--host') || flags.host || 'localhost';
|
||||
|
||||
printSuccess(`Starting MCP server on ${host}:${port}...`);
|
||||
console.log('🚀 MCP server would start with:');
|
||||
console.log(` Host: ${host}`);
|
||||
console.log(` Port: ${port}`);
|
||||
console.log(' Tools: Claude-Flow integration tools');
|
||||
console.log(' Transport: HTTP and stdio');
|
||||
console.log('\n📋 Note: Requires orchestrator to be running');
|
||||
}
|
||||
|
||||
async function stopMcpServer(subArgs, flags) {
|
||||
printSuccess('Stopping MCP server...');
|
||||
console.log('🛑 Server would be gracefully shut down');
|
||||
console.log('📝 Active connections would be closed');
|
||||
console.log('💾 State would be persisted');
|
||||
}
|
||||
|
||||
async function listMcpTools(subArgs, flags) {
|
||||
const verbose = subArgs.includes('--verbose') || subArgs.includes('-v') || flags.verbose;
|
||||
|
||||
printSuccess('Available MCP Tools:');
|
||||
console.log('\n🔧 Claude-Flow Tools:');
|
||||
console.log(' • agent_spawn Create and manage AI agents');
|
||||
console.log(' • task_create Create and execute tasks');
|
||||
console.log(' • memory_store Store information in memory bank');
|
||||
console.log(' • memory_query Query stored information');
|
||||
console.log(' • terminal_execute Execute terminal commands');
|
||||
console.log(' • workflow_run Execute predefined workflows');
|
||||
console.log(' • sparc_mode Run SPARC development modes');
|
||||
|
||||
if (verbose) {
|
||||
console.log('\n📋 Tool Details:');
|
||||
console.log(' agent_spawn:');
|
||||
console.log(' Description: Create AI agents with specific capabilities');
|
||||
console.log(' Parameters: type, name, capabilities');
|
||||
console.log(' Returns: agent_id, status, configuration');
|
||||
|
||||
console.log(' memory_store:');
|
||||
console.log(' Description: Store key-value pairs in persistent memory');
|
||||
console.log(' Parameters: key, value, namespace');
|
||||
console.log(' Returns: success, storage_info');
|
||||
|
||||
console.log(' sparc_mode:');
|
||||
console.log(' Description: Execute SPARC development workflows');
|
||||
console.log(' Parameters: mode, task_description, options');
|
||||
console.log(' Returns: execution_status, results');
|
||||
}
|
||||
|
||||
console.log('\n📡 Status: Tools available when server is running');
|
||||
}
|
||||
|
||||
async function manageMcpAuth(subArgs, flags) {
|
||||
const authCmd = subArgs[1];
|
||||
|
||||
switch (authCmd) {
|
||||
case 'setup':
|
||||
printSuccess('Setting up MCP authentication...');
|
||||
console.log('🔐 Authentication configuration:');
|
||||
console.log(' Type: API Key based');
|
||||
console.log(' Scope: Claude-Flow tools');
|
||||
console.log(' Security: TLS encrypted');
|
||||
break;
|
||||
|
||||
case 'status':
|
||||
printSuccess('MCP Authentication Status:');
|
||||
console.log('🔐 Status: Not configured');
|
||||
console.log('🔑 API Keys: 0 active');
|
||||
console.log('🛡️ Security: Default settings');
|
||||
break;
|
||||
|
||||
case 'rotate':
|
||||
printSuccess('Rotating MCP authentication keys...');
|
||||
console.log('🔄 New API keys would be generated');
|
||||
console.log('♻️ Old keys would be deprecated gracefully');
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log('Auth commands: setup, status, rotate');
|
||||
console.log('Examples:');
|
||||
console.log(' claude-flow mcp auth setup');
|
||||
console.log(' claude-flow mcp auth status');
|
||||
}
|
||||
}
|
||||
|
||||
async function showMcpConfig(subArgs, flags) {
|
||||
printSuccess('MCP Server Configuration:');
|
||||
console.log('\n📋 Server Settings:');
|
||||
console.log(' Host: localhost');
|
||||
console.log(' Port: 3000');
|
||||
console.log(' Protocol: HTTP/STDIO');
|
||||
console.log(' Timeout: 30000ms');
|
||||
|
||||
console.log('\n🔧 Tool Configuration:');
|
||||
console.log(' Available Tools: 7');
|
||||
console.log(' Authentication: API Key');
|
||||
console.log(' Rate Limiting: Enabled');
|
||||
|
||||
console.log('\n🔐 Security Settings:');
|
||||
console.log(' TLS: Enabled in production');
|
||||
console.log(' CORS: Configured');
|
||||
console.log(' API Key Rotation: 30 days');
|
||||
|
||||
console.log('\n📁 Configuration File: ./mcp_config/mcp.json');
|
||||
}
|
||||
|
||||
function getFlag(args, flagName) {
|
||||
const index = args.indexOf(flagName);
|
||||
return index !== -1 && index + 1 < args.length ? args[index + 1] : null;
|
||||
}
|
||||
|
||||
function showMcpHelp() {
|
||||
console.log('MCP commands:');
|
||||
console.log(' status Show MCP server status');
|
||||
console.log(' start [--port <port>] Start MCP server');
|
||||
console.log(' stop Stop MCP server');
|
||||
console.log(' tools [--verbose] List available tools');
|
||||
console.log(' auth <setup|status|rotate> Manage authentication');
|
||||
console.log(' config Show configuration');
|
||||
console.log();
|
||||
console.log('Options:');
|
||||
console.log(' --port <port> Server port (default: 3000)');
|
||||
console.log(' --host <host> Server host (default: localhost)');
|
||||
console.log(' --verbose, -v Show detailed information');
|
||||
console.log();
|
||||
console.log('Examples:');
|
||||
console.log(' claude-flow mcp status');
|
||||
console.log(' claude-flow mcp start --port 8080');
|
||||
console.log(' claude-flow mcp tools --verbose');
|
||||
console.log(' claude-flow mcp auth setup');
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
// memory.js - Memory management commands
|
||||
import { printSuccess, printError, printWarning } from '../utils.js';
|
||||
|
||||
export async function memoryCommand(subArgs, flags) {
|
||||
const memorySubcommand = subArgs[0];
|
||||
const memoryStore = './memory/memory-store.json';
|
||||
|
||||
// Helper to load memory data
|
||||
async function loadMemory() {
|
||||
try {
|
||||
const content = await Deno.readTextFile(memoryStore);
|
||||
return JSON.parse(content);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to save memory data
|
||||
async function saveMemory(data) {
|
||||
await Deno.mkdir('./memory', { recursive: true });
|
||||
await Deno.writeTextFile(memoryStore, JSON.stringify(data, null, 2));
|
||||
}
|
||||
|
||||
switch (memorySubcommand) {
|
||||
case 'store':
|
||||
await storeMemory(subArgs, loadMemory, saveMemory);
|
||||
break;
|
||||
|
||||
case 'query':
|
||||
await queryMemory(subArgs, loadMemory);
|
||||
break;
|
||||
|
||||
case 'stats':
|
||||
await showMemoryStats(loadMemory);
|
||||
break;
|
||||
|
||||
case 'export':
|
||||
await exportMemory(subArgs, loadMemory);
|
||||
break;
|
||||
|
||||
case 'import':
|
||||
await importMemory(subArgs, saveMemory);
|
||||
break;
|
||||
|
||||
case 'clear':
|
||||
await clearMemory(subArgs, saveMemory);
|
||||
break;
|
||||
|
||||
case 'list':
|
||||
await listNamespaces(loadMemory);
|
||||
break;
|
||||
|
||||
default:
|
||||
showMemoryHelp();
|
||||
}
|
||||
}
|
||||
|
||||
async function storeMemory(subArgs, loadMemory, saveMemory) {
|
||||
const key = subArgs[1];
|
||||
const value = subArgs.slice(2).join(' ');
|
||||
|
||||
if (!key || !value) {
|
||||
printError('Usage: memory store <key> <value>');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await loadMemory();
|
||||
const namespace = getNamespaceFromArgs(subArgs) || 'default';
|
||||
|
||||
if (!data[namespace]) {
|
||||
data[namespace] = [];
|
||||
}
|
||||
|
||||
// Remove existing entry with same key
|
||||
data[namespace] = data[namespace].filter(e => e.key !== key);
|
||||
|
||||
// Add new entry
|
||||
data[namespace].push({
|
||||
key,
|
||||
value,
|
||||
namespace,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
|
||||
await saveMemory(data);
|
||||
printSuccess('Stored successfully');
|
||||
console.log(`📝 Key: ${key}`);
|
||||
console.log(`📦 Namespace: ${namespace}`);
|
||||
console.log(`💾 Size: ${new TextEncoder().encode(value).length} bytes`);
|
||||
} catch (err) {
|
||||
printError(`Failed to store: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function queryMemory(subArgs, loadMemory) {
|
||||
const search = subArgs.slice(1).join(' ');
|
||||
|
||||
if (!search) {
|
||||
printError('Usage: memory query <search>');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await loadMemory();
|
||||
const namespace = getNamespaceFromArgs(subArgs);
|
||||
const results = [];
|
||||
|
||||
for (const [ns, entries] of Object.entries(data)) {
|
||||
if (namespace && ns !== namespace) continue;
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.key.includes(search) || entry.value.includes(search)) {
|
||||
results.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (results.length === 0) {
|
||||
printWarning('No results found');
|
||||
return;
|
||||
}
|
||||
|
||||
printSuccess(`Found ${results.length} results:`);
|
||||
|
||||
// Sort by timestamp (newest first)
|
||||
results.sort((a, b) => b.timestamp - a.timestamp);
|
||||
|
||||
for (const entry of results.slice(0, 10)) {
|
||||
console.log(`\n📌 ${entry.key}`);
|
||||
console.log(` Namespace: ${entry.namespace}`);
|
||||
console.log(` Value: ${entry.value.substring(0, 100)}${entry.value.length > 100 ? '...' : ''}`);
|
||||
console.log(` Stored: ${new Date(entry.timestamp).toLocaleString()}`);
|
||||
}
|
||||
|
||||
if (results.length > 10) {
|
||||
console.log(`\n... and ${results.length - 10} more results`);
|
||||
}
|
||||
} catch (err) {
|
||||
printError(`Failed to query: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showMemoryStats(loadMemory) {
|
||||
try {
|
||||
const data = await loadMemory();
|
||||
let totalEntries = 0;
|
||||
const namespaceStats = {};
|
||||
|
||||
for (const [namespace, entries] of Object.entries(data)) {
|
||||
namespaceStats[namespace] = entries.length;
|
||||
totalEntries += entries.length;
|
||||
}
|
||||
|
||||
printSuccess('Memory Bank Statistics:');
|
||||
console.log(` Total Entries: ${totalEntries}`);
|
||||
console.log(` Namespaces: ${Object.keys(data).length}`);
|
||||
console.log(` Size: ${(new TextEncoder().encode(JSON.stringify(data)).length / 1024).toFixed(2)} KB`);
|
||||
|
||||
if (Object.keys(data).length > 0) {
|
||||
console.log('\n📁 Namespace Breakdown:');
|
||||
for (const [namespace, count] of Object.entries(namespaceStats)) {
|
||||
console.log(` ${namespace}: ${count} entries`);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
printError(`Failed to get stats: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function exportMemory(subArgs, loadMemory) {
|
||||
const filename = subArgs[1] || `memory-export-${Date.now()}.json`;
|
||||
|
||||
try {
|
||||
const data = await loadMemory();
|
||||
const namespace = getNamespaceFromArgs(subArgs);
|
||||
|
||||
let exportData = data;
|
||||
if (namespace) {
|
||||
exportData = { [namespace]: data[namespace] || [] };
|
||||
}
|
||||
|
||||
await Deno.writeTextFile(filename, JSON.stringify(exportData, null, 2));
|
||||
printSuccess(`Memory exported to ${filename}`);
|
||||
|
||||
let totalEntries = 0;
|
||||
for (const entries of Object.values(exportData)) {
|
||||
totalEntries += entries.length;
|
||||
}
|
||||
console.log(`📦 Exported ${totalEntries} entries from ${Object.keys(exportData).length} namespace(s)`);
|
||||
} catch (err) {
|
||||
printError(`Failed to export memory: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function importMemory(subArgs, saveMemory) {
|
||||
const filename = subArgs[1];
|
||||
|
||||
if (!filename) {
|
||||
printError('Usage: memory import <filename>');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const importContent = await Deno.readTextFile(filename);
|
||||
const importData = JSON.parse(importContent);
|
||||
|
||||
// Load existing memory
|
||||
const existingData = await loadMemory();
|
||||
|
||||
// Merge imported data
|
||||
let totalImported = 0;
|
||||
for (const [namespace, entries] of Object.entries(importData)) {
|
||||
if (!existingData[namespace]) {
|
||||
existingData[namespace] = [];
|
||||
}
|
||||
|
||||
// Add entries that don't already exist (by key)
|
||||
const existingKeys = new Set(existingData[namespace].map(e => e.key));
|
||||
const newEntries = entries.filter(e => !existingKeys.has(e.key));
|
||||
|
||||
existingData[namespace].push(...newEntries);
|
||||
totalImported += newEntries.length;
|
||||
}
|
||||
|
||||
await saveMemory(existingData);
|
||||
printSuccess(`Imported ${totalImported} new entries from ${filename}`);
|
||||
} catch (err) {
|
||||
printError(`Failed to import memory: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function clearMemory(subArgs, saveMemory) {
|
||||
const namespace = getNamespaceFromArgs(subArgs);
|
||||
|
||||
if (!namespace) {
|
||||
printError('Usage: memory clear --namespace <namespace>');
|
||||
printWarning('This will clear all entries in the specified namespace');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await loadMemory();
|
||||
|
||||
if (!data[namespace]) {
|
||||
printWarning(`Namespace '${namespace}' does not exist`);
|
||||
return;
|
||||
}
|
||||
|
||||
const entryCount = data[namespace].length;
|
||||
delete data[namespace];
|
||||
|
||||
await saveMemory(data);
|
||||
printSuccess(`Cleared ${entryCount} entries from namespace '${namespace}'`);
|
||||
} catch (err) {
|
||||
printError(`Failed to clear memory: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function listNamespaces(loadMemory) {
|
||||
try {
|
||||
const data = await loadMemory();
|
||||
const namespaces = Object.keys(data);
|
||||
|
||||
if (namespaces.length === 0) {
|
||||
printWarning('No namespaces found');
|
||||
return;
|
||||
}
|
||||
|
||||
printSuccess('Available namespaces:');
|
||||
for (const namespace of namespaces) {
|
||||
const count = data[namespace].length;
|
||||
console.log(` ${namespace} (${count} entries)`);
|
||||
}
|
||||
} catch (err) {
|
||||
printError(`Failed to list namespaces: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function getNamespaceFromArgs(subArgs) {
|
||||
const namespaceIndex = subArgs.indexOf('--namespace');
|
||||
if (namespaceIndex !== -1 && namespaceIndex + 1 < subArgs.length) {
|
||||
return subArgs[namespaceIndex + 1];
|
||||
}
|
||||
|
||||
const nsIndex = subArgs.indexOf('--ns');
|
||||
if (nsIndex !== -1 && nsIndex + 1 < subArgs.length) {
|
||||
return subArgs[nsIndex + 1];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Helper to load memory data (needed for import function)
|
||||
async function loadMemory() {
|
||||
try {
|
||||
const content = await Deno.readTextFile('./memory/memory-store.json');
|
||||
return JSON.parse(content);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function showMemoryHelp() {
|
||||
console.log('Memory commands:');
|
||||
console.log(' store <key> <value> Store a key-value pair');
|
||||
console.log(' query <search> Search for entries');
|
||||
console.log(' stats Show memory statistics');
|
||||
console.log(' export [filename] Export memory to file');
|
||||
console.log(' import <filename> Import memory from file');
|
||||
console.log(' clear --namespace <ns> Clear a namespace');
|
||||
console.log(' list List all namespaces');
|
||||
console.log();
|
||||
console.log('Options:');
|
||||
console.log(' --namespace <ns> Specify namespace for operations');
|
||||
console.log(' --ns <ns> Short form of --namespace');
|
||||
console.log();
|
||||
console.log('Examples:');
|
||||
console.log(' memory store previous_work "Research findings from yesterday"');
|
||||
console.log(' memory query research --namespace sparc');
|
||||
console.log(' memory export backup.json --namespace default');
|
||||
console.log(' memory import project-memory.json');
|
||||
console.log(' memory stats');
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
// monitor.js - System monitoring commands
|
||||
import { printSuccess, printError, printWarning } from '../utils.js';
|
||||
|
||||
export async function monitorCommand(subArgs, flags) {
|
||||
const interval = getFlag(subArgs, '--interval') || flags.interval || 5000;
|
||||
const format = getFlag(subArgs, '--format') || flags.format || 'pretty';
|
||||
const continuous = subArgs.includes('--watch') || flags.watch;
|
||||
|
||||
if (continuous) {
|
||||
await runContinuousMonitoring(interval, format);
|
||||
} else {
|
||||
await showCurrentMetrics(format);
|
||||
}
|
||||
}
|
||||
|
||||
async function showCurrentMetrics(format) {
|
||||
const metrics = await collectMetrics();
|
||||
|
||||
if (format === 'json') {
|
||||
console.log(JSON.stringify(metrics, null, 2));
|
||||
} else {
|
||||
displayMetrics(metrics);
|
||||
}
|
||||
}
|
||||
|
||||
async function runContinuousMonitoring(interval, format) {
|
||||
printSuccess(`Starting continuous monitoring (interval: ${interval}ms)`);
|
||||
console.log('Press Ctrl+C to stop monitoring\n');
|
||||
|
||||
// Simulate monitoring - in a real implementation, this would collect actual metrics
|
||||
let iteration = 0;
|
||||
const maxIterations = 10; // Limit for demo purposes
|
||||
|
||||
const monitorInterval = setInterval(async () => {
|
||||
iteration++;
|
||||
|
||||
if (iteration > maxIterations) {
|
||||
console.log('\n📊 Monitoring demo completed (limited to 10 iterations)');
|
||||
console.log('In production, this would run continuously until stopped');
|
||||
clearInterval(monitorInterval);
|
||||
return;
|
||||
}
|
||||
|
||||
console.clear(); // Clear screen for fresh output
|
||||
console.log(`🔄 Monitoring Claude-Flow System - Update #${iteration}`);
|
||||
console.log(`⏰ ${new Date().toLocaleTimeString()}\n`);
|
||||
|
||||
const metrics = await collectMetrics();
|
||||
|
||||
if (format === 'json') {
|
||||
console.log(JSON.stringify(metrics, null, 2));
|
||||
} else {
|
||||
displayMetrics(metrics);
|
||||
}
|
||||
|
||||
console.log(`\n🔄 Next update in ${interval}ms...`);
|
||||
|
||||
}, interval);
|
||||
|
||||
// In a real implementation, you would handle Ctrl+C gracefully
|
||||
setTimeout(() => {
|
||||
clearInterval(monitorInterval);
|
||||
console.log('\n👋 Monitoring stopped');
|
||||
}, interval * (maxIterations + 1));
|
||||
}
|
||||
|
||||
async function collectMetrics() {
|
||||
// Simulate metric collection - in real implementation, this would gather actual system data
|
||||
const timestamp = Date.now();
|
||||
|
||||
return {
|
||||
timestamp,
|
||||
system: {
|
||||
uptime: Math.floor(Math.random() * 86400), // Random uptime in seconds
|
||||
cpu_usage: Math.round(Math.random() * 100 * 100) / 100, // Random CPU %
|
||||
memory_usage: Math.round(Math.random() * 8192 * 100) / 100, // Random memory MB
|
||||
disk_usage: Math.round(Math.random() * 100 * 100) / 100 // Random disk %
|
||||
},
|
||||
orchestrator: {
|
||||
status: Math.random() > 0.8 ? 'running' : 'stopped',
|
||||
active_agents: Math.floor(Math.random() * 5),
|
||||
queued_tasks: Math.floor(Math.random() * 10),
|
||||
completed_tasks: Math.floor(Math.random() * 50),
|
||||
errors: Math.floor(Math.random() * 3)
|
||||
},
|
||||
performance: {
|
||||
avg_task_duration: Math.round(Math.random() * 5000 * 100) / 100, // ms
|
||||
throughput: Math.round(Math.random() * 100 * 100) / 100, // tasks/min
|
||||
success_rate: Math.round((0.85 + Math.random() * 0.15) * 100 * 100) / 100 // %
|
||||
},
|
||||
resources: {
|
||||
memory_entries: Math.floor(Math.random() * 100),
|
||||
terminal_sessions: Math.floor(Math.random() * 5),
|
||||
mcp_connections: Math.floor(Math.random() * 3)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function displayMetrics(metrics) {
|
||||
const timestamp = new Date(metrics.timestamp).toLocaleTimeString();
|
||||
|
||||
console.log('📊 System Metrics');
|
||||
console.log('================');
|
||||
|
||||
// System metrics
|
||||
console.log('\n🖥️ System Resources:');
|
||||
console.log(` CPU Usage: ${metrics.system.cpu_usage.toFixed(1)}%`);
|
||||
console.log(` Memory: ${metrics.system.memory_usage.toFixed(1)} MB`);
|
||||
console.log(` Disk Usage: ${metrics.system.disk_usage.toFixed(1)}%`);
|
||||
console.log(` Uptime: ${formatUptime(metrics.system.uptime)}`);
|
||||
|
||||
// Orchestrator metrics
|
||||
console.log('\n🎭 Orchestrator:');
|
||||
console.log(` Status: ${getStatusIcon(metrics.orchestrator.status)} ${metrics.orchestrator.status}`);
|
||||
console.log(` Active Agents: ${metrics.orchestrator.active_agents}`);
|
||||
console.log(` Queued Tasks: ${metrics.orchestrator.queued_tasks}`);
|
||||
console.log(` Completed: ${metrics.orchestrator.completed_tasks}`);
|
||||
console.log(` Errors: ${metrics.orchestrator.errors}`);
|
||||
|
||||
// Performance metrics
|
||||
console.log('\n⚡ Performance:');
|
||||
console.log(` Avg Task Duration: ${metrics.performance.avg_task_duration.toFixed(0)}ms`);
|
||||
console.log(` Throughput: ${metrics.performance.throughput.toFixed(1)} tasks/min`);
|
||||
console.log(` Success Rate: ${metrics.performance.success_rate.toFixed(1)}%`);
|
||||
|
||||
// Resource utilization
|
||||
console.log('\n📦 Resources:');
|
||||
console.log(` Memory Entries: ${metrics.resources.memory_entries}`);
|
||||
console.log(` Terminal Sessions: ${metrics.resources.terminal_sessions}`);
|
||||
console.log(` MCP Connections: ${metrics.resources.mcp_connections}`);
|
||||
|
||||
console.log(`\n⏰ Last Updated: ${timestamp}`);
|
||||
}
|
||||
|
||||
function getStatusIcon(status) {
|
||||
switch (status) {
|
||||
case 'running': return '🟢';
|
||||
case 'stopped': return '🔴';
|
||||
case 'starting': return '🟡';
|
||||
case 'error': return '❌';
|
||||
default: return '⚪';
|
||||
}
|
||||
}
|
||||
|
||||
function formatUptime(seconds) {
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
const secs = seconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return `${hours}h ${minutes}m ${secs}s`;
|
||||
} else if (minutes > 0) {
|
||||
return `${minutes}m ${secs}s`;
|
||||
} else {
|
||||
return `${secs}s`;
|
||||
}
|
||||
}
|
||||
|
||||
function getFlag(args, flagName) {
|
||||
const index = args.indexOf(flagName);
|
||||
return index !== -1 && index + 1 < args.length ? args[index + 1] : null;
|
||||
}
|
||||
|
||||
export function showMonitorHelp() {
|
||||
console.log('Monitor commands:');
|
||||
console.log(' monitor [options] Show current system metrics');
|
||||
console.log(' monitor --watch Continuous monitoring mode');
|
||||
console.log();
|
||||
console.log('Options:');
|
||||
console.log(' --interval <ms> Update interval in milliseconds (default: 5000)');
|
||||
console.log(' --format <type> Output format: pretty, json (default: pretty)');
|
||||
console.log(' --watch Continuous monitoring mode');
|
||||
console.log();
|
||||
console.log('Examples:');
|
||||
console.log(' claude-flow monitor # Show current metrics');
|
||||
console.log(' claude-flow monitor --watch # Continuous monitoring');
|
||||
console.log(' claude-flow monitor --interval 1000 --watch # Fast updates');
|
||||
console.log(' claude-flow monitor --format json # JSON output');
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
// sparc.js - SPARC development mode commands
|
||||
import { printSuccess, printError, printWarning } from '../utils.js';
|
||||
|
||||
export async function sparcCommand(subArgs, flags) {
|
||||
const sparcCmd = subArgs[0];
|
||||
|
||||
switch (sparcCmd) {
|
||||
case 'modes':
|
||||
await listSparcModes(subArgs);
|
||||
break;
|
||||
|
||||
case 'info':
|
||||
await showModeInfo(subArgs);
|
||||
break;
|
||||
|
||||
case 'run':
|
||||
await runSparcMode(subArgs);
|
||||
break;
|
||||
|
||||
case 'tdd':
|
||||
await runTddWorkflow(subArgs);
|
||||
break;
|
||||
|
||||
default:
|
||||
showSparcHelp();
|
||||
}
|
||||
}
|
||||
|
||||
async function listSparcModes(subArgs) {
|
||||
try {
|
||||
const configPath = '.roomodes';
|
||||
let configContent;
|
||||
try {
|
||||
configContent = await Deno.readTextFile(configPath);
|
||||
} catch (error) {
|
||||
printError('SPARC configuration file (.roomodes) not found');
|
||||
console.log('Please ensure .roomodes file exists in the current directory');
|
||||
return;
|
||||
}
|
||||
|
||||
const config = JSON.parse(configContent);
|
||||
const verbose = subArgs.includes('--verbose') || subArgs.includes('-v');
|
||||
|
||||
printSuccess('Available SPARC Modes:');
|
||||
console.log();
|
||||
|
||||
for (const mode of config.customModes) {
|
||||
console.log(`• ${mode.name} (${mode.slug})`);
|
||||
if (verbose) {
|
||||
console.log(` ${mode.roleDefinition}`);
|
||||
console.log(` Tools: ${mode.groups.join(', ')}`);
|
||||
console.log();
|
||||
}
|
||||
}
|
||||
|
||||
if (!verbose) {
|
||||
console.log();
|
||||
console.log('Use --verbose for detailed descriptions');
|
||||
}
|
||||
} catch (err) {
|
||||
printError(`Failed to list SPARC modes: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showModeInfo(subArgs) {
|
||||
const modeSlug = subArgs[1];
|
||||
if (!modeSlug) {
|
||||
printError('Usage: sparc info <mode-slug>');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const configContent = await Deno.readTextFile('.roomodes');
|
||||
const config = JSON.parse(configContent);
|
||||
const mode = config.customModes.find(m => m.slug === modeSlug);
|
||||
|
||||
if (!mode) {
|
||||
printError(`Mode not found: ${modeSlug}`);
|
||||
console.log('Available modes:');
|
||||
for (const m of config.customModes) {
|
||||
console.log(` ${m.slug} - ${m.name}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
printSuccess(`SPARC Mode: ${mode.name}`);
|
||||
console.log();
|
||||
console.log('Role Definition:');
|
||||
console.log(mode.roleDefinition);
|
||||
console.log();
|
||||
console.log('Custom Instructions:');
|
||||
console.log(mode.customInstructions);
|
||||
console.log();
|
||||
console.log('Tool Groups:');
|
||||
console.log(mode.groups.join(', '));
|
||||
console.log();
|
||||
console.log('Source:');
|
||||
console.log(mode.source);
|
||||
|
||||
} catch (err) {
|
||||
printError(`Failed to show mode info: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runSparcMode(subArgs) {
|
||||
const runModeSlug = subArgs[1];
|
||||
const taskDescription = subArgs.slice(2).join(' ');
|
||||
|
||||
if (!runModeSlug || !taskDescription) {
|
||||
printError('Usage: sparc run <mode-slug> <task-description>');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const configContent = await Deno.readTextFile('.roomodes');
|
||||
const config = JSON.parse(configContent);
|
||||
const mode = config.customModes.find(m => m.slug === runModeSlug);
|
||||
|
||||
if (!mode) {
|
||||
printError(`Mode not found: ${runModeSlug}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Build enhanced SPARC prompt
|
||||
const memoryNamespace = subArgs.includes('--namespace') ?
|
||||
subArgs[subArgs.indexOf('--namespace') + 1] : mode.slug;
|
||||
|
||||
const enhancedTask = createSparcPrompt(mode, taskDescription, memoryNamespace);
|
||||
|
||||
// Build tools based on mode groups
|
||||
const tools = buildToolsFromGroups(mode.groups);
|
||||
const toolsList = Array.from(tools).join(',');
|
||||
const instanceId = `sparc-${runModeSlug}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
|
||||
if (subArgs.includes('--dry-run') || subArgs.includes('-d')) {
|
||||
printWarning('DRY RUN - SPARC Mode Configuration:');
|
||||
console.log(`Mode: ${mode.name} (${mode.slug})`);
|
||||
console.log(`Instance ID: ${instanceId}`);
|
||||
console.log(`Tools: ${toolsList}`);
|
||||
console.log(`Task: ${taskDescription}`);
|
||||
console.log();
|
||||
console.log('Enhanced prompt preview:');
|
||||
console.log(enhancedTask.substring(0, 300) + '...');
|
||||
return;
|
||||
}
|
||||
|
||||
printSuccess(`Starting SPARC mode: ${mode.name}`);
|
||||
console.log(`📝 Instance ID: ${instanceId}`);
|
||||
console.log(`🎯 Mode: ${mode.slug}`);
|
||||
console.log(`🔧 Tools: ${toolsList}`);
|
||||
console.log(`📋 Task: ${taskDescription}`);
|
||||
console.log();
|
||||
|
||||
// Execute Claude with SPARC configuration
|
||||
await executeClaude(enhancedTask, toolsList, instanceId, memoryNamespace, subArgs);
|
||||
|
||||
} catch (err) {
|
||||
printError(`Failed to run SPARC mode: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runTddWorkflow(subArgs) {
|
||||
const tddTaskDescription = subArgs.slice(1).join(' ');
|
||||
|
||||
if (!tddTaskDescription) {
|
||||
printError('Usage: sparc tdd <task-description>');
|
||||
return;
|
||||
}
|
||||
|
||||
printSuccess('Starting SPARC TDD Workflow');
|
||||
console.log('Following Test-Driven Development with SPARC methodology');
|
||||
console.log();
|
||||
|
||||
const phases = [
|
||||
{ name: 'Red', description: 'Write failing tests', mode: 'tdd' },
|
||||
{ name: 'Green', description: 'Minimal implementation', mode: 'code' },
|
||||
{ name: 'Refactor', description: 'Optimize and clean', mode: 'tdd' }
|
||||
];
|
||||
|
||||
console.log('TDD Phases:');
|
||||
for (const phase of phases) {
|
||||
console.log(` ${phase.name}: ${phase.description} (${phase.mode} mode)`);
|
||||
}
|
||||
console.log();
|
||||
|
||||
if (subArgs.includes('--interactive') || subArgs.includes('-i')) {
|
||||
printSuccess('Starting interactive TDD workflow');
|
||||
console.log('This would walk through each phase interactively');
|
||||
console.log('Run each phase with: sparc run <mode> "Phase: <task>"');
|
||||
} else {
|
||||
printSuccess('Starting full TDD workflow');
|
||||
console.log('This would execute all phases automatically');
|
||||
console.log('Use --interactive for step-by-step control');
|
||||
}
|
||||
}
|
||||
|
||||
function createSparcPrompt(mode, taskDescription, memoryNamespace) {
|
||||
return `# SPARC Development Mode: ${mode.name}
|
||||
|
||||
## Your Role
|
||||
${mode.roleDefinition}
|
||||
|
||||
## Your Task
|
||||
${taskDescription}
|
||||
|
||||
## Mode-Specific Instructions
|
||||
${mode.customInstructions}
|
||||
|
||||
## SPARC Development Environment
|
||||
|
||||
You are working within the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) methodology using claude-flow orchestration features.
|
||||
|
||||
### Available Development Tools
|
||||
- **Memory Persistence**: Use \`npx claude-flow memory store <key> "<value>"\` to save progress and findings
|
||||
- **Memory Retrieval**: Use \`npx claude-flow memory query <search>\` to access previous work
|
||||
- **Namespace**: Your work is stored in the "${memoryNamespace}" namespace
|
||||
|
||||
### SPARC Methodology Integration
|
||||
Follow the SPARC methodology for systematic development:
|
||||
1. **Specification**: Define clear requirements and constraints
|
||||
2. **Pseudocode**: Create detailed logic flows and algorithms
|
||||
3. **Architecture**: Design system structure and components
|
||||
4. **Refinement**: Implement, test, and optimize
|
||||
5. **Completion**: Integrate, document, and validate
|
||||
|
||||
### Best Practices
|
||||
1. **Modular Development**: Keep all files under 500 lines
|
||||
2. **Environment Safety**: Never hardcode secrets or environment values
|
||||
3. **Memory Usage**: Store key findings and decisions in memory for future reference
|
||||
4. **Tool Integration**: Use \`new_task\` for subtasks and \`attempt_completion\` when finished
|
||||
|
||||
### Memory Commands Examples
|
||||
\`\`\`bash
|
||||
# Store your progress
|
||||
npx claude-flow memory store ${memoryNamespace}_progress "Current status and findings"
|
||||
|
||||
# Check for previous work
|
||||
npx claude-flow memory query ${memoryNamespace}
|
||||
|
||||
# Store results
|
||||
npx claude-flow memory store ${memoryNamespace}_results "Implementation output and decisions"
|
||||
\`\`\`
|
||||
|
||||
Now proceed with your task following the SPARC methodology and your specific role instructions.`;
|
||||
}
|
||||
|
||||
function buildToolsFromGroups(groups) {
|
||||
const toolMappings = {
|
||||
read: ['View', 'LS', 'GlobTool', 'GrepTool'],
|
||||
edit: ['Edit', 'Replace', 'MultiEdit', 'Write'],
|
||||
browser: ['WebFetch'],
|
||||
mcp: ['mcp_tools'],
|
||||
command: ['Bash', 'Terminal']
|
||||
};
|
||||
|
||||
const tools = new Set(['View', 'Edit', 'Bash']); // Always include basic tools
|
||||
|
||||
for (const group of groups) {
|
||||
if (Array.isArray(group)) {
|
||||
const groupName = group[0];
|
||||
if (toolMappings[groupName]) {
|
||||
toolMappings[groupName].forEach(tool => tools.add(tool));
|
||||
}
|
||||
} else if (toolMappings[group]) {
|
||||
toolMappings[group].forEach(tool => tools.add(tool));
|
||||
}
|
||||
}
|
||||
|
||||
return tools;
|
||||
}
|
||||
|
||||
async function executeClaude(enhancedTask, toolsList, instanceId, memoryNamespace, subArgs) {
|
||||
const claudeArgs = [enhancedTask];
|
||||
claudeArgs.push('--allowedTools', toolsList);
|
||||
|
||||
if (subArgs.includes('--no-permissions')) {
|
||||
claudeArgs.push('--dangerously-skip-permissions');
|
||||
}
|
||||
|
||||
if (subArgs.includes('--config')) {
|
||||
const configIndex = subArgs.indexOf('--config');
|
||||
claudeArgs.push('--mcp-config', subArgs[configIndex + 1]);
|
||||
}
|
||||
|
||||
if (subArgs.includes('--verbose') || subArgs.includes('-v')) {
|
||||
claudeArgs.push('--verbose');
|
||||
}
|
||||
|
||||
try {
|
||||
const command = new Deno.Command('claude', {
|
||||
args: claudeArgs,
|
||||
env: {
|
||||
...Deno.env.toObject(),
|
||||
CLAUDE_INSTANCE_ID: instanceId,
|
||||
CLAUDE_SPARC_MODE: 'true',
|
||||
CLAUDE_FLOW_MEMORY_ENABLED: 'true',
|
||||
CLAUDE_FLOW_MEMORY_NAMESPACE: memoryNamespace,
|
||||
},
|
||||
stdin: 'inherit',
|
||||
stdout: 'inherit',
|
||||
stderr: 'inherit',
|
||||
});
|
||||
|
||||
const child = command.spawn();
|
||||
const status = await child.status;
|
||||
|
||||
if (status.success) {
|
||||
printSuccess(`SPARC instance ${instanceId} completed successfully`);
|
||||
} else {
|
||||
printError(`SPARC instance ${instanceId} exited with code ${status.code}`);
|
||||
}
|
||||
} catch (err) {
|
||||
printError(`Failed to execute Claude: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function showSparcHelp() {
|
||||
console.log('SPARC commands:');
|
||||
console.log(' modes List available SPARC development modes');
|
||||
console.log(' info <mode> Show detailed information about a mode');
|
||||
console.log(' run <mode> <task> Execute a task in specified SPARC mode');
|
||||
console.log(' tdd <task> Run Test-Driven Development workflow');
|
||||
console.log();
|
||||
console.log('Examples:');
|
||||
console.log(' claude-flow sparc modes --verbose');
|
||||
console.log(' claude-flow sparc info architect');
|
||||
console.log(' claude-flow sparc run code "implement user authentication"');
|
||||
console.log(' claude-flow sparc tdd "payment processing system"');
|
||||
console.log();
|
||||
console.log('Flags:');
|
||||
console.log(' --dry-run, -d Show configuration without executing');
|
||||
console.log(' --verbose, -v Show detailed output');
|
||||
console.log(' --interactive, -i Run TDD workflow interactively');
|
||||
console.log(' --no-permissions Skip Claude permissions prompts');
|
||||
console.log(' --namespace <ns> Use custom memory namespace');
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
// status.js - System status and monitoring commands
|
||||
import { printSuccess, printError, printWarning } from '../utils.js';
|
||||
|
||||
export async function statusCommand(subArgs, flags) {
|
||||
const verbose = subArgs.includes('--verbose') || subArgs.includes('-v') || flags.verbose;
|
||||
const json = subArgs.includes('--json') || flags.json;
|
||||
|
||||
const status = await getSystemStatus(verbose);
|
||||
|
||||
if (json) {
|
||||
console.log(JSON.stringify(status, null, 2));
|
||||
} else {
|
||||
displayStatus(status, verbose);
|
||||
}
|
||||
}
|
||||
|
||||
async function getSystemStatus(verbose = false) {
|
||||
const status = {
|
||||
timestamp: Date.now(),
|
||||
version: '1.0.30',
|
||||
orchestrator: {
|
||||
running: false,
|
||||
uptime: 0,
|
||||
status: 'Not Running'
|
||||
},
|
||||
agents: {
|
||||
active: 0,
|
||||
total: 0,
|
||||
types: {}
|
||||
},
|
||||
tasks: {
|
||||
queued: 0,
|
||||
running: 0,
|
||||
completed: 0,
|
||||
failed: 0
|
||||
},
|
||||
memory: {
|
||||
status: 'Ready',
|
||||
entries: await getMemoryStats(),
|
||||
size: '0.37 KB'
|
||||
},
|
||||
terminal: {
|
||||
status: 'Ready',
|
||||
poolSize: 10,
|
||||
active: 0
|
||||
},
|
||||
mcp: {
|
||||
status: 'Stopped',
|
||||
port: null,
|
||||
connections: 0
|
||||
},
|
||||
resources: verbose ? await getResourceUsage() : null
|
||||
};
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
async function getMemoryStats() {
|
||||
try {
|
||||
const memoryStore = './memory/memory-store.json';
|
||||
const content = await Deno.readTextFile(memoryStore);
|
||||
const data = JSON.parse(content);
|
||||
|
||||
let totalEntries = 0;
|
||||
for (const entries of Object.values(data)) {
|
||||
totalEntries += entries.length;
|
||||
}
|
||||
|
||||
return totalEntries;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
async function getResourceUsage() {
|
||||
// Get system resource information
|
||||
try {
|
||||
const memInfo = await Deno.systemMemoryInfo();
|
||||
return {
|
||||
memory: {
|
||||
total: formatBytes(memInfo.total),
|
||||
free: formatBytes(memInfo.free),
|
||||
available: formatBytes(memInfo.available),
|
||||
usage: `${Math.round(((memInfo.total - memInfo.available) / memInfo.total) * 100)}%`
|
||||
},
|
||||
cpu: {
|
||||
cores: navigator.hardwareConcurrency || 'Unknown',
|
||||
load: 'N/A' // Would need additional system calls
|
||||
}
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
memory: { usage: 'Unknown' },
|
||||
cpu: { cores: 'Unknown', load: 'Unknown' }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function displayStatus(status, verbose) {
|
||||
printSuccess('Claude-Flow System Status:');
|
||||
|
||||
// Overall status
|
||||
const overallStatus = status.orchestrator.running ? '🟢 Running' : '🟡 Not Running';
|
||||
console.log(`${overallStatus} (orchestrator ${status.orchestrator.running ? 'active' : 'not started'})`);
|
||||
|
||||
// Core components
|
||||
console.log(`🤖 Agents: ${status.agents.active} active`);
|
||||
console.log(`📋 Tasks: ${status.tasks.queued} in queue`);
|
||||
console.log(`💾 Memory: ${status.memory.status} (${status.memory.entries} entries)`);
|
||||
console.log(`🖥️ Terminal Pool: ${status.terminal.status}`);
|
||||
console.log(`🌐 MCP Server: ${status.mcp.status}`);
|
||||
|
||||
if (verbose) {
|
||||
console.log('\n📊 Detailed Information:');
|
||||
|
||||
// Orchestrator details
|
||||
console.log('\n🎭 Orchestrator:');
|
||||
console.log(` Status: ${status.orchestrator.status}`);
|
||||
console.log(` Uptime: ${formatUptime(status.orchestrator.uptime)}`);
|
||||
|
||||
// Agent details
|
||||
console.log('\n🤖 Agent Details:');
|
||||
console.log(` Total Registered: ${status.agents.total}`);
|
||||
console.log(` Currently Active: ${status.agents.active}`);
|
||||
if (Object.keys(status.agents.types).length > 0) {
|
||||
console.log(' Types:');
|
||||
for (const [type, count] of Object.entries(status.agents.types)) {
|
||||
console.log(` ${type}: ${count}`);
|
||||
}
|
||||
} else {
|
||||
console.log(' No agents currently registered');
|
||||
}
|
||||
|
||||
// Task details
|
||||
console.log('\n📋 Task Queue:');
|
||||
console.log(` Queued: ${status.tasks.queued}`);
|
||||
console.log(` Running: ${status.tasks.running}`);
|
||||
console.log(` Completed: ${status.tasks.completed}`);
|
||||
console.log(` Failed: ${status.tasks.failed}`);
|
||||
|
||||
// Memory details
|
||||
console.log('\n💾 Memory System:');
|
||||
console.log(` Total Entries: ${status.memory.entries}`);
|
||||
console.log(` Database Size: ${status.memory.size}`);
|
||||
console.log(` Status: ${status.memory.status}`);
|
||||
|
||||
// Terminal details
|
||||
console.log('\n🖥️ Terminal Pool:');
|
||||
console.log(` Pool Size: ${status.terminal.poolSize}`);
|
||||
console.log(` Active Sessions: ${status.terminal.active}`);
|
||||
console.log(` Status: ${status.terminal.status}`);
|
||||
|
||||
// MCP details
|
||||
console.log('\n🌐 MCP Server:');
|
||||
console.log(` Status: ${status.mcp.status}`);
|
||||
console.log(` Port: ${status.mcp.port || 'Not configured'}`);
|
||||
console.log(` Active Connections: ${status.mcp.connections}`);
|
||||
|
||||
// Resource usage
|
||||
if (status.resources) {
|
||||
console.log('\n📈 Resource Usage:');
|
||||
console.log(` Memory: ${status.resources.memory.usage} of ${status.resources.memory.total}`);
|
||||
console.log(` CPU Cores: ${status.resources.cpu.cores}`);
|
||||
console.log(` CPU Load: ${status.resources.cpu.load}`);
|
||||
}
|
||||
|
||||
console.log('\n🕐 Status captured at:', new Date(status.timestamp).toLocaleString());
|
||||
}
|
||||
|
||||
// Recommendations
|
||||
console.log('\n💡 Quick Actions:');
|
||||
if (!status.orchestrator.running) {
|
||||
console.log(' Run "claude-flow start" to begin orchestration');
|
||||
}
|
||||
if (status.agents.active === 0) {
|
||||
console.log(' Run "claude-flow agent spawn researcher" to create an agent');
|
||||
}
|
||||
if (status.memory.entries === 0) {
|
||||
console.log(' Run "claude-flow memory store key value" to test memory');
|
||||
}
|
||||
}
|
||||
|
||||
function formatBytes(bytes) {
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
let size = bytes;
|
||||
let unitIndex = 0;
|
||||
|
||||
while (size >= 1024 && unitIndex < units.length - 1) {
|
||||
size /= 1024;
|
||||
unitIndex++;
|
||||
}
|
||||
|
||||
return `${size.toFixed(2)} ${units[unitIndex]}`;
|
||||
}
|
||||
|
||||
function formatUptime(milliseconds) {
|
||||
if (milliseconds === 0) return '0s';
|
||||
|
||||
const seconds = Math.floor(milliseconds / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) return `${days}d ${hours % 24}h ${minutes % 60}m`;
|
||||
if (hours > 0) return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
|
||||
if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// task.js - Task management commands
|
||||
import { printSuccess, printError, printWarning } from '../utils.js';
|
||||
|
||||
export async function taskCommand(subArgs, flags) {
|
||||
const taskCmd = subArgs[0];
|
||||
|
||||
switch (taskCmd) {
|
||||
case 'create':
|
||||
await createTask(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'list':
|
||||
await listTasks(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'status':
|
||||
await showTaskStatus(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'cancel':
|
||||
await cancelTask(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'workflow':
|
||||
await executeWorkflow(subArgs, flags);
|
||||
break;
|
||||
|
||||
case 'coordination':
|
||||
await manageCoordination(subArgs, flags);
|
||||
break;
|
||||
|
||||
default:
|
||||
showTaskHelp();
|
||||
}
|
||||
}
|
||||
|
||||
async function createTask(subArgs, flags) {
|
||||
const taskType = subArgs[1];
|
||||
const description = subArgs.slice(2).join(' ');
|
||||
|
||||
if (!taskType || !description) {
|
||||
printError('Usage: task create <type> "<description>"');
|
||||
console.log('Types: research, code, analysis, coordination, general');
|
||||
return;
|
||||
}
|
||||
|
||||
const taskId = `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
const priority = getFlag(subArgs, '--priority') || '5';
|
||||
|
||||
printSuccess(`Creating ${taskType} task: ${taskId}`);
|
||||
console.log(`📋 Description: ${description}`);
|
||||
console.log(`⚡ Priority: ${priority}/10`);
|
||||
console.log(`🏷️ Type: ${taskType}`);
|
||||
console.log('📅 Status: Queued');
|
||||
console.log('\n📋 Note: Task queued for execution when orchestrator starts');
|
||||
}
|
||||
|
||||
async function listTasks(subArgs, flags) {
|
||||
const filter = getFlag(subArgs, '--filter');
|
||||
const verbose = subArgs.includes('--verbose') || subArgs.includes('-v');
|
||||
|
||||
printSuccess('Task queue:');
|
||||
|
||||
if (filter) {
|
||||
console.log(`📊 Filtered by status: ${filter}`);
|
||||
}
|
||||
|
||||
console.log('📋 No active tasks (orchestrator not running)');
|
||||
console.log('\nTask statuses: queued, running, completed, failed, cancelled');
|
||||
|
||||
if (verbose) {
|
||||
console.log('\nTo create tasks:');
|
||||
console.log(' claude-flow task create research "Market analysis"');
|
||||
console.log(' claude-flow task create code "Implement API"');
|
||||
console.log(' claude-flow task create analysis "Data processing"');
|
||||
}
|
||||
}
|
||||
|
||||
async function showTaskStatus(subArgs, flags) {
|
||||
const taskId = subArgs[1];
|
||||
|
||||
if (!taskId) {
|
||||
printError('Usage: task status <task-id>');
|
||||
return;
|
||||
}
|
||||
|
||||
printSuccess(`Task status: ${taskId}`);
|
||||
console.log('📊 Task details would include:');
|
||||
console.log(' Status, progress, assigned agent, execution time, results');
|
||||
}
|
||||
|
||||
async function cancelTask(subArgs, flags) {
|
||||
const taskId = subArgs[1];
|
||||
|
||||
if (!taskId) {
|
||||
printError('Usage: task cancel <task-id>');
|
||||
return;
|
||||
}
|
||||
|
||||
printSuccess(`Cancelling task: ${taskId}`);
|
||||
console.log('🛑 Task would be gracefully cancelled');
|
||||
}
|
||||
|
||||
async function executeWorkflow(subArgs, flags) {
|
||||
const workflowFile = subArgs[1];
|
||||
|
||||
if (!workflowFile) {
|
||||
printError('Usage: task workflow <workflow-file>');
|
||||
return;
|
||||
}
|
||||
|
||||
printSuccess(`Executing workflow: ${workflowFile}`);
|
||||
console.log('🔄 Workflow execution would include:');
|
||||
console.log(' - Parsing workflow definition');
|
||||
console.log(' - Creating dependent tasks');
|
||||
console.log(' - Orchestrating execution');
|
||||
console.log(' - Progress tracking');
|
||||
}
|
||||
|
||||
async function manageCoordination(subArgs, flags) {
|
||||
const coordCmd = subArgs[1];
|
||||
|
||||
switch (coordCmd) {
|
||||
case 'status':
|
||||
printSuccess('Task coordination status:');
|
||||
console.log('🎯 Coordination engine: Not running');
|
||||
console.log(' Active coordinators: 0');
|
||||
console.log(' Pending tasks: 0');
|
||||
console.log(' Resource utilization: 0%');
|
||||
break;
|
||||
|
||||
case 'optimize':
|
||||
printSuccess('Optimizing task coordination...');
|
||||
console.log('⚡ Optimization would include:');
|
||||
console.log(' - Task dependency analysis');
|
||||
console.log(' - Resource allocation optimization');
|
||||
console.log(' - Parallel execution planning');
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log('Coordination commands: status, optimize');
|
||||
}
|
||||
}
|
||||
|
||||
function getFlag(args, flagName) {
|
||||
const index = args.indexOf(flagName);
|
||||
return index !== -1 && index + 1 < args.length ? args[index + 1] : null;
|
||||
}
|
||||
|
||||
function showTaskHelp() {
|
||||
console.log('Task commands:');
|
||||
console.log(' create <type> "<description>" Create new task');
|
||||
console.log(' list [--filter <status>] List tasks');
|
||||
console.log(' status <id> Show task details');
|
||||
console.log(' cancel <id> Cancel running task');
|
||||
console.log(' workflow <file> Execute workflow file');
|
||||
console.log(' coordination <status|optimize> Manage coordination');
|
||||
console.log();
|
||||
console.log('Task Types:');
|
||||
console.log(' research Information gathering and analysis');
|
||||
console.log(' code Software development tasks');
|
||||
console.log(' analysis Data processing and insights');
|
||||
console.log(' coordination Task orchestration and management');
|
||||
console.log(' general General purpose tasks');
|
||||
console.log();
|
||||
console.log('Options:');
|
||||
console.log(' --priority <1-10> Set task priority');
|
||||
console.log(' --filter <status> Filter by status');
|
||||
console.log(' --verbose, -v Show detailed output');
|
||||
console.log();
|
||||
console.log('Examples:');
|
||||
console.log(' claude-flow task create research "Market analysis" --priority 8');
|
||||
console.log(' claude-flow task list --filter running');
|
||||
console.log(' claude-flow task workflow examples/development-workflow.json');
|
||||
console.log(' claude-flow task coordination status');
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
// utils.js - Shared CLI utility functions
|
||||
|
||||
// Color formatting functions
|
||||
export function printSuccess(message) {
|
||||
console.log(`✅ ${message}`);
|
||||
}
|
||||
|
||||
export function printError(message) {
|
||||
console.log(`❌ ${message}`);
|
||||
}
|
||||
|
||||
export function printWarning(message) {
|
||||
console.log(`⚠️ ${message}`);
|
||||
}
|
||||
|
||||
export function printInfo(message) {
|
||||
console.log(`ℹ️ ${message}`);
|
||||
}
|
||||
|
||||
// Command validation helpers
|
||||
export function validateArgs(args, minLength, usage) {
|
||||
if (args.length < minLength) {
|
||||
printError(`Usage: ${usage}`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// File system helpers
|
||||
export async function ensureDirectory(path) {
|
||||
try {
|
||||
await Deno.mkdir(path, { recursive: true });
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
||||
throw err;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fileExists(path) {
|
||||
try {
|
||||
await Deno.stat(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// JSON helpers
|
||||
export async function readJsonFile(path, defaultValue = {}) {
|
||||
try {
|
||||
const content = await Deno.readTextFile(path);
|
||||
return JSON.parse(content);
|
||||
} catch {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeJsonFile(path, data) {
|
||||
await Deno.writeTextFile(path, JSON.stringify(data, null, 2));
|
||||
}
|
||||
|
||||
// String helpers
|
||||
export function formatTimestamp(timestamp) {
|
||||
return new Date(timestamp).toLocaleString();
|
||||
}
|
||||
|
||||
export function truncateString(str, length = 100) {
|
||||
return str.length > length ? str.substring(0, length) + '...' : str;
|
||||
}
|
||||
|
||||
export function formatBytes(bytes) {
|
||||
const units = ['B', 'KB', 'MB', 'GB'];
|
||||
let size = bytes;
|
||||
let unitIndex = 0;
|
||||
|
||||
while (size >= 1024 && unitIndex < units.length - 1) {
|
||||
size /= 1024;
|
||||
unitIndex++;
|
||||
}
|
||||
|
||||
return `${size.toFixed(2)} ${units[unitIndex]}`;
|
||||
}
|
||||
|
||||
// Command execution helpers
|
||||
export function parseFlags(args) {
|
||||
const flags = {};
|
||||
const filteredArgs = [];
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
|
||||
if (arg.startsWith('--')) {
|
||||
const flagName = arg.substring(2);
|
||||
const nextArg = args[i + 1];
|
||||
|
||||
if (nextArg && !nextArg.startsWith('--')) {
|
||||
flags[flagName] = nextArg;
|
||||
i++; // Skip next arg since we consumed it
|
||||
} else {
|
||||
flags[flagName] = true;
|
||||
}
|
||||
} else if (arg.startsWith('-') && arg.length > 1) {
|
||||
// Short flags
|
||||
const shortFlags = arg.substring(1);
|
||||
for (const flag of shortFlags) {
|
||||
flags[flag] = true;
|
||||
}
|
||||
} else {
|
||||
filteredArgs.push(arg);
|
||||
}
|
||||
}
|
||||
|
||||
return { flags, args: filteredArgs };
|
||||
}
|
||||
|
||||
// Process execution helpers
|
||||
export async function runCommand(command, args = [], options = {}) {
|
||||
try {
|
||||
const cmd = new Deno.Command(command, {
|
||||
args,
|
||||
...options
|
||||
});
|
||||
|
||||
const result = await cmd.output();
|
||||
|
||||
return {
|
||||
success: result.code === 0,
|
||||
code: result.code,
|
||||
stdout: new TextDecoder().decode(result.stdout),
|
||||
stderr: new TextDecoder().decode(result.stderr)
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
success: false,
|
||||
code: -1,
|
||||
stdout: '',
|
||||
stderr: err.message
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Configuration helpers
|
||||
export async function loadConfig(path = 'claude-flow.config.json') {
|
||||
const defaultConfig = {
|
||||
terminal: {
|
||||
poolSize: 10,
|
||||
recycleAfter: 20,
|
||||
healthCheckInterval: 30000,
|
||||
type: "auto"
|
||||
},
|
||||
orchestrator: {
|
||||
maxConcurrentTasks: 10,
|
||||
taskTimeout: 300000
|
||||
},
|
||||
memory: {
|
||||
backend: "json",
|
||||
path: "./memory/claude-flow-data.json"
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const content = await Deno.readTextFile(path);
|
||||
return { ...defaultConfig, ...JSON.parse(content) };
|
||||
} catch {
|
||||
return defaultConfig;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveConfig(config, path = 'claude-flow.config.json') {
|
||||
await writeJsonFile(path, config);
|
||||
}
|
||||
|
||||
// ID generation
|
||||
export function generateId(prefix = '') {
|
||||
const timestamp = Date.now();
|
||||
const random = Math.random().toString(36).substr(2, 9);
|
||||
return prefix ? `${prefix}-${timestamp}-${random}` : `${timestamp}-${random}`;
|
||||
}
|
||||
|
||||
// Array helpers
|
||||
export function chunk(array, size) {
|
||||
const chunks = [];
|
||||
for (let i = 0; i < array.length; i += size) {
|
||||
chunks.push(array.slice(i, i + size));
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
// Environment helpers
|
||||
export function getEnvVar(name, defaultValue = null) {
|
||||
return Deno.env.get(name) ?? defaultValue;
|
||||
}
|
||||
|
||||
export function setEnvVar(name, value) {
|
||||
Deno.env.set(name, value);
|
||||
}
|
||||
|
||||
// Validation helpers
|
||||
export function isValidJson(str) {
|
||||
try {
|
||||
JSON.parse(str);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isValidUrl(str) {
|
||||
try {
|
||||
new URL(str);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Progress and status helpers
|
||||
export function showProgress(current, total, message = '') {
|
||||
const percentage = Math.round((current / total) * 100);
|
||||
const bar = '█'.repeat(Math.round(percentage / 5)) + '░'.repeat(20 - Math.round(percentage / 5));
|
||||
console.log(`\r${bar} ${percentage}% ${message}`);
|
||||
}
|
||||
|
||||
export function clearLine() {
|
||||
console.log('\r\x1b[K');
|
||||
}
|
||||
|
||||
// Async helpers
|
||||
export function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
export async function retry(fn, maxAttempts = 3, delay = 1000) {
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (err) {
|
||||
if (attempt === maxAttempts) {
|
||||
throw err;
|
||||
}
|
||||
await sleep(delay * attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
def test_repl():
|
||||
print("Testing Claude-Flow REPL...")
|
||||
|
||||
# Start the REPL process
|
||||
proc = subprocess.Popen(
|
||||
['./bin/claude-flow', 'repl'],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=0
|
||||
)
|
||||
|
||||
# Helper function to send command and read response
|
||||
def send_command(cmd):
|
||||
print(f"\n> Sending: {cmd}")
|
||||
proc.stdin.write(cmd + '\n')
|
||||
proc.stdin.flush()
|
||||
time.sleep(0.5) # Give it time to process
|
||||
|
||||
try:
|
||||
# Send test commands
|
||||
commands = [
|
||||
'help',
|
||||
'status',
|
||||
'agent spawn researcher bot1',
|
||||
'agent list',
|
||||
'task create research "test task"',
|
||||
'memory store test "hello world"',
|
||||
'memory list',
|
||||
'!echo "Shell test"',
|
||||
'exit'
|
||||
]
|
||||
|
||||
for cmd in commands:
|
||||
send_command(cmd)
|
||||
|
||||
# Wait for process to complete
|
||||
proc.wait(timeout=5)
|
||||
|
||||
# Read all output
|
||||
output, errors = proc.communicate()
|
||||
print("\nOutput:")
|
||||
print(output)
|
||||
|
||||
if errors:
|
||||
print("\nErrors:")
|
||||
print(errors)
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
print("\nTimeout reached, terminating...")
|
||||
proc.terminate()
|
||||
except Exception as e:
|
||||
print(f"\nError: {e}")
|
||||
proc.terminate()
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_repl()
|
||||
@@ -1,64 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Test REPL functionality
|
||||
echo "Testing Claude-Flow REPL..."
|
||||
|
||||
# Create a temporary expect script
|
||||
cat > /tmp/test-repl-expect.sh << 'EOF'
|
||||
#!/usr/bin/expect -f
|
||||
|
||||
set timeout 5
|
||||
|
||||
spawn ./bin/claude-flow repl
|
||||
|
||||
expect "claude-flow>"
|
||||
send "help\r"
|
||||
|
||||
expect "claude-flow>"
|
||||
send "status\r"
|
||||
|
||||
expect "claude-flow>"
|
||||
send "agent spawn researcher bot1\r"
|
||||
|
||||
expect "claude-flow>"
|
||||
send "agent list\r"
|
||||
|
||||
expect "claude-flow>"
|
||||
send "task create research 'test task'\r"
|
||||
|
||||
expect "claude-flow>"
|
||||
send "memory store test 'hello world'\r"
|
||||
|
||||
expect "claude-flow>"
|
||||
send "memory list\r"
|
||||
|
||||
expect "claude-flow>"
|
||||
send "!echo 'Shell command test'\r"
|
||||
|
||||
expect "claude-flow>"
|
||||
send "exit\r"
|
||||
|
||||
expect eof
|
||||
EOF
|
||||
|
||||
# Make it executable
|
||||
chmod +x /tmp/test-repl-expect.sh
|
||||
|
||||
# Check if expect is installed
|
||||
if command -v expect &> /dev/null; then
|
||||
echo "Running REPL test with expect..."
|
||||
/tmp/test-repl-expect.sh
|
||||
else
|
||||
echo "expect not found, testing with simple echo commands..."
|
||||
# Fallback to simple test
|
||||
timeout 5s ./bin/claude-flow repl << EOF
|
||||
help
|
||||
status
|
||||
exit
|
||||
EOF
|
||||
fi
|
||||
|
||||
# Cleanup
|
||||
rm -f /tmp/test-repl-expect.sh
|
||||
|
||||
echo "REPL test completed."
|
||||
Reference in new issue
Block a user