mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-25 06:36:49 +09:00
🔧 Fix embedded statusline fallback to match production version
The embedded createStatuslineScript() function was outdated (137 lines) compared to the working statusline template (175 lines). This caused remote installations to get an older version when the template file wasn't found. Fixed by regenerating the embedded function from the working ~/.claude/statusline-command.sh script. 🧠 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
d5135d01bb
commit
a9e2fae475
12 files changed
+439
-3999
No files matched your search
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Claude-Flow Smart Dispatcher - Detects and uses the best available runtime
|
||||
|
||||
VERSION="2.5.0-alpha.135"
|
||||
VERSION="2.5.0-alpha.136"
|
||||
|
||||
# Determine the correct path based on how the script is invoked
|
||||
if [ -L "$0" ]; then
|
||||
|
||||
@@ -85,9 +85,4 @@ export class HelpFormatter {
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=help-formatter.js.map/\s+/g, ' ');
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=help-formatter.js.map
|
||||
+166
-61
@@ -1,13 +1,47 @@
|
||||
#!/usr/bin/env -S deno run --allow-all
|
||||
import { promises as fs } from 'node:fs';
|
||||
#!/usr/bin/env node
|
||||
import { executeCommand, hasCommand, showCommandHelp, listCommands } from './command-registry.js';
|
||||
import { parseFlags } from './utils.js';
|
||||
import { args, cwd, isMainModule, exit, readTextFile, writeTextFile, mkdirAsync, errors } from './node-compat.js';
|
||||
import { spawn } from 'child_process';
|
||||
import process from 'process';
|
||||
import readline from 'readline';
|
||||
import { getMainHelp, getCommandHelp, getStandardizedCommandHelp } from './help-text.js';
|
||||
import { VERSION } from '../core/version.js';
|
||||
function printHelp() {
|
||||
const LEGACY_AGENT_MAPPING = {
|
||||
analyst: 'code-analyzer',
|
||||
coordinator: 'task-orchestrator',
|
||||
optimizer: 'perf-analyzer',
|
||||
documenter: 'api-docs',
|
||||
monitor: 'performance-benchmarker',
|
||||
specialist: 'system-architect',
|
||||
architect: 'system-architect'
|
||||
};
|
||||
function resolveLegacyAgentType(legacyType) {
|
||||
return LEGACY_AGENT_MAPPING[legacyType] || legacyType;
|
||||
}
|
||||
function printHelp(plain = false) {
|
||||
console.log(getMainHelp(plain));
|
||||
}
|
||||
function printCommandHelp(command) {
|
||||
const standardCommands = [
|
||||
'agent',
|
||||
'sparc',
|
||||
'memory'
|
||||
];
|
||||
if (standardCommands.includes(command)) {
|
||||
const help = getStandardizedCommandHelp(command);
|
||||
console.log(help);
|
||||
} else {
|
||||
const help = getCommandHelp(command);
|
||||
console.log(help);
|
||||
}
|
||||
}
|
||||
function printLegacyHelp() {
|
||||
console.log(`
|
||||
🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform
|
||||
|
||||
🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 27 MCP tools, neural networking, and production-ready infrastructure
|
||||
🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 90+ MCP tools, neural networking, and production-ready infrastructure
|
||||
⚡ ALPHA 85: Advanced automation capabilities & stream-JSON chaining for multi-agent pipelines
|
||||
|
||||
USAGE:
|
||||
claude-flow <command> [options]
|
||||
@@ -141,8 +175,8 @@ function printSuccess(message) {
|
||||
function printWarning(message) {
|
||||
console.warn(`⚠️ Warning: ${message}`);
|
||||
}
|
||||
function showHelpWithCommands() {
|
||||
printHelp();
|
||||
function showHelpWithCommands(plain = false) {
|
||||
printHelp(plain);
|
||||
console.log('\nRegistered Commands:');
|
||||
const commands = listCommands();
|
||||
for (const command of commands){
|
||||
@@ -151,14 +185,58 @@ function showHelpWithCommands() {
|
||||
console.log('\nUse "claude-flow help <command>" for detailed usage information');
|
||||
}
|
||||
async function main() {
|
||||
const args = Deno.args;
|
||||
if (args.length === 0) {
|
||||
printHelp();
|
||||
printHelp(usePlainHelp);
|
||||
return;
|
||||
}
|
||||
const command = args[0];
|
||||
const { flags, args: parsedArgs } = parseFlags(args.slice(1));
|
||||
const usePlainHelp = args.includes('--plain');
|
||||
let enhancedFlags = flags;
|
||||
try {
|
||||
const { detectExecutionEnvironment, applySmartDefaults } = await import('./utils/environment-detector.js');
|
||||
enhancedFlags = applySmartDefaults(flags);
|
||||
enhancedFlags._environment = detectExecutionEnvironment({
|
||||
skipWarnings: true
|
||||
});
|
||||
} catch (e) {
|
||||
enhancedFlags = flags;
|
||||
}
|
||||
if (command !== 'help' && command !== '--help' && command !== '-h' && (enhancedFlags.help || enhancedFlags.h)) {
|
||||
const detailedHelp = getCommandHelp(command);
|
||||
if (detailedHelp && !detailedHelp.includes('Help not available')) {
|
||||
printCommandHelp(command);
|
||||
} else if (hasCommand(command)) {
|
||||
showCommandHelp(command);
|
||||
} else {
|
||||
printError(`Unknown command: ${command}`);
|
||||
console.log('\nRun "claude-flow --help" to see available commands.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
switch(command){
|
||||
case 'env-check':
|
||||
case 'environment':
|
||||
if (enhancedFlags._environment) {
|
||||
const env = enhancedFlags._environment;
|
||||
console.log(`\n🖥️ Environment Detection Results:`);
|
||||
console.log(` Terminal: ${env.terminalType}`);
|
||||
console.log(` Interactive: ${env.isInteractive ? 'Yes' : 'No'}`);
|
||||
console.log(` TTY Support: ${env.supportsRawMode ? 'Yes' : 'No'}`);
|
||||
console.log(` Detected: ${env.isVSCode ? 'VS Code' : env.isCI ? 'CI/CD' : env.isDocker ? 'Docker' : env.isSSH ? 'SSH' : 'Standard Terminal'}`);
|
||||
if (env.recommendedFlags.length > 0) {
|
||||
console.log(`\n💡 Recommended flags:`);
|
||||
console.log(` ${env.recommendedFlags.join(' ')}`);
|
||||
}
|
||||
if (enhancedFlags.appliedDefaults && enhancedFlags.appliedDefaults.length > 0) {
|
||||
console.log(`\n✅ Auto-applied:`);
|
||||
console.log(` ${enhancedFlags.appliedDefaults.join(' ')}`);
|
||||
}
|
||||
console.log();
|
||||
} else {
|
||||
console.log('Environment detection not available');
|
||||
}
|
||||
return;
|
||||
case 'version':
|
||||
case '--version':
|
||||
case '-v':
|
||||
@@ -168,9 +246,14 @@ async function main() {
|
||||
case '--help':
|
||||
case '-h':
|
||||
if (parsedArgs.length > 0) {
|
||||
showCommandHelp(parsedArgs[0]);
|
||||
const detailedHelp = getCommandHelp(parsedArgs[0]);
|
||||
if (detailedHelp && !detailedHelp.includes('Help not available')) {
|
||||
printCommandHelp(parsedArgs[0]);
|
||||
} else {
|
||||
showCommandHelp(parsedArgs[0]);
|
||||
}
|
||||
} else {
|
||||
showHelpWithCommands();
|
||||
printHelp(usePlainHelp);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -180,6 +263,7 @@ async function main() {
|
||||
return;
|
||||
} catch (err) {
|
||||
printError(err.message);
|
||||
console.log(`\nRun "claude-flow ${command} --help" for usage information.`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -199,11 +283,12 @@ async function main() {
|
||||
console.log('📊 Real-time monitoring would display here');
|
||||
break;
|
||||
case 'spawn':
|
||||
const spawnType = subArgs[0] || 'general';
|
||||
const rawSpawnType = subArgs[0] || 'general';
|
||||
const spawnType = resolveLegacyAgentType(rawSpawnType);
|
||||
const spawnName = flags.name || `agent-${Date.now()}`;
|
||||
printSuccess(`Spawning ${spawnType} agent: ${spawnName}`);
|
||||
console.log('🤖 Agent would be created with the following configuration:');
|
||||
console.log(` Type: ${spawnType}`);
|
||||
console.log(` Type: ${spawnType}${rawSpawnType !== spawnType ? ` (resolved from: ${rawSpawnType})` : ''}`);
|
||||
console.log(` Name: ${spawnName}`);
|
||||
console.log(' Capabilities: Research, Analysis, Code Generation');
|
||||
console.log(' Status: Ready');
|
||||
@@ -228,7 +313,7 @@ async function main() {
|
||||
console.log(' • Max Pool Size: 10');
|
||||
console.log(' • Idle Timeout: 5 minutes');
|
||||
console.log(' • Shell: /bin/bash');
|
||||
console.log(' • Working Directory: ' + process.cwd());
|
||||
console.log(' • Working Directory: ' + cwd());
|
||||
console.log(' Performance:');
|
||||
console.log(' • Average Response Time: N/A');
|
||||
console.log(' • Terminal Creation Time: N/A');
|
||||
@@ -277,7 +362,7 @@ async function main() {
|
||||
const terminalConfig = {
|
||||
name: nameIndex >= 0 ? subArgs[nameIndex + 1] : 'terminal-' + Date.now(),
|
||||
shell: shellIndex >= 0 ? subArgs[shellIndex + 1] : 'bash',
|
||||
workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : process.cwd(),
|
||||
workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : cwd(),
|
||||
env: envIndex >= 0 ? subArgs[envIndex + 1] : '',
|
||||
persistent: persistentIndex >= 0
|
||||
};
|
||||
@@ -1234,10 +1319,9 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all
|
||||
console.log('Debug - Executing command:');
|
||||
console.log(`claude ${claudeArgs.map((arg)=>arg.includes(' ') || arg.includes('\n') ? `"${arg}"` : arg).join(' ')}`);
|
||||
}
|
||||
const command = new Deno.Command('claude', {
|
||||
args: claudeArgs,
|
||||
const child = spawn('claude', claudeArgs, {
|
||||
env: {
|
||||
...Deno.env.toObject(),
|
||||
...process.env,
|
||||
CLAUDE_INSTANCE_ID: instanceId,
|
||||
CLAUDE_FLOW_MODE: flags1.mode || 'full',
|
||||
CLAUDE_FLOW_COVERAGE: (flags1.coverage || 80).toString(),
|
||||
@@ -1247,17 +1331,18 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all
|
||||
CLAUDE_FLOW_COORDINATION_ENABLED: flags1.parallel ? 'true' : 'false',
|
||||
CLAUDE_FLOW_FEATURES: 'memory,coordination,swarm'
|
||||
},
|
||||
stdin: 'inherit',
|
||||
stdout: 'inherit',
|
||||
stderr: 'inherit'
|
||||
stdio: 'inherit'
|
||||
});
|
||||
await new Promise((resolve)=>{
|
||||
child.on('exit', (code)=>{
|
||||
if (code === 0) {
|
||||
printSuccess(`Claude instance ${instanceId} completed successfully`);
|
||||
} else {
|
||||
printError(`Claude instance ${instanceId} exited with code ${code}`);
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
const child = command.spawn();
|
||||
const status = await child.status;
|
||||
if (status.success) {
|
||||
printSuccess(`Claude instance ${instanceId} completed successfully`);
|
||||
} else {
|
||||
printError(`Claude instance ${instanceId} exited with code ${status.code}`);
|
||||
}
|
||||
} catch (err) {
|
||||
printError(`Failed to spawn Claude: ${err.message}`);
|
||||
console.log('Make sure you have the Claude CLI installed.');
|
||||
@@ -1810,7 +1895,7 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all
|
||||
console.log('\nDid you mean:');
|
||||
suggestions.forEach((cmd)=>console.log(` claude-flow ${cmd}`));
|
||||
}
|
||||
process.exit(1);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
async function startRepl() {
|
||||
@@ -1888,7 +1973,7 @@ Shortcuts:
|
||||
},
|
||||
config: async (key)=>{
|
||||
try {
|
||||
const config = JSON.parse(await fs.readFile('claude-flow.config.json', 'utf-8'));
|
||||
const config = JSON.parse(await readTextFile('claude-flow.config.json'));
|
||||
if (key) {
|
||||
const keys = key.split('.');
|
||||
let value = config;
|
||||
@@ -1916,21 +2001,25 @@ Shortcuts:
|
||||
if (trimmed.startsWith('!')) {
|
||||
const shellCmd = trimmed.substring(1);
|
||||
try {
|
||||
const command = new Deno.Command('sh', {
|
||||
args: [
|
||||
await new Promise((resolve)=>{
|
||||
const proc = spawn('sh', [
|
||||
'-c',
|
||||
shellCmd
|
||||
],
|
||||
stdout: 'piped',
|
||||
stderr: 'piped'
|
||||
], {
|
||||
stdio: [
|
||||
'inherit',
|
||||
'pipe',
|
||||
'pipe'
|
||||
]
|
||||
});
|
||||
proc.stdout.on('data', (data)=>{
|
||||
console.log(data.toString());
|
||||
});
|
||||
proc.stderr.on('data', (data)=>{
|
||||
console.error(data.toString());
|
||||
});
|
||||
proc.on('exit', resolve);
|
||||
});
|
||||
const { stdout, stderr } = await command.output();
|
||||
if (stdout.length > 0) {
|
||||
console.log(new TextDecoder().decode(stdout));
|
||||
}
|
||||
if (stderr.length > 0) {
|
||||
console.error(new TextDecoder().decode(stderr));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Shell error: ${err.message}`);
|
||||
}
|
||||
@@ -1950,7 +2039,7 @@ Shortcuts:
|
||||
const parts = trimmed.split(' ');
|
||||
const command = parts[0];
|
||||
const args = parts.slice(1);
|
||||
if (command in replCommands) {
|
||||
if (replCommands[command]) {
|
||||
await replCommands[command](...args);
|
||||
return true;
|
||||
}
|
||||
@@ -1971,7 +2060,8 @@ Shortcuts:
|
||||
const subCmd = args[0];
|
||||
switch(subCmd){
|
||||
case 'spawn':
|
||||
const type = args[1] || 'researcher';
|
||||
const rawType = args[1] || 'researcher';
|
||||
const type = resolveLegacyAgentType(rawType);
|
||||
const name = args[2] || `agent-${Date.now()}`;
|
||||
const agent = {
|
||||
id: `agent-${Date.now()}`,
|
||||
@@ -2176,18 +2266,33 @@ Shortcuts:
|
||||
console.log('Terminal commands: create, list, exec, attach, detach');
|
||||
}
|
||||
}
|
||||
const decoder = new TextDecoder();
|
||||
const encoder = new TextEncoder();
|
||||
while(true){
|
||||
const prompt = replState.currentSession ? `claude-flow:${replState.currentSession}> ` : 'claude-flow> ';
|
||||
await Deno.stdout.write(encoder.encode(prompt));
|
||||
const buf = new Uint8Array(1024);
|
||||
const n = await Deno.stdin.read(buf);
|
||||
if (n === null) break;
|
||||
const input = decoder.decode(buf.subarray(0, n)).trim();
|
||||
const shouldContinue = await processReplCommand(input);
|
||||
if (!shouldContinue) break;
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
});
|
||||
function updatePrompt() {
|
||||
rl.setPrompt(replState.currentSession ? `claude-flow:${replState.currentSession}> ` : 'claude-flow> ');
|
||||
}
|
||||
updatePrompt();
|
||||
rl.prompt();
|
||||
rl.on('line', async (input)=>{
|
||||
input = input.trim();
|
||||
const shouldContinue = await processReplCommand(input);
|
||||
if (!shouldContinue) {
|
||||
rl.close();
|
||||
} else {
|
||||
updatePrompt();
|
||||
rl.prompt();
|
||||
}
|
||||
});
|
||||
rl.on('SIGINT', ()=>{
|
||||
console.log('\nExiting Claude-Flow...');
|
||||
rl.close();
|
||||
process.exit(0);
|
||||
});
|
||||
return new Promise((resolve)=>{
|
||||
rl.on('close', resolve);
|
||||
});
|
||||
}
|
||||
function createMinimalClaudeMd() {
|
||||
return `# Claude Code Integration
|
||||
@@ -2504,30 +2609,30 @@ async function createSparcStructureManually() {
|
||||
];
|
||||
for (const dir of rooDirectories){
|
||||
try {
|
||||
await Deno.mkdir(dir, {
|
||||
await mkdirAsync(dir, {
|
||||
recursive: true
|
||||
});
|
||||
console.log(` ✓ Created ${dir}/`);
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
||||
if (!(err instanceof errors.AlreadyExists)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
let roomodesContent;
|
||||
try {
|
||||
roomodesContent = await fs.readFile('.roomodes');
|
||||
roomodesContent = await readTextFile('.roomodes');
|
||||
console.log(' ✓ Using existing .roomodes configuration');
|
||||
} catch {
|
||||
roomodesContent = createBasicRoomodesConfig();
|
||||
await fs.writeFile('.roomodes', roomodesContent);
|
||||
await writeTextFile('.roomodes', roomodesContent);
|
||||
console.log(' ✓ Created .roomodes configuration');
|
||||
}
|
||||
const basicWorkflow = createBasicSparcWorkflow();
|
||||
await fs.writeFile('.roo/workflows/basic-tdd.json', basicWorkflow);
|
||||
await writeTextFile('.roo/workflows/basic-tdd.json', basicWorkflow);
|
||||
console.log(' ✓ Created .roo/workflows/basic-tdd.json');
|
||||
const rooReadme = createRooReadme();
|
||||
await fs.writeFile('.roo/README.md', rooReadme);
|
||||
await writeTextFile('.roo/README.md', rooReadme);
|
||||
console.log(' ✓ Created .roo/README.md');
|
||||
console.log(' ✅ Basic SPARC structure created successfully');
|
||||
} catch (err) {
|
||||
@@ -2958,7 +3063,7 @@ This SPARC-enabled project follows a systematic development approach:
|
||||
For more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md
|
||||
`;
|
||||
}
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
if (isMainModule(import.meta.url)) {
|
||||
await main();
|
||||
}
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/cli/simple-cli.ts"],"sourcesContent":["#!/usr/bin/env -S deno run --allow-all\n/**\n * Simple CLI wrapper for Claude-Flow (JavaScript version)\n * This version avoids TypeScript issues in node_modules\n */\n\nimport { promises as fs } from 'node:fs';\nimport {\n executeCommand,\n hasCommand,\n showCommandHelp,\n showAllCommands,\n listCommands,\n} from './command-registry.js';\nimport { parseFlags } from './utils.js';\nimport { VERSION } from '../core/version.js';\n\nfunction printHelp() {\n console.log(`\n🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform\n\n🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 27 MCP tools, neural networking, and production-ready infrastructure\n\nUSAGE:\n claude-flow <command> [options]\n\n🚀 INSTALLATION & ENTERPRISE SETUP:\n npx claude-flow@2.0.0 init --sparc # Enterprise SPARC + ruv-swarm integration\n \n The --sparc flag creates:\n • Complete ruv-swarm integration with 27 MCP tools\n • Neural network processing with WASM optimization\n • Multi-agent coordination (hierarchical, mesh, ring, star topologies)\n • Cross-session memory and persistent learning\n • GitHub workflow automation (6 specialized modes)\n • Production-ready Docker infrastructure\n • Enterprise security and compliance features\n\n🧠 SWARM INTELLIGENCE COMMANDS (v2.0.0):\n swarm \"objective\" [--strategy] [--mode] [--max-agents N] [--parallel] [--monitor]\n --strategy: research, development, analysis, testing, optimization, maintenance\n --mode: centralized, distributed, hierarchical, mesh, hybrid\n --parallel: Enable parallel execution (2.8-4.4x speed improvement)\n --monitor: Real-time swarm monitoring and performance tracking\n\n🐙 GITHUB WORKFLOW AUTOMATION (v2.0.0):\n github gh-coordinator # GitHub workflow orchestration and coordination\n github pr-manager # Pull request management with multi-reviewer coordination\n github issue-tracker # Issue management and project coordination\n github release-manager # Release coordination and deployment pipelines\n github repo-architect # Repository structure optimization\n github sync-coordinator # Multi-package synchronization and version alignment\n\n🏗️ CORE ENTERPRISE COMMANDS:\n init [--sparc] # Initialize with enterprise environment + ruv-swarm\n start [--ui] [--swarm] # Start orchestration with swarm intelligence\n spawn <type> [--name] # Create AI agent with swarm coordination\n agent <subcommand> # Advanced agent management with neural patterns\n sparc <subcommand> # 17 SPARC modes with neural enhancement\n memory <subcommand> # Cross-session persistent memory with neural learning\n status # Comprehensive system status with performance metrics\n\n🤖 NEURAL AGENT TYPES (ruv-swarm Integration):\n researcher # Research with web access and data analysis\n coder # Code development with neural patterns\n analyst # Performance analysis and optimization\n architect # System design with enterprise patterns\n tester # Comprehensive testing with automation\n coordinator # Multi-agent orchestration and workflow management\n reviewer # Code review with security and quality checks\n optimizer # Performance optimization and bottleneck analysis\n\n🎮 ENTERPRISE QUICK START:\n # Initialize enterprise environment\n npx claude-flow@2.0.0 init --sparc\n \n # Start enterprise orchestration with swarm intelligence\n ./claude-flow start --ui --swarm\n \n # Deploy intelligent multi-agent development workflow\n ./claude-flow swarm \"build enterprise API\" --strategy development --parallel --monitor\n \n # GitHub workflow automation\n ./claude-flow github pr-manager \"coordinate release with automated testing\"\n \n # Neural memory management\n ./claude-flow memory store \"architecture\" \"microservices with API gateway pattern\"\n \n # Real-time system monitoring\n ./claude-flow status --verbose\n\n🏢 ENTERPRISE COMMAND CATEGORIES:\n Core Intelligence: swarm, agent, sparc, memory, neural\n GitHub Automation: github (6 specialized modes)\n Development: init, start, status, config, workflow\n Infrastructure: mcp, terminal, session, docker\n Enterprise: project, deploy, cloud, security, analytics, audit\n\n🧠 NEURAL NETWORK FEATURES (v2.0.0):\n • WASM-powered cognitive patterns with SIMD optimization\n • 27 MCP tools for comprehensive workflow automation\n • Cross-session learning and adaptation\n • Real-time performance monitoring (sub-10ms response times)\n • 32.3% token usage reduction through intelligent coordination\n • Self-healing workflows with automatic error recovery\n\n📊 ENTERPRISE PERFORMANCE METRICS:\n • 84.8% SWE-Bench solve rate through coordinated intelligence\n • 2.8-Line truncated
|
||||
{"version":3,"sources":["../../../src/cli/simple-cli.js"],"sourcesContent":["#!/usr/bin/env node\n/**\n * Simple CLI wrapper for Claude-Flow (JavaScript version)\n * This version avoids TypeScript issues in node_modules\n */\n\nimport {\n executeCommand,\n hasCommand,\n showCommandHelp,\n showAllCommands,\n listCommands,\n} from './command-registry.js';\nimport { parseFlags } from './utils.js';\nimport {\n args,\n cwd,\n isMainModule,\n exit,\n readTextFile,\n writeTextFile,\n mkdirAsync,\n errors,\n} from './node-compat.js';\nimport { spawn } from 'child_process';\nimport process from 'process';\nimport readline from 'readline';\nimport { getMainHelp, getCommandHelp, getStandardizedCommandHelp } from './help-text.js';\nimport { VERSION } from '../core/version.js';\n\n// Legacy agent type mapping for backward compatibility\nconst LEGACY_AGENT_MAPPING = {\n analyst: 'code-analyzer',\n coordinator: 'task-orchestrator', \n optimizer: 'perf-analyzer',\n documenter: 'api-docs',\n monitor: 'performance-benchmarker',\n specialist: 'system-architect',\n architect: 'system-architect',\n};\n\n// Resolve legacy agent types to current equivalents\nfunction resolveLegacyAgentType(legacyType) {\n return LEGACY_AGENT_MAPPING[legacyType] || legacyType;\n}\n\nfunction printHelp(plain = false) {\n console.log(getMainHelp(plain));\n}\n\nfunction printCommandHelp(command) {\n // Try standardized help first\n const standardCommands = ['agent', 'sparc', 'memory'];\n if (standardCommands.includes(command)) {\n const help = getStandardizedCommandHelp(command);\n console.log(help);\n } else {\n const help = getCommandHelp(command);\n console.log(help);\n }\n}\n\n// Legacy help function for backward compatibility\nfunction printLegacyHelp() {\n console.log(`\n🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform\n\n🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 90+ MCP tools, neural networking, and production-ready infrastructure\n⚡ ALPHA 85: Advanced automation capabilities & stream-JSON chaining for multi-agent pipelines\n\nUSAGE:\n claude-flow <command> [options]\n\n🚀 INSTALLATION & ENTERPRISE SETUP:\n npx claude-flow@2.0.0 init --sparc # Enterprise SPARC + ruv-swarm integration\n \n The --sparc flag creates:\n • Complete ruv-swarm integration with 27 MCP tools\n • Neural network processing with WASM optimization\n • Multi-agent coordination (hierarchical, mesh, ring, star topologies)\n • Cross-session memory and persistent learning\n • GitHub workflow automation (6 specialized modes)\n • Production-ready Docker infrastructure\n • Enterprise security and compliance features\n\n🧠 SWARM INTELLIGENCE COMMANDS (v2.0.0):\n swarm \"objective\" [--strategy] [--mode] [--max-agents N] [--parallel] [--monitor]\n --strategy: research, development, analysis, testing, optimization, maintenance\n --mode: centralized, distributed, hierarchical, mesh, hybrid\n --parallel: Enable parallel execution (2.8-4.4x speed improvement)\n --monitor: Real-time swarm monitoring and performance tracking\n\n🐙 GITHUB WORKFLOW AUTOMATION (v2.0.0):\n github gh-coordinator # GitHub workflow orchestration and coordination\n github pr-manager # Pull request management with multi-reviewer coordination\n github issue-tracker # Issue management and project coordination\n github release-manager # Release coordination and deployment pipelines\n github repo-architect # Repository structure optimization\n github sync-coordinator # Multi-package synchronization and version alignment\n\n🏗️ CORE ENTERPRISE COMMANDS:\n init [--sparc] # Initialize with enterprise environment + ruv-swarm\n start [--ui] [--swarm] # Start orchestration with swarm intelligence\n spawn <type> [--name] # Create AI agent with swarm coordination\n agent <subcommand> # Advanced agent management with neural patterns\n sparc <subcommand> # 17 SPARC modes with neural enhancement\n memory <subcommand> # Cross-session persistent memory with neural learning\n status # Comprehensive system status with performance metrics\n\n🤖 NEURAL AGENT TYPES (ruv-swarm Integration):\n researcher # Research with web access and data analysis\n coder # Code development with neural patterns\n analyst # Performance analysis and optimization\n architect # System design with enterprise patterns\n tester # Comprehensive testing with automation\n coordinator # Multi-agent orchestration and workflow management\n reviewer # Code review with security and quality checks\n optimizer # Performance optimization and bottleneck analysis\n\n🎮 ENTERPRISE QUICK START:\n # Initialize enterprise environment\n npx claude-flow@2.0.0 init --sparc\n \n # Start enterprise orchestration with swarm intelligence\n ./claude-flow start Line truncated
|
||||
@@ -121,15 +121,13 @@ async function setupMcpServers(dryRun1 = false) {
|
||||
}
|
||||
}
|
||||
function createStatuslineScript() {
|
||||
return `#!/bin/bash
|
||||
|
||||
# Claude Code Status Line with Claude-Flow Integration
|
||||
# Displays model, directory, git branch, and real-time swarm metrics
|
||||
return `
|
||||
#!/bin/bash
|
||||
|
||||
# Read JSON input from stdin
|
||||
INPUT=$(cat)
|
||||
MODEL=$(echo "$INPUT" | jq -r '.model.display_name // "Claude"')
|
||||
CWD=$(echo "$INPUT" | jq -r '.workspace.current_dir // .cwd')
|
||||
MODEL=$(echo "$INPUT" | jq -r \'.model.display_name // "Claude"\')
|
||||
CWD=$(echo "$INPUT" | jq -r \'.workspace.current_dir // .cwd\')
|
||||
DIR=$(basename "$CWD")
|
||||
|
||||
# Replace claude-code-flow with branded name
|
||||
@@ -150,10 +148,11 @@ FLOW_DIR="$CWD/.claude-flow"
|
||||
if [ -d "$FLOW_DIR" ]; then
|
||||
echo -ne " │"
|
||||
|
||||
# Swarm Configuration & Topology
|
||||
# 1. Swarm Configuration & Topology
|
||||
if [ -f "$FLOW_DIR/swarm-config.json" ]; then
|
||||
STRATEGY=$(jq -r '.defaultStrategy // empty' "$FLOW_DIR/swarm-config.json" 2>/dev/null)
|
||||
STRATEGY=$(jq -r \'.defaultStrategy // empty\' "$FLOW_DIR/swarm-config.json" 2>/dev/null)
|
||||
if [ -n "$STRATEGY" ]; then
|
||||
# Map strategy to topology icon
|
||||
case "$STRATEGY" in
|
||||
"balanced") TOPO_ICON="⚡mesh" ;;
|
||||
"conservative") TOPO_ICON="⚡hier" ;;
|
||||
@@ -162,96 +161,139 @@ if [ -d "$FLOW_DIR" ]; then
|
||||
esac
|
||||
echo -ne " \\033[35m$TOPO_ICON\\033[0m"
|
||||
|
||||
AGENT_COUNT=$(jq -r '.agentProfiles | length' "$FLOW_DIR/swarm-config.json" 2>/dev/null)
|
||||
# Count agent profiles as "configured agents"
|
||||
AGENT_COUNT=$(jq -r \'.agentProfiles | length\' "$FLOW_DIR/swarm-config.json" 2>/dev/null)
|
||||
if [ -n "$AGENT_COUNT" ] && [ "$AGENT_COUNT" != "null" ] && [ "$AGENT_COUNT" -gt 0 ]; then
|
||||
echo -ne " \\033[35m🤖 $AGENT_COUNT\\033[0m"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Real-time System Metrics
|
||||
# 2. Real-time System Metrics
|
||||
if [ -f "$FLOW_DIR/metrics/system-metrics.json" ]; then
|
||||
LATEST=$(jq -r '.[-1]' "$FLOW_DIR/metrics/system-metrics.json" 2>/dev/null)
|
||||
# Get latest metrics (last entry in array)
|
||||
LATEST=$(jq -r \'.[-1]\' "$FLOW_DIR/metrics/system-metrics.json" 2>/dev/null)
|
||||
|
||||
if [ -n "$LATEST" ] && [ "$LATEST" != "null" ]; then
|
||||
MEM_PERCENT=$(echo "$LATEST" | jq -r '.memoryUsagePercent // 0' | awk '{printf "%.0f", $1}')
|
||||
# Memory usage
|
||||
MEM_PERCENT=$(echo "$LATEST" | jq -r \'.memoryUsagePercent // 0\' | awk \'{printf "%.0f", $1}\')
|
||||
if [ -n "$MEM_PERCENT" ] && [ "$MEM_PERCENT" != "null" ]; then
|
||||
# Color-coded memory (green <60%, yellow 60-80%, red >80%)
|
||||
if [ "$MEM_PERCENT" -lt 60 ]; then
|
||||
MEM_COLOR="\\033[32m"
|
||||
MEM_COLOR="\\033[32m" # Green
|
||||
elif [ "$MEM_PERCENT" -lt 80 ]; then
|
||||
MEM_COLOR="\\033[33m"
|
||||
MEM_COLOR="\\033[33m" # Yellow
|
||||
else
|
||||
MEM_COLOR="\\033[31m"
|
||||
MEM_COLOR="\\033[31m" # Red
|
||||
fi
|
||||
echo -ne " \${MEM_COLOR}💾 \${MEM_PERCENT}%\\033[0m"
|
||||
echo -ne " ${MEM_COLOR}💾 ${MEM_PERCENT}%\\033[0m"
|
||||
fi
|
||||
|
||||
CPU_LOAD=$(echo "$LATEST" | jq -r '.cpuLoad // 0' | awk '{printf "%.0f", $1 * 100}')
|
||||
# CPU load
|
||||
CPU_LOAD=$(echo "$LATEST" | jq -r \'.cpuLoad // 0\' | awk \'{printf "%.0f", $1 * 100}\')
|
||||
if [ -n "$CPU_LOAD" ] && [ "$CPU_LOAD" != "null" ]; then
|
||||
# Color-coded CPU (green <50%, yellow 50-75%, red >75%)
|
||||
if [ "$CPU_LOAD" -lt 50 ]; then
|
||||
CPU_COLOR="\\033[32m"
|
||||
CPU_COLOR="\\033[32m" # Green
|
||||
elif [ "$CPU_LOAD" -lt 75 ]; then
|
||||
CPU_COLOR="\\033[33m"
|
||||
CPU_COLOR="\\033[33m" # Yellow
|
||||
else
|
||||
CPU_COLOR="\\033[31m"
|
||||
CPU_COLOR="\\033[31m" # Red
|
||||
fi
|
||||
echo -ne " \${CPU_COLOR}⚙ \${CPU_LOAD}%\\033[0m"
|
||||
echo -ne " ${CPU_COLOR}⚙ ${CPU_LOAD}%\\033[0m"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Performance Metrics
|
||||
# 3. Session State
|
||||
if [ -f "$FLOW_DIR/session-state.json" ]; then
|
||||
SESSION_ID=$(jq -r \'.sessionId // empty\' "$FLOW_DIR/session-state.json" 2>/dev/null)
|
||||
ACTIVE=$(jq -r \'.active // false\' "$FLOW_DIR/session-state.json" 2>/dev/null)
|
||||
|
||||
if [ "$ACTIVE" = "true" ] && [ -n "$SESSION_ID" ]; then
|
||||
# Show abbreviated session ID
|
||||
SHORT_ID=$(echo "$SESSION_ID" | cut -d\'-\' -f1)
|
||||
echo -ne " \\033[34m🔄 $SHORT_ID\\033[0m"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 4. Performance Metrics from task-metrics.json
|
||||
if [ -f "$FLOW_DIR/metrics/task-metrics.json" ]; then
|
||||
METRICS=$(jq -r '
|
||||
# Parse task metrics for success rate, avg time, and streak
|
||||
METRICS=$(jq -r \'
|
||||
# Calculate metrics
|
||||
(map(select(.success == true)) | length) as $successful |
|
||||
(length) as $total |
|
||||
(if $total > 0 then ($successful / $total * 100) else 0 end) as $success_rate |
|
||||
(map(.duration // 0) | add / length) as $avg_duration |
|
||||
(reverse | reduce .[] as $task (0; if $task.success == true then . + 1 else 0 end)) as $streak |
|
||||
{ success_rate: $success_rate, avg_duration: $avg_duration, streak: $streak, total: $total } | @json
|
||||
' "$FLOW_DIR/metrics/task-metrics.json" 2>/dev/null)
|
||||
# Calculate streak (consecutive successes from end)
|
||||
(reverse |
|
||||
reduce .[] as $task (0;
|
||||
if $task.success == true then . + 1 else 0 end
|
||||
)
|
||||
) as $streak |
|
||||
{
|
||||
success_rate: $success_rate,
|
||||
avg_duration: $avg_duration,
|
||||
streak: $streak,
|
||||
total: $total
|
||||
} | @json
|
||||
\' "$FLOW_DIR/metrics/task-metrics.json" 2>/dev/null)
|
||||
|
||||
if [ -n "$METRICS" ] && [ "$METRICS" != "null" ]; then
|
||||
SUCCESS_RATE=$(echo "$METRICS" | jq -r '.success_rate // 0' | awk '{printf "%.0f", $1}')
|
||||
TOTAL_TASKS=$(echo "$METRICS" | jq -r '.total // 0')
|
||||
# Success Rate
|
||||
SUCCESS_RATE=$(echo "$METRICS" | jq -r \'.success_rate // 0\' | awk \'{printf "%.0f", $1}\')
|
||||
TOTAL_TASKS=$(echo "$METRICS" | jq -r \'.total // 0\')
|
||||
|
||||
if [ -n "$SUCCESS_RATE" ] && [ "$TOTAL_TASKS" -gt 0 ]; then
|
||||
# Color-code: Green (>80%), Yellow (60-80%), Red (<60%)
|
||||
if [ "$SUCCESS_RATE" -gt 80 ]; then
|
||||
SUCCESS_COLOR="\\033[32m"
|
||||
SUCCESS_COLOR="\\033[32m" # Green
|
||||
elif [ "$SUCCESS_RATE" -ge 60 ]; then
|
||||
SUCCESS_COLOR="\\033[33m"
|
||||
SUCCESS_COLOR="\\033[33m" # Yellow
|
||||
else
|
||||
SUCCESS_COLOR="\\033[31m"
|
||||
SUCCESS_COLOR="\\033[31m" # Red
|
||||
fi
|
||||
echo -ne " \${SUCCESS_COLOR}🎯 \${SUCCESS_RATE}%\\033[0m"
|
||||
echo -ne " ${SUCCESS_COLOR}🎯 ${SUCCESS_RATE}%\\033[0m"
|
||||
fi
|
||||
|
||||
AVG_TIME=$(echo "$METRICS" | jq -r '.avg_duration // 0')
|
||||
# Average Time
|
||||
AVG_TIME=$(echo "$METRICS" | jq -r \'.avg_duration // 0\')
|
||||
if [ -n "$AVG_TIME" ] && [ "$TOTAL_TASKS" -gt 0 ]; then
|
||||
# Format smartly: seconds, minutes, or hours
|
||||
if [ $(echo "$AVG_TIME < 60" | bc -l 2>/dev/null || echo 0) -eq 1 ]; then
|
||||
TIME_STR=$(echo "$AVG_TIME" | awk '{printf "%.1fs", $1}')
|
||||
TIME_STR=$(echo "$AVG_TIME" | awk \'{printf "%.1fs", $1}\')
|
||||
elif [ $(echo "$AVG_TIME < 3600" | bc -l 2>/dev/null || echo 0) -eq 1 ]; then
|
||||
TIME_STR=$(echo "$AVG_TIME" | awk '{printf "%.1fm", $1/60}')
|
||||
TIME_STR=$(echo "$AVG_TIME" | awk \'{printf "%.1fm", $1/60}\')
|
||||
else
|
||||
TIME_STR=$(echo "$AVG_TIME" | awk '{printf "%.1fh", $1/3600}')
|
||||
TIME_STR=$(echo "$AVG_TIME" | awk \'{printf "%.1fh", $1/3600}\')
|
||||
fi
|
||||
echo -ne " \\033[36m⏱️ $TIME_STR\\033[0m"
|
||||
fi
|
||||
|
||||
STREAK=$(echo "$METRICS" | jq -r '.streak // 0')
|
||||
# Streak (only show if > 0)
|
||||
STREAK=$(echo "$METRICS" | jq -r \'.streak // 0\')
|
||||
if [ -n "$STREAK" ] && [ "$STREAK" -gt 0 ]; then
|
||||
echo -ne " \\033[91m🔥 $STREAK\\033[0m"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Active Tasks
|
||||
# 5. Active Tasks (check for task files)
|
||||
if [ -d "$FLOW_DIR/tasks" ]; then
|
||||
TASK_COUNT=$(find "$FLOW_DIR/tasks" -name "*.json" -type f 2>/dev/null | wc -l)
|
||||
if [ "$TASK_COUNT" -gt 0 ]; then
|
||||
echo -ne " \\033[36m📋 $TASK_COUNT\\033[0m"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 6. Check for hooks activity
|
||||
if [ -f "$FLOW_DIR/hooks-state.json" ]; then
|
||||
HOOKS_ACTIVE=$(jq -r \'.enabled // false\' "$FLOW_DIR/hooks-state.json" 2>/dev/null)
|
||||
if [ "$HOOKS_ACTIVE" = "true" ]; then
|
||||
echo -ne " \\033[35m🔗\\033[0m"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
echo
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/cli/simple-commands/init/index.js"],"sourcesContent":["// init/index.js - Initialize Claude Code integration files\nimport { printSuccess, printError, printWarning, exit } from '../../utils.js';\nimport { existsSync } from 'fs';\nimport process from 'process';\nimport os from 'os';\nimport { spawn, execSync } from 'child_process';\nimport { promisify } from 'util';\n\n// Helper to replace Deno.Command\nfunction runCommand(command, args, options = {}) {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd: options.cwd,\n env: { ...process.env, ...options.env },\n stdio: options.stdout === 'inherit' ? 'inherit' : 'pipe'\n });\n \n let stdout = '';\n let stderr = '';\n \n if (options.stdout !== 'inherit') {\n child.stdout.on('data', (data) => { stdout += data; });\n child.stderr.on('data', (data) => { stderr += data; });\n }\n \n child.on('close', (code) => {\n if (code === 0) {\n resolve({ success: true, code, stdout, stderr });\n } else {\n reject(new Error(`Command failed with exit code ${code}`));\n }\n });\n \n child.on('error', reject);\n });\n}\nimport { createLocalExecutable } from './executable-wrapper.js';\nimport { createSparcStructureManually } from './sparc-structure.js';\nimport { createClaudeSlashCommands } from './claude-commands/slash-commands.js';\nimport { createOptimizedClaudeSlashCommands } from './claude-commands/optimized-slash-commands.js';\n// execSync imported above as execSyncOriginal\\nconst execSync = execSyncOriginal;\nimport { promises as fs } from 'fs';\nimport { copyTemplates } from './template-copier.js';\nimport { copyRevisedTemplates, validateTemplatesExist } from './copy-revised-templates.js';\nimport { copyAgentFiles, createAgentDirectories, validateAgentSystem, copyCommandFiles } from './agent-copier.js';\nimport { showInitHelp } from './help.js';\nimport { batchInitCommand, batchInitFromConfig, validateBatchOptions } from './batch-init.js';\nimport { ValidationSystem, runFullValidation } from './validation/index.js';\nimport { RollbackSystem, createAtomicOperation } from './rollback/index.js';\nimport {\n createEnhancedClaudeMd,\n createEnhancedSettingsJson,\n createWrapperScript,\n createCommandDoc,\n createHelperScript,\n COMMAND_STRUCTURE,\n} from './templates/enhanced-templates.js';\nimport { createOptimizedSparcClaudeMd } from './templates/claude-md.js';\nimport { getIsolatedNpxEnv } from '../../../utils/npx-isolated-cache.js';\nimport { updateGitignore, needsGitignoreUpdate } from './gitignore-updater.js';\nimport {\n createFullClaudeMd,\n createSparcClaudeMd,\n createMinimalClaudeMd,\n} from './templates/claude-md.js';\nimport {\n createVerificationClaudeMd,\n createVerificationSettingsJson,\n} from './templates/verification-claude-md.js';\nimport {\n createFullMemoryBankMd,\n createMinimalMemoryBankMd,\n} from './templates/memory-bank-md.js';\nimport {\n createFullCoordinationMd,\n createMinimalCoordinationMd,\n} from './templates/coordination-md.js';\nimport { createAgentsReadme, createSessionsReadme } from './templates/readme-files.js';\nimport { \n initializeHiveMind, \n getHiveMindStatus,\n rollbackHiveMindInit\n} from './hive-mind-init.js';\n\n/**\n * Check if Claude Code CLI is installed\n */\nfunction isClaudeCodeInstalled() {\n try {\n execSync('which claude', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Set up MCP servers in Claude Code\n */\nasync function setupMcpServers(dryRun = false) {\n console.log('\\n🔌 Setting up MCP servers for Claude Code...');\n\n const servers = [\n {\n name: 'claude-flow',\n command: 'npx claude-flow@alpha mcp start',\n description: 'Claude Flow MCP server with swarm orchestration (alpha)',\n },\n {\n name: 'ruv-swarm',\n command: 'npx ruv-swarm mcp start',\n description: 'ruv-swarm MCP server for enhanced coordination',\n },\n {\n name: 'flow-nexus',\n command: 'npx flow-nexus@latest mcp start',\n description: 'Flow Nexus Complete MCP server for advanced AI orchestration',\n },\n {\n name: 'agentic-payments',\n command: 'npx agentic-payments@latest mcp',\n description: 'Agentic Payments MCP server for autonomous agent payment authorization',\n },\n ];\n\n for (const server of servers) {\n try {\n if (!dryRun) {\n console.log(` 🔄 Adding ${server.name}...`);\n execSync(`claude mcp add ${server.name} ${server.command}`, { stdio: 'inherit' });\n console.log(` ✅ Added ${server.name} - ${server.description}`);\n } else {\n console.log(` [DRY RUN] Would add ${server.name} - ${server.description}`);\n }\n } catch (err) {\n console.log(` ⚠️ Failed to add ${server.name}: ${err.message}`);\n console.log(\n ` You can add it Line truncated
|
||||
{"version":3,"sources":["../../../../../src/cli/simple-commands/init/index.js"],"sourcesContent":["// init/index.js - Initialize Claude Code integration files\nimport { printSuccess, printError, printWarning, exit } from '../../utils.js';\nimport { existsSync } from 'fs';\nimport process from 'process';\nimport os from 'os';\nimport { spawn, execSync } from 'child_process';\nimport { promisify } from 'util';\n\n// Helper to replace Deno.Command\nfunction runCommand(command, args, options = {}) {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd: options.cwd,\n env: { ...process.env, ...options.env },\n stdio: options.stdout === 'inherit' ? 'inherit' : 'pipe'\n });\n \n let stdout = '';\n let stderr = '';\n \n if (options.stdout !== 'inherit') {\n child.stdout.on('data', (data) => { stdout += data; });\n child.stderr.on('data', (data) => { stderr += data; });\n }\n \n child.on('close', (code) => {\n if (code === 0) {\n resolve({ success: true, code, stdout, stderr });\n } else {\n reject(new Error(`Command failed with exit code ${code}`));\n }\n });\n \n child.on('error', reject);\n });\n}\nimport { createLocalExecutable } from './executable-wrapper.js';\nimport { createSparcStructureManually } from './sparc-structure.js';\nimport { createClaudeSlashCommands } from './claude-commands/slash-commands.js';\nimport { createOptimizedClaudeSlashCommands } from './claude-commands/optimized-slash-commands.js';\n// execSync imported above as execSyncOriginal\\nconst execSync = execSyncOriginal;\nimport { promises as fs } from 'fs';\nimport { copyTemplates } from './template-copier.js';\nimport { copyRevisedTemplates, validateTemplatesExist } from './copy-revised-templates.js';\nimport { copyAgentFiles, createAgentDirectories, validateAgentSystem, copyCommandFiles } from './agent-copier.js';\nimport { showInitHelp } from './help.js';\nimport { batchInitCommand, batchInitFromConfig, validateBatchOptions } from './batch-init.js';\nimport { ValidationSystem, runFullValidation } from './validation/index.js';\nimport { RollbackSystem, createAtomicOperation } from './rollback/index.js';\nimport {\n createEnhancedClaudeMd,\n createEnhancedSettingsJson,\n createWrapperScript,\n createCommandDoc,\n createHelperScript,\n COMMAND_STRUCTURE,\n} from './templates/enhanced-templates.js';\nimport { createOptimizedSparcClaudeMd } from './templates/claude-md.js';\nimport { getIsolatedNpxEnv } from '../../../utils/npx-isolated-cache.js';\nimport { updateGitignore, needsGitignoreUpdate } from './gitignore-updater.js';\nimport {\n createFullClaudeMd,\n createSparcClaudeMd,\n createMinimalClaudeMd,\n} from './templates/claude-md.js';\nimport {\n createVerificationClaudeMd,\n createVerificationSettingsJson,\n} from './templates/verification-claude-md.js';\nimport {\n createFullMemoryBankMd,\n createMinimalMemoryBankMd,\n} from './templates/memory-bank-md.js';\nimport {\n createFullCoordinationMd,\n createMinimalCoordinationMd,\n} from './templates/coordination-md.js';\nimport { createAgentsReadme, createSessionsReadme } from './templates/readme-files.js';\nimport { \n initializeHiveMind, \n getHiveMindStatus,\n rollbackHiveMindInit\n} from './hive-mind-init.js';\n\n/**\n * Check if Claude Code CLI is installed\n */\nfunction isClaudeCodeInstalled() {\n try {\n execSync('which claude', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Set up MCP servers in Claude Code\n */\nasync function setupMcpServers(dryRun = false) {\n console.log('\\n🔌 Setting up MCP servers for Claude Code...');\n\n const servers = [\n {\n name: 'claude-flow',\n command: 'npx claude-flow@alpha mcp start',\n description: 'Claude Flow MCP server with swarm orchestration (alpha)',\n },\n {\n name: 'ruv-swarm',\n command: 'npx ruv-swarm mcp start',\n description: 'ruv-swarm MCP server for enhanced coordination',\n },\n {\n name: 'flow-nexus',\n command: 'npx flow-nexus@latest mcp start',\n description: 'Flow Nexus Complete MCP server for advanced AI orchestration',\n },\n {\n name: 'agentic-payments',\n command: 'npx agentic-payments@latest mcp',\n description: 'Agentic Payments MCP server for autonomous agent payment authorization',\n },\n ];\n\n for (const server of servers) {\n try {\n if (!dryRun) {\n console.log(` 🔄 Adding ${server.name}...`);\n execSync(`claude mcp add ${server.name} ${server.command}`, { stdio: 'inherit' });\n console.log(` ✅ Added ${server.name} - ${server.description}`);\n } else {\n console.log(` [DRY RUN] Would add ${server.name} - ${server.description}`);\n }\n } catch (err) {\n console.log(` ⚠️ Failed to add ${server.name}: ${err.message}`);\n console.log(\n ` You can add it Line truncated
|
||||
@@ -1,13 +1,11 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import * as fs from 'fs/promises';
|
||||
import * as path from 'path';
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
const execAsync = promisify(exec);
|
||||
let MetricsReader = class MetricsReader {
|
||||
constructor(){
|
||||
this.metricsDir = '.claude-flow/metrics';
|
||||
this.sessionsDir = '.claude-flow/sessions';
|
||||
}
|
||||
export class MetricsReader {
|
||||
metricsDir = '.claude-flow/metrics';
|
||||
sessionsDir = '.claude-flow/sessions';
|
||||
async getSystemMetrics() {
|
||||
try {
|
||||
const filePath = path.join(this.metricsDir, 'system-metrics.json');
|
||||
@@ -18,15 +16,6 @@ let MetricsReader = class MetricsReader {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
async getTaskQueue() {
|
||||
try {
|
||||
const queueFile = '.claude-flow/tasks/queue.json';
|
||||
const content = await fs.readFile(queueFile, 'utf8');
|
||||
return JSON.parse(content);
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
async getTaskMetrics() {
|
||||
try {
|
||||
const filePath = path.join(this.metricsDir, 'task-metrics.json');
|
||||
@@ -47,30 +36,30 @@ let MetricsReader = class MetricsReader {
|
||||
}
|
||||
async getActiveAgents() {
|
||||
try {
|
||||
const perfMetrics = await this.getPerformanceMetrics();
|
||||
const sessionFiles = await this.getSessionFiles();
|
||||
const agents = [];
|
||||
const agentsDir = '.claude-flow/agents';
|
||||
try {
|
||||
const agentFiles = await fs.readdir(agentsDir);
|
||||
for (const file of agentFiles){
|
||||
if (file.endsWith('.json')) {
|
||||
try {
|
||||
const content = await fs.readFile(path.join(agentsDir, file), 'utf8');
|
||||
const agent = JSON.parse(content);
|
||||
agents.push(agent);
|
||||
} catch {}
|
||||
for (const file of sessionFiles){
|
||||
try {
|
||||
const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');
|
||||
const sessionData = JSON.parse(content);
|
||||
if (sessionData.agents && Array.isArray(sessionData.agents)) {
|
||||
agents.push(...sessionData.agents);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
if (agents.length === 0) {
|
||||
const sessionFiles = await this.getSessionFiles();
|
||||
for (const file of sessionFiles){
|
||||
try {
|
||||
const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');
|
||||
const sessionData = JSON.parse(content);
|
||||
if (sessionData.agents && Array.isArray(sessionData.agents)) {
|
||||
agents.push(...sessionData.agents);
|
||||
}
|
||||
} catch {}
|
||||
} catch {}
|
||||
}
|
||||
if (agents.length === 0 && perfMetrics) {
|
||||
const activeCount = perfMetrics.activeAgents || 0;
|
||||
const totalCount = perfMetrics.totalAgents || 0;
|
||||
for(let i = 0; i < totalCount; i++){
|
||||
agents.push({
|
||||
id: `agent-${i + 1}`,
|
||||
name: `Agent ${i + 1}`,
|
||||
type: i === 0 ? 'orchestrator' : 'worker',
|
||||
status: i < activeCount ? 'active' : 'idle',
|
||||
activeTasks: i < activeCount ? 1 : 0,
|
||||
lastActivity: Date.now() - i * 1000
|
||||
});
|
||||
}
|
||||
}
|
||||
return agents;
|
||||
@@ -146,7 +135,7 @@ let MetricsReader = class MetricsReader {
|
||||
}
|
||||
async getMCPServerStatus() {
|
||||
try {
|
||||
const { stdout } = await execAsync('ps aux | grep -E "mcp" | grep -v grep | wc -l');
|
||||
const { stdout } = await execAsync('ps aux | grep -E "mcp-server\\.js|claude-flow mcp start" | grep -v grep | wc -l');
|
||||
const processCount = parseInt(stdout.trim(), 10);
|
||||
const { stdout: orchestratorOut } = await execAsync('ps aux | grep -E "claude-flow start" | grep -v grep | wc -l');
|
||||
const orchestratorRunning = parseInt(orchestratorOut.trim(), 10) > 0;
|
||||
@@ -175,7 +164,6 @@ let MetricsReader = class MetricsReader {
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
export { MetricsReader };
|
||||
}
|
||||
|
||||
//# sourceMappingURL=metrics-reader.js.map
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/utils/metrics-reader.js"],"sourcesContent":["import { promises as fs } from 'fs';\nimport path from 'path';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nclass MetricsReader {\n constructor() {\n this.metricsDir = '.claude-flow/metrics';\n this.sessionsDir = '.claude-flow/sessions';\n }\n\n async getSystemMetrics() {\n try {\n const filePath = path.join(this.metricsDir, 'system-metrics.json');\n const content = await fs.readFile(filePath, 'utf8');\n const metrics = JSON.parse(content);\n \n // Return the most recent metric\n return metrics.length > 0 ? metrics[metrics.length - 1] : null;\n } catch (error) {\n return null;\n }\n }\n\n async getTaskQueue() {\n try {\n const queueFile = '.claude-flow/tasks/queue.json';\n const content = await fs.readFile(queueFile, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return [];\n }\n }\n\n async getTaskMetrics() {\n try {\n const filePath = path.join(this.metricsDir, 'task-metrics.json');\n const content = await fs.readFile(filePath, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return [];\n }\n }\n\n async getPerformanceMetrics() {\n try {\n const filePath = path.join(this.metricsDir, 'performance.json');\n const content = await fs.readFile(filePath, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n }\n\n async getActiveAgents() {\n try {\n const agents = [];\n \n // Check for agents in the .claude-flow/agents directory\n const agentsDir = '.claude-flow/agents';\n try {\n const agentFiles = await fs.readdir(agentsDir);\n for (const file of agentFiles) {\n if (file.endsWith('.json')) {\n try {\n const content = await fs.readFile(path.join(agentsDir, file), 'utf8');\n const agent = JSON.parse(content);\n agents.push(agent);\n } catch {\n // Skip invalid agent files\n }\n }\n }\n } catch {\n // Agents directory doesn't exist yet\n }\n \n // If no agents found in directory, check session files\n if (agents.length === 0) {\n const sessionFiles = await this.getSessionFiles();\n for (const file of sessionFiles) {\n try {\n const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');\n const sessionData = JSON.parse(content);\n \n if (sessionData.agents && Array.isArray(sessionData.agents)) {\n agents.push(...sessionData.agents);\n }\n } catch {\n // Skip invalid session files\n }\n }\n }\n \n return agents;\n } catch (error) {\n return [];\n }\n }\n\n async getSessionStatus() {\n try {\n const sessionFiles = await this.getSessionFiles();\n \n if (sessionFiles.length === 0) {\n return null;\n }\n \n // Get the most recent session\n const mostRecentFile = sessionFiles[sessionFiles.length - 1];\n const content = await fs.readFile(path.join(this.sessionsDir, 'pair', mostRecentFile), 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n }\n\n async getRecentTasks(limit = 10) {\n try {\n const taskMetrics = await this.getTaskMetrics();\n \n // Sort by timestamp descending and take the limit\n return taskMetrics\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, limit)\n .map(task => ({\n id: task.id,\n type: task.type,\n status: task.success ? 'completed' : 'failed',\n startTime: task.timestamp - task.duration,\n endTime: task.timestamp,\n duration: task.duration\n }));\n } catch (error) {\n return [];\n }\n }\n\n async getOverallHealth() {\n try {\n const systemMetrics = await this.getSystemMetrics();\n const perfMetrics = await this.getPerformanceMetrics();\n \n if (!systemMetrics && !perfMetrics) {\n return 'error';\n }\n \n // Check memory usage\n if (systemMetrics && systemMetrics.memoryUsagePercent > 90) {\n return 'error';\n }\n \n if (systemMetrics && systemMetrics.memoryUsagePercent > 75) {\n return 'warning';\n }\n \n // Check CPU load\n if (systemMetrics && systemMetrics.cpuLoad > 0.8) {\n return 'warning';\n }\n \n // Check task failure rate\n if (perfMetrics && perfMetrics.totalTasks > 0) {\n const failureRate = perfMetrics.failedTasks / perfMetrics.totalTasks;\n if (failureRate > 0.5) {\n return 'error';\n }\n if (failureRatLine truncated
|
||||
{"version":3,"sources":["../../../src/utils/metrics-reader.ts"],"sourcesContent":["import * as fs from 'fs/promises';\nimport * as path from 'path';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\ninterface SystemMetrics {\n timestamp: number;\n memoryTotal: number;\n memoryUsed: number;\n memoryFree: number;\n memoryUsagePercent: number;\n memoryEfficiency: number;\n cpuCount: number;\n cpuLoad: number;\n platform: string;\n uptime: number;\n}\n\ninterface TaskMetric {\n id: string;\n type: string;\n success: boolean;\n duration: number;\n timestamp: number;\n metadata: Record<string, any>;\n}\n\ninterface PerformanceMetrics {\n startTime: number;\n totalTasks: number;\n successfulTasks: number;\n failedTasks: number;\n totalAgents: number;\n activeAgents: number;\n neuralEvents: number;\n}\n\ninterface Agent {\n id: string;\n name: string;\n type: string;\n status: 'active' | 'idle' | 'busy';\n activeTasks: number;\n lastActivity?: number;\n}\n\ninterface SessionData {\n id: string;\n startTime: number;\n endTime?: number;\n agents: Agent[];\n tasks: any[];\n status: 'active' | 'completed' | 'paused';\n}\n\ninterface MCPServerStatus {\n running: boolean;\n processCount: number;\n orchestratorRunning: boolean;\n port: number | null;\n connections: number;\n}\n\nexport class MetricsReader {\n private metricsDir = '.claude-flow/metrics';\n private sessionsDir = '.claude-flow/sessions';\n\n async getSystemMetrics(): Promise<SystemMetrics | null> {\n try {\n const filePath = path.join(this.metricsDir, 'system-metrics.json');\n const content = await fs.readFile(filePath, 'utf8');\n const metrics: SystemMetrics[] = JSON.parse(content);\n \n // Return the most recent metric\n return metrics.length > 0 ? metrics[metrics.length - 1] : null;\n } catch (error) {\n return null;\n }\n }\n\n async getTaskMetrics(): Promise<TaskMetric[]> {\n try {\n const filePath = path.join(this.metricsDir, 'task-metrics.json');\n const content = await fs.readFile(filePath, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return [];\n }\n }\n\n async getPerformanceMetrics(): Promise<PerformanceMetrics | null> {\n try {\n const filePath = path.join(this.metricsDir, 'performance.json');\n const content = await fs.readFile(filePath, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n }\n\n async getActiveAgents(): Promise<Agent[]> {\n try {\n // First check performance metrics for agent count\n const perfMetrics = await this.getPerformanceMetrics();\n \n // Also check session files for more detailed agent info\n const sessionFiles = await this.getSessionFiles();\n const agents: Agent[] = [];\n \n for (const file of sessionFiles) {\n try {\n const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');\n const sessionData = JSON.parse(content);\n \n if (sessionData.agents && Array.isArray(sessionData.agents)) {\n agents.push(...sessionData.agents);\n }\n } catch {\n // Skip invalid session files\n }\n }\n \n // If no agents found in sessions, create mock agents based on performance metrics\n if (agents.length === 0 && perfMetrics) {\n const activeCount = perfMetrics.activeAgents || 0;\n const totalCount = perfMetrics.totalAgents || 0;\n \n for (let i = 0; i < totalCount; i++) {\n agents.push({\n id: `agent-${i + 1}`,\n name: `Agent ${i + 1}`,\n type: i === 0 ? 'orchestrator' : 'worker',\n status: i < activeCount ? 'active' : 'idle',\n activeTasks: i < activeCount ? 1 : 0,\n lastActivity: Date.now() - (i * 1000)\n });\n }\n }\n \n return agents;\n } catch (error) {\n return [];\n }\n }\n\n async getSessionStatus(): Promise<SessionData | null> {\n try {\n const sessionFiles = await this.getSessionFiles();\n \n if (sessionFiles.length === 0) {\n return null;\n }\n \n // Get the most recent session\n const mostRecentFile = sessionFiles[sessionFiles.length - 1];\n const content = await fs.readFile(path.join(this.sessionsDir, 'pair', mostRecentFile), 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n }\n\n async getRecentTasks(limit: number = 10): Promise<any[]> {\n try {\n const taskMetrics = await this.getTaskMetrics();\n \n // Sort by timestamp descending and take the limit\n return taskMetrics\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, limit)\n .map(task => ({\n id: task.id,\n type: task.type,\n Line truncated
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "claude-flow",
|
||||
"version": "2.5.0-alpha.136",
|
||||
"version": "2.5.0-alpha.137",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "claude-flow",
|
||||
"version": "2.5.0-alpha.136",
|
||||
"version": "2.5.0-alpha.137",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "claude-flow",
|
||||
"version": "2.5.0-alpha.136",
|
||||
"version": "2.5.0-alpha.137",
|
||||
"description": "Enterprise-grade AI agent orchestration with ruv-swarm integration",
|
||||
"mcpName": "io.github.ruvnet/claude-flow",
|
||||
"main": "cli.mjs",
|
||||
|
||||
@@ -154,15 +154,13 @@ async function setupMcpServers(dryRun = false) {
|
||||
* Create statusline script content (embedded fallback for binary builds)
|
||||
*/
|
||||
function createStatuslineScript() {
|
||||
return `#!/bin/bash
|
||||
|
||||
# Claude Code Status Line with Claude-Flow Integration
|
||||
# Displays model, directory, git branch, and real-time swarm metrics
|
||||
return `
|
||||
#!/bin/bash
|
||||
|
||||
# Read JSON input from stdin
|
||||
INPUT=$(cat)
|
||||
MODEL=$(echo "$INPUT" | jq -r '.model.display_name // "Claude"')
|
||||
CWD=$(echo "$INPUT" | jq -r '.workspace.current_dir // .cwd')
|
||||
MODEL=$(echo "$INPUT" | jq -r \'.model.display_name // "Claude"\')
|
||||
CWD=$(echo "$INPUT" | jq -r \'.workspace.current_dir // .cwd\')
|
||||
DIR=$(basename "$CWD")
|
||||
|
||||
# Replace claude-code-flow with branded name
|
||||
@@ -183,10 +181,11 @@ FLOW_DIR="$CWD/.claude-flow"
|
||||
if [ -d "$FLOW_DIR" ]; then
|
||||
echo -ne " │"
|
||||
|
||||
# Swarm Configuration & Topology
|
||||
# 1. Swarm Configuration & Topology
|
||||
if [ -f "$FLOW_DIR/swarm-config.json" ]; then
|
||||
STRATEGY=$(jq -r '.defaultStrategy // empty' "$FLOW_DIR/swarm-config.json" 2>/dev/null)
|
||||
STRATEGY=$(jq -r \'.defaultStrategy // empty\' "$FLOW_DIR/swarm-config.json" 2>/dev/null)
|
||||
if [ -n "$STRATEGY" ]; then
|
||||
# Map strategy to topology icon
|
||||
case "$STRATEGY" in
|
||||
"balanced") TOPO_ICON="⚡mesh" ;;
|
||||
"conservative") TOPO_ICON="⚡hier" ;;
|
||||
@@ -195,96 +194,139 @@ if [ -d "$FLOW_DIR" ]; then
|
||||
esac
|
||||
echo -ne " \\033[35m$TOPO_ICON\\033[0m"
|
||||
|
||||
AGENT_COUNT=$(jq -r '.agentProfiles | length' "$FLOW_DIR/swarm-config.json" 2>/dev/null)
|
||||
# Count agent profiles as "configured agents"
|
||||
AGENT_COUNT=$(jq -r \'.agentProfiles | length\' "$FLOW_DIR/swarm-config.json" 2>/dev/null)
|
||||
if [ -n "$AGENT_COUNT" ] && [ "$AGENT_COUNT" != "null" ] && [ "$AGENT_COUNT" -gt 0 ]; then
|
||||
echo -ne " \\033[35m🤖 $AGENT_COUNT\\033[0m"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Real-time System Metrics
|
||||
# 2. Real-time System Metrics
|
||||
if [ -f "$FLOW_DIR/metrics/system-metrics.json" ]; then
|
||||
LATEST=$(jq -r '.[-1]' "$FLOW_DIR/metrics/system-metrics.json" 2>/dev/null)
|
||||
# Get latest metrics (last entry in array)
|
||||
LATEST=$(jq -r \'.[-1]\' "$FLOW_DIR/metrics/system-metrics.json" 2>/dev/null)
|
||||
|
||||
if [ -n "$LATEST" ] && [ "$LATEST" != "null" ]; then
|
||||
MEM_PERCENT=$(echo "$LATEST" | jq -r '.memoryUsagePercent // 0' | awk '{printf "%.0f", $1}')
|
||||
# Memory usage
|
||||
MEM_PERCENT=$(echo "$LATEST" | jq -r \'.memoryUsagePercent // 0\' | awk \'{printf "%.0f", $1}\')
|
||||
if [ -n "$MEM_PERCENT" ] && [ "$MEM_PERCENT" != "null" ]; then
|
||||
# Color-coded memory (green <60%, yellow 60-80%, red >80%)
|
||||
if [ "$MEM_PERCENT" -lt 60 ]; then
|
||||
MEM_COLOR="\\033[32m"
|
||||
MEM_COLOR="\\033[32m" # Green
|
||||
elif [ "$MEM_PERCENT" -lt 80 ]; then
|
||||
MEM_COLOR="\\033[33m"
|
||||
MEM_COLOR="\\033[33m" # Yellow
|
||||
else
|
||||
MEM_COLOR="\\033[31m"
|
||||
MEM_COLOR="\\033[31m" # Red
|
||||
fi
|
||||
echo -ne " \${MEM_COLOR}💾 \${MEM_PERCENT}%\\033[0m"
|
||||
echo -ne " ${MEM_COLOR}💾 ${MEM_PERCENT}%\\033[0m"
|
||||
fi
|
||||
|
||||
CPU_LOAD=$(echo "$LATEST" | jq -r '.cpuLoad // 0' | awk '{printf "%.0f", $1 * 100}')
|
||||
# CPU load
|
||||
CPU_LOAD=$(echo "$LATEST" | jq -r \'.cpuLoad // 0\' | awk \'{printf "%.0f", $1 * 100}\')
|
||||
if [ -n "$CPU_LOAD" ] && [ "$CPU_LOAD" != "null" ]; then
|
||||
# Color-coded CPU (green <50%, yellow 50-75%, red >75%)
|
||||
if [ "$CPU_LOAD" -lt 50 ]; then
|
||||
CPU_COLOR="\\033[32m"
|
||||
CPU_COLOR="\\033[32m" # Green
|
||||
elif [ "$CPU_LOAD" -lt 75 ]; then
|
||||
CPU_COLOR="\\033[33m"
|
||||
CPU_COLOR="\\033[33m" # Yellow
|
||||
else
|
||||
CPU_COLOR="\\033[31m"
|
||||
CPU_COLOR="\\033[31m" # Red
|
||||
fi
|
||||
echo -ne " \${CPU_COLOR}⚙ \${CPU_LOAD}%\\033[0m"
|
||||
echo -ne " ${CPU_COLOR}⚙ ${CPU_LOAD}%\\033[0m"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Performance Metrics
|
||||
# 3. Session State
|
||||
if [ -f "$FLOW_DIR/session-state.json" ]; then
|
||||
SESSION_ID=$(jq -r \'.sessionId // empty\' "$FLOW_DIR/session-state.json" 2>/dev/null)
|
||||
ACTIVE=$(jq -r \'.active // false\' "$FLOW_DIR/session-state.json" 2>/dev/null)
|
||||
|
||||
if [ "$ACTIVE" = "true" ] && [ -n "$SESSION_ID" ]; then
|
||||
# Show abbreviated session ID
|
||||
SHORT_ID=$(echo "$SESSION_ID" | cut -d\'-\' -f1)
|
||||
echo -ne " \\033[34m🔄 $SHORT_ID\\033[0m"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 4. Performance Metrics from task-metrics.json
|
||||
if [ -f "$FLOW_DIR/metrics/task-metrics.json" ]; then
|
||||
METRICS=$(jq -r '
|
||||
# Parse task metrics for success rate, avg time, and streak
|
||||
METRICS=$(jq -r \'
|
||||
# Calculate metrics
|
||||
(map(select(.success == true)) | length) as $successful |
|
||||
(length) as $total |
|
||||
(if $total > 0 then ($successful / $total * 100) else 0 end) as $success_rate |
|
||||
(map(.duration // 0) | add / length) as $avg_duration |
|
||||
(reverse | reduce .[] as $task (0; if $task.success == true then . + 1 else 0 end)) as $streak |
|
||||
{ success_rate: $success_rate, avg_duration: $avg_duration, streak: $streak, total: $total } | @json
|
||||
' "$FLOW_DIR/metrics/task-metrics.json" 2>/dev/null)
|
||||
# Calculate streak (consecutive successes from end)
|
||||
(reverse |
|
||||
reduce .[] as $task (0;
|
||||
if $task.success == true then . + 1 else 0 end
|
||||
)
|
||||
) as $streak |
|
||||
{
|
||||
success_rate: $success_rate,
|
||||
avg_duration: $avg_duration,
|
||||
streak: $streak,
|
||||
total: $total
|
||||
} | @json
|
||||
\' "$FLOW_DIR/metrics/task-metrics.json" 2>/dev/null)
|
||||
|
||||
if [ -n "$METRICS" ] && [ "$METRICS" != "null" ]; then
|
||||
SUCCESS_RATE=$(echo "$METRICS" | jq -r '.success_rate // 0' | awk '{printf "%.0f", $1}')
|
||||
TOTAL_TASKS=$(echo "$METRICS" | jq -r '.total // 0')
|
||||
# Success Rate
|
||||
SUCCESS_RATE=$(echo "$METRICS" | jq -r \'.success_rate // 0\' | awk \'{printf "%.0f", $1}\')
|
||||
TOTAL_TASKS=$(echo "$METRICS" | jq -r \'.total // 0\')
|
||||
|
||||
if [ -n "$SUCCESS_RATE" ] && [ "$TOTAL_TASKS" -gt 0 ]; then
|
||||
# Color-code: Green (>80%), Yellow (60-80%), Red (<60%)
|
||||
if [ "$SUCCESS_RATE" -gt 80 ]; then
|
||||
SUCCESS_COLOR="\\033[32m"
|
||||
SUCCESS_COLOR="\\033[32m" # Green
|
||||
elif [ "$SUCCESS_RATE" -ge 60 ]; then
|
||||
SUCCESS_COLOR="\\033[33m"
|
||||
SUCCESS_COLOR="\\033[33m" # Yellow
|
||||
else
|
||||
SUCCESS_COLOR="\\033[31m"
|
||||
SUCCESS_COLOR="\\033[31m" # Red
|
||||
fi
|
||||
echo -ne " \${SUCCESS_COLOR}🎯 \${SUCCESS_RATE}%\\033[0m"
|
||||
echo -ne " ${SUCCESS_COLOR}🎯 ${SUCCESS_RATE}%\\033[0m"
|
||||
fi
|
||||
|
||||
AVG_TIME=$(echo "$METRICS" | jq -r '.avg_duration // 0')
|
||||
# Average Time
|
||||
AVG_TIME=$(echo "$METRICS" | jq -r \'.avg_duration // 0\')
|
||||
if [ -n "$AVG_TIME" ] && [ "$TOTAL_TASKS" -gt 0 ]; then
|
||||
# Format smartly: seconds, minutes, or hours
|
||||
if [ $(echo "$AVG_TIME < 60" | bc -l 2>/dev/null || echo 0) -eq 1 ]; then
|
||||
TIME_STR=$(echo "$AVG_TIME" | awk '{printf "%.1fs", $1}')
|
||||
TIME_STR=$(echo "$AVG_TIME" | awk \'{printf "%.1fs", $1}\')
|
||||
elif [ $(echo "$AVG_TIME < 3600" | bc -l 2>/dev/null || echo 0) -eq 1 ]; then
|
||||
TIME_STR=$(echo "$AVG_TIME" | awk '{printf "%.1fm", $1/60}')
|
||||
TIME_STR=$(echo "$AVG_TIME" | awk \'{printf "%.1fm", $1/60}\')
|
||||
else
|
||||
TIME_STR=$(echo "$AVG_TIME" | awk '{printf "%.1fh", $1/3600}')
|
||||
TIME_STR=$(echo "$AVG_TIME" | awk \'{printf "%.1fh", $1/3600}\')
|
||||
fi
|
||||
echo -ne " \\033[36m⏱️ $TIME_STR\\033[0m"
|
||||
fi
|
||||
|
||||
STREAK=$(echo "$METRICS" | jq -r '.streak // 0')
|
||||
# Streak (only show if > 0)
|
||||
STREAK=$(echo "$METRICS" | jq -r \'.streak // 0\')
|
||||
if [ -n "$STREAK" ] && [ "$STREAK" -gt 0 ]; then
|
||||
echo -ne " \\033[91m🔥 $STREAK\\033[0m"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Active Tasks
|
||||
# 5. Active Tasks (check for task files)
|
||||
if [ -d "$FLOW_DIR/tasks" ]; then
|
||||
TASK_COUNT=$(find "$FLOW_DIR/tasks" -name "*.json" -type f 2>/dev/null | wc -l)
|
||||
if [ "$TASK_COUNT" -gt 0 ]; then
|
||||
echo -ne " \\033[36m📋 $TASK_COUNT\\033[0m"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 6. Check for hooks activity
|
||||
if [ -f "$FLOW_DIR/hooks-state.json" ]; then
|
||||
HOOKS_ACTIVE=$(jq -r \'.enabled // false\' "$FLOW_DIR/hooks-state.json" 2>/dev/null)
|
||||
if [ "$HOOKS_ACTIVE" = "true" ]; then
|
||||
echo -ne " \\033[35m🔗\\033[0m"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
echo
|
||||
|
||||
Reference in new issue
Block a user