diff --git a/package.json b/package.json index 27f5cda2a5..1312555e5d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "claude-flow", - "version": "3.5.75", + "version": "3.5.77", "description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration", "main": "dist/index.js", "type": "module", diff --git a/ruflo/package.json b/ruflo/package.json index 0df499dfbf..3b3146d104 100644 --- a/ruflo/package.json +++ b/ruflo/package.json @@ -1,6 +1,6 @@ { "name": "ruflo", - "version": "3.5.75", + "version": "3.5.77", "description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration", "main": "bin/ruflo.js", "type": "module", diff --git a/v3/@claude-flow/cli/bin/cli.js b/v3/@claude-flow/cli/bin/cli.js index db28271de6..35c28a0352 100755 --- a/v3/@claude-flow/cli/bin/cli.js +++ b/v3/@claude-flow/cli/bin/cli.js @@ -158,8 +158,15 @@ if (isMCPMode) { // Run normal CLI mode const { CLI } = await import('../dist/src/index.js'); const cli = new CLI(); - cli.run().catch((error) => { - console.error('Fatal error:', error.message); - process.exit(1); - }); + cli.run() + .then(() => { + // #1552: Exit cleanly after one-shot commands. + // Long-running commands (daemon foreground, mcp, status --watch) never resolve, + // so this only fires for normal CLI commands. + process.exit(0); + }) + .catch((error) => { + console.error('Fatal error:', error.message); + process.exit(1); + }); } diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json index 37735e5c63..adb164879f 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.5.75", + "version": "3.5.77", "type": "module", "description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code", "main": "dist/src/index.js", diff --git a/v3/@claude-flow/cli/src/autopilot-state.ts b/v3/@claude-flow/cli/src/autopilot-state.ts index c73f16af9d..da52e874ba 100644 --- a/v3/@claude-flow/cli/src/autopilot-state.ts +++ b/v3/@claude-flow/cli/src/autopilot-state.ts @@ -8,6 +8,11 @@ * Security: Addresses prototype pollution, NaN bypass, input validation */ +import { randomUUID } from 'node:crypto'; +import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, renameSync } from 'node:fs'; +import { resolve, join } from 'node:path'; +import { homedir } from 'node:os'; + // ── Constants ───────────────────────────────────────────────── export const STATE_DIR = '.claude-flow/data'; @@ -113,9 +118,8 @@ export function validateTaskSources(sources: unknown): string[] { // ── State Management ────────────────────────────────────────── export function getDefaultState(): AutopilotState { - const crypto = require('crypto') as typeof import('crypto'); return { - sessionId: crypto.randomUUID(), + sessionId: randomUUID(), enabled: false, startTime: Date.now(), iterations: 0, @@ -128,13 +132,11 @@ export function getDefaultState(): AutopilotState { } export function loadState(): AutopilotState { - const fs = require('fs') as typeof import('fs'); - const path = require('path') as typeof import('path'); - const filePath = path.resolve(STATE_FILE); + const filePath = resolve(STATE_FILE); const defaults = getDefaultState(); try { - if (fs.existsSync(filePath)) { - const raw = safeJsonParse>(fs.readFileSync(filePath, 'utf-8')); + if (existsSync(filePath)) { + const raw = safeJsonParse>(readFileSync(filePath, 'utf-8')); const merged = { ...defaults, ...raw }; // Re-validate fields that could be tampered with merged.maxIterations = validateNumber(merged.maxIterations, 1, 1000, 50); @@ -154,29 +156,25 @@ export function loadState(): AutopilotState { } export function saveState(state: AutopilotState): void { - const fs = require('fs') as typeof import('fs'); - const path = require('path') as typeof import('path'); - const dir = path.resolve(STATE_DIR); - if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + const dir = resolve(STATE_DIR); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true }); // Cap history before saving if (state.history.length > MAX_HISTORY_ENTRIES) { state.history = state.history.slice(-MAX_HISTORY_ENTRIES); } - const tmpFile = path.resolve(STATE_FILE) + '.tmp'; - fs.writeFileSync(tmpFile, JSON.stringify(state, null, 2)); - fs.renameSync(tmpFile, path.resolve(STATE_FILE)); + const tmpFile = resolve(STATE_FILE) + '.tmp'; + writeFileSync(tmpFile, JSON.stringify(state, null, 2)); + renameSync(tmpFile, resolve(STATE_FILE)); } export function appendLog(entry: AutopilotLogEntry): void { - const fs = require('fs') as typeof import('fs'); - const path = require('path') as typeof import('path'); - const filePath = path.resolve(LOG_FILE); - const dir = path.resolve(STATE_DIR); - if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + const filePath = resolve(LOG_FILE); + const dir = resolve(STATE_DIR); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true }); let log: AutopilotLogEntry[] = []; try { - if (fs.existsSync(filePath)) { - log = safeJsonParse(fs.readFileSync(filePath, 'utf-8')); + if (existsSync(filePath)) { + log = safeJsonParse(readFileSync(filePath, 'utf-8')); if (!Array.isArray(log)) log = []; } } catch { @@ -185,17 +183,15 @@ export function appendLog(entry: AutopilotLogEntry): void { log.push(entry); if (log.length > MAX_LOG_ENTRIES) log = log.slice(-MAX_LOG_ENTRIES); const tmpFile = filePath + '.tmp'; - fs.writeFileSync(tmpFile, JSON.stringify(log, null, 2)); - fs.renameSync(tmpFile, filePath); + writeFileSync(tmpFile, JSON.stringify(log, null, 2)); + renameSync(tmpFile, filePath); } export function loadLog(): AutopilotLogEntry[] { - const fs = require('fs') as typeof import('fs'); - const path = require('path') as typeof import('path'); - const filePath = path.resolve(LOG_FILE); + const filePath = resolve(LOG_FILE); try { - if (fs.existsSync(filePath)) { - const result = safeJsonParse(fs.readFileSync(filePath, 'utf-8')); + if (existsSync(filePath)) { + const result = safeJsonParse(readFileSync(filePath, 'utf-8')); return Array.isArray(result) ? result : []; } } catch { @@ -207,9 +203,6 @@ export function loadLog(): AutopilotLogEntry[] { // ── Task Discovery ──────────────────────────────────────────── export function discoverTasks(sources: string[]): TaskInfo[] { - const fs = require('fs') as typeof import('fs'); - const path = require('path') as typeof import('path'); - const os = require('os') as typeof import('os'); const tasks: TaskInfo[] = []; // Only process valid sources @@ -217,17 +210,17 @@ export function discoverTasks(sources: string[]): TaskInfo[] { for (const source of validSources) { if (source === 'team-tasks') { - const tasksDir = path.join(os.homedir(), '.claude', 'tasks'); + const tasksDir = join(homedir(), '.claude', 'tasks'); try { - if (fs.existsSync(tasksDir)) { - const teams = fs.readdirSync(tasksDir, { withFileTypes: true }); + if (existsSync(tasksDir)) { + const teams = readdirSync(tasksDir, { withFileTypes: true }); for (const team of teams) { if (!team.isDirectory()) continue; - const teamDir = path.join(tasksDir, team.name); - const files = fs.readdirSync(teamDir).filter((f: string) => f.endsWith('.json')); + const teamDir = join(tasksDir, team.name); + const files = readdirSync(teamDir).filter((f: string) => f.endsWith('.json')); for (const file of files) { try { - const data = safeJsonParse>(fs.readFileSync(path.join(teamDir, file), 'utf-8')); + const data = safeJsonParse>(readFileSync(join(teamDir, file), 'utf-8')); tasks.push({ id: String(data.id || file.replace('.json', '')), subject: String(data.subject || data.title || file), @@ -242,10 +235,10 @@ export function discoverTasks(sources: string[]): TaskInfo[] { } if (source === 'swarm-tasks') { - const swarmFile = path.resolve('.claude-flow/swarm-tasks.json'); + const swarmFile = resolve('.claude-flow/swarm-tasks.json'); try { - if (fs.existsSync(swarmFile)) { - const data = safeJsonParse | unknown[]>(fs.readFileSync(swarmFile, 'utf-8')); + if (existsSync(swarmFile)) { + const data = safeJsonParse | unknown[]>(readFileSync(swarmFile, 'utf-8')); const swarmTasks = Array.isArray(data) ? data : ((data as Record).tasks as unknown[] || []); for (const t of swarmTasks) { if (t && typeof t === 'object') { @@ -263,10 +256,10 @@ export function discoverTasks(sources: string[]): TaskInfo[] { } if (source === 'file-checklist') { - const checklistFile = path.resolve('.claude-flow/data/checklist.json'); + const checklistFile = resolve('.claude-flow/data/checklist.json'); try { - if (fs.existsSync(checklistFile)) { - const data = safeJsonParse | unknown[]>(fs.readFileSync(checklistFile, 'utf-8')); + if (existsSync(checklistFile)) { + const data = safeJsonParse | unknown[]>(readFileSync(checklistFile, 'utf-8')); const items = Array.isArray(data) ? data : ((data as Record).items as unknown[] || []); for (const item of items) { if (item && typeof item === 'object') { diff --git a/v3/@claude-flow/cli/src/commands/autopilot.ts b/v3/@claude-flow/cli/src/commands/autopilot.ts index 6fed1ed891..9c420f9153 100644 --- a/v3/@claude-flow/cli/src/commands/autopilot.ts +++ b/v3/@claude-flow/cli/src/commands/autopilot.ts @@ -212,9 +212,9 @@ const logCommand: Command = { ], action: async (ctx: CommandContext): Promise => { if (ctx.flags?.clear) { - const fs = require('fs') as typeof import('fs'); - const path = require('path') as typeof import('path'); - try { fs.writeFileSync(path.resolve(LOG_FILE), '[]'); } catch { /* ignore */ } + const { writeFileSync } = await import('node:fs'); + const { resolve } = await import('node:path'); + try { writeFileSync(resolve(LOG_FILE), '[]'); } catch { /* ignore */ } output.writeln('Autopilot log cleared'); return { success: true }; } diff --git a/v3/@claude-flow/cli/src/commands/claims.ts b/v3/@claude-flow/cli/src/commands/claims.ts index 3412966dba..7d2289ebfa 100644 --- a/v3/@claude-flow/cli/src/commands/claims.ts +++ b/v3/@claude-flow/cli/src/commands/claims.ts @@ -5,6 +5,8 @@ * Created with ❤️ by ruv.io */ +import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs'; +import { resolve, dirname } from 'node:path'; import type { Command, CommandContext, CommandResult } from '../types.js'; import { output } from '../output.js'; @@ -20,23 +22,19 @@ const CLAIMS_CONFIG_PATHS = [ ]; function getClaimsConfigPaths(): string[] { - // Lazy import to keep top-level synchronous - // eslint-disable-next-line @typescript-eslint/no-var-requires - const path = require('path') as typeof import('path'); return [ - path.resolve(CLAIMS_CONFIG_PATHS[0]), - path.resolve(CLAIMS_CONFIG_PATHS[1]), - path.resolve(process.env.HOME || '~', '.config/claude-flow/claims.json'), + resolve(CLAIMS_CONFIG_PATHS[0]), + resolve(CLAIMS_CONFIG_PATHS[1]), + resolve(process.env.HOME || '~', '.config/claude-flow/claims.json'), ]; } function loadClaimsConfig(): { config: ClaimsConfig; path: string } { - const fs = require('fs') as typeof import('fs'); const configPaths = getClaimsConfigPaths(); for (const configPath of configPaths) { - if (fs.existsSync(configPath)) { - const content = fs.readFileSync(configPath, 'utf-8'); + if (existsSync(configPath)) { + const content = readFileSync(configPath, 'utf-8'); return { config: JSON.parse(content) as ClaimsConfig, path: configPath }; } } @@ -55,17 +53,14 @@ function loadClaimsConfig(): { config: ClaimsConfig; path: string } { } function saveClaimsConfig(config: ClaimsConfig, configPath: string): void { - const fs = require('fs') as typeof import('fs'); - const path = require('path') as typeof import('path'); - - const dir = path.dirname(configPath); - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true }); + const dir = dirname(configPath); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); } const tmpPath = configPath + '.tmp'; - fs.writeFileSync(tmpPath, JSON.stringify(config, null, 2) + '\n', 'utf-8'); - fs.renameSync(tmpPath, configPath); + writeFileSync(tmpPath, JSON.stringify(config, null, 2) + '\n', 'utf-8'); + renameSync(tmpPath, configPath); } // List subcommand diff --git a/v3/@claude-flow/cli/src/commands/cleanup.ts b/v3/@claude-flow/cli/src/commands/cleanup.ts index ffbb30af26..e21a6df80b 100644 --- a/v3/@claude-flow/cli/src/commands/cleanup.ts +++ b/v3/@claude-flow/cli/src/commands/cleanup.ts @@ -7,14 +7,23 @@ import type { Command, CommandContext, CommandResult } from '../types.js'; import { output } from '../output.js'; -import { existsSync, statSync, rmSync, readdirSync } from 'fs'; +import { existsSync, statSync, rmSync, readdirSync, readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; +/** + * Ruflo-owned subdirectories within .claude/ that are safe to delete. + * Everything else in .claude/ (agents, skills, commands, settings.local.json, + * memory.db, worktrees, launch.json) belongs to Claude Code and must be preserved. + * See: https://github.com/ruvnet/ruflo/issues/1557 + */ +const CLAUDE_OWNED_SUBDIRS = [ + { path: join('.claude', 'helpers'), description: 'Ruflo hook scripts' }, +]; + /** * Artifact directories and files that claude-flow/ruflo may create */ const ARTIFACT_DIRS = [ - { path: '.claude', description: 'Claude settings, helpers, agents' }, { path: '.claude-flow', description: 'Capabilities and configuration' }, { path: 'data', description: 'Memory databases' }, { path: '.swarm', description: 'Swarm state' }, @@ -129,7 +138,23 @@ export const cleanupCommand: Command = { const found: { path: string; description: string; size: number; type: 'dir' | 'file'; skipped?: boolean }[] = []; let totalSize = 0; - // Scan directories + // Scan ruflo-owned subdirs within .claude/ (surgical — preserves Claude Code files) + for (const artifact of CLAUDE_OWNED_SUBDIRS) { + const fullPath = join(cwd, artifact.path); + if (existsSync(fullPath)) { + const size = getSize(fullPath); + found.push({ path: artifact.path, description: artifact.description, size, type: 'dir' }); + totalSize += size; + } + } + + // Check if .claude/settings.json has ruflo hooks/claudeFlow blocks to clean + const settingsPath = join(cwd, '.claude', 'settings.json'); + if (existsSync(settingsPath)) { + found.push({ path: join('.claude', 'settings.json'), description: 'Remove ruflo hooks/claudeFlow blocks (preserves rest)', size: 0, type: 'file' }); + } + + // Scan standalone artifact directories for (const artifact of ARTIFACT_DIRS) { const fullPath = join(cwd, artifact.path); if (existsSync(fullPath)) { @@ -187,7 +212,15 @@ export const cleanupCommand: Command = { // Actually delete try { const fullPath = join(cwd, item.path); - if (item.type === 'dir') { + // Special handling: surgically clean settings.json instead of deleting + if (item.path === join('.claude', 'settings.json')) { + try { + const raw = JSON.parse(readFileSync(fullPath, 'utf-8')); + delete raw.hooks; + delete raw.claudeFlow; + writeFileSync(fullPath, JSON.stringify(raw, null, 2) + '\n', 'utf-8'); + } catch { /* settings.json parse failed, skip */ } + } else if (item.type === 'dir') { rmSync(fullPath, { recursive: true, force: true }); } else { rmSync(fullPath, { force: true }); diff --git a/v3/@claude-flow/cli/src/commands/daemon.ts b/v3/@claude-flow/cli/src/commands/daemon.ts index 05232781b9..0b94ad8407 100644 --- a/v3/@claude-flow/cli/src/commands/daemon.ts +++ b/v3/@claude-flow/cli/src/commands/daemon.ts @@ -74,10 +74,12 @@ const startCommand: Command = { const bgPid = getBackgroundDaemonPid(projectRoot); if (bgPid && isProcessRunning(bgPid)) { if (!quiet) { - output.printWarning(`Daemon already running in background (PID: ${bgPid})`); + output.printWarning(`Daemon already running in background (PID: ${bgPid}). Stop it first with: daemon stop`); } return { success: true }; } + // #1551: Kill any stale daemon processes that weren't tracked by PID file + await killStaleDaemons(projectRoot, quiet); } // Background mode (default): fork a detached process @@ -347,10 +349,14 @@ const stopCommand: Command = { // Also kill any background daemon by PID const killed = await killBackgroundDaemon(projectRoot); + // #1551: Also kill stale daemon processes not tracked by PID file + await killStaleDaemons(projectRoot, true); + spinner.succeed(killed ? 'Worker daemon stopped' : 'Worker daemon was not running'); } else { await stopDaemon(); await killBackgroundDaemon(projectRoot); + await killStaleDaemons(projectRoot, true); } return { success: true }; @@ -417,6 +423,43 @@ async function killBackgroundDaemon(projectRoot: string): Promise { } } +/** + * Kill stale daemon processes not tracked by the PID file (#1551). + * Uses `ps` to find all daemon processes for this project and kills them. + */ +async function killStaleDaemons(projectRoot: string, quiet: boolean): Promise { + try { + const { execFileSync } = await import('child_process'); + const psOutput = execFileSync('ps', ['-eo', 'pid,command'], { encoding: 'utf-8', timeout: 5000 }); + const lines = psOutput.split('\n'); + const currentPid = process.pid; + const trackedPid = getBackgroundDaemonPid(projectRoot); + let killed = 0; + + for (const line of lines) { + if (!line.includes('daemon start --foreground')) continue; + if (!line.includes('claude-flow') && !line.includes('@claude-flow/cli')) continue; + const pidStr = line.trim().split(/\s+/)[0]; + const pid = parseInt(pidStr, 10); + if (isNaN(pid) || pid === currentPid || pid === trackedPid) continue; + if (!isProcessRunning(pid)) continue; + try { + process.kill(pid, 'SIGTERM'); + killed++; + if (!quiet) { + output.printWarning(`Killed stale daemon process (PID: ${pid})`); + } + } catch { /* ignore — may have exited between check and kill */ } + } + + if (killed > 0 && !quiet) { + output.printInfo(`Cleaned up ${killed} stale daemon process(es)`); + } + } catch { + // ps not available or failed — skip stale cleanup + } +} + /** * Get PID of background daemon from PID file */ diff --git a/v3/@claude-flow/memory/src/auto-memory-bridge.ts b/v3/@claude-flow/memory/src/auto-memory-bridge.ts index 2d4d25f8d0..a853a70257 100644 --- a/v3/@claude-flow/memory/src/auto-memory-bridge.ts +++ b/v3/@claude-flow/memory/src/auto-memory-bridge.ts @@ -168,7 +168,7 @@ type ResolvedConfig = Required