Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add daemon background and pid cleanup

Guse6c3cf47cced
diff --git a/src/cli/commands/daemon.test.ts b/src/cli/commands/daemon.test.ts
new file mode 100644
index 000000000..ed9c21388
--- /dev/null
+++ b/src/cli/commands/daemon.test.ts
@@ -0,0 +1,342 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import type { EventEmitter } from "events";
+
+vi.mock("../daemon/daemon.js", () => ({
+ startDaemon: vi.fn(async () => {}),
+}));
+
+vi.mock("../daemon/pidfile.js", () => ({
+ readDaemonPid: vi.fn(() => null),
+ isProcessAlive: vi.fn(() => false),
+ removePidFileIfMatches: vi.fn(),
+}));
+
+vi.mock("../daemon/config.js", () => ({
+ daemonLogFilePath: vi.fn(() => "/tmp/alook/daemon/logs/2026-04-17.log"),
+ pidFilePath: vi.fn(() => "/tmp/fake.pid"),
+}));
+
+vi.mock("fs", () => ({
+ openSync: vi.fn(() => 99),
+ closeSync: vi.fn(),
+ mkdirSync: vi.fn(),
+}));
+
+vi.mock("child_process", () => {
+ const { EventEmitter } = require("events");
+ return {
+ spawn: vi.fn(() => {
+ const child = new EventEmitter();
+ (child as EventEmitter & { pid: number; unref: () => void }).pid = 40000;
+ (child as EventEmitter & { pid: number; unref: () => void }).unref = vi.fn();
+ return child;
+ }),
+ };
+});
+
+import { Command } from "commander";
+import { spawn } from "child_process";
+import { openSync, closeSync, mkdirSync } from "fs";
+import { startDaemon } from "../daemon/daemon.js";
+import {
+ readDaemonPid,
+ isProcessAlive,
+ removePidFileIfMatches,
+} from "../daemon/pidfile.js";
+import { daemonCommand } from "./daemon.js";
+
+const startDaemonMock = vi.mocked(startDaemon);
+const readDaemonPidMock = vi.mocked(readDaemonPid);
+const isProcessAliveMock = vi.mocked(isProcessAlive);
+const removePidFileIfMatchesMock = vi.mocked(removePidFileIfMatches);
+const spawnMock = vi.mocked(spawn);
+const openSyncMock = vi.mocked(openSync);
+const closeSyncMock = vi.mocked(closeSync);
+const mkdirMock = vi.mocked(mkdirSync);
+
+interface ChildLike extends EventEmitter {
+ pid: number;
+ unref: ReturnType<typeof vi.fn>;
+}
+
+function resetAll() {
+ startDaemonMock.mockClear();
+ readDaemonPidMock.mockClear();
+ readDaemonPidMock.mockReturnValue(null);
+ isProcessAliveMock.mockClear();
+ isProcessAliveMock.mockReturnValue(false);
+ removePidFileIfMatchesMock.mockClear();
+ spawnMock.mockClear();
+ openSyncMock.mockClear();
+ closeSyncMock.mockClear();
+ mkdirMock.mockClear();
+}
+
+// Mount the daemon subcommand under a root program with the same top-level
+// --profile / --server flags as the real CLI, so parentOpts resolution is
+// exercised the way users actually invoke it.
+async function runCLI(
+ args: string[],
+ rootFlags: string[] = [],
+): Promise<{ out: string[]; err: string[] }> {
+ const out: string[] = [];
+ const err: string[] = [];
+ const logSpy = vi.spyOn(console, "log").mockImplementation((m: unknown) => {
+ out.push(String(m));
+ });
+ const errSpy = vi.spyOn(console, "error").mockImplementation((m: unknown) => {
+ err.push(String(m));
+ });
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation((m: unknown) => {
+ err.push(String(m));
+ });
+ const exitSpy = vi
+ .spyOn(process, "exit")
+ .mockImplementation(((_code?: number) => {
+ throw new Error("__exit__");
+ }) as never);
+ try {
+ const program = new Command()
+ .name("alook")
+ .option("--server <url>", "Server URL")
+ .option("--profile <name>", "Profile name");
+ program.addCommand(daemonCommand());
+ await program.parseAsync([...rootFlags, "daemon", ...args], {
+ from: "user",
+ });
+ } catch (e) {
+ if (!(e instanceof Error) || e.message !== "__exit__") throw e;
+ } finally {
+ logSpy.mockRestore();
+ errSpy.mockRestore();
+ warnSpy.mockRestore();
+ exitSpy.mockRestore();
+ }
+ return { out, err };
+}
+
+describe("daemon status", () => {
+ beforeEach(resetAll);
+
+ it("prints 'not running' when no pidfile", async () => {
+ const { out } = await runCLI(["status"]);
+ expect(out.join("\n")).toContain("Daemon not running.");
+ });
+
+ it("prints running + pid when alive", async () => {
+ readDaemonPidMock.mockReturnValue(12345);
+ isProcessAliveMock.mockReturnValue(true);
+ const { out } = await runCLI(["status"]);
+ expect(out.join("\n")).toContain("Daemon running (pid=12345)");
+ });
+
+ it("prints stale pidfile when pid is dead", async () => {
+ readDaemonPidMock.mockReturnValue(99999);
+ isProcessAliveMock.mockReturnValue(false);
+ const { out } = await runCLI(["status"]);
+ expect(out.join("\n")).toContain("stale pidfile");
+ });
+});
+
+describe("daemon stop", () => {
+ let killSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ resetAll();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ killSpy?.mockRestore();
+ vi.useRealTimers();
+ });
+
+ it("prints 'not running' and does not signal when no pidfile", async () => {
+ killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
+ const { out } = await runCLI(["stop"]);
+ expect(out.join("\n")).toContain("Daemon not running.");
+ expect(killSpy).not.toHaveBeenCalled();
+ });
+
+ it("sends SIGTERM and reports clean stop when process exits", async () => {
+ readDaemonPidMock.mockReturnValue(777);
+ let alive = true;
+ isProcessAliveMock.mockImplementation(() => alive);
+ killSpy = vi.spyOn(process, "kill").mockImplementation((_p, sig) => {
+ if (sig === "SIGTERM") alive = false;
+ return true;
+ });
+
+ const promise = runCLI(["stop"]);
+ await vi.advanceTimersByTimeAsync(500);
+ const { out } = await promise;
+
+ expect(killSpy).toHaveBeenCalledWith(777, "SIGTERM");
+ expect(killSpy).not.toHaveBeenCalledWith(777, "SIGKILL");
+ expect(out.join("\n")).toContain("Daemon stopped.");
+ });
+
+ it("falls back to SIGKILL and removes pidfile when shutdown times out", async () => {
+ readDaemonPidMock.mockReturnValue(888);
+ let alive = true;
+ isProcessAliveMock.mockImplementation(() => alive);
+ process.env.ALOOK_SHUTDOWN_TIMEOUT_MS = "1000";
+
+ killSpy = vi.spyOn(process, "kill").mockImplementation((_p, sig) => {
+ if (sig === "SIGKILL") alive = false;
+ return true;
+ });
+
+ const promise = runCLI(["stop"]);
+ await vi.advanceTimersByTimeAsync(1500);
+ const { out, err } = await promise;
+
+ expect(killSpy).toHaveBeenCalledWith(888, "SIGTERM");
+ expect(killSpy).toHaveBeenCalledWith(888, "SIGKILL");
+ expect(removePidFileIfMatchesMock).toHaveBeenCalledWith(888, undefined);
+ expect(err.join("\n")).toContain("SIGKILL");
+ expect(out.join("\n")).toContain("Daemon stopped.");
+
+ delete process.env.ALOOK_SHUTDOWN_TIMEOUT_MS;
+ });
+
+ it("cleans up stale pidfile and reports not running when pid is dead", async () => {
+ readDaemonPidMock.mockReturnValue(444);
+ isProcessAliveMock.mockReturnValue(false);
+ killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
+
+ const { out } = await runCLI(["stop"]);
+
+ expect(killSpy).not.toHaveBeenCalled();
+ expect(removePidFileIfMatchesMock).toHaveBeenCalledWith(444, undefined);
+ expect(out.join("\n")).toContain("Daemon not running.");
+ });
+});
+
+describe("daemon start (foreground)", () => {
+ beforeEach(resetAll);
+
+ it("delegates to startDaemon and does not spawn", async () => {
+ await runCLI(["start", "--foreground"]);
+ expect(startDaemonMock).toHaveBeenCalledTimes(1);
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("daemon start (background)", () => {
+ beforeEach(() => {
+ resetAll();
+ vi.useFakeTimers();
+ // Default spawn: fresh EventEmitter with fake pid each call
+ spawnMock.mockImplementation(() => {
+ const { EventEmitter } = require("events");
+ const c = new EventEmitter() as ChildLike;
+ c.pid = 40000;
+ c.unref = vi.fn();
+ return c as never;
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("spawns detached with log fds and reconstructed args", async () => {
+ // Initial pre-check: no daemon running. After spawn: pidfile has pid 55555.
+ let calls = 0;
+ readDaemonPidMock.mockImplementation(() => (++calls === 1 ? null : 55555));
+ isProcessAliveMock.mockImplementation((p: number) => p === 55555);
+
+ const promise = runCLI(["start"]);
+ await vi.advanceTimersByTimeAsync(250);
+ const { out } = await promise;
+
+ expect(startDaemonMock).not.toHaveBeenCalled();
+ expect(spawnMock).toHaveBeenCalledTimes(1);
+ const call = spawnMock.mock.calls[0];
+ expect(call[0]).toBe(process.execPath);
+ const args = call[1] as string[];
+ expect(args).toContain("daemon");
+ expect(args).toContain("start");
+ expect(args).toContain("--foreground");
+ const opts = call[2] as { detached?: boolean; stdio?: unknown };
+ expect(opts.detached).toBe(true);
+ expect(Array.isArray(opts.stdio)).toBe(true);
+ expect((opts.stdio as unknown[])[0]).toBe("ignore");
+ expect((opts.stdio as unknown[])[1]).toBe(99);
+ expect((opts.stdio as unknown[])[2]).toBe(99);
+
+ expect(closeSyncMock).toHaveBeenCalledWith(99);
+
+ expect(out.join("\n")).toContain("Daemon started (pid=55555)");
+ expect(out.join("\n")).toContain("Logs: /tmp/alook/daemon/logs/2026-04-17.log");
+ });
+
+ it("forwards --server to child argv", async () => {
+ let calls = 0;
+ readDaemonPidMock.mockImplementation(() => (++calls === 1 ? null : 101));
+ isProcessAliveMock.mockImplementation((p: number) => p === 101);
+
+ const promise = runCLI(["start", "--server", "http://x.test"]);
+ await vi.advanceTimersByTimeAsync(250);
+ await promise;
+
+ const args = spawnMock.mock.calls[0][1] as string[];
+ const serverIdx = args.indexOf("--server");
+ expect(serverIdx).toBeGreaterThanOrEqual(0);
+ expect(args[serverIdx + 1]).toBe("http://x.test");
+ });
+
+ it("forwards root-level --profile to child argv", async () => {
+ let calls = 0;
+ readDaemonPidMock.mockImplementation(() => (++calls === 1 ? null : 202));
+ isProcessAliveMock.mockImplementation((p: number) => p === 202);
+
+ const promise = runCLI(["start"], ["--profile", "staging"]);
+ await vi.advanceTimersByTimeAsync(250);
+ await promise;
+
+ const args = spawnMock.mock.calls[0][1] as string[];
+ const profileIdx = args.indexOf("--profile");
+ expect(profileIdx).toBeGreaterThanOrEqual(0);
+ expect(args[profileIdx + 1]).toBe("staging");
+ });
+
+ it("forwards root-level --server to child argv", async () => {
+ let calls = 0;
+ readDaemonPidMock.mockImplementation(() => (++calls === 1 ? null : 303));
+ isProcessAliveMock.mockImplementation((p: number) => p === 303);
+
+ const promise = runCLI(["start"], ["--server", "http://root.test"]);
+ await vi.advanceTimersByTimeAsync(250);
+ await promise;
+
+ const args = spawnMock.mock.calls[0][1] as string[];
+ const serverIdx = args.indexOf("--server");
+ expect(serverIdx).toBeGreaterThanOrEqual(0);
+ expect(args[serverIdx + 1]).toBe("http://root.test");
+ });
+
+ it("warns and exits non-zero when pidfile never appears", async () => {
+ readDaemonPidMock.mockReturnValue(null); // never set
+ isProcessAliveMock.mockReturnValue(false);
+
+ const promise = runCLI(["start"]);
+ await vi.advanceTimersByTimeAsync(2500);
+ const { err } = await promise;
+
+ expect(err.join("\n")).toContain("did not write a pidfile");
+ expect(err.join("\n")).toContain("/tmp/alook/daemon/logs/2026-04-17.log");
+ });
+
+ it("refuses to start when another daemon is already alive", async () => {
+ // Pre-existing alive daemon: readDaemonPid returns pid, isProcessAlive true
+ readDaemonPidMock.mockReturnValue(333);
+ isProcessAliveMock.mockReturnValue(true);
+
+ const { err } = await runCLI(["start"]);
+
+ expect(spawnMock).not.toHaveBeenCalled();
+ expect(err.join("\n")).toContain("Daemon already running (pid=333)");
+ });
+});
diff --git a/src/cli/commands/daemon.ts b/src/cli/commands/daemon.ts
index 8ad07ab0f..33299626f 100644
--- a/src/cli/commands/daemon.ts
+++ b/src/cli/commands/daemon.ts
@@ -1,6 +1,134 @@
import { Command } from "commander";
+import { spawn } from "child_process";
+import { openSync, closeSync, mkdirSync } from "fs";
+import { dirname } from "path";
import { startDaemon } from "../daemon/daemon.js";
-import { cmdPrefix } from "../lib/env.js";
+import { daemonLogFilePath, pidFilePath } from "../daemon/config.js";
+import {
+ isProcessAlive,
+ readDaemonPid,
+ removePidFileIfMatches,
+} from "../daemon/pidfile.js";
+
+const PID_POLL_INTERVAL_MS = 200;
+const PID_POLL_TIMEOUT_MS = 2000;
+const STOP_POLL_INTERVAL_MS = 200;
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((r) => setTimeout(r, ms));
+}
+
+function buildChildArgs(profile?: string, serverUrl?: string): string[] {
+ const entry = process.argv[1];
+ const args = [entry];
+ if (profile) args.push("--profile", profile);
+ if (serverUrl) args.push("--server", serverUrl);
+ args.push("daemon", "start", "--foreground");
+ return args;
+}
+
+async function waitForPidFile(profile: string | undefined): Promise<number | null> {
+ const deadline = Date.now() + PID_POLL_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ const pid = readDaemonPid(profile);
+ if (pid != null && isProcessAlive(pid)) return pid;
+ await sleep(PID_POLL_INTERVAL_MS);
+ }
+ return null;
+}
+
+async function startInBackground(
+ profile?: string,
+ serverUrl?: string,
+): Promise<void> {
+ const existing = readDaemonPid(profile);
+ if (existing != null && isProcessAlive(existing)) {
+ console.error(`Daemon already running (pid=${existing}).`);
+ process.exit(1);
+ return;
+ }
+
+ const logPath = daemonLogFilePath();
+ mkdirSync(dirname(logPath), { recursive: true, mode: 0o700 });
+ const logFd = openSync(logPath, "a", 0o600);
+
+ const child = spawn(process.execPath, buildChildArgs(profile, serverUrl), {
+ detached: true,
+ stdio: ["ignore", logFd, logFd],
+ });
+ child.unref();
+ closeSync(logFd);
+
+ const pid = await waitForPidFile(profile);
+ if (pid != null) {
+ console.log(`Daemon started (pid=${pid})`);
+ console.log(`Logs: ${logPath}`);
+ return;
+ }
+ console.error(
+ `Daemon did not write a pidfile within ${PID_POLL_TIMEOUT_MS}ms — check logs: ${logPath}`,
+ );
+ process.exit(1);
+}
+
+function statusCommand(profile: string | undefined): void {
+ const pid = readDaemonPid(profile);
+ const profileSuffix = profile ? ` profile=${profile}` : "";
+ if (pid == null) {
+ console.log(`Daemon not running.${profileSuffix}`);
+ return;
+ }
+ if (!isProcessAlive(pid)) {
+ console.log(
+ `Daemon not running (stale pidfile at ${pidFilePath(profile)}).${profileSuffix}`,
+ );
+ return;
+ }
+ console.log(`Daemon running (pid=${pid})${profileSuffix}`);
+}
+
+async function stopCommand(profile: string | undefined): Promise<void> {
+ const pid = readDaemonPid(profile);
+ if (pid == null) {
+ console.log("Daemon not running.");
+ return;
+ }
+ if (!isProcessAlive(pid)) {
+ removePidFileIfMatches(pid, profile);
+ console.log("Daemon not running.");
+ return;
+ }
+
+ console.log(`Stopping daemon (pid=${pid})...`);
+ try {
+ process.kill(pid, "SIGTERM");
+ } catch (e) {
+ console.error(`Failed to signal daemon: ${e}`);
+ process.exit(1);
+ }
+
+ const shutdownMs =
+ Number(process.env.ALOOK_SHUTDOWN_TIMEOUT_MS) || 5000;
+ const deadline = Date.now() + shutdownMs;
+ while (Date.now() < deadline) {
+ if (!isProcessAlive(pid)) {
+ console.log("Daemon stopped.");
+ return;
+ }
+ await sleep(STOP_POLL_INTERVAL_MS);
+ }
+
+ console.warn(
+ `Daemon did not exit within ${shutdownMs}ms — sending SIGKILL.`,
+ );
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {
+ // already dead
+ }
+ removePidFileIfMatches(pid, profile);
+ console.log("Daemon stopped.");
+}
export function daemonCommand(): Command {
const cmd = new Command("daemon").description("Manage the Alook daemon");
@@ -13,25 +141,30 @@ export function daemonCommand(): Command {
.action(async (opts, command) => {
const parentOpts = command.parent?.parent?.opts() || {};
const profile: string | undefined = parentOpts.profile;
- const serverUrl: string | undefined =
- opts.server || parentOpts.server;
+ const serverUrl: string | undefined = opts.server || parentOpts.server;
- if (!opts.foreground) {
- console.log(
- `Hint: run '${cmdPrefix()} daemon start --foreground' to start the daemon in the foreground.`,
- );
+ if (opts.foreground) {
+ await startDaemon(profile, serverUrl);
return;
}
- await startDaemon(profile, serverUrl);
+ await startInBackground(profile, serverUrl);
});
cmd
.command("status")
.description("Show daemon status")
- .action(() => {
- const port = process.env.ALOOK_HEALTH_PORT || "19514";
- console.log(`check http://localhost:${port}/health`);
+ .action((_opts, command) => {
+ const parentOpts = command.parent?.parent?.opts() || {};
+ statusCommand(parentOpts.profile);
+ });
+
+ cmd
+ .command("stop")
+ .description("Stop the running daemon")
+ .action(async (_opts, command) => {
+ const parentOpts = command.parent?.parent?.opts() || {};
+ await stopCommand(parentOpts.profile);
});
return cmd;
diff --git a/src/cli/daemon/config.test.ts b/src/cli/daemon/config.test.ts
index c983416a3..7d021caf9 100644
--- a/src/cli/daemon/config.test.ts
+++ b/src/cli/daemon/config.test.ts
@@ -2,7 +2,7 @@ import { vi, describe, it, expect, afterEach } from "vitest";
import { hostname } from "os";
import { join } from "path";
import { homedir } from "os";
-import { loadDaemonConfig, normalizeServerBaseURL } from "./config.js";
+import { loadDaemonConfig, normalizeServerBaseURL, daemonLogFilePath, daemonLogDir } from "./config.js";
const DAEMON_ENV_KEYS = [
"ALOOK_SERVER_URL",
@@ -103,6 +103,25 @@ describe("daemonId profile suffix", () => {
});
});
+describe("daemonLogFilePath", () => {
+ it("returns <configDir>/daemon/logs/YYYY-MM-DD.log for a fixed date", () => {
+ const d = new Date(2026, 3, 17); // 2026-04-17 local
+ const p = daemonLogFilePath(d);
+ expect(p).toBe(join(homedir(), ".alook", "daemon", "logs", "2026-04-17.log"));
+ });
+
+ it("zero-pads month and day", () => {
+ const d = new Date(2026, 0, 5); // 2026-01-05 local
+ expect(daemonLogFilePath(d).endsWith("2026-01-05.log")).toBe(true);
+ });
+
+ it("honours ALOOK_PROJECT_ROOT in dev mode", () => {
+ process.env.ALOOK_SERVER_URL = "http://localhost:3000";
+ process.env.ALOOK_PROJECT_ROOT = "/tmp/proj";
+ expect(daemonLogDir()).toBe(join("/tmp/proj", ".alook", "daemon", "logs"));
+ });
+});
+
describe("workspacesRoot profile handling", () => {
it("defaults to ~/.alook/workspaces without profile in production", () => {
const cfg = loadDaemonConfig();
diff --git a/src/cli/daemon/config.ts b/src/cli/daemon/config.ts
index b5686d808..7691f596e 100644
--- a/src/cli/daemon/config.ts
+++ b/src/cli/daemon/config.ts
@@ -7,6 +7,17 @@ export function pidFilePath(profile?: string): string {
return join(configDir(), name);
}
+export function daemonLogDir(): string {
+ return join(configDir(), "daemon", "logs");
+}
+
+export function daemonLogFilePath(date: Date = new Date()): string {
+ const y = date.getFullYear();
+ const m = String(date.getMonth() + 1).padStart(2, "0");
+ const d = String(date.getDate()).padStart(2, "0");
+ return join(daemonLogDir(), `${y}-${m}-${d}.log`);
+}
+
function parseDuration(s: string): number {
if (!s) return 0;
let total = 0;
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
index e7098c164..f888e070c 100644
--- a/src/cli/daemon/daemon.test.ts
+++ b/src/cli/daemon/daemon.test.ts
@@ -95,19 +95,36 @@ vi.mock("path", async () => {
return actual;
});
-// Capture signal handlers and prevent actual process.exit
+// Capture signal handlers and prevent actual process.exit.
+// We also intercept "once" registrations for exit/uncaughtException/unhandledRejection
+// so daemon safety-net handlers don't bleed across tests.
const signalHandlers = new Map<string, (...args: any[]) => any>();
+const capturedEvents = new Set([
+ "SIGTERM",
+ "SIGINT",
+ "exit",
+ "uncaughtException",
+ "unhandledRejection",
+]);
const originalOn = process.on.bind(process);
const mockProcessExit = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
vi.spyOn(process, "on").mockImplementation(((event: string, handler: any) => {
- if (event === "SIGTERM" || event === "SIGINT") {
+ if (capturedEvents.has(event)) {
signalHandlers.set(event, handler);
return process;
}
return originalOn(event, handler);
}) as any);
+vi.spyOn(process, "once").mockImplementation(((event: string, handler: any) => {
+ if (capturedEvents.has(event)) {
+ signalHandlers.set(event, handler);
+ return process;
+ }
+ return process.on(event, handler);
+}) as any);
+
// Track setInterval/clearInterval calls
const realSetInterval = globalThis.setInterval;
const realClearInterval = globalThis.clearInterval;
@@ -127,8 +144,11 @@ vi.spyOn(globalThis, "clearInterval").mockImplementation(((timer: any) => {
import { spawn } from "child_process";
import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";
+import { releaseDaemonPid } from "./pidfile.js";
import { startDaemon, spawnSessionRunner } from "./daemon.js";
+const mockReleaseDaemonPid = vi.mocked(releaseDaemonPid);
+
function decodeSpawnInput(call: any[]): any {
// spawn('bun', ['run', path, encodedInput], opts)
const args = call[1] as string[];
@@ -641,6 +661,117 @@ describe("daemon agent_ids lazy sync", () => {
});
});
+describe("daemon startup failures release pidfile", () => {
+ beforeEach(async () => {
+ signalHandlers.clear();
+ intervalTimers.length = 0;
+ clearedTimers.length = 0;
+ spawnedChildren.length = 0;
+ nextPid = 50000;
+ vi.clearAllMocks();
+ mockProcessExit.mockImplementation((() => {}) as any);
+
+ // Restore defaults that other describe-level tests override.
+ vi.mocked(loadCLIConfigForProfile).mockReturnValue({
+ server_url: "",
+ watched_workspaces: [
+ { id: "ws1", name: "Test WS", token: "al_test_token" },
+ ],
+ });
+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
+ mockClientInstance.poll.mockResolvedValue([]);
+ const cp = await import("child_process");
+ vi.mocked(cp.execSync).mockImplementation(() => undefined as never);
+ });
+
+ afterEach(() => {
+ for (const t of intervalTimers) realClearInterval(t);
+ });
+
+ it("exits with code 1 and logs when no workspaces are configured", async () => {
+ vi.mocked(loadCLIConfigForProfile).mockReturnValue({
+ server_url: "",
+ watched_workspaces: [],
+ });
+ const stderrWrite = vi.spyOn(process.stderr, "write").mockReturnValue(true);
+
+ await startDaemon();
+
+ expect(mockProcessExit.mock.calls[0]?.[0]).toBe(1);
+ const logs = stderrWrite.mock.calls.map((c) => String(c[0])).join("");
+ expect(logs).toContain("No watched workspaces configured.");
+ stderrWrite.mockRestore();
+ });
+
+ it("registers an exit handler that releases the pidfile", async () => {
+ await startDaemon();
+
+ const exitHandler = signalHandlers.get("exit");
+ expect(exitHandler).toBeDefined();
+ mockReleaseDaemonPid.mockClear();
+ exitHandler!();
+ expect(mockReleaseDaemonPid).toHaveBeenCalled();
+ });
+
+ it("uncaughtException handler releases pidfile and exits 1", async () => {
+ await startDaemon();
+
+ const handler = signalHandlers.get("uncaughtException");
+ expect(handler).toBeDefined();
+ mockReleaseDaemonPid.mockClear();
+ mockProcessExit.mockClear();
+ handler!(new Error("boom"));
+ expect(mockReleaseDaemonPid).toHaveBeenCalled();
+ expect(mockProcessExit).toHaveBeenCalledWith(1);
+ });
+
+ it("unhandledRejection handler releases pidfile and exits 1", async () => {
+ await startDaemon();
+
+ const handler = signalHandlers.get("unhandledRejection");
+ expect(handler).toBeDefined();
+ mockReleaseDaemonPid.mockClear();
+ mockProcessExit.mockClear();
+ handler!(new Error("async-boom"));
+ expect(mockReleaseDaemonPid).toHaveBeenCalled();
+ expect(mockProcessExit).toHaveBeenCalledWith(1);
+ });
+
+ it("exits with code 1 and logs when no agent CLI tools are found on PATH", async () => {
+ const cp = await import("child_process");
+ vi.mocked(cp.execSync).mockImplementation(() => {
+ throw new Error("not found");
+ });
+ const stderrWrite = vi.spyOn(process.stderr, "write").mockReturnValue(true);
+
+ await startDaemon();
+
+ expect(mockProcessExit.mock.calls[0]?.[0]).toBe(1);
+ const logs = stderrWrite.mock.calls.map((c) => String(c[0])).join("");
+ expect(logs).toContain("No agent CLI tools found on PATH.");
+ stderrWrite.mockRestore();
+ });
+
+ it("exits with code 1 and logs when every register call fails", async () => {
+ vi.mocked(loadCLIConfigForProfile).mockReturnValue({
+ server_url: "",
+ watched_workspaces: [
+ { id: "ws1", name: "Personal", token: "al_tok_ws1" },
+ { id: "ws2", name: "Team", token: "al_tok_ws2" },
+ ],
+ });
+ mockClientInstance.register.mockRejectedValue(new Error("ECONNREFUSED"));
+ const stderrWrite = vi.spyOn(process.stderr, "write").mockReturnValue(true);
+
+ await startDaemon();
+
+ expect(mockProcessExit.mock.calls[0]?.[0]).toBe(1);
+ const logs = stderrWrite.mock.calls.map((c) => String(c[0])).join("");
+ expect(logs).toContain("No workspaces registered successfully.");
+ stderrWrite.mockRestore();
+ });
+});
+
describe("spawnSessionRunner", () => {
beforeEach(() => {
spawnedChildren.length = 0;
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index 3ab87b05f..5125aa69a 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -40,6 +40,23 @@ export async function startDaemon(
process.exit(1);
}
+ // Safety net: no matter how the process terminates (normal exit, early
+ // process.exit, shutdown timeout kick, uncaughtException), release the
+ // pidfile. `releaseDaemonPid` only deletes when the file still points at us,
+ // so a newer daemon's pidfile is safe.
+ process.once("exit", () => releaseDaemonPid(profile));
+ const bailOnUnexpected = (label: string, err: unknown) => {
+ log.error(`${label} — shutting down`, err);
+ releaseDaemonPid(profile);
+ process.exit(1);
+ };
+ process.once("uncaughtException", (err) =>
+ bailOnUnexpected("uncaughtException", err),
+ );
+ process.once("unhandledRejection", (err) =>
+ bailOnUnexpected("unhandledRejection", err),
+ );
+
const config = loadDaemonConfig(profile);
if (serverUrl) config.serverURL = serverUrl;
@@ -49,6 +66,7 @@ export async function startDaemon(
if (workspaces.length === 0) {
log.error("No watched workspaces configured.");
process.exit(1);
+ return;
}
// Validate: each workspace must have its own token
@@ -58,6 +76,7 @@ export async function startDaemon(
`Config uses old format. Run '${cmdPrefix()} register --token <token>' for each workspace to upgrade.`,
);
process.exit(1);
+ return;
}
// Use server_url from first workspace's config if available
@@ -81,6 +100,7 @@ export async function startDaemon(
if (providers.length === 0) {
log.error("No agent CLI tools found on PATH.");
process.exit(1);
+ return;
}
log.info(
@@ -128,6 +148,7 @@ export async function startDaemon(
if (workspaceStates.length === 0) {
log.error("No workspaces registered successfully.");
process.exit(1);
+ return;
}
const allRuntimeIds = workspaceStates.flatMap((ws) => ws.runtimeIds);
diff --git a/src/cli/daemon/pidfile.test.ts b/src/cli/daemon/pidfile.test.ts
index c52f5f817..701e8db4b 100644
--- a/src/cli/daemon/pidfile.test.ts
+++ b/src/cli/daemon/pidfile.test.ts
@@ -17,7 +17,7 @@ vi.mock("../lib/logger.js", () => ({
log: { error: vi.fn(), info: vi.fn(), warn: vi.fn(), debug: vi.fn() },
}));
-import { acquireDaemonPid, releaseDaemonPid } from "./pidfile.js";
+import { acquireDaemonPid, releaseDaemonPid, isProcessAlive, readDaemonPid } from "./pidfile.js";
describe("pidfile", () => {
beforeEach(() => {
@@ -75,6 +75,18 @@ describe("pidfile", () => {
expect(() => releaseDaemonPid()).not.toThrow();
});
+ it("release does not remove pidfile owned by a different process", () => {
+ writeFileSync(join(testDir, "daemon.pid"), "999999999");
+ releaseDaemonPid();
+ expect(existsSync(join(testDir, "daemon.pid"))).toBe(true);
+ });
+
+ it("release removes pidfile when contents match own pid", () => {
+ writeFileSync(join(testDir, "daemon.pid"), String(process.pid));
+ releaseDaemonPid();
+ expect(existsSync(join(testDir, "daemon.pid"))).toBe(false);
+ });
+
it("uses profile-specific PID file path", () => {
const result = acquireDaemonPid("dev");
expect(result).toBe(true);
@@ -82,3 +94,54 @@ describe("pidfile", () => {
expect(existsSync(join(testDir, "daemon_dev.pid"))).toBe(true);
});
});
+
+describe("isProcessAlive", () => {
+ it("returns true for the current process", () => {
+ expect(isProcessAlive(process.pid)).toBe(true);
+ });
+
+ it("returns false for a PID that does not exist", () => {
+ expect(isProcessAlive(999999999)).toBe(false);
+ });
+});
+
+describe("readDaemonPid", () => {
+ beforeEach(() => {
+ testDir = join(tmpdir(), `pidfile-read-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(testDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ try {
+ for (const name of ["daemon.pid", "daemon_dev.pid"]) {
+ try { unlinkSync(join(testDir, name)); } catch {}
+ }
+ unlinkSync(testDir);
+ } catch {}
+ });
+
+ it("returns null when pidfile is absent", () => {
+ expect(readDaemonPid()).toBeNull();
+ });
+
+ it("returns integer when pidfile contains a number", () => {
+ writeFileSync(join(testDir, "daemon.pid"), "12345");
+ expect(readDaemonPid()).toBe(12345);
+ });
+
+ it("trims whitespace before parsing", () => {
+ writeFileSync(join(testDir, "daemon.pid"), " 42 \n");
+ expect(readDaemonPid()).toBe(42);
+ });
+
+ it("returns null when contents are unparsable", () => {
+ writeFileSync(join(testDir, "daemon.pid"), "not-a-number");
+ expect(readDaemonPid()).toBeNull();
+ });
+
+ it("uses profile-specific path", () => {
+ writeFileSync(join(testDir, "daemon_dev.pid"), "7");
+ expect(readDaemonPid("dev")).toBe(7);
+ expect(readDaemonPid()).toBeNull();
+ });
+});
diff --git a/src/cli/daemon/pidfile.ts b/src/cli/daemon/pidfile.ts
index 9ec241f59..1e41eeaab 100644
--- a/src/cli/daemon/pidfile.ts
+++ b/src/cli/daemon/pidfile.ts
@@ -3,7 +3,7 @@ import { dirname } from "path";
import { pidFilePath } from "./config.js";
import { log } from "../lib/logger.js";
-function isProcessAlive(pid: number): boolean {
+export function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
@@ -12,6 +12,16 @@ function isProcessAlive(pid: number): boolean {
}
}
+export function readDaemonPid(profile?: string): number | null {
+ try {
+ const content = readFileSync(pidFilePath(profile), "utf-8").trim();
+ const pid = parseInt(content, 10);
+ return Number.isNaN(pid) ? null : pid;
+ } catch {
+ return null;
+ }
+}
+
/**
* Write a PID file to prevent duplicate daemon starts.
* Returns true if acquired, false if another daemon is already running.
@@ -38,11 +48,23 @@ export function acquireDaemonPid(profile?: string): boolean {
return true;
}
-/** Remove the PID file on shutdown. */
-export function releaseDaemonPid(profile?: string): void {
+/**
+ * Remove the pidfile only if its contents match the given PID. Prevents a
+ * daemon from deleting someone else's pidfile (e.g. after a PID was reused or
+ * a newer daemon acquired the slot).
+ */
+export function removePidFileIfMatches(pid: number, profile?: string): void {
+ const pidPath = pidFilePath(profile);
+ const onDisk = readDaemonPid(profile);
+ if (onDisk !== pid) return;
try {
- unlinkSync(pidFilePath(profile));
+ unlinkSync(pidPath);
} catch {
- // already removed or never existed
+ // already removed
}
}
+
+/** Remove our own pidfile on shutdown. */
+export function releaseDaemonPid(profile?: string): void {
+ removePidFileIfMatches(process.pid, profile);
+}