Merge pull request #9 from ruvnet/claude-code-integration

Claude code integration
This commit is contained in:
rUv authored and GitHub committed 2025-06-10 15:48:52 -04:00
commit f8f2822a2f
10 files changed
+1073 -17

No files matched your search

+35 -3
View File
@@ -177,7 +177,19 @@ npx claude-flow task create code "Implement authentication" --priority 9
npx claude-flow task list --verbose
```
### 5. **Monitor System Status**
### 5. **Spawn Claude Instances** 🆕
```bash
# Spawn Claude with specific configuration
npx claude-flow claude spawn "implement user authentication" --research --parallel
# Run with custom tools
npx claude-flow claude spawn "fix payment bug" --tools "View,Edit,Bash" --no-permissions
# Execute batch workflow
npx claude-flow claude batch examples/claude-workflow.json --dry-run
```
### 6. **Monitor System Status**
```bash
# Check system health
npx claude-flow status
@@ -343,8 +355,28 @@ npx claude-flow mcp <subcommand>
#### `monitor` - Real-time Monitoring
```bash
npx claude-flow monitor [options]
--interval <ms> Update interval (default: 5000)
--metrics Show performance metrics
-i, --interval <seconds> Update interval (default: 2)
-c, --compact Compact view mode
-f, --focus <component> Focus on specific component
```
#### `claude` - Spawn Claude Instances 🆕
```bash
npx claude-flow claude <subcommand>
spawn <task> Spawn Claude with specific configuration
-t, --tools <tools> Allowed tools (comma-separated)
--no-permissions Use --dangerously-skip-permissions flag
-c, --config <file> MCP config file path
-m, --mode <mode> Development mode (full/backend-only/frontend-only/api-only)
--parallel Enable parallel execution with BatchTool
--research Enable web research with WebFetchTool
--coverage <n> Test coverage target percentage (default: 80)
--commit <freq> Commit frequency (phase/feature/manual)
-v, --verbose Enable verbose output
-d, --dry-run Show what would be executed without running
batch <workflow-file> Execute multiple Claude instances from workflow
--dry-run Show what would be executed without running
```
#### `config` - Configuration Management
Binary file not shown.
+262
View File
@@ -0,0 +1,262 @@
# Claude Instance Spawning
## Overview
Claude-Flow provides powerful capabilities to spawn and manage Claude Code instances with specific configurations. This feature allows you to programmatically launch Claude with tailored tool permissions, development modes, and execution parameters - similar to the claude-sparc.sh script but integrated into the orchestration system.
## Key Features
- **Flexible Tool Configuration**: Specify exactly which tools Claude can use
- **Development Mode Selection**: Choose between full, backend-only, frontend-only, or api-only modes
- **Parallel Execution Support**: Enable BatchTool and dispatch_agent for concurrent operations
- **Research Capabilities**: Toggle WebFetchTool for web research tasks
- **Workflow Automation**: Execute multiple Claude instances from JSON workflow files
- **Dry-Run Mode**: Preview commands before execution
## Command Reference
### Spawn Individual Claude Instance
```bash
npx claude-flow claude spawn <task> [options]
```
#### Options
| Option | Short | Description | Default |
|--------|-------|-------------|---------|
| `--tools` | `-t` | Comma-separated list of allowed tools | View,Edit,Replace,GlobTool,GrepTool,LS,Bash |
| `--no-permissions` | | Use --dangerously-skip-permissions flag | false |
| `--config` | `-c` | MCP config file path | |
| `--mode` | `-m` | Development mode (full/backend-only/frontend-only/api-only) | full |
| `--parallel` | | Enable parallel execution with BatchTool | false |
| `--research` | | Enable web research with WebFetchTool | false |
| `--coverage` | | Test coverage target percentage | 80 |
| `--commit` | | Commit frequency (phase/feature/manual) | phase |
| `--verbose` | `-v` | Enable verbose output | false |
| `--dry-run` | `-d` | Show what would be executed without running | false |
#### Examples
```bash
# Basic task with default tools
npx claude-flow claude spawn "implement user authentication system"
# Research task with web capabilities
npx claude-flow claude spawn "research best practices for microservices" --research --parallel
# Backend development with specific tools
npx claude-flow claude spawn "create REST API endpoints" --mode backend-only --tools "View,Edit,Replace,Bash"
# Frontend task with no permission prompts
npx claude-flow claude spawn "build React dashboard" --mode frontend-only --no-permissions
# Dry run to preview command
npx claude-flow claude spawn "refactor payment module" --coverage 95 --dry-run
```
### Batch Workflow Execution
```bash
npx claude-flow claude batch <workflow-file> [options]
```
Execute multiple Claude instances based on a JSON workflow file.
#### Workflow File Format
```json
{
"name": "Development Workflow",
"description": "Multi-task development workflow",
"parallel": true,
"tasks": [
{
"id": "task-1",
"name": "Research Task",
"description": "Research authentication best practices",
"tools": ["WebFetchTool", "View", "Edit"],
"skipPermissions": true,
"config": ".roo/mcp.json"
},
{
"id": "task-2",
"name": "Implementation Task",
"description": "Implement authentication system",
"tools": "View,Edit,Replace,GlobTool,GrepTool,LS,Bash",
"mode": "backend-only",
"coverage": 90
}
]
}
```
#### Task Properties
| Property | Type | Description | Required |
|----------|------|-------------|----------|
| `id` | string | Unique task identifier | Yes |
| `name` | string | Task name for display | No |
| `description` | string | Task description (used as Claude prompt) | Yes |
| `tools` | string/array | Allowed tools (comma-separated string or array) | No |
| `skipPermissions` | boolean | Use --dangerously-skip-permissions flag | No |
| `dangerouslySkipPermissions` | boolean | Alternative to skipPermissions | No |
| `config` | string | MCP config file path | No |
| `mode` | string | Development mode | No |
| `coverage` | number | Test coverage target | No |
| `type` | string | Task type for categorization | No |
#### Examples
```bash
# Execute workflow with dry run
npx claude-flow claude batch development-workflow.json --dry-run
# Execute workflow in production
npx claude-flow claude batch production-tasks.json
```
## Environment Variables
When Claude instances are spawned, the following environment variables are set:
| Variable | Description |
|----------|-------------|
| `CLAUDE_INSTANCE_ID` | Unique identifier for the Claude instance |
| `CLAUDE_FLOW_MODE` | Development mode (full/backend-only/etc) |
| `CLAUDE_FLOW_COVERAGE` | Test coverage target percentage |
| `CLAUDE_FLOW_COMMIT` | Commit frequency setting |
| `CLAUDE_TASK_ID` | Task ID (for batch execution) |
| `CLAUDE_TASK_TYPE` | Task type (for batch execution) |
## Integration with Orchestration System
The Claude spawning feature integrates seamlessly with the existing orchestration system:
1. **Agent Delegation**: Agents can spawn Claude instances for specific subtasks
2. **Task Coordination**: Claude instances can be part of larger task workflows
3. **Memory Sharing**: Claude instances can access the shared memory bank
4. **Status Tracking**: Monitor Claude instance status through the orchestrator
## Best Practices
### Tool Selection
- Use minimal tool sets for security and performance
- Include `WebFetchTool` only when web research is needed
- Add `BatchTool` for tasks requiring parallel execution
- Consider `dispatch_agent` for complex multi-step operations
### Development Modes
- **full**: Use for complete full-stack development
- **backend-only**: Focus on server-side implementation
- **frontend-only**: UI/UX development tasks
- **api-only**: REST/GraphQL API development
### Workflow Design
1. Group related tasks together
2. Use parallel execution for independent tasks
3. Set appropriate coverage targets based on criticality
4. Use descriptive task IDs and names for tracking
### Error Handling
- Always test with `--dry-run` first
- Check Claude instance exit codes
- Monitor logs for execution errors
- Use verbose mode for debugging
## Advanced Usage
### Conditional Task Execution
Create workflows with conditional logic:
```json
{
"tasks": [
{
"id": "test-task",
"description": "Run unit tests",
"tools": "Bash,View",
"onSuccess": "deploy-task",
"onFailure": "debug-task"
}
]
}
```
### Custom Tool Combinations
Define tool presets for common scenarios:
```bash
# Research preset
RESEARCH_TOOLS="WebFetchTool,View,Edit,GrepTool"
# Development preset
DEV_TOOLS="View,Edit,Replace,GlobTool,GrepTool,LS,Bash,BatchTool"
# Minimal preset
MIN_TOOLS="View,Edit"
npx claude-flow claude spawn "research task" --tools "$RESEARCH_TOOLS"
```
### Integration with CI/CD
Use Claude spawning in CI/CD pipelines:
```yaml
# GitHub Actions example
- name: Run Claude Development Task
run: |
npx claude-flow claude spawn \
"implement feature from issue #123" \
--mode backend-only \
--coverage 90 \
--commit feature \
--no-permissions
```
## Troubleshooting
### Common Issues
1. **"Raw mode not supported" error**
- This occurs when running in non-interactive environments
- Use `--no-permissions` flag to bypass interactive prompts
2. **Tool not found errors**
- Ensure tool names are spelled correctly
- Check that required tools are installed in the environment
3. **Workflow file parsing errors**
- Validate JSON syntax
- Ensure all required fields are present
- Check for proper quotation marks
### Debug Mode
Enable verbose logging for troubleshooting:
```bash
npx claude-flow claude spawn "debug task" --verbose --dry-run
```
## Security Considerations
1. **Tool Permissions**: Be cautious with tool permissions in production
2. **File Access**: Claude instances inherit file system permissions
3. **Network Access**: WebFetchTool enables internet access
4. **Credential Handling**: Never include credentials in task descriptions
## Future Enhancements
- Template library for common task types
- Visual workflow designer
- Real-time Claude instance monitoring
- Integration with more AI models
- Distributed execution across multiple machines
+1
View File
@@ -23,6 +23,7 @@ This guide is organized into 10 comprehensive sections, progressing from basic u
### 🔧 Integration and Tools
- **[07. MCP Integration](./07-mcp-integration.md)** - External tools and Model Context Protocol
- **[08. Terminal Management](./08-terminal-management.md)** - Session handling and multi-terminal workflows
- **[11. Claude Spawning](./11-claude-spawning.md)** 🆕 - Spawn Claude instances with specific configurations
### 🛠️ Support and Advanced Usage
- **[09. Troubleshooting](./09-troubleshooting.md)** - Common issues and diagnostic procedures
+106 -8
View File
@@ -609,9 +609,9 @@ claude-flow status [options]
---
### `monitor` - System Monitoring
### `monitor` - Live Monitoring Dashboard
Monitor system performance and metrics.
Start the real-time monitoring dashboard to track system performance and activity.
```bash
claude-flow monitor [options]
@@ -619,12 +619,110 @@ claude-flow monitor [options]
**Options:**
| Option | Description |
|--------|-------------|
| `--interval <ms>` | Update interval |
| `--metrics <list>` | Specific metrics to monitor |
| `--export <file>` | Export metrics to file |
| `--dashboard` | Show dashboard view |
| Option | Short | Description | Default |
|--------|-------|-------------|---------|
| `--interval` | `-i` | Update interval in seconds | `2` |
| `--compact` | `-c` | Compact view mode (hide lists) | `false` |
| `--focus` | `-f` | Focus on specific component | |
**Examples:**
```bash
# Start monitor with default settings
claude-flow monitor
# Monitor with 5-second updates
claude-flow monitor --interval 5
# Compact mode for smaller screens
claude-flow monitor --compact
# Focus on specific component
claude-flow monitor --focus orchestrator
```
---
### `claude` - Spawn Claude Instances
Spawn and manage Claude Code instances with specific configurations, similar to claude-sparc.sh but integrated into the orchestration system.
```bash
claude-flow claude <subcommand> [options]
```
#### `spawn` - Spawn Single Claude Instance
```bash
claude-flow claude spawn <task> [options]
```
**Options:**
| Option | Short | Description | Default |
|--------|-------|-------------|---------|
| `--tools` | `-t` | Comma-separated list of allowed tools | `View,Edit,Replace,GlobTool,GrepTool,LS,Bash` |
| `--no-permissions` | | Use --dangerously-skip-permissions flag | `false` |
| `--config` | `-c` | MCP config file path | |
| `--mode` | `-m` | Development mode (full/backend-only/frontend-only/api-only) | `full` |
| `--parallel` | | Enable parallel execution with BatchTool | `false` |
| `--research` | | Enable web research with WebFetchTool | `false` |
| `--coverage` | | Test coverage target percentage | `80` |
| `--commit` | | Commit frequency (phase/feature/manual) | `phase` |
| `--verbose` | `-v` | Enable verbose output | `false` |
| `--dry-run` | `-d` | Show what would be executed without running | `false` |
**Examples:**
```bash
# Basic task
claude-flow claude spawn "implement user authentication"
# Research task
claude-flow claude spawn "research microservices patterns" --research --parallel
# Backend development
claude-flow claude spawn "create REST API" --mode backend-only --coverage 90
# Frontend with no permissions
claude-flow claude spawn "build dashboard" --mode frontend-only --no-permissions
# Dry run
claude-flow claude spawn "refactor code" --dry-run
```
#### `batch` - Execute Workflow File
```bash
claude-flow claude batch <workflow-file> [options]
```
Execute multiple Claude instances from a JSON workflow file.
**Workflow Format:**
```json
{
"name": "Workflow Name",
"parallel": true,
"tasks": [{
"id": "task-1",
"description": "Task description",
"tools": ["View", "Edit"],
"skipPermissions": true
}]
}
```
**Example:**
```bash
# Execute workflow
claude-flow claude batch workflow.json
# Dry run
claude-flow claude batch workflow.json --dry-run
```
---
+70
View File
@@ -0,0 +1,70 @@
{
"name": "Multi-Agent Claude Development Workflow",
"description": "Example workflow showing how to spawn multiple Claude instances with different configurations",
"parallel": true,
"tasks": [
{
"id": "research-task",
"name": "Research Best Practices",
"type": "research",
"description": "Research current best practices for authentication systems and security patterns",
"tools": ["WebFetchTool", "View", "Edit", "GrepTool"],
"skipPermissions": true,
"config": ".roo/mcp.json"
},
{
"id": "backend-task",
"name": "Implement Backend API",
"type": "implementation",
"description": "Implement user authentication backend with JWT tokens and secure password hashing",
"tools": ["View", "Edit", "Replace", "GlobTool", "GrepTool", "LS", "Bash"],
"skipPermissions": true,
"mode": "backend-only",
"coverage": 90
},
{
"id": "frontend-task",
"name": "Build Frontend Components",
"type": "implementation",
"description": "Create React components for login, registration, and password reset flows",
"tools": ["View", "Edit", "Replace", "GlobTool", "GrepTool", "LS", "Bash"],
"skipPermissions": true,
"mode": "frontend-only"
},
{
"id": "testing-task",
"name": "Write Comprehensive Tests",
"type": "testing",
"description": "Write unit and integration tests for authentication system with 95% coverage",
"tools": ["View", "Edit", "Replace", "GlobTool", "GrepTool", "LS", "Bash", "BatchTool"],
"skipPermissions": true,
"coverage": 95
}
],
"agents": [
{
"id": "research-agent",
"type": "researcher",
"capabilities": ["web-search", "information-gathering", "analysis"],
"assignedTasks": ["research-task"]
},
{
"id": "backend-agent",
"type": "implementer",
"capabilities": ["code-generation", "api-development", "database-design"],
"assignedTasks": ["backend-task"]
},
{
"id": "frontend-agent",
"type": "implementer",
"capabilities": ["ui-development", "react", "component-design"],
"assignedTasks": ["frontend-task"]
},
{
"id": "test-agent",
"type": "tester",
"capabilities": ["test-writing", "coverage-analysis", "quality-assurance"],
"assignedTasks": ["testing-task"]
}
]
}
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "claude-flow",
"version": "1.0.1",
"description": "Advanced AI agent orchestration system for Claude",
"version": "1.0.4",
"description": "Advanced AI agent orchestration system for Claude Code",
"main": "src/cli/main.ts",
"bin": {
"claude-flow": "./bin/claude-flow"
+1 -1
View File
@@ -8,7 +8,7 @@ import { red, green, yellow, blue, bold, cyan } from "https://deno.land/std@0.22
import { ensureDir } from "https://deno.land/std@0.224.0/fs/mod.ts";
import { join } from "https://deno.land/std@0.224.0/path/mod.ts";
export const VERSION = "1.0.1";
export const VERSION = "1.0.3";
interface CommandContext {
args: string[];
+175
View File
@@ -0,0 +1,175 @@
/**
* Claude instance management commands
*/
import { Command } from '@cliffy/command';
import { colors } from '@cliffy/ansi/colors';
import { spawn } from 'node:child_process';
import { generateId } from '../../utils/helpers.ts';
export const claudeCommand = new Command()
.description('Manage Claude instances')
.action(() => {
claudeCommand.showHelp();
})
.command('spawn', new Command()
.description('Spawn a new Claude instance with specific configuration')
.arguments('<task:string>')
.option('-t, --tools <tools:string>', 'Allowed tools (comma-separated)', {
default: 'View,Edit,Replace,GlobTool,GrepTool,LS,Bash'
})
.option('--no-permissions', 'Use --dangerously-skip-permissions flag')
.option('-c, --config <config:string>', 'MCP config file path')
.option('-m, --mode <mode:string>', 'Development mode (full, backend-only, frontend-only, api-only)', {
default: 'full'
})
.option('--parallel', 'Enable parallel execution with BatchTool')
.option('--research', 'Enable web research with WebFetchTool')
.option('--coverage <coverage:number>', 'Test coverage target', { default: 80 })
.option('--commit <frequency:string>', 'Commit frequency (phase, feature, manual)', {
default: 'phase'
})
.option('-v, --verbose', 'Enable verbose output')
.option('--dry-run', 'Show what would be executed without running')
.action(async (options: any, task: string) => {
try {
const instanceId = generateId('claude');
// Build allowed tools list
let tools = options.tools;
if (options.parallel && !tools.includes('BatchTool')) {
tools += ',BatchTool,dispatch_agent';
}
if (options.research && !tools.includes('WebFetchTool')) {
tools += ',WebFetchTool';
}
// Build Claude command
const claudeArgs = [task];
claudeArgs.push('--allowedTools', tools);
if (options.noPermissions) {
claudeArgs.push('--dangerously-skip-permissions');
}
if (options.config) {
claudeArgs.push('--mcp-config', options.config);
}
if (options.verbose) {
claudeArgs.push('--verbose');
}
if (options.dryRun) {
console.log(colors.yellow('DRY RUN - Would execute:'));
console.log(colors.gray(`claude ${claudeArgs.join(' ')}`));
console.log('\nConfiguration:');
console.log(` Instance ID: ${instanceId}`);
console.log(` Task: ${task}`);
console.log(` Tools: ${tools}`);
console.log(` Mode: ${options.mode}`);
console.log(` Coverage: ${options.coverage}%`);
console.log(` Commit: ${options.commit}`);
return;
}
console.log(colors.green(`Spawning Claude instance: ${instanceId}`));
console.log(colors.gray(`Task: ${task}`));
console.log(colors.gray(`Tools: ${tools}`));
// Spawn Claude process
const claude = spawn('claude', claudeArgs, {
stdio: 'inherit',
env: {
...process.env,
CLAUDE_INSTANCE_ID: instanceId,
CLAUDE_FLOW_MODE: options.mode,
CLAUDE_FLOW_COVERAGE: options.coverage.toString(),
CLAUDE_FLOW_COMMIT: options.commit,
}
});
claude.on('error', (err) => {
console.error(colors.red('Failed to spawn Claude:'), err.message);
});
claude.on('exit', (code) => {
if (code === 0) {
console.log(colors.green(`Claude instance ${instanceId} completed successfully`));
} else {
console.log(colors.red(`Claude instance ${instanceId} exited with code ${code}`));
}
});
} catch (error) {
console.error(colors.red('Failed to spawn Claude:'), (error as Error).message);
}
}),
)
.command('batch', new Command()
.description('Spawn multiple Claude instances from workflow')
.arguments('<workflow-file:string>')
.option('--dry-run', 'Show what would be executed without running')
.action(async (options: any, workflowFile: string) => {
try {
const content = await Deno.readTextFile(workflowFile);
const workflow = JSON.parse(content);
console.log(colors.green('Loading workflow:'), workflow.name || 'Unnamed');
console.log(colors.gray(`Tasks: ${workflow.tasks?.length || 0}`));
if (!workflow.tasks || workflow.tasks.length === 0) {
console.log(colors.yellow('No tasks found in workflow'));
return;
}
for (const task of workflow.tasks) {
const claudeArgs = [task.description || task.name];
// Add tools
if (task.tools) {
claudeArgs.push('--allowedTools', Array.isArray(task.tools) ? task.tools.join(',') : task.tools);
}
// Add flags
if (task.skipPermissions) {
claudeArgs.push('--dangerously-skip-permissions');
}
if (task.config) {
claudeArgs.push('--mcp-config', task.config);
}
if (options.dryRun) {
console.log(colors.yellow(`\nDRY RUN - Task: ${task.name || task.id}`));
console.log(colors.gray(`claude ${claudeArgs.join(' ')}`));
} else {
console.log(colors.blue(`\nSpawning Claude for task: ${task.name || task.id}`));
const claude = spawn('claude', claudeArgs, {
stdio: 'inherit',
env: {
...process.env,
CLAUDE_TASK_ID: task.id || generateId('task'),
CLAUDE_TASK_TYPE: task.type || 'general',
}
});
// Wait for completion if sequential
if (!workflow.parallel) {
await new Promise((resolve) => {
claude.on('exit', resolve);
});
}
}
}
if (!options.dryRun && workflow.parallel) {
console.log(colors.green('\nAll Claude instances spawned in parallel mode'));
}
} catch (error) {
console.error(colors.red('Failed to process workflow:'), (error as Error).message);
}
}),
);
+421 -3
View File
@@ -1,6 +1,6 @@
import { CLI, success, error, warning, info, VERSION } from "../cli-core.ts";
import type { Command, CommandContext } from "../cli-core.ts";
import { bold, blue } from "https://deno.land/std@0.224.0/fmt/colors.ts";
import { bold, blue, yellow } from "https://deno.land/std@0.224.0/fmt/colors.ts";
import { Orchestrator } from "../../core/orchestrator-fixed.ts";
import { ConfigManager } from "../../core/config.ts";
import { MemoryManager } from "../../memory/manager.ts";
@@ -607,12 +607,430 @@ export function setupCommands(cli: CLI): void {
},
});
// Claude command
cli.command({
name: "claude",
description: "Spawn Claude instances with specific configurations",
aliases: ["cl"],
options: [
{
name: "tools",
short: "t",
description: "Allowed tools (comma-separated)",
type: "string",
default: "View,Edit,Replace,GlobTool,GrepTool,LS,Bash",
},
{
name: "no-permissions",
description: "Use --dangerously-skip-permissions flag",
type: "boolean",
},
{
name: "config",
short: "c",
description: "MCP config file path",
type: "string",
},
{
name: "mode",
short: "m",
description: "Development mode (full, backend-only, frontend-only, api-only)",
type: "string",
default: "full",
},
{
name: "parallel",
description: "Enable parallel execution with BatchTool",
type: "boolean",
},
{
name: "research",
description: "Enable web research with WebFetchTool",
type: "boolean",
},
{
name: "coverage",
description: "Test coverage target percentage",
type: "number",
default: 80,
},
{
name: "commit",
description: "Commit frequency (phase, feature, manual)",
type: "string",
default: "phase",
},
{
name: "verbose",
short: "v",
description: "Enable verbose output",
type: "boolean",
},
{
name: "dry-run",
short: "d",
description: "Show what would be executed without running",
type: "boolean",
},
],
action: async (ctx: CommandContext) => {
const subcommand = ctx.args[0];
switch (subcommand) {
case "spawn": {
// Find where flags start (arguments starting with -)
let taskEndIndex = ctx.args.length;
for (let i = 1; i < ctx.args.length; i++) {
if (ctx.args[i].startsWith("-")) {
taskEndIndex = i;
break;
}
}
const task = ctx.args.slice(1, taskEndIndex).join(" ");
if (!task) {
error("Usage: claude spawn <task description>");
break;
}
try {
// Build allowed tools list
let tools = ctx.flags.tools as string || "View,Edit,Replace,GlobTool,GrepTool,LS,Bash";
if (ctx.flags.parallel) {
tools += ",BatchTool,dispatch_agent";
}
if (ctx.flags.research) {
tools += ",WebFetchTool";
}
// Build Claude command
const claudeCmd = ["claude", `"${task}"`];
claudeCmd.push("--allowedTools", tools);
if (ctx.flags.noPermissions || ctx.flags["skip-permissions"]) {
claudeCmd.push("--dangerously-skip-permissions");
}
if (ctx.flags.config) {
claudeCmd.push("--mcp-config", ctx.flags.config as string);
}
if (ctx.flags.verbose) {
claudeCmd.push("--verbose");
}
const instanceId = `claude-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
if (ctx.flags.dryRun || ctx.flags["dry-run"] || ctx.flags.d) {
warning("DRY RUN - Would execute:");
console.log(`Command: ${claudeCmd.join(" ")}`);
console.log(`Instance ID: ${instanceId}`);
console.log(`Task: ${task}`);
console.log(`Tools: ${tools}`);
console.log(`Mode: ${ctx.flags.mode || "full"}`);
return;
}
success(`Spawning Claude instance: ${instanceId}`);
console.log(`📝 Task: ${task}`);
console.log(`🔧 Tools: ${tools}`);
console.log(`⚙️ Mode: ${ctx.flags.mode || "full"}`);
// Execute Claude command
const command = new Deno.Command("claude", {
args: claudeCmd.slice(1).map(arg => arg.replace(/^"|"$/g, '')),
env: {
...Deno.env.toObject(),
CLAUDE_INSTANCE_ID: instanceId,
CLAUDE_FLOW_MODE: ctx.flags.mode as string || "full",
CLAUDE_FLOW_COVERAGE: (ctx.flags.coverage || 80).toString(),
CLAUDE_FLOW_COMMIT: ctx.flags.commit as string || "phase",
},
stdin: "inherit",
stdout: "inherit",
stderr: "inherit",
});
const child = command.spawn();
const status = await child.status;
if (status.success) {
success(`Claude instance ${instanceId} completed successfully`);
} else {
error(`Claude instance ${instanceId} exited with code ${status.code}`);
}
} catch (err) {
error(`Failed to spawn Claude: ${(err as Error).message}`);
}
break;
}
case "batch": {
const workflowFile = ctx.args[1];
if (!workflowFile) {
error("Usage: claude batch <workflow-file>");
break;
}
try {
const content = await Deno.readTextFile(workflowFile);
const workflow = JSON.parse(content);
success(`Loading workflow: ${workflow.name || "Unnamed"}`);
console.log(`📋 Tasks: ${workflow.tasks?.length || 0}`);
if (!workflow.tasks || workflow.tasks.length === 0) {
warning("No tasks found in workflow");
return;
}
const promises = [];
for (const task of workflow.tasks) {
const claudeCmd = ["claude", `"${task.description || task.name}"`];
// Add tools
if (task.tools) {
const toolsList = Array.isArray(task.tools) ? task.tools.join(",") : task.tools;
claudeCmd.push("--allowedTools", toolsList);
}
// Add flags
if (task.skipPermissions || task.dangerouslySkipPermissions) {
claudeCmd.push("--dangerously-skip-permissions");
}
if (task.config) {
claudeCmd.push("--mcp-config", task.config);
}
const taskId = task.id || `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
if (ctx.flags.dryRun || ctx.flags["dry-run"]) {
console.log(`\n${yellow("DRY RUN")} - Task: ${task.name || taskId}`);
console.log(`Command: ${claudeCmd.join(" ")}`);
continue;
}
console.log(`\n🚀 Spawning Claude for task: ${task.name || taskId}`);
const command = new Deno.Command("claude", {
args: claudeCmd.slice(1).map(arg => arg.replace(/^"|"$/g, '')),
env: {
...Deno.env.toObject(),
CLAUDE_TASK_ID: taskId,
CLAUDE_TASK_TYPE: task.type || "general",
},
stdin: "inherit",
stdout: "inherit",
stderr: "inherit",
});
const child = command.spawn();
if (workflow.parallel) {
promises.push(child.status);
} else {
// Wait for completion if sequential
const status = await child.status;
if (!status.success) {
error(`Task ${taskId} failed with code ${status.code}`);
}
}
}
if (workflow.parallel && promises.length > 0) {
success("All Claude instances spawned in parallel mode");
const results = await Promise.all(promises);
const failed = results.filter(s => !s.success).length;
if (failed > 0) {
warning(`${failed} tasks failed`);
} else {
success("All tasks completed successfully");
}
}
} catch (err) {
error(`Failed to process workflow: ${(err as Error).message}`);
}
break;
}
default: {
console.log("Available subcommands: spawn, batch");
console.log("\nExamples:");
console.log(" claude-flow claude spawn \"implement user authentication\" --research --parallel");
console.log(" claude-flow claude spawn \"fix bug in payment system\" --no-permissions");
console.log(" claude-flow claude batch workflow.json --dry-run");
break;
}
}
},
});
// Monitor command
cli.command({
name: "monitor",
description: "Live monitoring dashboard",
options: [
{
name: "interval",
short: "i",
description: "Update interval in seconds",
type: "number",
default: 2,
},
{
name: "compact",
short: "c",
description: "Compact view mode",
type: "boolean",
},
{
name: "focus",
short: "f",
description: "Focus on specific component",
type: "string",
},
],
action: async (ctx: CommandContext) => {
try {
const persist = await getPersistence();
const stats = await persist.getStats();
// Check if orchestrator is running
const isRunning = await Deno.stat("orchestrator.log").then(() => true).catch(() => false);
if (!isRunning) {
warning("Orchestrator is not running. Start it first with 'claude-flow start'");
return;
}
info("Starting live monitoring dashboard...");
console.log("Press Ctrl+C to exit");
// Simple monitoring loop
const interval = (ctx.flags.interval as number || ctx.flags.i as number || 2) * 1000;
const isCompact = ctx.flags.compact as boolean || ctx.flags.c as boolean || false;
let running = true;
const cleanup = () => {
running = false;
console.log("\nMonitor stopped");
Deno.exit(0);
};
Deno.addSignalListener("SIGINT", cleanup);
Deno.addSignalListener("SIGTERM", cleanup);
// Hide cursor
Deno.stdout.writeSync(new TextEncoder().encode('\x1b[?25l'));
while (running) {
try {
// Clear screen
console.clear();
// Get latest stats
const currentStats = await persist.getStats();
const agents = await persist.getActiveAgents();
const tasks = await persist.getActiveTasks();
// Header
success("Claude-Flow Live Monitor");
console.log("═".repeat(50));
// System overview
console.log("\n📊 System Overview:");
console.log(` 🟢 Status: ${isRunning ? 'Running' : 'Stopped'}`);
console.log(` 🤖 Agents: ${currentStats.activeAgents} active (${currentStats.totalAgents} total)`);
console.log(` 📋 Tasks: ${currentStats.pendingTasks} pending (${currentStats.totalTasks} total)`);
console.log(` ✅ Completed: ${currentStats.completedTasks} tasks`);
// Active agents
if (agents.length > 0 && !isCompact) {
console.log("\n🤖 Active Agents:");
for (const agent of agents.slice(0, 5)) {
console.log(` • ${agent.id.substring(0, 20)}... (${agent.type}) - ${agent.status}`);
}
if (agents.length > 5) {
console.log(` ... and ${agents.length - 5} more`);
}
}
// Active tasks
if (tasks.length > 0 && !isCompact) {
console.log("\n📋 Active Tasks:");
for (const task of tasks.slice(0, 5)) {
const assignedTo = task.assignedAgent ? `→ ${task.assignedAgent.substring(0, 15)}...` : '(unassigned)';
console.log(` • ${task.id.substring(0, 20)}... (${task.type}) - ${task.status} ${assignedTo}`);
}
if (tasks.length > 5) {
console.log(` ... and ${tasks.length - 5} more`);
}
}
// Footer
console.log("\n" + "─".repeat(50));
console.log(`Last updated: ${new Date().toLocaleTimeString()} • Interval: ${interval/1000}s`);
await new Promise(resolve => setTimeout(resolve, interval));
} catch (err) {
error(`Monitor error: ${(err as Error).message}`);
await new Promise(resolve => setTimeout(resolve, interval));
}
}
// Show cursor
Deno.stdout.writeSync(new TextEncoder().encode('\x1b[?25h'));
} catch (err) {
error(`Failed to start monitor: ${(err as Error).message}`);
}
},
});
// Help command
cli.command({
name: "help",
description: "Show help information",
action: () => {
// The CLI will show help automatically
action: (ctx: CommandContext) => {
const command = ctx.args[0];
if (command === "claude") {
console.log(bold(blue("Claude Instance Management")));
console.log();
console.log("Spawn and manage Claude Code instances with specific configurations.");
console.log();
console.log(bold("Subcommands:"));
console.log(" spawn <task> Spawn Claude with specific configuration");
console.log(" batch <file> Execute multiple Claude instances from workflow");
console.log();
console.log(bold("Spawn Options:"));
console.log(" -t, --tools <tools> Allowed tools (comma-separated)");
console.log(" --no-permissions Use --dangerously-skip-permissions flag");
console.log(" -c, --config <file> MCP config file path");
console.log(" -m, --mode <mode> Development mode (full/backend-only/frontend-only/api-only)");
console.log(" --parallel Enable parallel execution with BatchTool");
console.log(" --research Enable web research with WebFetchTool");
console.log(" --coverage <n> Test coverage target percentage (default: 80)");
console.log(" --commit <freq> Commit frequency (phase/feature/manual)");
console.log(" -v, --verbose Enable verbose output");
console.log(" -d, --dry-run Show what would be executed without running");
console.log();
console.log(bold("Examples:"));
console.log(` ${blue("claude-flow claude spawn")} "implement user authentication" --research --parallel`);
console.log(` ${blue("claude-flow claude spawn")} "fix payment bug" --tools "View,Edit,Bash" --no-permissions`);
console.log(` ${blue("claude-flow claude batch")} workflow.json --dry-run`);
console.log();
console.log("For more information, see: https://github.com/ruvnet/claude-code-flow/docs/11-claude-spawning.md");
} else {
// Show general help
cli.showHelp();
}
},
});
}