π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(3.7.0-alpha.17): #1565 supervisor, #1856 mid-flight detector, #1857 Windows tasklist
Reuven66f7f644d84e
diff --git a/package.json b/package.jsonindex 565097cf8a..6c8668a945 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "claude-flow",- "version": "3.7.0-alpha.16",+ "version": "3.7.0-alpha.17","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.jsonindex e610c615b4..bf329705de 100644--- a/ruflo/package.json+++ b/ruflo/package.json@@ -1,6 +1,6 @@{"name": "ruflo",- "version": "3.7.0-alpha.16",+ "version": "3.7.0-alpha.17","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/package.json b/v3/@claude-flow/cli/package.jsonindex bd83559c85..0e37dbcfac 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.7.0-alpha.16",+ "version": "3.7.0-alpha.17","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/commands/daemon.ts b/v3/@claude-flow/cli/src/commands/daemon.tsindex 4fae377a6a..68b0c65a26 100644--- a/v3/@claude-flow/cli/src/commands/daemon.ts+++ b/v3/@claude-flow/cli/src/commands/daemon.ts@@ -441,10 +441,18 @@ async function killBackgroundDaemon(projectRoot: string): Promise<boolean> {}/**- * Kill stale daemon processes not tracked by the PID file (#1551).- * Uses `ps` to find all daemon processes for this project and kills them.+ * Kill stale daemon processes not tracked by the PID file (#1551, #1857).+ * Uses `ps` on POSIX and `tasklist` on Windows to find all daemon+ * processes for this project and kill them.*/async function killStaleDaemons(projectRoot: string, quiet: boolean): Promise<void> {+ if (process.platform === 'win32') {+ return killStaleDaemonsWindows(projectRoot, quiet);+ }+ return killStaleDaemonsPosix(projectRoot, quiet);+}++async function killStaleDaemonsPosix(projectRoot: string, quiet: boolean): Promise<void> {try {const { execFileSync } = await import('child_process');const psOutput = execFileSync('ps', ['-eo', 'pid,command'], { encoding: 'utf-8', timeout: 5000 });@@ -477,6 +485,61 @@ async function killStaleDaemons(projectRoot: string, quiet: boolean): Promise<vo}}+/**+ * #1857: Windows replacement for the POSIX `ps -eo pid,command` path.+ * Uses `tasklist /v /fo csv` which returns CSV with the full Window+ * Title column (last field) β Node-spawned daemon processes carry+ * their command line there. Best-effort like the POSIX path: any+ * tooling failure (tasklist missing, parse error, etc.) is swallowed+ * silently so cleanup doesn't break daemon start.+ */+async function killStaleDaemonsWindows(projectRoot: string, quiet: boolean): Promise<void> {+ try {+ const { execFileSync } = await import('child_process');+ // /v includes the Window Title; /fo csv uses comma-separated quoted fields+ const out = execFileSync('tasklist', ['/v', '/fo', 'csv', '/nh'], { encoding: 'utf-8', timeout: 5000 });+ const lines = out.split(/\r?\n/);+ const currentPid = process.pid;+ const trackedPid = getBackgroundDaemonPid(projectRoot);+ let killed = 0;++ for (const line of lines) {+ if (!line.trim()) continue;+ // Match daemon command line markers β the Window Title field+ // typically holds the full invocation. Skip rows that aren't ours.+ if (!line.includes('daemon start --foreground')) continue;+ if (!line.includes('claude-flow') && !line.includes('@claude-flow/cli')) continue;++ // Parse CSV: tasklist quotes each field, so split on `","`+ const fields = line.split(/","/).map(f => f.replace(/^"|"$/g, ''));+ // fields[0] = Image Name, fields[1] = PID, β¦+ const pidStr = fields[1];+ const pid = parseInt(pidStr ?? '', 10);+ if (isNaN(pid) || pid === currentPid || pid === trackedPid) continue;+ if (!isProcessRunning(pid)) continue;++ try {+ // taskkill is the Windows equivalent of kill β /pid <n> /f forces.+ // Use SIGTERM-equivalent (no /f) first; the daemon's signal handler+ // catches and cleans up; force-kill is the next start's job.+ execFileSync('taskkill', ['/pid', String(pid), '/t'], { encoding: 'utf-8', timeout: 5000 });+ killed++;+ if (!quiet) {+ output.printWarning(`Killed stale daemon process (PID: ${pid})`);+ }+ } catch { /* taskkill failed β process may have exited; ignore */ }+ }++ if (killed > 0 && !quiet) {+ output.printInfo(`Cleaned up ${killed} stale daemon process(es)`);+ }+ } catch {+ // tasklist not available or failed β skip stale cleanup. Defensive+ // shape matches the POSIX path. Not tested on Windows by the+ // maintainer; please report regressions on the issue tracker.+ }+}+/*** Get PID of background daemon from PID file*/@@ -747,6 +810,213 @@ function formatTimeUntil(date: Date): string {return `in ${Math.floor(seconds / 86400)}d`;}+// #1565: Supervisor installer subcommand. Writes a native auto-restart+// unit (launchd plist on macOS, systemd-user .service on Linux) so the+// daemon survives crashes and reboots without requiring the operator+// to manually run `daemon start` after every failure.+const installSupervisorCommand: Command = {+ name: 'install-supervisor',+ description: 'Install OS-level auto-restart supervisor (launchd on macOS, systemd-user on Linux)',+ options: [+ { name: 'force', short: 'f', type: 'boolean', description: 'Overwrite existing unit file', default: 'false' },+ { name: 'load', type: 'boolean', description: 'Load/enable the unit immediately', default: 'true' },+ { name: 'dry-run', type: 'boolean', description: 'Print the unit file content without writing', default: 'false' },+ ],+ examples: [+ { command: 'claude-flow daemon install-supervisor', description: 'Install + load (auto-restart enabled)' },+ { command: 'claude-flow daemon install-supervisor --no-load', description: 'Write unit file but do not enable yet' },+ { command: 'claude-flow daemon install-supervisor --dry-run', description: 'Preview the unit file' },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const force = ctx.flags.force === true;+ const load = ctx.flags.load !== false;+ const dryRun = ctx.flags['dry-run'] === true || ctx.flags.dryRun === true;+ const projectRoot = process.cwd();+ const platform = process.platform;++ if (platform === 'win32') {+ output.printError('Windows scheduled-task installer is not yet implemented.');+ output.printInfo('Use Task Scheduler manually, or follow this issue: https://github.com/ruvnet/ruflo/issues/1565');+ return { success: false, exitCode: 1 };+ }+ if (platform !== 'darwin' && platform !== 'linux') {+ output.printError(`Unsupported platform: ${platform}. Supported: darwin (launchd), linux (systemd-user).`);+ return { success: false, exitCode: 1 };+ }++ // Resolve absolute paths the unit file will reference.+ const home = process.env.HOME ?? process.env.USERPROFILE ?? '';+ if (!home) {+ output.printError('HOME/USERPROFILE not set; cannot resolve user unit path.');+ return { success: false, exitCode: 1 };+ }+ const nodeBin = process.execPath;+ const __filename = fileURLToPath(import.meta.url);+ const __dirname = dirname(__filename);+ const cliJs = resolve(join(__dirname, '..', '..', '..', 'bin', 'cli.js'));+ if (!fs.existsSync(cliJs)) {+ output.printError(`CLI not found at: ${cliJs}`);+ return { success: false, exitCode: 1 };+ }++ if (platform === 'darwin') {+ const plistDir = join(home, 'Library', 'LaunchAgents');+ const plistPath = join(plistDir, 'io.ruv.ruflo.daemon.plist');+ const logDir = join(projectRoot, '.claude-flow', 'logs');+ const plist = `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key><string>io.ruv.ruflo.daemon</string>+ <key>ProgramArguments</key>+ <array>+ <string>${nodeBin}</string>+ <string>${cliJs}</string>+ <string>daemon</string><string>start</string><string>--foreground</string><string>--quiet</string>+ </array>+ <key>WorkingDirectory</key><string>${projectRoot}</string>+ <key>RunAtLoad</key><true/>+ <key>KeepAlive</key>+ <dict>+ <key>SuccessfulExit</key><false/>+ <key>Crashed</key><true/>+ </dict>+ <key>ThrottleInterval</key><integer>10</integer>+ <key>StandardOutPath</key><string>${logDir}/supervisor.out.log</string>+ <key>StandardErrorPath</key><string>${logDir}/supervisor.err.log</string>+ <key>EnvironmentVariables</key>+ <dict>+ <key>CLAUDE_FLOW_DAEMON</key><string>1</string>+ </dict>+</dict>+</plist>+`;++ if (dryRun) {+ output.writeln(plist);+ return { success: true };+ }+ if (fs.existsSync(plistPath) && !force) {+ output.printWarning(`Already installed: ${plistPath}`);+ output.printInfo('Use --force to overwrite.');+ return { success: false, exitCode: 1 };+ }+ if (!fs.existsSync(plistDir)) fs.mkdirSync(plistDir, { recursive: true });+ if (!fs.existsSync(logDir)) fs.mkdirSync(logDir, { recursive: true });+ fs.writeFileSync(plistPath, plist, 'utf-8');+ output.printSuccess(`Wrote ${plistPath}`);++ if (load) {+ try {+ const { execFileSync } = await import('child_process');+ // unload first in case a previous version is loaded+ try { execFileSync('launchctl', ['unload', plistPath], { encoding: 'utf-8', timeout: 5000 }); } catch { /* ok */ }+ execFileSync('launchctl', ['load', '-w', plistPath], { encoding: 'utf-8', timeout: 5000 });+ output.printSuccess('Supervisor loaded β daemon will auto-restart on crash and survive reboot.');+ } catch (err) {+ output.printWarning(`launchctl load failed: ${err instanceof Error ? err.message : String(err)}`);+ output.printInfo(`Run manually: launchctl load -w ${plistPath}`);+ }+ } else {+ output.printInfo(`Run when ready: launchctl load -w ${plistPath}`);+ }+ return { success: true };+ }++ // Linux: systemd-user+ const unitDir = join(home, '.config', 'systemd', 'user');+ const unitPath = join(unitDir, 'ruflo-daemon.service');+ const unit = `[Unit]+Description=RuFlo background worker daemon+After=default.target++[Service]+Type=simple+WorkingDirectory=${projectRoot}+Environment=CLAUDE_FLOW_DAEMON=1+ExecStart=${nodeBin} ${cliJs} daemon start --foreground --quiet+Restart=on-failure+RestartSec=10+# Restart on Crashed (signal) too+StartLimitIntervalSec=300+StartLimitBurst=5++[Install]+WantedBy=default.target+`;++ if (dryRun) {+ output.writeln(unit);+ return { success: true };+ }+ if (fs.existsSync(unitPath) && !force) {+ output.printWarning(`Already installed: ${unitPath}`);+ output.printInfo('Use --force to overwrite.');+ return { success: false, exitCode: 1 };+ }+ if (!fs.existsSync(unitDir)) fs.mkdirSync(unitDir, { recursive: true });+ fs.writeFileSync(unitPath, unit, 'utf-8');+ output.printSuccess(`Wrote ${unitPath}`);++ if (load) {+ try {+ const { execFileSync } = await import('child_process');+ execFileSync('systemctl', ['--user', 'daemon-reload'], { encoding: 'utf-8', timeout: 5000 });+ execFileSync('systemctl', ['--user', 'enable', '--now', 'ruflo-daemon.service'], { encoding: 'utf-8', timeout: 10000 });+ output.printSuccess('Supervisor enabled β daemon will auto-restart on crash and survive reboot.');+ output.printInfo('Note: requires `loginctl enable-linger $USER` for restart-after-logout on some distros.');+ } catch (err) {+ output.printWarning(`systemctl --user enable failed: ${err instanceof Error ? err.message : String(err)}`);+ output.printInfo(`Run manually: systemctl --user daemon-reload && systemctl --user enable --now ruflo-daemon.service`);+ }+ } else {+ output.printInfo(`Run when ready: systemctl --user daemon-reload && systemctl --user enable --now ruflo-daemon.service`);+ }+ return { success: true };+ },+};++const uninstallSupervisorCommand: Command = {+ name: 'uninstall-supervisor',+ description: 'Remove the auto-restart supervisor unit (launchd on macOS, systemd-user on Linux)',+ options: [],+ action: async (): Promise<CommandResult> => {+ const platform = process.platform;+ const home = process.env.HOME ?? process.env.USERPROFILE ?? '';++ if (platform === 'darwin') {+ const plistPath = join(home, 'Library', 'LaunchAgents', 'io.ruv.ruflo.daemon.plist');+ try {+ const { execFileSync } = await import('child_process');+ try { execFileSync('launchctl', ['unload', plistPath], { encoding: 'utf-8', timeout: 5000 }); } catch { /* ok */ }+ } catch { /* ignore */ }+ if (fs.existsSync(plistPath)) {+ fs.unlinkSync(plistPath);+ output.printSuccess(`Removed ${plistPath}`);+ } else {+ output.printInfo(`Not installed: ${plistPath}`);+ }+ return { success: true };+ }+ if (platform === 'linux') {+ const unitPath = join(home, '.config', 'systemd', 'user', 'ruflo-daemon.service');+ try {+ const { execFileSync } = await import('child_process');+ try { execFileSync('systemctl', ['--user', 'disable', '--now', 'ruflo-daemon.service'], { encoding: 'utf-8', timeout: 5000 }); } catch { /* ok */ }+ } catch { /* ignore */ }+ if (fs.existsSync(unitPath)) {+ fs.unlinkSync(unitPath);+ output.printSuccess(`Removed ${unitPath}`);+ } else {+ output.printInfo(`Not installed: ${unitPath}`);+ }+ return { success: true };+ }+ output.printError(`Unsupported platform: ${platform}`);+ return { success: false, exitCode: 1 };+ },+};+// Main daemon commandexport const daemonCommand: Command = {name: 'daemon',@@ -757,6 +1027,8 @@ export const daemonCommand: Command = {statusCommand,triggerCommand,enableCommand,+ installSupervisorCommand,+ uninstallSupervisorCommand,],options: [],examples: [diff --git a/v3/@claude-flow/cli/src/services/worker-daemon.ts b/v3/@claude-flow/cli/src/services/worker-daemon.tsindex 7276a8440c..e7e0a90881 100644--- a/v3/@claude-flow/cli/src/services/worker-daemon.ts+++ b/v3/@claude-flow/cli/src/services/worker-daemon.ts@@ -54,6 +54,12 @@ interface WorkerState {failureCount: number;averageDurationMs: number;isRunning: boolean;+ // #1856: track when the worker last *started* in addition to when it+ // last successfully completed (lastRun). On crash recovery we scan for+ // workers where lastStartedAt > lastRun and count them as failed β+ // otherwise their runCount drifts above successCount + failureCount+ // with no diagnostic trail.+ lastStartedAt?: Date;}interface WorkerResult {@@ -427,6 +433,37 @@ export class WorkerDaemon extends EventEmitter {return join(this.projectRoot, '.claude-flow', 'daemon-children.json');}+ /**+ * #1856: detect workers that were mid-flight when the previous daemon+ * lifetime ended. A mid-flight worker has `lastStartedAt > lastRun`+ * (started after the last successful completion). On crash recovery+ * we count these as failures so the run-counter math stays consistent+ * (`runCount === successCount + failureCount`). Workers naturally+ * retry at their next scheduled interval; we deliberately don't+ * immediately re-run because the failure may have been deterministic.+ */+ private detectMidFlightFailures(): void {+ let detected = 0;+ for (const [type, state] of this.workers.entries()) {+ const startedAt = state.lastStartedAt?.getTime() ?? 0;+ const lastRunAt = state.lastRun?.getTime() ?? 0;+ // started after the last successful completion β was mid-flight+ if (startedAt > 0 && startedAt > lastRunAt) {+ state.failureCount++;+ state.isRunning = false;+ // Don't bump runCount β it was already incremented at start+ this.log(+ 'info',+ `Worker ${type} was mid-flight at last crash (started ${state.lastStartedAt?.toISOString()}); counted as failure, will retry at next scheduled interval`,+ );+ detected++;+ }+ }+ if (detected > 0) {+ this.saveState();+ }+ }+/*** Snapshot the currently-active headless worker child PIDs to disk.* Best-effort; failures don't propagate.@@ -570,12 +607,14 @@ export class WorkerDaemon extends EventEmitter {for (const [type, state] of Object.entries(saved.workers)) {const savedState = state as Record<string, unknown>;const lastRunValue = savedState.lastRun;+ const lastStartedAtValue = savedState.lastStartedAt;this.workers.set(type as WorkerType, {runCount: (savedState.runCount as number) || 0,successCount: (savedState.successCount as number) || 0,failureCount: (savedState.failureCount as number) || 0,averageDurationMs: (savedState.averageDurationMs as number) || 0,lastRun: lastRunValue ? new Date(lastRunValue as string) : undefined,+ lastStartedAt: lastStartedAtValue ? new Date(lastStartedAtValue as string) : undefined,nextRun: undefined,isRunning: false,});@@ -677,6 +716,14 @@ export class WorkerDaemon extends EventEmitter {// last-snapshot is the authoritative list.this.reapOrphanedChildren();+ // #1856: detect workers that were mid-flight at the previous crash+ // and count them as failures so runCount/successCount/failureCount+ // stay consistent. Workers retry naturally at their next scheduled+ // interval β we don't immediately re-run them, which avoids a+ // freshly-recovered daemon hammering the same code path that just+ // killed it.+ this.detectMidFlightFailures();+this.running = true;this.startedAt = new Date();this.writePidFile();@@ -877,6 +924,8 @@ export class WorkerDaemon extends EventEmitter {// Track running workerthis.runningWorkers.add(workerConfig.type);state.isRunning = true;+ state.lastStartedAt = new Date(); // #1856: timestamp the start+ this.saveState(); // persist before we run anythingthis.emit('worker:start', { workerId, type: workerConfig.type });this.log('info', `Starting worker: ${workerConfig.type} (${this.runningWorkers.size}/${this.config.maxConcurrent} concurrent)`);@@ -1386,6 +1435,7 @@ export class WorkerDaemon extends EventEmitter {{...state,lastRun: state.lastRun?.toISOString(),+ lastStartedAt: state.lastStartedAt?.toISOString(),nextRun: state.nextRun?.toISOString(),}])