From 57daafff6eb7609d34ce41f71e6013a159d9047b Mon Sep 17 00:00:00 2001 From: rUv Date: Thu, 8 Jan 2026 00:33:18 +0000 Subject: [PATCH] Checkpoint: File edits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Automatic checkpoint created by Claude Code - Branch: v3 - Timestamp: 2026-01-08T00:33:18Z - Changes: 17 file(s) πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- agents/architect.yaml | 2 +- agents/coder.yaml | 2 +- agents/reviewer.yaml | 2 +- agents/security-architect.yaml | 2 +- agents/tester.yaml | 2 +- v3/@claude-flow/cli/.claude/helpers/memory.js | 83 ++++ .../cli/.claude/helpers/post-commit | 16 + .../cli/.claude/helpers/pre-commit | 26 ++ v3/@claude-flow/cli/.claude/helpers/router.js | 66 +++ .../cli/.claude/helpers/session.js | 127 ++++++ .../cli/.claude/helpers/statusline-hook.sh | 21 + .../cli/.claude/helpers/statusline.js | 227 ++++++++++ v3/@claude-flow/cli/.claude/settings.json | 212 +++++++++ v3/@claude-flow/cli/CLAUDE.md | 411 ++++++++++++++++++ v3/@claude-flow/cli/package.json | 2 +- .../cli/src/init/settings-generator.ts | 2 + v3/package-lock.json | 2 +- 17 files changed, 1198 insertions(+), 7 deletions(-) create mode 100644 v3/@claude-flow/cli/.claude/helpers/memory.js create mode 100755 v3/@claude-flow/cli/.claude/helpers/post-commit create mode 100755 v3/@claude-flow/cli/.claude/helpers/pre-commit create mode 100644 v3/@claude-flow/cli/.claude/helpers/router.js create mode 100644 v3/@claude-flow/cli/.claude/helpers/session.js create mode 100644 v3/@claude-flow/cli/.claude/helpers/statusline-hook.sh create mode 100644 v3/@claude-flow/cli/.claude/helpers/statusline.js create mode 100644 v3/@claude-flow/cli/.claude/settings.json create mode 100644 v3/@claude-flow/cli/CLAUDE.md diff --git a/agents/architect.yaml b/agents/architect.yaml index c1ceacb41a..6cddd8ab6b 100644 --- a/agents/architect.yaml +++ b/agents/architect.yaml @@ -8,4 +8,4 @@ capabilities: optimizations: - context-caching - memory-persistence -createdAt: "2026-01-08T00:08:02.208Z" +createdAt: "2026-01-08T00:32:09.314Z" diff --git a/agents/coder.yaml b/agents/coder.yaml index f5c81e3369..3b61bebe08 100644 --- a/agents/coder.yaml +++ b/agents/coder.yaml @@ -8,4 +8,4 @@ capabilities: optimizations: - flash-attention - token-reduction -createdAt: "2026-01-08T00:08:02.208Z" +createdAt: "2026-01-08T00:32:09.313Z" diff --git a/agents/reviewer.yaml b/agents/reviewer.yaml index 823d33728c..65d2173bd1 100644 --- a/agents/reviewer.yaml +++ b/agents/reviewer.yaml @@ -7,4 +7,4 @@ capabilities: - best-practices optimizations: - incremental-analysis -createdAt: "2026-01-08T00:08:02.208Z" +createdAt: "2026-01-08T00:32:09.314Z" diff --git a/agents/security-architect.yaml b/agents/security-architect.yaml index 8bffeb062c..1df15fd478 100644 --- a/agents/security-architect.yaml +++ b/agents/security-architect.yaml @@ -7,4 +7,4 @@ capabilities: - security-review optimizations: - pattern-matching -createdAt: "2026-01-08T00:08:02.208Z" +createdAt: "2026-01-08T00:32:09.314Z" diff --git a/agents/tester.yaml b/agents/tester.yaml index c54f2a0eb0..52d40125ff 100644 --- a/agents/tester.yaml +++ b/agents/tester.yaml @@ -7,4 +7,4 @@ capabilities: - coverage optimizations: - parallel-execution -createdAt: "2026-01-08T00:08:02.208Z" +createdAt: "2026-01-08T00:32:09.314Z" diff --git a/v3/@claude-flow/cli/.claude/helpers/memory.js b/v3/@claude-flow/cli/.claude/helpers/memory.js new file mode 100644 index 0000000000..7bd7dfbca9 --- /dev/null +++ b/v3/@claude-flow/cli/.claude/helpers/memory.js @@ -0,0 +1,83 @@ +#!/usr/bin/env node +/** + * Claude Flow Memory Helper + * Simple key-value memory for cross-session context + */ + +const fs = require('fs'); +const path = require('path'); + +const MEMORY_DIR = path.join(process.cwd(), '.claude-flow', 'data'); +const MEMORY_FILE = path.join(MEMORY_DIR, 'memory.json'); + +function loadMemory() { + try { + if (fs.existsSync(MEMORY_FILE)) { + return JSON.parse(fs.readFileSync(MEMORY_FILE, 'utf-8')); + } + } catch (e) { + // Ignore + } + return {}; +} + +function saveMemory(memory) { + fs.mkdirSync(MEMORY_DIR, { recursive: true }); + fs.writeFileSync(MEMORY_FILE, JSON.stringify(memory, null, 2)); +} + +const commands = { + get: (key) => { + const memory = loadMemory(); + const value = key ? memory[key] : memory; + console.log(JSON.stringify(value, null, 2)); + return value; + }, + + set: (key, value) => { + if (!key) { + console.error('Key required'); + return; + } + const memory = loadMemory(); + memory[key] = value; + memory._updated = new Date().toISOString(); + saveMemory(memory); + console.log(`Set: ${key}`); + }, + + delete: (key) => { + if (!key) { + console.error('Key required'); + return; + } + const memory = loadMemory(); + delete memory[key]; + saveMemory(memory); + console.log(`Deleted: ${key}`); + }, + + clear: () => { + saveMemory({}); + console.log('Memory cleared'); + }, + + keys: () => { + const memory = loadMemory(); + const keys = Object.keys(memory).filter(k => !k.startsWith('_')); + console.log(keys.join('\n')); + return keys; + }, +}; + +// CLI +const [,, command, key, ...valueParts] = process.argv; +const value = valueParts.join(' '); + +if (command && commands[command]) { + commands[command](key, value); +} else { + console.log('Usage: memory.js [key] [value]'); +} + +module.exports = commands; diff --git a/v3/@claude-flow/cli/.claude/helpers/post-commit b/v3/@claude-flow/cli/.claude/helpers/post-commit new file mode 100755 index 0000000000..17141a0cd0 --- /dev/null +++ b/v3/@claude-flow/cli/.claude/helpers/post-commit @@ -0,0 +1,16 @@ +#!/bin/bash +# Claude Flow Post-Commit Hook +# Records commit metrics and trains patterns + +COMMIT_HASH=$(git rev-parse HEAD) +COMMIT_MSG=$(git log -1 --pretty=%B) + +echo "πŸ“Š Recording commit metrics..." + +# Notify claude-flow of commit +npx @claude-flow/cli hooks notify \ + --message "Commit: $COMMIT_MSG" \ + --level info \ + --metadata '{"hash": "'$COMMIT_HASH'"}' 2>/dev/null || true + +echo "βœ… Commit recorded" diff --git a/v3/@claude-flow/cli/.claude/helpers/pre-commit b/v3/@claude-flow/cli/.claude/helpers/pre-commit new file mode 100755 index 0000000000..66eba588f3 --- /dev/null +++ b/v3/@claude-flow/cli/.claude/helpers/pre-commit @@ -0,0 +1,26 @@ +#!/bin/bash +# Claude Flow Pre-Commit Hook +# Validates code quality before commit + +set -e + +echo "πŸ” Running Claude Flow pre-commit checks..." + +# Get staged files +STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM) + +# Run validation for each staged file +for FILE in $STAGED_FILES; do + if [[ "$FILE" =~ \.(ts|js|tsx|jsx)$ ]]; then + echo " Validating: $FILE" + npx @claude-flow/cli hooks pre-edit --file "$FILE" --validate-syntax 2>/dev/null || true + fi +done + +# Run tests if available +if [ -f "package.json" ] && grep -q '"test"' package.json; then + echo "πŸ§ͺ Running tests..." + npm test --if-present 2>/dev/null || echo " Tests skipped or failed" +fi + +echo "βœ… Pre-commit checks complete" diff --git a/v3/@claude-flow/cli/.claude/helpers/router.js b/v3/@claude-flow/cli/.claude/helpers/router.js new file mode 100644 index 0000000000..8a7f14344a --- /dev/null +++ b/v3/@claude-flow/cli/.claude/helpers/router.js @@ -0,0 +1,66 @@ +#!/usr/bin/env node +/** + * Claude Flow Agent Router + * Routes tasks to optimal agents based on learned patterns + */ + +const AGENT_CAPABILITIES = { + coder: ['code-generation', 'refactoring', 'debugging', 'implementation'], + tester: ['unit-testing', 'integration-testing', 'coverage', 'test-generation'], + reviewer: ['code-review', 'security-audit', 'quality-check', 'best-practices'], + researcher: ['web-search', 'documentation', 'analysis', 'summarization'], + architect: ['system-design', 'architecture', 'patterns', 'scalability'], + 'backend-dev': ['api', 'database', 'server', 'authentication'], + 'frontend-dev': ['ui', 'react', 'css', 'components'], + devops: ['ci-cd', 'docker', 'deployment', 'infrastructure'], +}; + +const TASK_PATTERNS = { + // Code patterns + 'implement|create|build|add|write code': 'coder', + 'test|spec|coverage|unit test|integration': 'tester', + 'review|audit|check|validate|security': 'reviewer', + 'research|find|search|documentation|explore': 'researcher', + 'design|architect|structure|plan': 'architect', + + // Domain patterns + 'api|endpoint|server|backend|database': 'backend-dev', + 'ui|frontend|component|react|css|style': 'frontend-dev', + 'deploy|docker|ci|cd|pipeline|infrastructure': 'devops', +}; + +function routeTask(task) { + const taskLower = task.toLowerCase(); + + // Check patterns + for (const [pattern, agent] of Object.entries(TASK_PATTERNS)) { + const regex = new RegExp(pattern, 'i'); + if (regex.test(taskLower)) { + return { + agent, + confidence: 0.8, + reason: `Matched pattern: ${pattern}`, + }; + } + } + + // Default to coder for unknown tasks + return { + agent: 'coder', + confidence: 0.5, + reason: 'Default routing - no specific pattern matched', + }; +} + +// CLI +const task = process.argv.slice(2).join(' '); + +if (task) { + const result = routeTask(task); + console.log(JSON.stringify(result, null, 2)); +} else { + console.log('Usage: router.js '); + console.log('\nAvailable agents:', Object.keys(AGENT_CAPABILITIES).join(', ')); +} + +module.exports = { routeTask, AGENT_CAPABILITIES, TASK_PATTERNS }; diff --git a/v3/@claude-flow/cli/.claude/helpers/session.js b/v3/@claude-flow/cli/.claude/helpers/session.js new file mode 100644 index 0000000000..ab32233744 --- /dev/null +++ b/v3/@claude-flow/cli/.claude/helpers/session.js @@ -0,0 +1,127 @@ +#!/usr/bin/env node +/** + * Claude Flow Session Manager + * Handles session lifecycle: start, restore, end + */ + +const fs = require('fs'); +const path = require('path'); + +const SESSION_DIR = path.join(process.cwd(), '.claude-flow', 'sessions'); +const SESSION_FILE = path.join(SESSION_DIR, 'current.json'); + +const commands = { + start: () => { + const sessionId = `session-${Date.now()}`; + const session = { + id: sessionId, + startedAt: new Date().toISOString(), + cwd: process.cwd(), + context: {}, + metrics: { + edits: 0, + commands: 0, + tasks: 0, + errors: 0, + }, + }; + + fs.mkdirSync(SESSION_DIR, { recursive: true }); + fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2)); + + console.log(`Session started: ${sessionId}`); + return session; + }, + + restore: () => { + if (!fs.existsSync(SESSION_FILE)) { + console.log('No session to restore'); + return null; + } + + const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + session.restoredAt = new Date().toISOString(); + fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2)); + + console.log(`Session restored: ${session.id}`); + return session; + }, + + end: () => { + if (!fs.existsSync(SESSION_FILE)) { + console.log('No active session'); + return null; + } + + const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + session.endedAt = new Date().toISOString(); + session.duration = Date.now() - new Date(session.startedAt).getTime(); + + // Archive session + const archivePath = path.join(SESSION_DIR, `${session.id}.json`); + fs.writeFileSync(archivePath, JSON.stringify(session, null, 2)); + fs.unlinkSync(SESSION_FILE); + + console.log(`Session ended: ${session.id}`); + console.log(`Duration: ${Math.round(session.duration / 1000 / 60)} minutes`); + console.log(`Metrics: ${JSON.stringify(session.metrics)}`); + + return session; + }, + + status: () => { + if (!fs.existsSync(SESSION_FILE)) { + console.log('No active session'); + return null; + } + + const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + const duration = Date.now() - new Date(session.startedAt).getTime(); + + console.log(`Session: ${session.id}`); + console.log(`Started: ${session.startedAt}`); + console.log(`Duration: ${Math.round(duration / 1000 / 60)} minutes`); + console.log(`Metrics: ${JSON.stringify(session.metrics)}`); + + return session; + }, + + update: (key, value) => { + if (!fs.existsSync(SESSION_FILE)) { + console.log('No active session'); + return null; + } + + const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + session.context[key] = value; + session.updatedAt = new Date().toISOString(); + fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2)); + + return session; + }, + + metric: (name) => { + if (!fs.existsSync(SESSION_FILE)) { + return null; + } + + const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')); + if (session.metrics[name] !== undefined) { + session.metrics[name]++; + fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2)); + } + + return session; + }, +}; + +// CLI +const [,, command, ...args] = process.argv; + +if (command && commands[command]) { + commands[command](...args); +} else { + console.log('Usage: session.js [args]'); +} + +module.exports = commands; diff --git a/v3/@claude-flow/cli/.claude/helpers/statusline-hook.sh b/v3/@claude-flow/cli/.claude/helpers/statusline-hook.sh new file mode 100644 index 0000000000..82a7ac4cf9 --- /dev/null +++ b/v3/@claude-flow/cli/.claude/helpers/statusline-hook.sh @@ -0,0 +1,21 @@ +# Claude Flow V3 Statusline Hook +# Add to your shell RC file (.bashrc, .zshrc, etc.) + +# Function to get statusline +claude_flow_statusline() { + local statusline_script="${CLAUDE_FLOW_DIR:-.claude}/helpers/statusline.js" + if [ -f "$statusline_script" ]; then + node "$statusline_script" 2>/dev/null || echo "" + fi +} + +# For bash PS1 +# export PS1='$(claude_flow_statusline) \n\$ ' + +# For zsh RPROMPT +# export RPROMPT='$(claude_flow_statusline)' + +# For starship (add to starship.toml) +# [custom.claude_flow] +# command = "node .claude/helpers/statusline.js 2>/dev/null" +# when = "test -f .claude/helpers/statusline.js" diff --git a/v3/@claude-flow/cli/.claude/helpers/statusline.js b/v3/@claude-flow/cli/.claude/helpers/statusline.js new file mode 100644 index 0000000000..817ee62678 --- /dev/null +++ b/v3/@claude-flow/cli/.claude/helpers/statusline.js @@ -0,0 +1,227 @@ +#!/usr/bin/env node +/** + * Claude Flow V3 Statusline Generator + * Displays real-time V3 implementation progress and system status + * + * Usage: node statusline.js [--json] [--compact] + */ + +const fs = require('fs'); +const path = require('path'); +const { execSync } = require('child_process'); + +// Configuration +const CONFIG = { + enabled: true, + showProgress: true, + showSecurity: true, + showSwarm: true, + showHooks: true, + showPerformance: true, + refreshInterval: 5000, + maxAgents: 15, + topology: 'hierarchical-mesh', +}; + +// ANSI colors +const c = { + reset: '\x1b[0m', + bold: '\x1b[1m', + dim: '\x1b[2m', + red: '\x1b[0;31m', + green: '\x1b[0;32m', + yellow: '\x1b[0;33m', + blue: '\x1b[0;34m', + purple: '\x1b[0;35m', + cyan: '\x1b[0;36m', + brightRed: '\x1b[1;31m', + brightGreen: '\x1b[1;32m', + brightYellow: '\x1b[1;33m', + brightBlue: '\x1b[1;34m', + brightPurple: '\x1b[1;35m', + brightCyan: '\x1b[1;36m', + brightWhite: '\x1b[1;37m', +}; + +// Get user info +function getUserInfo() { + let name = 'user'; + let gitBranch = ''; + let modelName = 'Opus 4.5'; + + try { + name = execSync('git config user.name 2>/dev/null || echo "user"', { encoding: 'utf-8' }).trim(); + gitBranch = execSync('git branch --show-current 2>/dev/null || echo ""', { encoding: 'utf-8' }).trim(); + } catch (e) { + // Ignore errors + } + + return { name, gitBranch, modelName }; +} + +// Get V3 progress from filesystem +function getV3Progress() { + const v3Path = path.join(process.cwd(), 'v3', '@claude-flow'); + let domainsCompleted = 5; + let totalDomains = 5; + let dddProgress = 100; + let modulesCount = 0; + let filesCount = 0; + + try { + if (fs.existsSync(v3Path)) { + const modules = fs.readdirSync(v3Path); + modulesCount = modules.filter(m => fs.statSync(path.join(v3Path, m)).isDirectory()).length; + domainsCompleted = Math.min(5, Math.floor(modulesCount / 3)); + dddProgress = Math.min(100, Math.floor((modulesCount / 15) * 100)); + } + } catch (e) { + // Ignore errors + } + + return { domainsCompleted, totalDomains, dddProgress, modulesCount, filesCount }; +} + +// Get security status +function getSecurityStatus() { + const securityPath = path.join(process.cwd(), 'v3', '@claude-flow', 'security'); + const exists = fs.existsSync(securityPath); + + return { + status: exists ? 'CLEAN' : 'IN_PROGRESS', + cvesFixed: exists ? 3 : 2, + totalCves: 3, + }; +} + +// Get swarm status +function getSwarmStatus() { + let activeAgents = 0; + let coordinationActive = false; + + try { + const ps = execSync('ps aux 2>/dev/null | grep -c agentic-flow || echo "0"', { encoding: 'utf-8' }); + activeAgents = Math.max(0, parseInt(ps.trim()) - 1); + coordinationActive = activeAgents > 0; + } catch (e) { + // Ignore errors + } + + return { + activeAgents, + maxAgents: CONFIG.maxAgents, + coordinationActive, + }; +} + +// Get system metrics +function getSystemMetrics() { + let memoryMB = 0; + let subAgents = 0; + + try { + const mem = execSync('ps aux | grep -E "(node|agentic|claude)" | grep -v grep | awk \'{sum += \$6} END {print int(sum/1024)}\'', { encoding: 'utf-8' }); + memoryMB = parseInt(mem.trim()) || 0; + } catch (e) { + // Fallback + memoryMB = Math.floor(process.memoryUsage().heapUsed / 1024 / 1024); + } + + return { + memoryMB, + contextPct: 56, // Would need Claude Code input + intelligencePct: 30, + subAgents, + }; +} + +// Generate progress bar +function progressBar(current, total) { + const width = 5; + const filled = Math.round((current / total) * width); + const empty = width - filled; + return '[' + '\u25CF'.repeat(filled) + '\u25CB'.repeat(empty) + ']'; +} + +// Generate full statusline +function generateStatusline() { + const user = getUserInfo(); + const progress = getV3Progress(); + const security = getSecurityStatus(); + const swarm = getSwarmStatus(); + const system = getSystemMetrics(); + const lines = []; + + // Header Line + let header = `${c.bold}${c.brightPurple}β–Š Claude Flow V3 ${c.reset}`; + header += `${swarm.coordinationActive ? c.brightCyan : c.dim}● ${c.brightCyan}${user.name}${c.reset}`; + if (user.gitBranch) { + header += ` ${c.dim}β”‚${c.reset} ${c.brightBlue}βŽ‡ ${user.gitBranch}${c.reset}`; + } + header += ` ${c.dim}β”‚${c.reset} ${c.purple}${user.modelName}${c.reset}`; + lines.push(header); + + // Separator + lines.push(`${c.dim}─────────────────────────────────────────────────────${c.reset}`); + + // Line 1: DDD Domain Progress + const domainsColor = progress.domainsCompleted >= 3 ? c.brightGreen : progress.domainsCompleted > 0 ? c.yellow : c.red; + lines.push( + `${c.brightCyan}πŸ—οΈ DDD Domains${c.reset} ${progressBar(progress.domainsCompleted, progress.totalDomains)} ` + + `${domainsColor}${progress.domainsCompleted}${c.reset}/${c.brightWhite}${progress.totalDomains}${c.reset} ` + + `${c.brightYellow}⚑ 1.0x${c.reset} ${c.dim}β†’${c.reset} ${c.brightYellow}2.49x-7.47x${c.reset}` + ); + + // Line 2: Swarm + CVE + Memory + Context + Intelligence + const swarmIndicator = swarm.coordinationActive ? `${c.brightGreen}β—‰${c.reset}` : `${c.dim}β—‹${c.reset}`; + const agentsColor = swarm.activeAgents > 0 ? c.brightGreen : c.red; + let securityIcon = security.status === 'CLEAN' ? '🟒' : security.status === 'IN_PROGRESS' ? '🟑' : 'πŸ”΄'; + let securityColor = security.status === 'CLEAN' ? c.brightGreen : security.status === 'IN_PROGRESS' ? c.brightYellow : c.brightRed; + + lines.push( + `${c.brightYellow}πŸ€– Swarm${c.reset} ${swarmIndicator} [${agentsColor}${String(swarm.activeAgents).padStart(2)}${c.reset}/${c.brightWhite}${swarm.maxAgents}${c.reset}] ` + + `${c.brightPurple}πŸ‘₯ ${system.subAgents}${c.reset} ` + + `${securityIcon} ${securityColor}CVE ${security.cvesFixed}${c.reset}/${c.brightWhite}${security.totalCves}${c.reset} ` + + `${c.brightCyan}πŸ’Ύ ${system.memoryMB}MB${c.reset} ` + + `${c.brightGreen}πŸ“‚ ${String(system.contextPct).padStart(3)}%${c.reset} ` + + `${c.dim}🧠 ${String(system.intelligencePct).padStart(3)}%${c.reset}` + ); + + // Line 3: Architecture status + const dddColor = progress.dddProgress >= 50 ? c.brightGreen : progress.dddProgress > 0 ? c.yellow : c.red; + lines.push( + `${c.brightPurple}πŸ”§ Architecture${c.reset} ` + + `${c.cyan}DDD${c.reset} ${dddColor}●${String(progress.dddProgress).padStart(3)}%${c.reset} ${c.dim}β”‚${c.reset} ` + + `${c.cyan}Security${c.reset} ${securityColor}●${security.status}${c.reset} ${c.dim}β”‚${c.reset} ` + + `${c.cyan}Memory${c.reset} ${c.brightGreen}●AgentDB${c.reset} ${c.dim}β”‚${c.reset} ` + + `${c.cyan}Integration${c.reset} ${swarm.coordinationActive ? c.brightCyan : c.dim}●${c.reset}` + ); + + return lines.join('\n'); +} + +// Generate JSON data +function generateJSON() { + return { + user: getUserInfo(), + v3Progress: getV3Progress(), + security: getSecurityStatus(), + swarm: getSwarmStatus(), + system: getSystemMetrics(), + performance: { + flashAttentionTarget: '2.49x-7.47x', + searchImprovement: '150x-12,500x', + memoryReduction: '50-75%', + }, + lastUpdated: new Date().toISOString(), + }; +} + +// Main +if (process.argv.includes('--json')) { + console.log(JSON.stringify(generateJSON(), null, 2)); +} else if (process.argv.includes('--compact')) { + console.log(JSON.stringify(generateJSON())); +} else { + console.log(generateStatusline()); +} diff --git a/v3/@claude-flow/cli/.claude/settings.json b/v3/@claude-flow/cli/.claude/settings.json new file mode 100644 index 0000000000..2f67707b9c --- /dev/null +++ b/v3/@claude-flow/cli/.claude/settings.json @@ -0,0 +1,212 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "^(Write|Edit|MultiEdit)$", + "hooks": [ + { + "type": "command", + "command": "npx claude-flow@v3alpha hooks pre-edit --file \"$TOOL_INPUT_file_path\" --intelligence", + "timeout": 5000, + "continueOnError": true + } + ] + }, + { + "matcher": "^Bash$", + "hooks": [ + { + "type": "command", + "command": "npx claude-flow@v3alpha hooks pre-command --command \"$TOOL_INPUT_command\"", + "timeout": 5000, + "continueOnError": true + } + ] + }, + { + "matcher": "^Task$", + "hooks": [ + { + "type": "command", + "command": "npx claude-flow@v3alpha hooks pre-task --task-id \"task-$(date +%s)\" --description \"$TOOL_INPUT_prompt\"", + "timeout": 5000, + "continueOnError": true + } + ] + }, + { + "matcher": "^(Grep|Glob|Read)$", + "hooks": [ + { + "type": "command", + "command": "npx claude-flow@v3alpha hooks pre-search --pattern \"$TOOL_INPUT_pattern\"", + "timeout": 2000, + "continueOnError": true + } + ] + } + ], + "PostToolUse": [ + { + "matcher": "^(Write|Edit|MultiEdit)$", + "hooks": [ + { + "type": "command", + "command": "npx claude-flow@v3alpha hooks post-edit --file \"$TOOL_INPUT_file_path\" --success \"$TOOL_SUCCESS\" --train-patterns", + "timeout": 5000, + "continueOnError": true + } + ] + }, + { + "matcher": "^Bash$", + "hooks": [ + { + "type": "command", + "command": "npx claude-flow@v3alpha hooks post-command --command \"$TOOL_INPUT_command\" --success \"$TOOL_SUCCESS\" --exit-code \"$TOOL_EXIT_CODE\"", + "timeout": 5000, + "continueOnError": true + } + ] + }, + { + "matcher": "^Task$", + "hooks": [ + { + "type": "command", + "command": "npx claude-flow@v3alpha hooks post-task --agent-id \"$TOOL_RESULT_agent_id\" --success \"$TOOL_SUCCESS\" --analyze", + "timeout": 5000, + "continueOnError": true + } + ] + }, + { + "matcher": "^(Grep|Glob)$", + "hooks": [ + { + "type": "command", + "command": "npx claude-flow@v3alpha hooks post-search --cache-results", + "timeout": 2000, + "continueOnError": true + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "npx claude-flow@v3alpha hooks route --task \"$PROMPT\" --intelligence --include-explanation", + "timeout": 5000, + "continueOnError": true + } + ] + } + ], + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "npx claude-flow@v3alpha daemon start --quiet 2>/dev/null || true", + "timeout": 5000, + "continueOnError": true + }, + { + "type": "command", + "command": "npx claude-flow@v3alpha hooks session-start --session-id \"$SESSION_ID\" --load-context", + "timeout": 10000, + "continueOnError": true + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "prompt", + "prompt": "Evaluate task completion. Consider:\n1. Were all requested changes made?\n2. Did builds/tests pass?\n3. Is follow-up work needed?\n\nRespond with {\"decision\": \"stop\"} if complete, or {\"decision\": \"continue\", \"reason\": \"...\"} if more work is needed." + } + ] + } + ], + "Notification": [ + { + "hooks": [ + { + "type": "command", + "command": "npx claude-flow@v3alpha hooks notify --message \"$NOTIFICATION_MESSAGE\" --swarm-status", + "timeout": 3000, + "continueOnError": true + } + ] + } + ], + "PermissionRequest": [ + { + "matcher": "^mcp__claude-flow__.*$", + "hooks": [ + { + "type": "command", + "command": "echo '{\"decision\": \"allow\", \"reason\": \"claude-flow MCP tool auto-approved\"}'", + "timeout": 1000 + } + ] + }, + { + "matcher": "^Bash\\(npx @?claude-flow.*\\)$", + "hooks": [ + { + "type": "command", + "command": "echo '{\"decision\": \"allow\", \"reason\": \"claude-flow CLI auto-approved\"}'", + "timeout": 1000 + } + ] + } + ] + }, + "statusLine": { + "command": "npx @claude-flow/hooks statusline 2>/dev/null || node .claude/helpers/statusline.js 2>/dev/null || echo \"β–Š V3\"", + "refreshMs": 5000, + "enabled": true + }, + "permissions": { + "allow": [ + "Bash(npx claude-flow*)", + "Bash(npx @claude-flow/*)", + "mcp__claude-flow__*" + ], + "deny": [] + }, + "claudeFlow": { + "version": "3.0.0", + "enabled": true, + "modelPreferences": { + "default": "claude-sonnet-4-20250514", + "routing": "claude-haiku" + }, + "swarm": { + "topology": "hierarchical-mesh", + "maxAgents": 15 + }, + "memory": { + "backend": "hybrid", + "enableHNSW": true + }, + "neural": { + "enabled": true + }, + "daemon": { + "autoStart": true, + "workers": [ + "map", + "audit", + "optimize", + "consolidate", + "testgaps" + ] + } + } +} \ No newline at end of file diff --git a/v3/@claude-flow/cli/CLAUDE.md b/v3/@claude-flow/cli/CLAUDE.md new file mode 100644 index 0000000000..1f8b9807a9 --- /dev/null +++ b/v3/@claude-flow/cli/CLAUDE.md @@ -0,0 +1,411 @@ +# Claude Code Configuration - Claude Flow V3 + +## 🚨 AUTOMATIC SWARM ORCHESTRATION + +**When starting work on complex tasks, Claude Code MUST automatically:** + +1. **Initialize the swarm** using MCP tools +2. **Spawn concurrent agents** using Claude Code's Task tool +3. **Coordinate via hooks** and memory + +### 🚨 CRITICAL: MCP + Task Tool in SAME Message + +**When user says "spawn swarm" or requests complex work, Claude Code MUST in ONE message:** +1. Call MCP tools to initialize coordination +2. **IMMEDIATELY** call Task tool to spawn REAL working agents +3. Both MCP and Task calls must be in the SAME response + +**MCP alone does NOT execute work - Task tool agents do the actual work!** + +### πŸ”„ Auto-Start Swarm Protocol + +When the user requests a complex task (multi-file changes, feature implementation, refactoring), **immediately execute this pattern in a SINGLE message:** + +```javascript +// STEP 1: Initialize swarm coordination via MCP (in parallel with agent spawning) +mcp__claude-flow__swarm_init({ + topology: "hierarchical-mesh", + maxAgents: 15, + strategy: "adaptive" +}) + +// STEP 2: Spawn agents concurrently using Claude Code's Task tool +// ALL Task calls MUST be in the SAME message for parallel execution +Task("Coordinator", "You are the swarm coordinator. Initialize session, coordinate other agents via memory. Run: npx claude-flow@v3alpha hooks session-start", "hierarchical-coordinator") +Task("Researcher", "Analyze requirements and existing code patterns. Store findings in memory via hooks.", "researcher") +Task("Architect", "Design implementation approach based on research. Document decisions in memory.", "system-architect") +Task("Coder", "Implement the solution following architect's design. Coordinate via hooks.", "coder") +Task("Tester", "Write tests for the implementation. Report coverage via hooks.", "tester") +Task("Reviewer", "Review code quality and security. Document findings.", "reviewer") + +// STEP 3: Batch all todos +TodoWrite({ todos: [ + {content: "Initialize swarm coordination", status: "in_progress", activeForm: "Initializing swarm"}, + {content: "Research and analyze requirements", status: "in_progress", activeForm: "Researching requirements"}, + {content: "Design architecture", status: "pending", activeForm: "Designing architecture"}, + {content: "Implement solution", status: "pending", activeForm: "Implementing solution"}, + {content: "Write tests", status: "pending", activeForm: "Writing tests"}, + {content: "Review and finalize", status: "pending", activeForm: "Reviewing code"} +]}) + +// STEP 4: Store swarm state in memory +mcp__claude-flow__memory_usage({ + action: "store", + namespace: "swarm", + key: "current-session", + value: JSON.stringify({task: "[user's task]", agents: 6, startedAt: new Date().toISOString()}) +}) +``` + +### πŸ“‹ Agent Routing by Task Type + +| Task Type | Required Agents | Topology | +|-----------|-----------------|----------| +| Bug Fix | researcher, coder, tester | mesh | +| New Feature | coordinator, architect, coder, tester, reviewer | hierarchical | +| Refactoring | architect, coder, reviewer | mesh | +| Performance | researcher, performance-engineer, coder | hierarchical | +| Security Audit | security-architect, security-auditor, reviewer | hierarchical | +| Memory Optimization | memory-specialist, performance-engineer | mesh | +| Documentation | researcher, api-docs | mesh | + +### 🎯 Task Complexity Detection + +**AUTO-INVOKE SWARM when task involves:** +- Multiple files (3+) +- New feature implementation +- Refactoring across modules +- API changes with tests +- Security-related changes +- Performance optimization +- Database schema changes + +**SKIP SWARM for:** +- Single file edits +- Simple bug fixes (1-2 lines) +- Documentation updates +- Configuration changes +- Quick questions/exploration + +## 🚨 CRITICAL: CONCURRENT EXECUTION & FILE MANAGEMENT + +**ABSOLUTE RULES**: +1. ALL operations MUST be concurrent/parallel in a single message +2. **NEVER save working files, text/mds and tests to the root folder** +3. ALWAYS organize files in appropriate subdirectories +4. **USE CLAUDE CODE'S TASK TOOL** for spawning agents concurrently, not just MCP + +### ⚑ GOLDEN RULE: "1 MESSAGE = ALL RELATED OPERATIONS" + +**MANDATORY PATTERNS:** +- **TodoWrite**: ALWAYS batch ALL todos in ONE call (5-10+ todos minimum) +- **Task tool (Claude Code)**: ALWAYS spawn ALL agents in ONE message with full instructions +- **File operations**: ALWAYS batch ALL reads/writes/edits in ONE message +- **Bash commands**: ALWAYS batch ALL terminal operations in ONE message +- **Memory operations**: ALWAYS batch ALL memory store/retrieve in ONE message + +### πŸ“ File Organization Rules + +**NEVER save to root folder. Use these directories:** +- `/src` - Source code files +- `/tests` - Test files +- `/docs` - Documentation and markdown files +- `/config` - Configuration files +- `/scripts` - Utility scripts +- `/examples` - Example code + +## Project Configuration + +This project is configured with Claude Flow V3: +- **Topology**: hierarchical-mesh +- **Max Agents**: 15 +- **Memory Backend**: hybrid +- **HNSW Indexing**: Enabled (150x-12,500x faster) +- **Neural Learning**: Enabled (SONA) + +## πŸš€ V3 CLI Commands (26 Commands, 140+ Subcommands) + +### Core Commands + +| Command | Subcommands | Description | +|---------|-------------|-------------| +| `init` | 4 | Project initialization with wizard, presets, skills, hooks | +| `agent` | 8 | Agent lifecycle (spawn, list, status, stop, metrics, pool, health, logs) | +| `swarm` | 6 | Multi-agent swarm coordination and orchestration | +| `memory` | 11 | AgentDB memory with vector search (150x-12,500x faster) | +| `mcp` | 9 | MCP server management and tool execution | +| `task` | 6 | Task creation, assignment, and lifecycle | +| `session` | 7 | Session state management and persistence | +| `config` | 7 | Configuration management and provider setup | +| `status` | 3 | System status monitoring with watch mode | +| `workflow` | 6 | Workflow execution and template management | +| `hooks` | 17 | Self-learning hooks + 12 background workers | +| `hive-mind` | 6 | Queen-led Byzantine fault-tolerant consensus | + +### Advanced Commands + +| Command | Subcommands | Description | +|---------|-------------|-------------| +| `daemon` | 5 | Background worker daemon (start, stop, status, trigger, enable) | +| `neural` | 5 | Neural pattern training (train, status, patterns, predict, optimize) | +| `security` | 6 | Security scanning (scan, audit, cve, threats, validate, report) | +| `performance` | 5 | Performance profiling (benchmark, profile, metrics, optimize, report) | +| `providers` | 5 | AI providers (list, add, remove, test, configure) | +| `plugins` | 5 | Plugin management (list, install, uninstall, enable, disable) | +| `deployment` | 5 | Deployment management (deploy, rollback, status, environments, release) | +| `embeddings` | 4 | Vector embeddings (embed, batch, search, init) - 75x faster with agentic-flow | +| `claims` | 4 | Claims-based authorization (check, grant, revoke, list) | +| `migrate` | 5 | V2 to V3 migration with rollback support | +| `doctor` | 1 | System diagnostics with health checks | +| `completions` | 4 | Shell completions (bash, zsh, fish, powershell) | + +### Quick CLI Examples + +```bash +# Initialize project +npx claude-flow@v3alpha init --wizard + +# Start daemon with background workers +npx claude-flow@v3alpha daemon start + +# Spawn an agent +npx claude-flow@v3alpha agent spawn -t coder --name my-coder + +# Initialize swarm +npx claude-flow@v3alpha swarm init --v3-mode + +# Search memory (HNSW-indexed) +npx claude-flow@v3alpha memory search -q "authentication patterns" + +# System diagnostics +npx claude-flow@v3alpha doctor --fix + +# Security scan +npx claude-flow@v3alpha security scan --depth full + +# Performance benchmark +npx claude-flow@v3alpha performance benchmark --suite all +``` + +## πŸš€ Available Agents (60+ Types) + +### Core Development +`coder`, `reviewer`, `tester`, `planner`, `researcher` + +### V3 Specialized Agents +`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer` + +### Swarm Coordination +`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`, `collective-intelligence-coordinator`, `swarm-memory-manager` + +### Consensus & Distributed +`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`, `consensus-builder`, `crdt-synchronizer`, `quorum-manager`, `security-manager` + +### Performance & Optimization +`perf-analyzer`, `performance-benchmarker`, `task-orchestrator`, `memory-coordinator`, `smart-agent` + +### GitHub & Repository +`github-modes`, `pr-manager`, `code-review-swarm`, `issue-tracker`, `release-manager`, `workflow-automation`, `project-board-sync`, `repo-architect`, `multi-repo-swarm` + +### SPARC Methodology +`sparc-coord`, `sparc-coder`, `specification`, `pseudocode`, `architecture`, `refinement` + +### Specialized Development +`backend-dev`, `mobile-dev`, `ml-developer`, `cicd-engineer`, `api-docs`, `system-architect`, `code-analyzer`, `base-template-generator` + +### Testing & Validation +`tdd-london-swarm`, `production-validator` + +## πŸͺ V3 Hooks System (17 Hooks + 12 Workers) + +### Hook Categories + +| Category | Hooks | Purpose | +|----------|-------|---------| +| **Core** | `pre-edit`, `post-edit`, `pre-command`, `post-command`, `pre-task`, `post-task` | Tool lifecycle | +| **Session** | `session-start`, `session-end`, `session-restore`, `notify` | Context management | +| **Intelligence** | `route`, `explain`, `pretrain`, `build-agents`, `transfer` | Neural learning | +| **Learning** | `intelligence` (trajectory-start/step/end, pattern-store/search, stats, attention) | Reinforcement | + +### 12 Background Workers + +| Worker | Priority | Description | +|--------|----------|-------------| +| `ultralearn` | normal | Deep knowledge acquisition | +| `optimize` | high | Performance optimization | +| `consolidate` | low | Memory consolidation | +| `predict` | normal | Predictive preloading | +| `audit` | critical | Security analysis | +| `map` | normal | Codebase mapping | +| `preload` | low | Resource preloading | +| `deepdive` | normal | Deep code analysis | +| `document` | normal | Auto-documentation | +| `refactor` | normal | Refactoring suggestions | +| `benchmark` | normal | Performance benchmarking | +| `testgaps` | normal | Test coverage analysis | + +### Essential Hook Commands + +```bash +# Core hooks +npx claude-flow@v3alpha hooks pre-task --description "[task]" +npx claude-flow@v3alpha hooks post-task --task-id "[id]" --success true +npx claude-flow@v3alpha hooks post-edit --file "[file]" --train-patterns + +# Session management +npx claude-flow@v3alpha hooks session-start --session-id "[id]" +npx claude-flow@v3alpha hooks session-end --export-metrics true +npx claude-flow@v3alpha hooks session-restore --session-id "[id]" + +# Intelligence routing +npx claude-flow@v3alpha hooks route --task "[task]" +npx claude-flow@v3alpha hooks explain --topic "[topic]" + +# Neural learning +npx claude-flow@v3alpha hooks pretrain --model-type moe --epochs 10 +npx claude-flow@v3alpha hooks build-agents --agent-types coder,tester + +# Background workers +npx claude-flow@v3alpha hooks worker list +npx claude-flow@v3alpha hooks worker dispatch --trigger audit +npx claude-flow@v3alpha hooks worker status +``` + +## 🧠 Intelligence System (RuVector) + +V3 includes the RuVector Intelligence System: +- **SONA**: Self-Optimizing Neural Architecture (<0.05ms adaptation) +- **MoE**: Mixture of Experts for specialized routing +- **HNSW**: 150x-12,500x faster pattern search +- **EWC++**: Elastic Weight Consolidation (prevents forgetting) +- **Flash Attention**: 2.49x-7.47x speedup + +The 4-step intelligence pipeline: +1. **RETRIEVE** - Fetch relevant patterns via HNSW +2. **JUDGE** - Evaluate with verdicts (success/failure) +3. **DISTILL** - Extract key learnings via LoRA +4. **CONSOLIDATE** - Prevent catastrophic forgetting via EWC++ + +## πŸ“¦ Embeddings Package (v3.0.0-alpha.12) + +Features: +- **sql.js**: Cross-platform SQLite persistent cache (WASM, no native compilation) +- **Document chunking**: Configurable overlap and size +- **Normalization**: L2, L1, min-max, z-score +- **Hyperbolic embeddings**: PoincarΓ© ball model for hierarchical data +- **75x faster**: With agentic-flow ONNX integration +- **Neural substrate**: Integration with RuVector + +## 🐝 Hive-Mind Consensus + +### Topologies +- `hierarchical` - Queen controls workers directly +- `mesh` - Fully connected peer network +- `hierarchical-mesh` - Hybrid (recommended) +- `adaptive` - Dynamic based on load + +### Consensus Strategies +- `byzantine` - BFT (tolerates f < n/3 faulty) +- `raft` - Leader-based (tolerates f < n/2) +- `gossip` - Epidemic for eventual consistency +- `crdt` - Conflict-free replicated data types +- `quorum` - Configurable quorum-based + +## V3 Performance Targets + +| Metric | Target | +|--------|--------| +| Flash Attention | 2.49x-7.47x speedup | +| HNSW Search | 150x-12,500x faster | +| Memory Reduction | 50-75% with quantization | +| MCP Response | <100ms | +| CLI Startup | <500ms | +| SONA Adaptation | <0.05ms | + +## πŸ”§ Environment Variables + +```bash +# Configuration +CLAUDE_FLOW_CONFIG=./claude-flow.config.json +CLAUDE_FLOW_LOG_LEVEL=info + +# Provider API Keys +ANTHROPIC_API_KEY=sk-ant-... +OPENAI_API_KEY=sk-... +GOOGLE_API_KEY=... + +# MCP Server +CLAUDE_FLOW_MCP_PORT=3000 +CLAUDE_FLOW_MCP_HOST=localhost +CLAUDE_FLOW_MCP_TRANSPORT=stdio + +# Memory +CLAUDE_FLOW_MEMORY_BACKEND=hybrid +CLAUDE_FLOW_MEMORY_PATH=./data/memory +``` + +## πŸ” Doctor Health Checks + +Run `npx claude-flow@v3alpha doctor` to check: +- Node.js version (20+) +- npm version (9+) +- Git installation +- Config file validity +- Daemon status +- Memory database +- API keys +- MCP servers +- Disk space +- TypeScript installation + +## πŸš€ Quick Setup + +```bash +# Add MCP servers +claude mcp add claude-flow npx claude-flow@v3alpha mcp start +claude mcp add ruv-swarm npx ruv-swarm mcp start # Optional +claude mcp add flow-nexus npx flow-nexus@latest mcp start # Optional + +# Start daemon +npx claude-flow@v3alpha daemon start + +# Run doctor +npx claude-flow@v3alpha doctor --fix +``` + +## 🎯 Claude Code vs MCP Tools + +### Claude Code Handles ALL EXECUTION: +- **Task tool**: Spawn and run agents concurrently +- File operations (Read, Write, Edit, MultiEdit, Glob, Grep) +- Code generation and programming +- Bash commands and system operations +- TodoWrite and task management +- Git operations + +### MCP Tools ONLY COORDINATE: +- Swarm initialization (topology setup) +- Agent type definitions +- Task orchestration +- Memory management +- Neural features +- Performance tracking + +**KEY**: MCP coordinates the strategy, Claude Code's Task tool executes with real agents. + +## Support + +- Documentation: https://github.com/ruvnet/claude-flow +- Issues: https://github.com/ruvnet/claude-flow/issues + +--- + +Remember: **Claude Flow coordinates, Claude Code creates!** + +# important-instruction-reminders +Do what has been asked; nothing more, nothing less. +NEVER create files unless they're absolutely necessary for achieving your goal. +ALWAYS prefer editing an existing file to creating a new one. +NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User. +Never save working files, text/mds and tests to the root folder. +After spawning a swarm, wait, don't continuously check status. diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json index d1bd94585a..4456b1254e 100644 --- a/v3/@claude-flow/cli/package.json +++ b/v3/@claude-flow/cli/package.json @@ -1,6 +1,6 @@ { "name": "@claude-flow/cli", - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.30", "type": "module", "description": "CLI module - command parsing, prompts, output formatting", "main": "dist/src/index.js", diff --git a/v3/@claude-flow/cli/src/init/settings-generator.ts b/v3/@claude-flow/cli/src/init/settings-generator.ts index 0b67db84a6..ffb09f26a2 100644 --- a/v3/@claude-flow/cli/src/init/settings-generator.ts +++ b/v3/@claude-flow/cli/src/init/settings-generator.ts @@ -76,6 +76,8 @@ function generateStatusLineConfig(options: InitOptions): object { const statuslineCommand = 'npx @claude-flow/hooks statusline 2>/dev/null || node .claude/helpers/statusline.js 2>/dev/null || echo "β–Š V3"'; return { + // Type must be "command" for Claude Code validation + type: 'command', // Command to execute for statusline content command: statuslineCommand, // Refresh interval in milliseconds (5 seconds default) diff --git a/v3/package-lock.json b/v3/package-lock.json index f3e0214a54..f960f5a92c 100644 --- a/v3/package-lock.json +++ b/v3/package-lock.json @@ -124,7 +124,7 @@ } }, "@claude-flow/cli": { - "version": "3.0.0-alpha.29", + "version": "3.0.0-alpha.30", "dependencies": { "@claude-flow/shared": "^3.0.0-alpha.1" },