mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-24 06:06:02 +09:00
fix(daemon): self-terminating TTL + idle shutdown, global status --all, honest HNSW/init footguns (#2361)
Carry-forward of the still-open, fixable-in-ruflo findings from pacphi/ruflo-machine-ref (token-leak + honesty investigations). Most of that kit's findings already landed upstream (#2219 SQLite, #2222 route persistence, #2239 encoder collapse in 3.10.11); this addresses what remained. Daemon token-leak (root cause of multi-day background token burn): - worker-daemon: self-terminating lifecycle. New ttlMs (default 24h) + idleShutdownMs (opt-in) config, sourced constructor > config.json (daemon.ttlSecs/idleSecs) > env (RUFLO_DAEMON_TTL_SECS/IDLE_SECS) > default. A monitor (unref'd, 60s) grace-shuts-down via stop()+exit(0), mirroring the signal path so the foreground ref'd keep-alive can't leave a zombie. An explicit 0 disables (preserves run-until-stopped). - daemon command: --ttl flag (forwarded through the background fork) and TTL shown in the status/start boxes. - daemon status --all: global view across every workspace via the same ps/tasklist scan used by kill-stale, reading each workspace's daemon-state.json for age + TTL and flagging daemons past their TTL/12h. Leaked daemons in other workspaces were previously invisible. Honest status / init footguns: - neural status: getHNSWStatus() now reports real capability (@ruvector/core resolvable) vs in-process load, ending the false "HNSW Not loaded" when the package is installed. - init: keep auth-gated cloud MCP servers (ruv-swarm, flow-nexus) opt-in even under --full via a new --cloud-mcp flag (committed .mcp.json + per-session token cost). - claudemd-generator: emit `ruflo@latest mcp start` (matches the actual generated .mcp.json) instead of legacy `@claude-flow/cli@latest`, and note the daemon's token cost + TTL. Tests: TTL/idle precedence + 0-disable + monitor arming; the extractWorkspaceFromDaemonLine helper behind --all; HNSW status contract updated to assert initialized-vs-available separation. Credit: investigation, reproductions, and statistical eval by @pacphi (https://github.com/pacphi/ruflo-machine-ref).
This commit is contained in:
1 parent
d687753cc2
commit
a553da3439
9 files changed
+522
-10
No files matched your search
@@ -12,6 +12,7 @@ import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
resolveWorkspaceFlag,
|
||||
daemonCommandLineBelongsToWorkspace,
|
||||
extractWorkspaceFromDaemonLine,
|
||||
} from '../src/commands/daemon.js';
|
||||
|
||||
const psLine = (root: string, pid = 4242, extra = '') =>
|
||||
@@ -61,6 +62,41 @@ describe('#1914 — daemon workspace scoping', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// #2356 — the inverse helper that powers `daemon status --all`: pull the
|
||||
// workspace root back out of a daemon process command line so leaked daemons
|
||||
// in other workspaces can be enumerated and aged.
|
||||
describe('extractWorkspaceFromDaemonLine', () => {
|
||||
it('extracts the workspace stamped last in the argv', () => {
|
||||
expect(extractWorkspaceFromDaemonLine(psLine('/Users/me/proj-a'))).toBe('/Users/me/proj-a');
|
||||
});
|
||||
|
||||
it('extracts a workspace path containing spaces', () => {
|
||||
const root = '/Users/some user/My Project';
|
||||
expect(extractWorkspaceFromDaemonLine(psLine(root))).toBe(root);
|
||||
});
|
||||
|
||||
it('extracts even when extra flags precede --workspace', () => {
|
||||
expect(extractWorkspaceFromDaemonLine(psLine('/Users/me/proj-a', 7, ' --max-cpu-load 4.0'))).toBe('/Users/me/proj-a');
|
||||
});
|
||||
|
||||
it('tolerates trailing whitespace after the workspace', () => {
|
||||
expect(extractWorkspaceFromDaemonLine(`${psLine('/Users/me/proj-a')} `)).toBe('/Users/me/proj-a');
|
||||
});
|
||||
|
||||
it('returns null for a pre-#1914 daemon line with no --workspace stamp', () => {
|
||||
const legacy = '4242 node /usr/local/lib/node_modules/@claude-flow/cli/bin/cli.js daemon start --foreground --quiet';
|
||||
expect(extractWorkspaceFromDaemonLine(legacy)).toBeNull();
|
||||
});
|
||||
|
||||
it('round-trips with daemonCommandLineBelongsToWorkspace', () => {
|
||||
const root = '/Users/me/proj-a';
|
||||
const line = psLine(root);
|
||||
const extracted = extractWorkspaceFromDaemonLine(line);
|
||||
expect(extracted).toBe(root);
|
||||
expect(daemonCommandLineBelongsToWorkspace(line, extracted as string)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveWorkspaceFlag', () => {
|
||||
it('returns null when the flag is absent / not a string', () => {
|
||||
expect(resolveWorkspaceFlag(undefined)).toBeNull();
|
||||
|
||||
@@ -249,12 +249,21 @@ describe('Memory Initializer', () => {
|
||||
});
|
||||
|
||||
describe('HNSW status', () => {
|
||||
it('should report unavailable when not initialized', async () => {
|
||||
// #2356: `getHNSWStatus()` now separates "loaded in this process"
|
||||
// (`initialized`) from "@ruvector/core capability present" (`available`).
|
||||
// Previously `available` tracked the lazy in-process singleton, so a fresh
|
||||
// `neural status` process always reported "Not loaded" even when the
|
||||
// package was installed — a false negative. After clearing the index the
|
||||
// contract is: not initialized, 0 entries, 384-dim; `available` reflects
|
||||
// whether @ruvector/core is resolvable (env-dependent, so not hard-asserted).
|
||||
it('should report not-initialized after the index is cleared', async () => {
|
||||
const { getHNSWStatus, clearHNSWIndex } = await import('../src/memory/memory-initializer.js');
|
||||
clearHNSWIndex();
|
||||
const status = getHNSWStatus();
|
||||
expect(status.available).toBe(false);
|
||||
expect(status.initialized).toBe(false);
|
||||
expect(status.entryCount).toBe(0);
|
||||
expect(status.dimensions).toBe(384);
|
||||
expect(typeof status.available).toBe('boolean');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -743,4 +743,109 @@ describe('WorkerDaemon resource thresholds', () => {
|
||||
expect(config.resourceThresholds.maxCpuLoad).toBeCloseTo(expectedMaxCpuLoad, 1);
|
||||
});
|
||||
});
|
||||
|
||||
// =========================================================================
|
||||
// #2356 — Self-terminating lifecycle (TTL + idle shutdown)
|
||||
// Caps how long a forgotten daemon can keep dispatching headless worker
|
||||
// sweeps. Precedence: constructor arg > config.json (seconds) > env
|
||||
// (RUFLO_DAEMON_TTL_SECS / RUFLO_DAEMON_IDLE_SECS) > built-in default.
|
||||
// =========================================================================
|
||||
describe('self-terminating lifecycle (ttl/idle)', () => {
|
||||
const TTL_ENV = 'RUFLO_DAEMON_TTL_SECS';
|
||||
const IDLE_ENV = 'RUFLO_DAEMON_IDLE_SECS';
|
||||
let savedTtl: string | undefined;
|
||||
let savedIdle: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
savedTtl = process.env[TTL_ENV];
|
||||
savedIdle = process.env[IDLE_ENV];
|
||||
delete process.env[TTL_ENV];
|
||||
delete process.env[IDLE_ENV];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (savedTtl === undefined) delete process.env[TTL_ENV]; else process.env[TTL_ENV] = savedTtl;
|
||||
if (savedIdle === undefined) delete process.env[IDLE_ENV]; else process.env[IDLE_ENV] = savedIdle;
|
||||
});
|
||||
|
||||
it('defaults ttlMs to 12h and idleShutdownMs to 0 (opt-in)', () => {
|
||||
const config = new WorkerDaemon(tempDir).getStatus().config;
|
||||
expect(config.ttlMs).toBe(12 * 60 * 60 * 1000);
|
||||
expect(config.idleShutdownMs).toBe(0);
|
||||
});
|
||||
|
||||
it('honors RUFLO_DAEMON_TTL_SECS env override (seconds → ms)', () => {
|
||||
process.env[TTL_ENV] = '3600';
|
||||
const config = new WorkerDaemon(tempDir).getStatus().config;
|
||||
expect(config.ttlMs).toBe(3600 * 1000);
|
||||
});
|
||||
|
||||
it('honors an explicit RUFLO_DAEMON_TTL_SECS=0 as "disabled" (not falling back to default)', () => {
|
||||
process.env[TTL_ENV] = '0';
|
||||
const config = new WorkerDaemon(tempDir).getStatus().config;
|
||||
expect(config.ttlMs).toBe(0);
|
||||
});
|
||||
|
||||
it('falls back to default for an invalid/negative env value', () => {
|
||||
process.env[TTL_ENV] = '-5';
|
||||
const config = new WorkerDaemon(tempDir).getStatus().config;
|
||||
expect(config.ttlMs).toBe(12 * 60 * 60 * 1000);
|
||||
});
|
||||
|
||||
it('honors RUFLO_DAEMON_IDLE_SECS env override', () => {
|
||||
process.env[IDLE_ENV] = '7200';
|
||||
const config = new WorkerDaemon(tempDir).getStatus().config;
|
||||
expect(config.idleShutdownMs).toBe(7200 * 1000);
|
||||
});
|
||||
|
||||
it('reads daemon.ttlSecs / daemon.idleSecs from config.json (seconds → ms)', () => {
|
||||
const configFile = join(tempDir, '.claude-flow', 'config.json');
|
||||
writeFileSync(configFile, JSON.stringify({
|
||||
'daemon.ttlSecs': 1800,
|
||||
'daemon.idleSecs': 900,
|
||||
}));
|
||||
const config = new WorkerDaemon(tempDir).getStatus().config;
|
||||
expect(config.ttlMs).toBe(1800 * 1000);
|
||||
expect(config.idleShutdownMs).toBe(900 * 1000);
|
||||
});
|
||||
|
||||
it('honors config.json daemon.ttlSecs=0 as disabled', () => {
|
||||
const configFile = join(tempDir, '.claude-flow', 'config.json');
|
||||
writeFileSync(configFile, JSON.stringify({ 'daemon.ttlSecs': 0 }));
|
||||
const config = new WorkerDaemon(tempDir).getStatus().config;
|
||||
expect(config.ttlMs).toBe(0);
|
||||
});
|
||||
|
||||
it('prefers constructor arg over config.json and env', () => {
|
||||
process.env[TTL_ENV] = '3600';
|
||||
const configFile = join(tempDir, '.claude-flow', 'config.json');
|
||||
writeFileSync(configFile, JSON.stringify({ 'daemon.ttlSecs': 1800 }));
|
||||
const config = new WorkerDaemon(tempDir, { ttlMs: 60_000 }).getStatus().config;
|
||||
expect(config.ttlMs).toBe(60_000);
|
||||
});
|
||||
|
||||
it('prefers config.json over env', () => {
|
||||
process.env[TTL_ENV] = '3600';
|
||||
const configFile = join(tempDir, '.claude-flow', 'config.json');
|
||||
writeFileSync(configFile, JSON.stringify({ 'daemon.ttlSecs': 1800 }));
|
||||
const config = new WorkerDaemon(tempDir).getStatus().config;
|
||||
expect(config.ttlMs).toBe(1800 * 1000);
|
||||
});
|
||||
|
||||
it('does not arm the lifecycle monitor when both limits are disabled', () => {
|
||||
const daemon = new WorkerDaemon(tempDir, { ttlMs: 0, idleShutdownMs: 0 });
|
||||
// startLifecycleMonitor is a no-op when both are 0 — no timer is stored.
|
||||
(daemon as any).startLifecycleMonitor();
|
||||
expect((daemon as any).lifecycleTimer).toBeUndefined();
|
||||
});
|
||||
|
||||
it('arms (and can clear) the lifecycle monitor when a TTL is set', () => {
|
||||
const daemon = new WorkerDaemon(tempDir, { ttlMs: 60_000, idleShutdownMs: 0 });
|
||||
(daemon as any).startLifecycleMonitor();
|
||||
expect((daemon as any).lifecycleTimer).toBeDefined();
|
||||
// The monitor timer must be unref'd so it never keeps the process alive.
|
||||
clearInterval((daemon as any).lifecycleTimer);
|
||||
(daemon as any).lifecycleTimer = undefined;
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,9 @@ const startCommand: Command = {
|
||||
{ name: 'sandbox', type: 'string', description: 'Default sandbox mode for headless workers', choices: ['strict', 'permissive', 'disabled'] },
|
||||
{ name: 'max-cpu-load', type: 'string', description: 'Override maxCpuLoad resource threshold (e.g. 4.0)' },
|
||||
{ name: 'min-free-memory', type: 'string', description: 'Override minFreeMemoryPercent resource threshold (e.g. 15)' },
|
||||
// #2356: self-terminating lifecycle. Caps how long a forgotten daemon can
|
||||
// keep dispatching headless worker sweeps. Default 12h (or RUFLO_DAEMON_TTL_SECS); 0 = run until stopped.
|
||||
{ name: 'ttl', type: 'string', description: 'Max daemon age in seconds before graceful self-shutdown (0 = run until stopped; default 43200 = 12h)' },
|
||||
// #1914: workspace root for this daemon. Set automatically when the
|
||||
// background launcher forks the foreground child so the daemon process
|
||||
// carries its workspace path in argv — `killStaleDaemons` then only
|
||||
@@ -76,6 +79,18 @@ const startCommand: Command = {
|
||||
}
|
||||
}
|
||||
|
||||
// #2356: parse --ttl (seconds → ms). Integer-only so 0 (disable) is valid;
|
||||
// INT_RE forbids the decimals NUMERIC_RE allows, since a TTL is whole seconds.
|
||||
const rawTtl = ctx.flags.ttl as string | undefined;
|
||||
const INT_RE = /^\d+$/;
|
||||
if (rawTtl !== undefined) {
|
||||
if (INT_RE.test(rawTtl)) {
|
||||
config.ttlMs = parseInt(rawTtl, 10) * 1000;
|
||||
} else if (!quiet) {
|
||||
output.printWarning(`Ignoring invalid --ttl value: ${sanitize(rawTtl)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if background daemon already running (skip if we ARE the daemon process)
|
||||
if (!isDaemonProcess) {
|
||||
const bgPid = getBackgroundDaemonPid(projectRoot);
|
||||
@@ -101,6 +116,7 @@ const startCommand: Command = {
|
||||
workers: ctx.flags.workers as string | undefined,
|
||||
headless: ctx.flags.headless as boolean | undefined,
|
||||
sandbox: ctx.flags.sandbox as string | undefined,
|
||||
ttl: rawTtl,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -148,6 +164,9 @@ const startCommand: Command = {
|
||||
[
|
||||
`PID: ${status.pid}`,
|
||||
`Started: ${status.startedAt?.toISOString()}`,
|
||||
status.config.ttlMs > 0
|
||||
? `TTL: ${Math.round(status.config.ttlMs / 3600000)}h (self-shutdown)`
|
||||
: `TTL: off (runs until stopped)`,
|
||||
`Workers: ${status.config.workers.filter(w => w.enabled).length} enabled`,
|
||||
`Max Concurrent: ${status.config.maxConcurrent}`,
|
||||
`Max CPU Load: ${status.config.resourceThresholds.maxCpuLoad}`,
|
||||
@@ -268,6 +287,20 @@ export function daemonCommandLineBelongsToWorkspace(commandLine: string, workspa
|
||||
return commandLine.replace(/[\s"']+$/u, '').endsWith(`--workspace ${workspaceRoot}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* #2356: extract the workspace root from a daemon process command line for the
|
||||
* global `daemon status --all` view. The launcher always appends
|
||||
* `--workspace <root>` as the FINAL argv entry (see startBackgroundDaemon), so
|
||||
* we capture everything after it to end-of-line and strip trailing quotes.
|
||||
* Returns null for pre-#1914 daemons that never stamped a workspace.
|
||||
*/
|
||||
export function extractWorkspaceFromDaemonLine(commandLine: string): string | null {
|
||||
const m = commandLine.match(/--workspace\s+(.+?)\s*$/u);
|
||||
if (!m) return null;
|
||||
const ws = m[1].replace(/["']+$/u, '').trim();
|
||||
return ws.length > 0 ? ws : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start daemon as a detached background process
|
||||
*/
|
||||
@@ -277,10 +310,11 @@ interface ForwardedDaemonFlags {
|
||||
workers?: string;
|
||||
headless?: boolean;
|
||||
sandbox?: string;
|
||||
ttl?: string;
|
||||
}
|
||||
|
||||
async function startBackgroundDaemon(projectRoot: string, quiet: boolean, forwarded: ForwardedDaemonFlags = {}): Promise<CommandResult> {
|
||||
const { maxCpuLoad, minFreeMemory, workers, headless, sandbox } = forwarded;
|
||||
const { maxCpuLoad, minFreeMemory, workers, headless, sandbox, ttl } = forwarded;
|
||||
// Validate and resolve project root
|
||||
const resolvedRoot = resolve(projectRoot);
|
||||
validatePath(resolvedRoot, 'Project root');
|
||||
@@ -355,6 +389,11 @@ async function startBackgroundDaemon(projectRoot: string, quiet: boolean, forwar
|
||||
if (minFreeMemory && SPAWN_NUMERIC_RE.test(minFreeMemory)) {
|
||||
forkArgs.push('--min-free-memory', minFreeMemory);
|
||||
}
|
||||
// #2356: forward the TTL so the background daemon enforces it too. Integer
|
||||
// seconds only (incl. 0 to disable) — reject anything else before it hits argv.
|
||||
if (typeof ttl === 'string' && /^\d+$/.test(ttl)) {
|
||||
forkArgs.push('--ttl', ttl);
|
||||
}
|
||||
// #1968: forward worker-selection / sandbox flags. The previous launcher
|
||||
// dropped these, so `daemon start --workers map` ran with the default
|
||||
// five-worker set instead of just `map`. Validate each before passing
|
||||
@@ -655,6 +694,124 @@ function isProcessRunning(pid: number): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* #2356: enumerate every running ruflo daemon across ALL workspaces. Reuses
|
||||
* the same `ps`/`tasklist` scan as killStaleDaemons but, instead of killing,
|
||||
* returns each live daemon's PID + workspace so `daemon status --all` can
|
||||
* surface daemons leaked in other projects. Best-effort: any tooling failure
|
||||
* yields an empty list (matching the kill-stale paths).
|
||||
*/
|
||||
async function scanRunningDaemons(): Promise<Array<{ pid: number; workspace: string | null }>> {
|
||||
const isWin = process.platform === 'win32';
|
||||
try {
|
||||
const { execFileSync } = await import('child_process');
|
||||
const out = isWin
|
||||
? execFileSync('tasklist', ['/v', '/fo', 'csv', '/nh'], { encoding: 'utf-8', timeout: 5000 })
|
||||
: execFileSync('ps', ['-eo', 'pid,command'], { encoding: 'utf-8', timeout: 5000 });
|
||||
const lines = out.split(/\r?\n/);
|
||||
const found: Array<{ pid: number; workspace: string | null }> = [];
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.includes('daemon start --foreground')) continue;
|
||||
if (!line.includes('claude-flow') && !line.includes('@claude-flow/cli')) continue;
|
||||
|
||||
let pid: number;
|
||||
let cmd: string;
|
||||
if (isWin) {
|
||||
// tasklist /fo csv: quoted fields; PID is field[1], Window Title is last.
|
||||
const fields = line.split(/","/).map(f => f.replace(/^"|"$/g, ''));
|
||||
pid = parseInt(fields[1] ?? '', 10);
|
||||
cmd = fields[fields.length - 1] ?? line;
|
||||
} else {
|
||||
pid = parseInt(line.trim().split(/\s+/)[0], 10);
|
||||
cmd = line;
|
||||
}
|
||||
if (Number.isNaN(pid) || !isProcessRunning(pid)) continue;
|
||||
found.push({ pid, workspace: extractWorkspaceFromDaemonLine(cmd) });
|
||||
}
|
||||
return found;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* #2356: render the global `daemon status --all` view. For each running daemon
|
||||
* it reads that workspace's daemon-state.json to show age + configured TTL,
|
||||
* and flags any daemon that has outlived its TTL (or 12h when TTL is unknown)
|
||||
* as stale — the visibility that was missing when leaked daemons ran for days.
|
||||
*/
|
||||
async function renderAllDaemonsStatus(): Promise<CommandResult> {
|
||||
const daemons = await scanRunningDaemons();
|
||||
output.writeln();
|
||||
|
||||
if (daemons.length === 0) {
|
||||
output.printBox(
|
||||
'No ruflo daemons are running in any workspace.',
|
||||
'RuFlo Daemons (all workspaces)'
|
||||
);
|
||||
return { success: true, data: { daemons: [] } };
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const TWELVE_HOURS_MS = 12 * 60 * 60 * 1000;
|
||||
let staleCount = 0;
|
||||
|
||||
const rows = daemons.map(d => {
|
||||
let startedAt: Date | undefined;
|
||||
let ttlMs: number | undefined;
|
||||
if (d.workspace) {
|
||||
try {
|
||||
const statePath = join(d.workspace, '.claude-flow', 'daemon-state.json');
|
||||
if (fs.existsSync(statePath)) {
|
||||
const st = JSON.parse(fs.readFileSync(statePath, 'utf-8'));
|
||||
if (st?.startedAt) startedAt = new Date(st.startedAt);
|
||||
if (typeof st?.config?.ttlMs === 'number') ttlMs = st.config.ttlMs;
|
||||
}
|
||||
} catch { /* unreadable/partial state — show what we have */ }
|
||||
}
|
||||
|
||||
const ageMs = startedAt ? now - startedAt.getTime() : undefined;
|
||||
const overTtl = ttlMs !== undefined && ttlMs > 0 && ageMs !== undefined && ageMs > ttlMs;
|
||||
const overTwelveH = ageMs !== undefined && ageMs > TWELVE_HOURS_MS;
|
||||
const isStale = overTtl || overTwelveH;
|
||||
if (isStale) staleCount++;
|
||||
|
||||
const ageText = ageMs !== undefined ? formatTimeAgo(startedAt as Date).replace(' ago', '') : '?';
|
||||
const ttlText = ttlMs !== undefined
|
||||
? (ttlMs > 0 ? `${Math.round(ttlMs / 3600000)}h` : 'off')
|
||||
: '?';
|
||||
|
||||
return {
|
||||
pid: isStale ? output.warning(String(d.pid)) : String(d.pid),
|
||||
workspace: d.workspace ?? output.dim('(unknown)'),
|
||||
age: isStale ? output.warning(ageText) : ageText,
|
||||
ttl: ttlText === 'off' ? output.dim('off') : ttlText,
|
||||
};
|
||||
});
|
||||
|
||||
output.printTable({
|
||||
columns: [
|
||||
{ key: 'pid', header: 'PID', width: 8 },
|
||||
{ key: 'age', header: 'Age', width: 8 },
|
||||
{ key: 'ttl', header: 'TTL', width: 6 },
|
||||
{ key: 'workspace', header: 'Workspace', width: 50 },
|
||||
],
|
||||
data: rows,
|
||||
});
|
||||
|
||||
output.writeln();
|
||||
if (staleCount > 0) {
|
||||
output.printWarning(
|
||||
`${staleCount} daemon(s) have outlived their TTL (or have run >12h). Stop one with: cd <workspace> && ruflo daemon stop`
|
||||
);
|
||||
} else {
|
||||
output.printInfo(`${daemons.length} daemon(s) running, all within their TTL.`);
|
||||
}
|
||||
|
||||
return { success: true, data: { daemons: rows.length } };
|
||||
}
|
||||
|
||||
// Status subcommand
|
||||
const statusCommand: Command = {
|
||||
name: 'status',
|
||||
@@ -662,15 +819,24 @@ const statusCommand: Command = {
|
||||
options: [
|
||||
{ name: 'verbose', short: 'v', type: 'boolean', description: 'Show detailed worker statistics' },
|
||||
{ name: 'show-modes', type: 'boolean', description: 'Show worker execution modes (local/headless) and sandbox settings' },
|
||||
// #2356: the default status reads only the CURRENT workspace, so a daemon
|
||||
// leaked in another project is invisible. --all scans every running ruflo
|
||||
// daemon across all workspaces (the global view that surfaces leaks).
|
||||
{ name: 'all', short: 'a', type: 'boolean', description: 'List ruflo daemons across ALL workspaces (global view — surfaces leaked daemons)' },
|
||||
],
|
||||
examples: [
|
||||
{ command: 'claude-flow daemon status', description: 'Show daemon status' },
|
||||
{ command: 'claude-flow daemon status -v', description: 'Show detailed status' },
|
||||
{ command: 'claude-flow daemon status --show-modes', description: 'Show worker execution modes' },
|
||||
{ command: 'claude-flow daemon status --all', description: 'List daemons across all workspaces' },
|
||||
],
|
||||
action: async (ctx: CommandContext): Promise<CommandResult> => {
|
||||
const verbose = ctx.flags.verbose as boolean;
|
||||
const showModes = ctx.flags['show-modes'] as boolean;
|
||||
// #2356: global view across every workspace, not just cwd.
|
||||
if (ctx.flags.all as boolean) {
|
||||
return renderAllDaemonsStatus();
|
||||
}
|
||||
const projectRoot = process.cwd();
|
||||
|
||||
try {
|
||||
@@ -696,6 +862,9 @@ const statusCommand: Command = {
|
||||
`Status: ${statusIcon} ${statusText}${mode}`,
|
||||
`PID: ${displayPid}`,
|
||||
status.startedAt ? `Started: ${status.startedAt.toISOString()}` : '',
|
||||
status.config.ttlMs > 0
|
||||
? `TTL: ${Math.round(status.config.ttlMs / 3600000)}h (self-shutdown)`
|
||||
: `TTL: ${output.dim('off (runs until stopped)')}`,
|
||||
`Workers Enabled: ${status.config.workers.filter(w => w.enabled).length}`,
|
||||
`Max Concurrent: ${status.config.maxConcurrent}`,
|
||||
`Max CPU Load: ${status.config.resourceThresholds.maxCpuLoad}`,
|
||||
|
||||
@@ -234,6 +234,7 @@ const initAction = async (ctx: CommandContext): Promise<CommandResult> => {
|
||||
// set still got `~/.claude/CLAUDE.md` modified. Read the real key.
|
||||
const noGlobal = ctx.flags['no-global'] === true || ctx.flags['global'] === false;
|
||||
const allAgents = ctx.flags['all-agents'] as boolean;
|
||||
const cloudMcp = ctx.flags['cloud-mcp'] as boolean;
|
||||
const codexMode = ctx.flags.codex as boolean;
|
||||
const dualMode = ctx.flags.dual as boolean;
|
||||
const cwd = ctx.cwd;
|
||||
@@ -278,6 +279,12 @@ const initAction = async (ctx: CommandContext): Promise<CommandResult> => {
|
||||
options = { ...MINIMAL_INIT_OPTIONS, targetDir: cwd, force };
|
||||
} else if (full) {
|
||||
options = { ...FULL_INIT_OPTIONS, targetDir: cwd, force };
|
||||
// #2356: keep auth-gated cloud MCP servers opt-in even under --full. They
|
||||
// require a login, get committed into .mcp.json, and add per-session MCP
|
||||
// tool-definition token cost. --cloud-mcp restores the all-three behavior.
|
||||
if (!cloudMcp) {
|
||||
options.mcp = { ...options.mcp, ruvSwarm: false, flowNexus: false };
|
||||
}
|
||||
} else {
|
||||
options = { ...DEFAULT_INIT_OPTIONS, targetDir: cwd, force };
|
||||
}
|
||||
@@ -1118,6 +1125,16 @@ export const initCommand: Command = {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
{
|
||||
// #2356: under --full, the auth-gated cloud MCP servers (ruv-swarm,
|
||||
// flow-nexus) get written into a committed .mcp.json and add MCP
|
||||
// tool-definition token cost every session. Keep them opt-in even with
|
||||
// --full; pass --cloud-mcp to register them.
|
||||
name: 'cloud-mcp',
|
||||
description: 'Register auth-gated cloud MCP servers (ruv-swarm, flow-nexus) in .mcp.json (only relevant with --full)',
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
{
|
||||
name: 'skip-claude',
|
||||
description: 'Skip .claude/ directory creation (runtime only)',
|
||||
|
||||
@@ -485,11 +485,21 @@ const statusCommand: Command = {
|
||||
details: `${stats.patternsLearned} patterns stored`,
|
||||
},
|
||||
{
|
||||
// #2356: distinguish "loaded in this process" from "installed but
|
||||
// not yet loaded" from "not installed". Previously `neural status`
|
||||
// always printed "Not loaded" because it never warms the lazy
|
||||
// singleton — a false negative even when @ruvector/core is present.
|
||||
component: 'HNSW Index',
|
||||
status: hnswStatus.available ? output.success('Ready') : output.dim('Not loaded'),
|
||||
details: hnswStatus.available
|
||||
status: hnswStatus.initialized
|
||||
? output.success('Ready')
|
||||
: hnswStatus.available
|
||||
? output.info('Available')
|
||||
: output.dim('Not installed'),
|
||||
details: hnswStatus.initialized
|
||||
? `${hnswStatus.entryCount} vectors, ${hnswStatus.dimensions}-dim`
|
||||
: '@ruvector/core not available',
|
||||
: hnswStatus.available
|
||||
? '@ruvector/core installed (loads on first vector search)'
|
||||
: '@ruvector/core not available',
|
||||
},
|
||||
{
|
||||
component: 'Embedding Model',
|
||||
|
||||
@@ -182,11 +182,15 @@ function setupAndBoundary(): string {
|
||||
return `## Setup
|
||||
|
||||
\`\`\`bash
|
||||
claude mcp add claude-flow -- npx -y @claude-flow/cli@latest
|
||||
npx @claude-flow/cli@latest daemon start
|
||||
npx @claude-flow/cli@latest doctor --fix
|
||||
claude mcp add claude-flow -- npx -y ruflo@latest mcp start
|
||||
npx ruflo@latest doctor --fix
|
||||
\`\`\`
|
||||
|
||||
> The background \`daemon\` is optional. It runs interval workers that each spawn
|
||||
> a headless \`claude\` session, so it consumes tokens continuously. Start it only
|
||||
> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h
|
||||
> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons).
|
||||
|
||||
**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash.`;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,8 +11,30 @@
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFileMaybeEncrypted, writeFileRestricted } from '../fs-secure.js';
|
||||
|
||||
/**
|
||||
* #2356 — cached, synchronous capability probe for @ruvector/core. `getHNSWStatus`
|
||||
* is sync and is called by `neural status` in a fresh process that never warms
|
||||
* the lazy HNSW singleton, so reporting availability off the warm singleton
|
||||
* alone produced a false "Not loaded — @ruvector/core not available" even when
|
||||
* the package is installed and exposes VectorDb. Resolving the module (without
|
||||
* importing/initializing it) is a faithful, cheap availability signal.
|
||||
*/
|
||||
let _ruvectorCoreResolvable: boolean | undefined;
|
||||
function isRuvectorCoreResolvable(): boolean {
|
||||
if (_ruvectorCoreResolvable !== undefined) return _ruvectorCoreResolvable;
|
||||
try {
|
||||
const req = createRequire(import.meta.url);
|
||||
req.resolve('@ruvector/core');
|
||||
_ruvectorCoreResolvable = true;
|
||||
} catch {
|
||||
_ruvectorCoreResolvable = false;
|
||||
}
|
||||
return _ruvectorCoreResolvable;
|
||||
}
|
||||
|
||||
/**
|
||||
* #1854: previously every site that needed the memory directory hardcoded
|
||||
* `getMemoryRoot()`, so the documented config entry
|
||||
@@ -737,8 +759,13 @@ export function getHNSWStatus(): {
|
||||
};
|
||||
}
|
||||
|
||||
// #2356: `available` now reflects real capability (index already loaded OR
|
||||
// @ruvector/core installed and resolvable), not merely whether the lazy
|
||||
// singleton happens to be warm in this process. `initialized` still reports
|
||||
// whether the in-process index is actually loaded, so callers can tell
|
||||
// "installed but not yet loaded" apart from "loaded".
|
||||
return {
|
||||
available: hnswIndex !== null,
|
||||
available: hnswIndex !== null || isRuvectorCoreResolvable(),
|
||||
initialized: hnswIndex?.initialized ?? false,
|
||||
entryCount: hnswIndex?.entries.size ?? 0,
|
||||
dimensions: hnswIndex?.dimensions ?? 384
|
||||
|
||||
@@ -90,6 +90,13 @@ export interface DaemonConfig {
|
||||
maxCpuLoad: number;
|
||||
minFreeMemoryPercent: number;
|
||||
};
|
||||
// #2356 (carry-forward from pacphi/ruflo-machine-ref token-leak findings):
|
||||
// self-terminating lifecycle so a forgotten daemon cannot run for days
|
||||
// dispatching headless `claude --print` sweeps. ttlMs = graceful shutdown
|
||||
// once daemon age exceeds this (0 disables). idleShutdownMs = graceful
|
||||
// shutdown if no worker has run within this window (0 disables).
|
||||
ttlMs: number;
|
||||
idleShutdownMs: number;
|
||||
workers: WorkerConfig[];
|
||||
}
|
||||
|
||||
@@ -113,6 +120,30 @@ const DEFAULT_WORKERS: WorkerConfigInternal[] = [
|
||||
// Previously 5 min, which caused orphan processes when daemon timeout fired before executor timeout (#1117).
|
||||
const DEFAULT_WORKER_TIMEOUT_MS = 16 * 60 * 1000;
|
||||
|
||||
// #2356 — Self-terminating lifecycle defaults. A background daemon with no
|
||||
// upper bound on its lifetime runs until the box reboots; in the field this
|
||||
// leaked tens of thousands of headless `claude --print` sweeps over many days
|
||||
// (one observed daemon ran 19 days). A 12h default age cap (matching the
|
||||
// pacphi/ruflo-machine-ref kit's proven value) heals a forgotten daemon within
|
||||
// half a day; set RUFLO_DAEMON_TTL_SECS=0 (or `--ttl 0`) to opt out. Idle
|
||||
// shutdown is opt-in (0 = disabled) since a legitimately quiet daemon is not a leak.
|
||||
const DEFAULT_DAEMON_TTL_MS = 12 * 60 * 60 * 1000;
|
||||
const DEFAULT_DAEMON_IDLE_SHUTDOWN_MS = 0;
|
||||
|
||||
/**
|
||||
* Read a non-negative seconds value from an env var and return it as ms.
|
||||
* Unlike the `parseInt(x) || default` idiom used elsewhere, an explicit `0`
|
||||
* is honored (it disables the corresponding limit) rather than falling back
|
||||
* to the default. Invalid / negative / absent values fall back.
|
||||
*/
|
||||
function readEnvSecsAsMs(name: string, defaultMs: number): number {
|
||||
const raw = process.env[name];
|
||||
if (raw === undefined || raw.trim() === '') return defaultMs;
|
||||
const secs = Number.parseInt(raw, 10);
|
||||
if (!Number.isFinite(secs) || secs < 0) return defaultMs;
|
||||
return secs * 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Worker Daemon - Manages background workers with Node.js
|
||||
*/
|
||||
@@ -123,6 +154,9 @@ export class WorkerDaemon extends EventEmitter {
|
||||
// #1845: separate timer for the MCP-dispatch queue poller. Kept off
|
||||
// the per-worker map so stop() clears both kinds without confusion.
|
||||
private queuePollTimer?: NodeJS.Timeout;
|
||||
// #2356: separate timer that enforces the daemon's max-age TTL + idle
|
||||
// shutdown. Cleared in stop() alongside the worker/queue timers.
|
||||
private lifecycleTimer?: NodeJS.Timeout;
|
||||
private running = false;
|
||||
private startedAt?: Date;
|
||||
private projectRoot: string;
|
||||
@@ -187,6 +221,11 @@ export class WorkerDaemon extends EventEmitter {
|
||||
maxCpuLoad: config?.resourceThresholds?.maxCpuLoad ?? fileConfig.maxCpuLoad ?? smartMaxCpuLoad,
|
||||
minFreeMemoryPercent: config?.resourceThresholds?.minFreeMemoryPercent ?? fileConfig.minFreeMemoryPercent ?? defaultMinFreeMemory,
|
||||
},
|
||||
// #2356 — precedence: constructor arg > config.json (daemon.ttlSecs) >
|
||||
// env (RUFLO_DAEMON_TTL_SECS) > built-in default. readEnvSecsAsMs folds
|
||||
// env-or-default and honors an explicit 0 (disable).
|
||||
ttlMs: config?.ttlMs ?? fileConfig.ttlMs ?? readEnvSecsAsMs('RUFLO_DAEMON_TTL_SECS', DEFAULT_DAEMON_TTL_MS),
|
||||
idleShutdownMs: config?.idleShutdownMs ?? fileConfig.idleShutdownMs ?? readEnvSecsAsMs('RUFLO_DAEMON_IDLE_SECS', DEFAULT_DAEMON_IDLE_SHUTDOWN_MS),
|
||||
workers: config?.workers ?? DEFAULT_WORKERS,
|
||||
};
|
||||
|
||||
@@ -339,6 +378,8 @@ export class WorkerDaemon extends EventEmitter {
|
||||
workerTimeoutMs?: number;
|
||||
maxCpuLoad?: number;
|
||||
minFreeMemoryPercent?: number;
|
||||
ttlMs?: number;
|
||||
idleShutdownMs?: number;
|
||||
} {
|
||||
const jsonPath = join(claudeFlowDir, 'config.json');
|
||||
const yamlPath = join(claudeFlowDir, 'config.yaml');
|
||||
@@ -389,12 +430,19 @@ export class WorkerDaemon extends EventEmitter {
|
||||
const rawMinMem = cfg['daemon.resourceThresholds.minFreeMemoryPercent'] ?? raw['daemon.resourceThresholds.minFreeMemoryPercent'];
|
||||
const rawMaxConcurrent = cfg['daemon.maxConcurrent'] ?? raw['daemon.maxConcurrent'];
|
||||
const rawTimeout = cfg['daemon.workerTimeoutMs'] ?? raw['daemon.workerTimeoutMs'];
|
||||
// #2356 — lifecycle limits are configured in SECONDS in config.json
|
||||
// (`daemon.ttlSecs` / `daemon.idleSecs`) for parity with the CLI flag
|
||||
// and env var; stored internally as ms. An explicit 0 disables.
|
||||
const rawTtl = cfg['daemon.ttlSecs'] ?? raw['daemon.ttlSecs'];
|
||||
const rawIdle = cfg['daemon.idleSecs'] ?? raw['daemon.idleSecs'];
|
||||
return {
|
||||
autoStart: typeof raw['daemon.autoStart'] === 'boolean' ? raw['daemon.autoStart'] : undefined,
|
||||
maxConcurrent: (typeof rawMaxConcurrent === 'number' && rawMaxConcurrent > 0) ? rawMaxConcurrent : undefined,
|
||||
workerTimeoutMs: (typeof rawTimeout === 'number' && rawTimeout > 0) ? rawTimeout : undefined,
|
||||
maxCpuLoad: (typeof rawCpuLoad === 'number' && rawCpuLoad > 0 && rawCpuLoad < 1000) ? rawCpuLoad : undefined,
|
||||
minFreeMemoryPercent: (typeof rawMinMem === 'number' && rawMinMem >= 0 && rawMinMem <= 100) ? rawMinMem : undefined,
|
||||
ttlMs: (typeof rawTtl === 'number' && rawTtl >= 0) ? rawTtl * 1000 : undefined,
|
||||
idleShutdownMs: (typeof rawIdle === 'number' && rawIdle >= 0) ? rawIdle * 1000 : undefined,
|
||||
};
|
||||
} catch {
|
||||
return {};
|
||||
@@ -788,6 +836,10 @@ export class WorkerDaemon extends EventEmitter {
|
||||
this.queuePollTimer.unref();
|
||||
}
|
||||
|
||||
// #2356: self-terminating lifecycle. Without an upper bound on lifetime a
|
||||
// forgotten daemon keeps dispatching headless worker sweeps for days.
|
||||
this.startLifecycleMonitor();
|
||||
|
||||
// Save state
|
||||
this.saveState();
|
||||
|
||||
@@ -872,6 +924,12 @@ export class WorkerDaemon extends EventEmitter {
|
||||
this.queuePollTimer = undefined;
|
||||
}
|
||||
|
||||
// #2356: stop the TTL/idle lifecycle monitor.
|
||||
if (this.lifecycleTimer) {
|
||||
clearInterval(this.lifecycleTimer);
|
||||
this.lifecycleTimer = undefined;
|
||||
}
|
||||
|
||||
this.running = false;
|
||||
this.removePidFile();
|
||||
this.saveState();
|
||||
@@ -879,6 +937,83 @@ export class WorkerDaemon extends EventEmitter {
|
||||
this.log('info', 'Daemon stopped');
|
||||
}
|
||||
|
||||
/**
|
||||
* #2356 — Self-terminating lifecycle monitor. A daemon with no upper bound
|
||||
* on its lifetime is the documented root cause of multi-day token leaks:
|
||||
* each interval worker spawns a headless `claude --print` sweep, so a daemon
|
||||
* left running for days dispatches tens of thousands of sessions invisibly.
|
||||
* This timer enforces a max age (`ttlMs`) and an optional idle window
|
||||
* (`idleShutdownMs`), shutting the daemon down gracefully when either trips.
|
||||
* Checked once a minute and `unref()`'d so it never keeps the process alive
|
||||
* on its own. A no-op when both limits are disabled (0).
|
||||
*/
|
||||
private startLifecycleMonitor(): void {
|
||||
const ttlMs = this.config.ttlMs;
|
||||
const idleMs = this.config.idleShutdownMs;
|
||||
if ((!ttlMs || ttlMs <= 0) && (!idleMs || idleMs <= 0)) {
|
||||
return; // both limits disabled — preserve legacy run-until-stopped behavior
|
||||
}
|
||||
|
||||
const CHECK_INTERVAL_MS = 60_000;
|
||||
this.lifecycleTimer = setInterval(() => {
|
||||
if (!this.running) return;
|
||||
const now = Date.now();
|
||||
const startedMs = this.startedAt?.getTime() ?? now;
|
||||
|
||||
if (ttlMs > 0 && now - startedMs >= ttlMs) {
|
||||
void this.selfShutdown(`max age ${Math.round(ttlMs / 1000)}s reached`);
|
||||
return;
|
||||
}
|
||||
if (idleMs > 0) {
|
||||
const lastActivity = this.lastWorkerActivityMs() ?? startedMs;
|
||||
if (now - lastActivity >= idleMs) {
|
||||
void this.selfShutdown(`idle for ${Math.round(idleMs / 1000)}s (no worker activity)`);
|
||||
}
|
||||
}
|
||||
}, CHECK_INTERVAL_MS);
|
||||
if (typeof this.lifecycleTimer.unref === 'function') {
|
||||
this.lifecycleTimer.unref();
|
||||
}
|
||||
|
||||
const parts: string[] = [];
|
||||
if (ttlMs > 0) parts.push(`ttl=${Math.round(ttlMs / 1000)}s`);
|
||||
if (idleMs > 0) parts.push(`idle=${Math.round(idleMs / 1000)}s`);
|
||||
this.log('info', `Lifecycle monitor active (${parts.join(', ')})`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Most recent worker start/finish time across all workers (epoch ms), or
|
||||
* null if no worker has ever started. Used for idle-shutdown detection.
|
||||
*/
|
||||
private lastWorkerActivityMs(): number | null {
|
||||
let latest: number | null = null;
|
||||
for (const state of this.workers.values()) {
|
||||
for (const t of [state.lastRun, state.lastStartedAt]) {
|
||||
if (t) {
|
||||
const ms = t.getTime();
|
||||
if (latest === null || ms > latest) latest = ms;
|
||||
}
|
||||
}
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Graceful self-shutdown triggered by the lifecycle monitor. Mirrors the
|
||||
* signal-handler path (`stop()` then `process.exit(0)`) because the
|
||||
* foreground keep-alive in the daemon command is a *ref'd* `setInterval`
|
||||
* that would otherwise hold the process open after `stop()` clears the
|
||||
* service timers — leaving a zombie that reports stopped but never exits.
|
||||
*/
|
||||
private async selfShutdown(reason: string): Promise<void> {
|
||||
this.log('info', `Daemon self-shutdown: ${reason}`);
|
||||
this.emit('self-shutdown', { reason });
|
||||
try {
|
||||
await this.stop();
|
||||
} catch { /* best-effort — we are exiting regardless */ }
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get daemon status
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user