mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-03 22:12:01 +09:00
Every ruflo-core plugin hook runs the CLI, and the CLI auto-starts a daemon whenever none is alive, so a daemon the user stopped came back within minutes. daemon stop now writes .claude-flow/daemon.stopped (only in a Ruflo project or an existing .claude-flow/; stop --all marks every stamped workspace). ensureDaemonRunning declines to spawn while the marker exists. An explicit daemon start clears it. The start that auto-start spawns carries RUFLO_DAEMON_AUTOSTARTED=1: it never clears the marker and re-checks it, so a stop that lands after the hook checked still wins. Co-authored-by: r <r@x>
This commit is contained in:
1 parent
d2e33508f4
commit
8a033a4e63
3 files changed
+201
-2
No files matched your search
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* #4654 — after `daemon stop`, the daemon respawned from plugin hooks.
|
||||
*
|
||||
* Every ruflo-core hook runs the CLI, and the CLI auto-starts a daemon when
|
||||
* none is alive (`ensureDaemonRunning`). `daemon stop` now records a stop
|
||||
* marker in `.claude-flow/`; auto-start honours it until an explicit
|
||||
* `daemon start` clears it. Spawning is always injected — nothing real starts.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, existsSync, rmSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import {
|
||||
AUTOSTART_ENV,
|
||||
DAEMON_STOP_MARKER,
|
||||
ensureDaemonRunning,
|
||||
isDaemonStopMarked,
|
||||
writeDaemonStopMarker,
|
||||
} from '../src/services/daemon-autostart.js';
|
||||
import { daemonCommand } from '../src/commands/daemon.js';
|
||||
import type { CommandContext } from '../src/types.js';
|
||||
|
||||
const roots: string[] = [];
|
||||
function project(): string {
|
||||
const cwd = mkdtempSync(join(tmpdir(), 'daemon-stop-4654-'));
|
||||
mkdirSync(join(cwd, '.claude-flow'), { recursive: true });
|
||||
writeFileSync(join(cwd, '.claude-flow', 'config.yaml'), 'version: 3\n');
|
||||
roots.push(cwd);
|
||||
return cwd;
|
||||
}
|
||||
|
||||
function sub(name: string) {
|
||||
const c = daemonCommand.subcommands?.find((s) => s.name === name);
|
||||
if (!c?.action) throw new Error(`no daemon ${name} subcommand`);
|
||||
return c.action;
|
||||
}
|
||||
|
||||
function ctx(cwd: string, flags: Record<string, unknown>): CommandContext {
|
||||
return { args: [], flags: { quiet: true, ...flags }, cwd, interactive: false } as unknown as CommandContext;
|
||||
}
|
||||
|
||||
/** Auto-start with an injected spawn; returns how many daemons it tried to spawn. */
|
||||
function autostart(cwd: string): { spawned: number; reason?: string } {
|
||||
let spawned = 0;
|
||||
const r = ensureDaemonRunning(cwd, { isAlive: () => false, spawnFn: () => { spawned++; } });
|
||||
return { spawned, reason: r.reason };
|
||||
}
|
||||
|
||||
describe('#4654 daemon stop marker', () => {
|
||||
const savedEnv = { auto: process.env.RUFLO_DAEMON_AUTOSTART, spawned: process.env[AUTOSTART_ENV] };
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.RUFLO_DAEMON_AUTOSTART;
|
||||
delete process.env[AUTOSTART_ENV];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
if (savedEnv.auto === undefined) delete process.env.RUFLO_DAEMON_AUTOSTART;
|
||||
else process.env.RUFLO_DAEMON_AUTOSTART = savedEnv.auto;
|
||||
if (savedEnv.spawned === undefined) delete process.env[AUTOSTART_ENV];
|
||||
else process.env[AUTOSTART_ENV] = savedEnv.spawned;
|
||||
for (const r of roots.splice(0)) rmSync(r, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('auto-start without a marker still spawns', () => {
|
||||
const cwd = project();
|
||||
expect(isDaemonStopMarked(cwd)).toBe(false);
|
||||
expect(autostart(cwd).spawned).toBe(1);
|
||||
});
|
||||
|
||||
it('`daemon stop` writes the marker, and auto-start then spawns nothing', async () => {
|
||||
const cwd = project();
|
||||
vi.spyOn(process, 'cwd').mockReturnValue(cwd);
|
||||
|
||||
const res = await sub('stop')(ctx(cwd, {}));
|
||||
expect(res?.success).toBe(true);
|
||||
expect(existsSync(join(cwd, '.claude-flow', DAEMON_STOP_MARKER))).toBe(true);
|
||||
|
||||
const r = autostart(cwd);
|
||||
expect(r.spawned).toBe(0);
|
||||
expect(r.reason).toMatch(/stopped by user/);
|
||||
});
|
||||
|
||||
it('the marker holds for a hook invoked from a subdirectory of the project', () => {
|
||||
const cwd = project();
|
||||
writeDaemonStopMarker(cwd);
|
||||
const nested = join(cwd, 'packages', 'app');
|
||||
mkdirSync(nested, { recursive: true });
|
||||
expect(autostart(nested).spawned).toBe(0);
|
||||
});
|
||||
|
||||
it('an explicit `daemon start` clears the marker so auto-start works again', async () => {
|
||||
const cwd = project();
|
||||
writeDaemonStopMarker(cwd);
|
||||
expect(autostart(cwd).spawned).toBe(0);
|
||||
|
||||
// An invalid --workers list makes start return before it takes the lock or
|
||||
// forks anything; the marker is cleared before that point.
|
||||
const res = await sub('start')(ctx(cwd, { workspace: cwd, workers: 'NOT A WORKER LIST!' }));
|
||||
expect(res?.success).toBe(false);
|
||||
expect(isDaemonStopMarked(cwd)).toBe(false);
|
||||
expect(autostart(cwd).spawned).toBe(1);
|
||||
});
|
||||
|
||||
it('a start spawned by auto-start honours a stop that landed after the hook checked', async () => {
|
||||
const cwd = project();
|
||||
writeDaemonStopMarker(cwd);
|
||||
process.env[AUTOSTART_ENV] = '1';
|
||||
const res = await sub('start')(ctx(cwd, { workspace: cwd }));
|
||||
expect(res?.success).toBe(true);
|
||||
expect(isDaemonStopMarked(cwd)).toBe(true);
|
||||
expect(existsSync(join(cwd, '.claude-flow', 'daemon.pid'))).toBe(false);
|
||||
expect(existsSync(join(cwd, '.claude-flow', 'daemon.lock'))).toBe(false);
|
||||
});
|
||||
|
||||
it('`daemon stop` in a non-ruflo directory does not create .claude-flow/', async () => {
|
||||
const cwd = mkdtempSync(join(tmpdir(), 'daemon-stop-4654-plain-'));
|
||||
roots.push(cwd);
|
||||
vi.spyOn(process, 'cwd').mockReturnValue(cwd);
|
||||
await sub('stop')(ctx(cwd, {}));
|
||||
expect(existsSync(join(cwd, '.claude-flow'))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,13 @@
|
||||
import type { Command, CommandContext, CommandResult } from '../types.js';
|
||||
import { output } from '../output.js';
|
||||
import { WorkerDaemon, getDaemon, startDaemon, stopDaemon, type WorkerType, type DaemonConfig, parseEnabledWorkers } from '../services/worker-daemon.js';
|
||||
import { resolveDaemonProjectRoot } from '../services/daemon-autostart.js';
|
||||
import {
|
||||
AUTOSTART_ENV,
|
||||
clearDaemonStopMarker,
|
||||
isDaemonStopMarked,
|
||||
resolveDaemonProjectRoot,
|
||||
writeDaemonStopMarker,
|
||||
} from '../services/daemon-autostart.js';
|
||||
import { spawn, execFile, fork } from 'child_process';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname, join, resolve, isAbsolute } from 'path';
|
||||
@@ -77,6 +83,18 @@ const startCommand: Command = {
|
||||
?? resolveDaemonProjectRoot(process.cwd());
|
||||
const isDaemonProcess = process.env.CLAUDE_FLOW_DAEMON === '1';
|
||||
|
||||
// #4654: an explicit start re-enables auto-start after `daemon stop`. The
|
||||
// start that auto-start spawned must not clear it, and must re-check it:
|
||||
// a `daemon stop` may have landed after the hook checked, and starting
|
||||
// anyway would bring back the daemon the user just stopped.
|
||||
if (!isDaemonProcess) {
|
||||
if (process.env[AUTOSTART_ENV] === '1') {
|
||||
if (isDaemonStopMarked(projectRoot)) return { success: true };
|
||||
} else {
|
||||
clearDaemonStopMarker(projectRoot);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse resource threshold overrides from CLI flags
|
||||
const config: Partial<DaemonConfig> = {};
|
||||
|
||||
@@ -673,6 +691,10 @@ const stopCommand: Command = {
|
||||
// Git worktrees. Only processes positively identified as ruflo daemons
|
||||
// (via their self-identifying argv) are touched; each receives SIGTERM
|
||||
// so its own shutdown path reaps in-flight Claude process groups.
|
||||
// #4654: record the opt-out first, so a hook firing mid-stop cannot
|
||||
// auto-start a fresh daemon. Cleared only by an explicit `daemon start`.
|
||||
writeDaemonStopMarker(projectRoot);
|
||||
|
||||
if (ctx.flags.all as boolean) {
|
||||
return stopAllDaemons(quiet);
|
||||
}
|
||||
@@ -744,6 +766,8 @@ async function stopAllDaemons(quiet: boolean): Promise<CommandResult> {
|
||||
} else {
|
||||
process.kill(d.pid, 'SIGTERM');
|
||||
}
|
||||
// #4654: keep each stopped workspace stopped until an explicit start.
|
||||
if (d.workspace) writeDaemonStopMarker(d.workspace);
|
||||
stopped++;
|
||||
if (!quiet) {
|
||||
output.printInfo(`Stopping daemon PID ${d.pid}${d.workspace ? ` (${d.workspace})` : ''}`);
|
||||
|
||||
@@ -76,6 +76,54 @@ function autostartDisabledByProjectConfig(projectRoot: string): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* #4654: an explicit `daemon stop` is an opt-out that must survive the next
|
||||
* hook. Every ruflo-core plugin hook (PreToolUse/PostToolUse, PreCompact, Stop)
|
||||
* runs the CLI, and the CLI auto-starts a daemon whenever none is alive, so a
|
||||
* stopped daemon came back within minutes. `daemon stop` now writes this
|
||||
* marker, auto-start honours it, and only an explicit `daemon start` clears it.
|
||||
*/
|
||||
export const DAEMON_STOP_MARKER = 'daemon.stopped';
|
||||
|
||||
/**
|
||||
* Set on the daemon that auto-start spawns, so that spawned `daemon start` does
|
||||
* not clear a stop marker written after auto-start checked it (a `daemon stop`
|
||||
* racing a hook). Only a user-driven start clears the marker.
|
||||
*/
|
||||
export const AUTOSTART_ENV = 'RUFLO_DAEMON_AUTOSTARTED';
|
||||
|
||||
function stopMarkerPath(projectRoot: string): string {
|
||||
return path.join(projectRoot, '.claude-flow', DAEMON_STOP_MARKER);
|
||||
}
|
||||
|
||||
/** True if the user explicitly stopped the daemon for this project (#4654). */
|
||||
export function isDaemonStopMarked(projectRoot: string): boolean {
|
||||
try { return fs.existsSync(stopMarkerPath(projectRoot)); } catch { return false; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Record an explicit `daemon stop` (#4654). Writes only into a directory that is
|
||||
* already a Ruflo project or already has `.claude-flow/`, so `daemon stop` in an
|
||||
* unrelated directory does not litter it. Best-effort; never throws.
|
||||
*/
|
||||
export function writeDaemonStopMarker(projectRoot: string): boolean {
|
||||
try {
|
||||
const dir = path.join(projectRoot, '.claude-flow');
|
||||
if (!fs.existsSync(dir) && !isRufloProject(projectRoot)) return false;
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
stopMarkerPath(projectRoot),
|
||||
JSON.stringify({ stoppedAt: new Date().toISOString(), pid: process.pid }) + '\n',
|
||||
);
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
/** Clear the stop marker. Called by an explicit `daemon start` (#4654). Never throws. */
|
||||
export function clearDaemonStopMarker(projectRoot: string): void {
|
||||
try { fs.unlinkSync(stopMarkerPath(projectRoot)); } catch { /* absent */ }
|
||||
}
|
||||
|
||||
function autostartDisabled(projectRoot: string): boolean {
|
||||
if (/^(0|false|no|off)$/i.test(process.env.RUFLO_DAEMON_AUTOSTART ?? '')) return true;
|
||||
return autostartDisabledByProjectConfig(projectRoot);
|
||||
@@ -167,7 +215,7 @@ const defaultSpawn: SpawnDaemonFn = (projectRoot) => {
|
||||
cwd: projectRoot,
|
||||
detached: true,
|
||||
stdio: 'ignore',
|
||||
env: { ...process.env },
|
||||
env: { ...process.env, [AUTOSTART_ENV]: '1' },
|
||||
});
|
||||
child.unref();
|
||||
};
|
||||
@@ -190,6 +238,9 @@ export function ensureDaemonRunning(
|
||||
if (!isRufloProject(projectRoot)) {
|
||||
return { started: false, reason: 'not a ruflo project' };
|
||||
}
|
||||
if (isDaemonStopMarked(projectRoot)) {
|
||||
return { started: false, reason: 'stopped by user (daemon stop); run `daemon start` to re-enable' };
|
||||
}
|
||||
const alive = (opts.isAlive ?? isDaemonAlive)(projectRoot);
|
||||
if (alive) return { started: false, reason: 'already running' };
|
||||
(opts.spawnFn ?? defaultSpawn)(projectRoot);
|
||||
|
||||
Reference in new issue
Block a user