Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(cli): prevent daemon restart loop during update
Generb0ea5f44a423
diff --git a/src/cli/daemon/config.ts b/src/cli/daemon/config.tsindex 7d19297e6..fc0ca5ece 100644--- a/src/cli/daemon/config.ts+++ b/src/cli/daemon/config.ts@@ -8,6 +8,11 @@ export function pidFilePath(profile?: string): string {return join(configDir(), name);}+export function lastUpdateMarkerPath(profile?: string): string {+ const name = profile ? `last_update_${profile}` : "last_update";+ return join(configDir(), name);+}+export function daemonLogDir(): string {return join(configDir(), "daemon", "logs");}diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.tsindex c6bb3a2a1..f2fe86c2e 100644--- a/src/cli/daemon/daemon.test.ts+++ b/src/cli/daemon/daemon.test.ts@@ -37,6 +37,9 @@ vi.mock("./config.js", () => ({cliVersion: "0.1.0",})),sessionRunnerLogDir: vi.fn(() => "/tmp/alook/daemon/session-runners"),+ lastUpdateMarkerPath: vi.fn((profile?: string) =>+ profile ? `/tmp/alook/last_update_${profile}` : "/tmp/alook/last_update",+ ),}));vi.mock("./health.js", () => ({@@ -66,6 +69,8 @@ vi.mock("./pidfile.js", () => ({vi.mock("./update-handler.js", () => ({handleCliUpdate: vi.fn(),isUpdating: vi.fn(() => false),+ readUpdateMarker: vi.fn(() => null),+ clearUpdateMarker: vi.fn(),}));// Track spawned children@@ -170,7 +175,7 @@ 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 { handleCliUpdate } from "./update-handler.js";+import { handleCliUpdate, readUpdateMarker, clearUpdateMarker } from "./update-handler.js";import { startDaemon, spawnSessionRunner, pruneSessionRunnerLogs } from "./daemon.js";const mockReleaseDaemonPid = vi.mocked(releaseDaemonPid);@@ -1187,7 +1192,29 @@ describe("daemon restart via update", () => {await startDaemon();- expect(handleCliUpdate).toHaveBeenCalledWith("2.0.0", expect.any(Function));+ expect(handleCliUpdate).toHaveBeenCalledWith("2.0.0", expect.any(Function), undefined);+ });++ it("handleCliUpdate is not called when pending_update.version matches cliVersion", async () => {+ vi.clearAllMocks();+ mockProcessExit.mockImplementation((() => {}) as any);++ vi.mocked(loadCLIConfigForProfile).mockReturnValue({+ server_url: "",+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],+ });+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });++ // pending_update version matches cliVersion (0.1.0 from config mock)+ mockClientInstance.poll.mockResolvedValue({+ tasks: [],+ evicted: false,+ pending_update: { version: "0.1.0" },+ });++ await startDaemon();++ expect(handleCliUpdate).not.toHaveBeenCalled();});it("handleCliUpdate is not called when isUpdating returns true", async () => {@@ -1212,4 +1239,40 @@ describe("daemon restart via update", () => {expect(handleCliUpdate).not.toHaveBeenCalled();vi.mocked(isUpdating).mockReturnValue(false);});++ it("clears update marker on startup when current version matches marker", async () => {+ vi.clearAllMocks();+ mockProcessExit.mockImplementation((() => {}) as any);++ vi.mocked(readUpdateMarker).mockReturnValue("0.1.0"); // matches cliVersion++ 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({ tasks: [], evicted: false });++ await startDaemon();++ expect(clearUpdateMarker).toHaveBeenCalled();+ });++ it("does not clear update marker when versions differ", async () => {+ vi.clearAllMocks();+ mockProcessExit.mockImplementation((() => {}) as any);++ vi.mocked(readUpdateMarker).mockReturnValue("0.0.9"); // differs from cliVersion 0.1.0++ 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({ tasks: [], evicted: false });++ await startDaemon();++ expect(clearUpdateMarker).not.toHaveBeenCalled();+ });});diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex 820308f64..9623f4ec5 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -7,7 +7,7 @@ import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.import { log } from "../lib/logger.js";import { cmdPrefix } from "../lib/env.js";import { acquireDaemonPid, releaseDaemonPid } from "./pidfile.js";-import { handleCliUpdate, isUpdating } from "./update-handler.js";+import { handleCliUpdate, isUpdating, readUpdateMarker, clearUpdateMarker } from "./update-handler.js";import { existsSync, mkdirSync, openSync, closeSync, renameSync, readdirSync, statSync, unlinkSync } from "fs";import { execSync, spawn, type ChildProcess } from "child_process";import { fileURLToPath } from "url";@@ -101,6 +101,12 @@ export async function startDaemon(const config = loadDaemonConfig(profile);if (serverUrl) config.serverURL = serverUrl;+ const marker = readUpdateMarker(profile);+ if (marker && marker === config.cliVersion) {+ clearUpdateMarker(profile);+ log.info(`Cleared update marker — now running v${config.cliVersion}`);+ }+const cliConfig = loadCLIConfigForProfile(profile);const workspaces = cliConfig.watched_workspaces || [];@@ -292,8 +298,8 @@ export async function startDaemon(continue;}- if (pending_update && !isUpdating()) {- handleCliUpdate(pending_update.version, () => requestRestart());+ if (pending_update && !isUpdating() && pending_update.version !== config.cliVersion) {+ handleCliUpdate(pending_update.version, () => requestRestart(), profile);}for (const apiTask of apiTasks) {diff --git a/src/cli/daemon/update-handler.test.ts b/src/cli/daemon/update-handler.test.tsindex d9bcdcd10..ca843d023 100644--- a/src/cli/daemon/update-handler.test.ts+++ b/src/cli/daemon/update-handler.test.ts@@ -8,12 +8,35 @@ vi.mock("../lib/logger.js", () => ({log: { info: vi.fn(), error: vi.fn(), debug: vi.fn(), warn: vi.fn() },}));-import { handleCliUpdate, isUpdating, resetUpdateState } from "./update-handler";+const mockReadFileSync = vi.fn();+const mockWriteFileSync = vi.fn();+const mockUnlinkSync = vi.fn();+vi.mock("fs", () => ({+ readFileSync: (...args: any[]) => mockReadFileSync(...args),+ writeFileSync: (...args: any[]) => mockWriteFileSync(...args),+ unlinkSync: (...args: any[]) => mockUnlinkSync(...args),+}));++vi.mock("./config.js", () => ({+ lastUpdateMarkerPath: vi.fn((profile?: string) =>+ profile ? `/tmp/alook/last_update_${profile}` : "/tmp/alook/last_update",+ ),+}));++import {+ handleCliUpdate,+ isUpdating,+ resetUpdateState,+ readUpdateMarker,+ writeUpdateMarker,+ clearUpdateMarker,+} from "./update-handler";describe("update-handler", () => {beforeEach(() => {vi.clearAllMocks();resetUpdateState();+ mockReadFileSync.mockImplementation(() => { throw new Error("ENOENT"); });});it("calls runNpmUpdate and invokes onSuccess on success", async () => {@@ -26,6 +49,19 @@ describe("update-handler", () => {expect(onSuccess).toHaveBeenCalled();});+ it("writes marker file after successful update", async () => {+ mockRunNpmUpdate.mockResolvedValue({ success: true, output: "ok" });+ const onSuccess = vi.fn();++ await handleCliUpdate("1.0.0", onSuccess);++ expect(mockWriteFileSync).toHaveBeenCalledWith(+ "/tmp/alook/last_update",+ "1.0.0",+ { mode: 0o600 },+ );+ });+it("does not call onSuccess on failure", async () => {mockRunNpmUpdate.mockResolvedValue({ success: false, output: "error" });const onSuccess = vi.fn();@@ -35,6 +71,36 @@ describe("update-handler", () => {expect(onSuccess).not.toHaveBeenCalled();});+ it("does not write marker file on failure", async () => {+ mockRunNpmUpdate.mockResolvedValue({ success: false, output: "error" });+ const onSuccess = vi.fn();++ await handleCliUpdate("1.0.0", onSuccess);++ expect(mockWriteFileSync).not.toHaveBeenCalled();+ });++ it("skips update when marker file matches target version", async () => {+ mockReadFileSync.mockReturnValue("1.0.0");+ const onSuccess = vi.fn();++ await handleCliUpdate("1.0.0", onSuccess);++ expect(mockRunNpmUpdate).not.toHaveBeenCalled();+ expect(onSuccess).not.toHaveBeenCalled();+ });++ it("proceeds with update when marker file has different version", async () => {+ mockReadFileSync.mockReturnValue("0.9.0");+ mockRunNpmUpdate.mockResolvedValue({ success: true, output: "ok" });+ const onSuccess = vi.fn();++ await handleCliUpdate("1.0.0", onSuccess);++ expect(mockRunNpmUpdate).toHaveBeenCalledWith("1.0.0");+ expect(onSuccess).toHaveBeenCalled();+ });+it("retries up to 3 times then stops", async () => {mockRunNpmUpdate.mockResolvedValue({ success: false, output: "fail" });const onSuccess = vi.fn();@@ -66,3 +132,47 @@ describe("update-handler", () => {expect(isUpdating()).toBe(false);});});++describe("update marker helpers", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("readUpdateMarker returns version from file", () => {+ mockReadFileSync.mockReturnValue("1.2.3\n");+ expect(readUpdateMarker()).toBe("1.2.3");+ });++ it("readUpdateMarker returns null when file does not exist", () => {+ mockReadFileSync.mockImplementation(() => { throw new Error("ENOENT"); });+ expect(readUpdateMarker()).toBeNull();+ });++ it("writeUpdateMarker writes version to file", () => {+ writeUpdateMarker("2.0.0");+ expect(mockWriteFileSync).toHaveBeenCalledWith(+ "/tmp/alook/last_update",+ "2.0.0",+ { mode: 0o600 },+ );+ });++ it("writeUpdateMarker uses profile path when provided", () => {+ writeUpdateMarker("2.0.0", "staging");+ expect(mockWriteFileSync).toHaveBeenCalledWith(+ "/tmp/alook/last_update_staging",+ "2.0.0",+ { mode: 0o600 },+ );+ });++ it("clearUpdateMarker deletes the marker file", () => {+ clearUpdateMarker();+ expect(mockUnlinkSync).toHaveBeenCalledWith("/tmp/alook/last_update");+ });++ it("clearUpdateMarker does not throw when file is missing", () => {+ mockUnlinkSync.mockImplementation(() => { throw new Error("ENOENT"); });+ expect(() => clearUpdateMarker()).not.toThrow();+ });+});diff --git a/src/cli/daemon/update-handler.ts b/src/cli/daemon/update-handler.tsindex 67ddaf6f2..ce7f5463e 100644--- a/src/cli/daemon/update-handler.ts+++ b/src/cli/daemon/update-handler.ts@@ -1,5 +1,7 @@+import { readFileSync, writeFileSync, unlinkSync } from "fs";import { runNpmUpdate } from "../lib/update.js";import { log } from "../lib/logger.js";+import { lastUpdateMarkerPath } from "./config.js";let updating = false;let retryCount = 0;@@ -14,18 +16,50 @@ export function resetUpdateState(): void {retryCount = 0;}+export function readUpdateMarker(profile?: string): string | null {+ try {+ return readFileSync(lastUpdateMarkerPath(profile), "utf-8").trim() || null;+ } catch {+ return null;+ }+}++export function writeUpdateMarker(version: string, profile?: string): void {+ try {+ writeFileSync(lastUpdateMarkerPath(profile), version, { mode: 0o600 });+ } catch {+ // best-effort+ }+}++export function clearUpdateMarker(profile?: string): void {+ try {+ unlinkSync(lastUpdateMarkerPath(profile));+ } catch {+ // already gone+ }+}+export async function handleCliUpdate(version: string,onSuccess: () => void,+ profile?: string,): Promise<void> {if (updating) return;if (retryCount >= MAX_RETRIES) return;+ const marker = readUpdateMarker(profile);+ if (marker === version) {+ log.info(`Skipping update to v${version} — already attempted (marker exists)`);+ return;+ }+updating = true;try {log.info(`Updating CLI to v${version}...`);const result = await runNpmUpdate(version);if (result.success) {+ writeUpdateMarker(version, profile);log.info(`CLI updated to v${version} — restarting`);onSuccess();} else {diff --git a/src/cli/package.json b/src/cli/package.jsonindex 8cc7aeb2a..a76d3e9ba 100644--- a/src/cli/package.json+++ b/src/cli/package.json@@ -1,6 +1,6 @@{"name": "@alook/cli",- "version": "0.0.10",+ "version": "0.0.11","description": "Alook CLI — register and run always-on AI coding agents.","license": "Apache-2.0","homepage": "https://github.com/alookai/alook#readme",