π 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(daemon): hold lockfile through spawn lifecycle (#2484) (#2505)
rUv016eba0c9b1b
diff --git a/v3/@claude-flow/cli/__tests__/daemon-lockfile-race-2484.test.ts b/v3/@claude-flow/cli/__tests__/daemon-lockfile-race-2484.test.tsnew file mode 100644index 0000000000..0af3e07a7b--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/daemon-lockfile-race-2484.test.ts@@ -0,0 +1,85 @@+/**+ * Regression test for #2484: "Multiple daemon instances spawned per Claude+ * Code session."+ *+ * Original report: 4 identical `daemon start --foreground --quiet` processes+ * per Claude Code session, accumulating to ~1.7 GB swap on a 16 GB machine+ * with 4 concurrent sessions.+ *+ * Root cause: the `daemon start` launcher held a lockfile during the+ * "is a daemon already running?" check (good) but RELEASED it BEFORE calling+ * startBackgroundDaemon (which forks the actual background process and only+ * then writes the PID file). Concurrent callers could land in the window+ * between lock-release and PID-file-write, see neither lock nor PID, and+ * each proceed to spawn their own background daemon.+ *+ * Fix (this PR): hold the lockfile through the entire spawn lifecycle.+ * The lock is now released INSIDE the finally block of the+ * `if (!foreground) { return await startBackgroundDaemon(...) }` path,+ * so the lock-loser ALWAYS sees either an active lock OR a populated PID+ * file β never the empty window.+ *+ * This test is a STATIC contract check on the source: the lock release+ * patterns must NOT appear between the `if (!isDaemonProcess) { ... }`+ * block and the `if (!foreground) {` branch. It does NOT spawn real+ * daemons (those tests are flaky in CI); it asserts the structural+ * property that closes the race window.+ */+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++const DAEMON_SRC = join(+ __dirname,+ '..',+ 'src',+ 'commands',+ 'daemon.ts',+);++describe('#2484 β daemon lockfile race window is closed', () => {+ const src = readFileSync(DAEMON_SRC, 'utf-8');++ it('the lock is released INSIDE the !foreground branch, not before it', () => {+ // The fix marker β finally block inside the background-spawn path.+ expect(src).toMatch(/if \(!foreground\) \{[\s\S]+?try \{[\s\S]+?startBackgroundDaemon[\s\S]+?\} finally \{[\s\S]+?fs\.closeSync\(lockFd\)/);+ });++ it('lockFd is declared in the outer function scope, not block-scoped', () => {+ // Must be visible to the !foreground branch β block-scoping was the bug.+ expect(src).toMatch(/let lockFd: number \| null = null;[\s\S]+?if \(!isDaemonProcess\)/);+ });++ it('the foreground branch also releases the lock before blocking', () => {+ // The foreground path runs forever, so we MUST release the lock first+ // β otherwise a concurrent `daemon start` would wait 5s before+ // recovering via the stale-lockfile fallback.+ expect(src).toMatch(/\/\/ Foreground path: release the lock[\s\S]+?fs\.closeSync\(lockFd\)/);+ });++ it('the early-return path (daemon already running) also releases the lock', () => {+ // dedup-check finds a running daemon β return early β must still+ // release the lock so the NEXT invocation doesn't wait 5s on the stale+ // lockfile fallback.+ expect(src).toMatch(/printWarning\(`Daemon already running[\s\S]{0,400}?fs\.closeSync\(lockFd\)/);+ });++ it('the issue is documented in a code comment so a future refactor cannot un-fix it', () => {+ expect(src).toMatch(/#2484/);+ expect(src).toMatch(/EDortta/);+ });++ it('does NOT contain the old race pattern (lock release inside the original finally)', () => {+ // The original code had a `finally` block IMMEDIATELY after the dedup+ // check that released the lock unconditionally. If that pattern+ // reappears, the race is back. Asserts the OLD lock-release block is+ // not within 60 lines of the lockFd declaration.+ const lockFdLine = src.split('\n').findIndex((l) => l.includes('let lockFd: number | null = null'));+ expect(lockFdLine).toBeGreaterThan(-1);+ const window = src.split('\n').slice(lockFdLine, lockFdLine + 60).join('\n');+ // The dedup block should NOT have a finally that closes lockFd.+ // (The legitimate close-on-early-return is in the IF branch above, not a finally.)+ const finallyCloseCount = (window.match(/\} finally \{[\s\S]+?fs\.closeSync\(lockFd\)/g) || []).length;+ expect(finallyCloseCount).toBe(0);+ });+});diff --git a/v3/@claude-flow/cli/src/commands/daemon.ts b/v3/@claude-flow/cli/src/commands/daemon.tsindex d49450b96d..b3bd5f8989 100644--- a/v3/@claude-flow/cli/src/commands/daemon.ts+++ b/v3/@claude-flow/cli/src/commands/daemon.ts@@ -103,11 +103,23 @@ const startCommand: Command = {// dedup is process-atomic. Lock holder gets to spawn; competing callers// see EEXIST, wait briefly, then re-read the PID file (which the holder// has now written), and return "already running" cleanly.+ // #2484 β previously the lockfile was released BEFORE startBackgroundDaemon+ // ran, opening a race window where a concurrent caller could see no lock+ // AND no PID file (PID hadn't been written yet) and proceed to fork ITS+ // OWN background daemon. EDortta reported 4 identical daemons per Claude+ // Code session on v3.10.37 under exactly this pattern (MCP startup+ // racing with a sibling invocation).+ //+ // Fix: hold the lock across the entire spawn lifecycle (dedup check β+ // killStaleDaemons β fork β PID file write), so the lock-loser ALWAYS+ // sees either a live lock or a populated PID file, never the empty+ // window in between.+ let lockFd: number | null = null;+ let lockFile = '';if (!isDaemonProcess) {const stateDir = join(resolve(projectRoot), '.claude-flow');- const lockFile = join(stateDir, 'daemon.lock');+ lockFile = join(stateDir, 'daemon.lock');try { fs.mkdirSync(stateDir, { recursive: true }); } catch { /* exists */ }- let lockFd: number | null = null;try {lockFd = fs.openSync(lockFile, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY);fs.writeSync(lockFd, String(process.pid));@@ -136,42 +148,70 @@ const startCommand: Command = {throw e;}}+ // Dedup check while holding the lock.try {const bgPid = getBackgroundDaemonPid(projectRoot);if (bgPid && isProcessRunning(bgPid)) {if (!quiet) {output.printWarning(`Daemon already running in background (PID: ${bgPid}). Stop it first with: daemon stop`);}+ // Release the lock on the early-return path.+ if (lockFd !== null) {+ try { fs.closeSync(lockFd); } catch { /* ignore */ }+ try { fs.unlinkSync(lockFile); } catch { /* ignore */ }+ }return { success: true };}// #1551: Kill any stale daemon processes that weren't tracked by PID fileawait killStaleDaemons(projectRoot, quiet);- } finally {- // Release the lock so the lock-loser can re-check (or the next- // legitimate invocation can spawn). startBackgroundDaemon below- // writes the PID file synchronously before returning so the- // post-release re-check finds it.+ } catch (e) {+ // Anything that throws here MUST still release the lock before+ // rethrowing so we don't leave the lockfile behind for future+ // invocations to wait on for 5s before recovering.if (lockFd !== null) {try { fs.closeSync(lockFd); } catch { /* ignore */ }try { fs.unlinkSync(lockFile); } catch { /* ignore */ }+ lockFd = null;}+ throw e;}}- // Background mode (default): fork a detached process.+ // Background mode (default): fork a detached process. The lock (if held)+ // is released AFTER startBackgroundDaemon's PID file write completes β+ // see the cleanup inside startBackgroundDaemon's caller path below.// #1968: previously only forwarded resource thresholds β `--workers`,// `--headless`, and `--sandbox` were dropped on the floor when the// launcher forked the foreground child, so `daemon start --workers map`// got the full default worker set instead.if (!foreground) {- return startBackgroundDaemon(projectRoot, quiet, {- maxCpuLoad: rawMaxCpu,- minFreeMemory: rawMinMem,- workers: ctx.flags.workers as string | undefined,- headless: ctx.flags.headless as boolean | undefined,- sandbox: ctx.flags.sandbox as string | undefined,- ttl: rawTtl,- });+ try {+ return await startBackgroundDaemon(projectRoot, quiet, {+ maxCpuLoad: rawMaxCpu,+ minFreeMemory: rawMinMem,+ workers: ctx.flags.workers as string | undefined,+ headless: ctx.flags.headless as boolean | undefined,+ sandbox: ctx.flags.sandbox as string | undefined,+ ttl: rawTtl,+ });+ } finally {+ // Release the lock NOW β startBackgroundDaemon has either written+ // the PID file (success path) or thrown (in which case the next+ // caller's killStaleDaemons sweep handles the orphan).+ if (lockFd !== null) {+ try { fs.closeSync(lockFd); } catch { /* ignore */ }+ try { fs.unlinkSync(lockFile); } catch { /* ignore */ }+ }+ }+ }++ // Foreground path: release the lock before we start the (potentially+ // long-running) foreground daemon so other callers can dedup against+ // our PID file (foreground writes its own PID).+ if (lockFd !== null) {+ try { fs.closeSync(lockFd); } catch { /* ignore */ }+ try { fs.unlinkSync(lockFile); } catch { /* ignore */ }+ lockFd = null;}// Foreground mode: run in current process (blocks terminal)