From 3d402912832cb40001ef67ff2b938ec90cc17c73 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 18:38:46 +0200 Subject: [PATCH 01/13] test: the CLI's status fails at once with the daemon's start error when the launched daemon exits (#760) --- src/cli/index.test.ts | 41 ++++++++++++++++++++++++++++++++++++ src/ports/daemon-launcher.ts | 31 +++++++++++++++++++++++---- src/ports/index.ts | 3 +++ 3 files changed, 71 insertions(+), 4 deletions(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 653b2f75e..86d606cc1 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1485,6 +1485,47 @@ describe("CLI: auto-launch's failed start (#672)", () => { }); }); +describe("CLI: auto-launch's daemon that exits while starting (#760)", () => { + it("status fails at once with the daemon's start error when the launched daemon exits with a fatal line", async () => { + const clock = new FakeClock(0); + const fatal = JSON.stringify({ + message: "Daemon failed to start", + fields: { message: "Found /simlock/state.json, remove it" }, + }); + const launcher = new FakeDaemonLauncher(undefined, { + exit: { code: 1, signal: null }, + output: `older line\n${fatal}\n`, + }); + const output = outputCapture({ + filesystem: new MemoryFilesystem(), + clock, + systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ipc: new MemoryIpcTransport(), + launcher, + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, + }); + let settled = false; + const exitCode = runCli(["status"], output.environmentWith()).then((code) => { + settled = true; + return code; + }); + for (let tick = 0; tick < 100 && !settled; tick += 1) { + clock.advance(50); + await settle(); + await settle(); + } + expect(settled, "status had not settled by 5 s").toBe(true); + expect(clock.now()).toBeLessThan(20_000); + expect(await exitCode).toBe(1); + expect(JSON.parse(output.stderr)).toEqual({ + error: { + code: "DAEMON_STARTUP_FAILED", + message: "The daemon could not start: Found /simlock/state.json, remove it", + }, + }); + }); +}); + describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", () => { it.each([ { closeAfter: "hello", rejectedCredential: false }, diff --git a/src/ports/daemon-launcher.ts b/src/ports/daemon-launcher.ts index 930a345b6..1fd2bc4ec 100644 --- a/src/ports/daemon-launcher.ts +++ b/src/ports/daemon-launcher.ts @@ -4,7 +4,21 @@ import { dirname } from "node:path"; /** Starts the detached daemon owned by the operating system rather than the CLI. */ export interface DaemonLauncher { - launch(): Promise; + launch(): Promise; +} + +export interface DaemonExit { + readonly code: number | null; + readonly signal: string | null; +} + +export interface LaunchedDaemon { + readonly exited: Promise; + readOutput(): Promise; +} + +export function startErrorFrom(_exit: DaemonExit, _output: string): string { + return ""; } /** @@ -35,7 +49,7 @@ export interface NodeDaemonLauncherOptions { export class NodeDaemonLauncher implements DaemonLauncher { constructor(private readonly options: NodeDaemonLauncherOptions) {} - async launch(): Promise { + async launch(): Promise { await mkdir(dirname(this.options.logPath), { recursive: true }); // why: 0600 at creation, like the other files that hold secrets or state under the home: // this `open` is what first creates `daemon.log` for an auto-launched daemon -- the daemon's @@ -58,16 +72,25 @@ export class NodeDaemonLauncher implements DaemonLauncher { } finally { await log.close(); } + return { exited: new Promise(() => undefined), readOutput: async () => "" }; } } export class FakeDaemonLauncher implements DaemonLauncher { launches = 0; - constructor(private readonly onLaunch: () => Promise | void = () => undefined) {} + constructor( + private readonly onLaunch: () => Promise | void = () => undefined, + private readonly result: { readonly exit?: DaemonExit; readonly output?: string } = {}, + ) {} - async launch(): Promise { + async launch(): Promise { this.launches += 1; await this.onLaunch(); + const { exit, output = "" } = this.result; + return { + exited: exit === undefined ? new Promise(() => undefined) : Promise.resolve(exit), + readOutput: async () => output, + }; } } diff --git a/src/ports/index.ts b/src/ports/index.ts index 06f9bdeca..e93a2037b 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -17,9 +17,12 @@ export { } from "./paths.js"; export { DAEMON_STARTUP_TIMEOUT_MS, + type DaemonExit, type DaemonLauncher, FakeDaemonLauncher, + type LaunchedDaemon, NodeDaemonLauncher, + startErrorFrom, } from "./daemon-launcher.js"; export { type IpcConnection, From 8b59da698bb686ea4155c2515c7e6dfc2caa8bb8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 18:39:17 +0200 Subject: [PATCH 02/13] feat(cli): an auto-started daemon that exits while starting fails the command with its start error (#760) --- src/cli/environment.ts | 23 ++++++++++++++++++++++- src/ports/daemon-launcher.ts | 24 ++++++++++++++++++++++-- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/src/cli/environment.ts b/src/cli/environment.ts index 468ff5482..8929ae992 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -8,6 +8,7 @@ import type { SimlockAdminClient } from "../admin/index.js"; import type { ConfigOverrides, ModuleConfigEntry } from "../core/index.js"; import type { Clock, + DaemonExit, DaemonLauncher, Filesystem, IpcConnector, @@ -38,7 +39,11 @@ class AutoLaunchAdminConnector { if (!(await isUnavailable(error))) throw error; } await this.checkConfig(); - await this.launcher.launch(); + const launched = await this.launcher.launch(); + let exit: DaemonExit | undefined; + void launched.exited.then((value) => { + exit = value; + }); // why: the constant lives behind the ports barrel, which loads on the first connection that needs it. const { DAEMON_STARTUP_TIMEOUT_MS } = await import("../ports/index.js"); const deadline = this.clock.now() + DAEMON_STARTUP_TIMEOUT_MS; @@ -50,6 +55,22 @@ class AutoLaunchAdminConnector { } catch (error: unknown) { if (!(await isUnavailable(error))) throw error; lastError = error; + if (exit !== undefined) { + const output = await launched.readOutput().catch(() => ""); + try { + return await this.finishConnection(await this.connectClient(resolveCredential)); + } catch (lastAttempt: unknown) { + if (!(await isUnavailable(lastAttempt))) throw lastAttempt; + } + const { SimlockError } = await import("../contract/index.js"); + const { startErrorFrom } = await import("../ports/index.js"); + throw new SimlockError( + "DAEMON_STARTUP_FAILED", + "transport", + startErrorFrom(exit, output), + {}, + ); + } await new Promise((resolve) => this.clock.setTimer(50, resolve)); } } diff --git a/src/ports/daemon-launcher.ts b/src/ports/daemon-launcher.ts index 1fd2bc4ec..4e8346fae 100644 --- a/src/ports/daemon-launcher.ts +++ b/src/ports/daemon-launcher.ts @@ -17,8 +17,28 @@ export interface LaunchedDaemon { readOutput(): Promise; } -export function startErrorFrom(_exit: DaemonExit, _output: string): string { - return ""; +export function startErrorFrom(exit: DaemonExit, output: string): string { + const lines = output.split("\n"); + for (let index = lines.length - 1; index >= 0; index -= 1) { + const message = fatalMessage(lines[index] ?? ""); + if (message !== undefined) return `The daemon could not start: ${message}`; + } + return `The daemon exited with code ${String(exit.code ?? exit.signal)} while starting; see \`simlock daemon logs\``; +} + +function fatalMessage(line: string): string | undefined { + let record: unknown; + try { + record = JSON.parse(line); + } catch { + return undefined; + } + if (typeof record !== "object" || record === null) return undefined; + const { message, fields } = record as { message?: unknown; fields?: unknown }; + if (message !== "Daemon failed to start") return undefined; + if (typeof fields !== "object" || fields === null) return undefined; + const detail = (fields as { message?: unknown }).message; + return typeof detail === "string" ? detail : undefined; } /** From 554a66911116e2f68010d5f2d5da9a4907bf9431 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 18:40:28 +0200 Subject: [PATCH 03/13] test: the CLI's status goes on with the winner when the launched daemon exits already running (#760) --- src/cli/index.test.ts | 59 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 86d606cc1..8dc7c4be5 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1526,6 +1526,65 @@ describe("CLI: auto-launch's daemon that exits while starting (#760)", () => { }); }); +describe("CLI: auto-launch's daemon that lost the socket to another daemon (#760)", () => { + it("status goes on with the daemon that holds the socket when the launched daemon exits already running", async () => { + const filesystem = new MemoryFilesystem(); + const clock = new FakeClock(0); + // why: the winner is not listening yet at the first poll after the launch, so the loop reaches + // the launched daemon's exit before it finds the winner. + class LateWinnerTransport extends MemoryIpcTransport { + connects = 0; + override async connect(endpoint: string): ReturnType { + this.connects += 1; + if (this.connects === 2) { + throw new IpcError("endpoint-not-found", `No IPC endpoint at ${endpoint}`, undefined); + } + return super.connect(endpoint); + } + } + const ipcTransport = new LateWinnerTransport(); + const launcher = new FakeDaemonLauncher( + async () => { + await startInMemoryDaemon({ + adminTokenPath: "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/simlock/admin.token", + filesystem, + ipcTransport, + socketPath: "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/simlock/daemon.sock", + }); + }, + { + exit: { code: 1, signal: null }, + output: `${JSON.stringify({ + message: "Daemon failed to start", + fields: { message: "Simlock daemon is already running at /simlock/daemon.sock" }, + })}\n`, + }, + ); + const output = outputCapture({ + filesystem, + clock, + systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ipc: ipcTransport, + launcher, + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, + }); + let settled = false; + const exitCode = runCli(["status"], output.environmentWith()).then((code) => { + settled = true; + return code; + }); + for (let tick = 0; tick < 100 && !settled; tick += 1) { + clock.advance(50); + await settle(); + await settle(); + } + expect(settled, "status had not settled by 5 s").toBe(true); + expect(await exitCode).toBe(0); + expect(output.stderr).not.toContain("DAEMON_STARTUP_FAILED"); + expect(ipcTransport.connects).toBeGreaterThanOrEqual(3); + }); +}); + describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", () => { it.each([ { closeAfter: "hello", rejectedCredential: false }, From c2722a1a9edab7fa8d764d8386c13f7a251a2784 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 18:40:42 +0200 Subject: [PATCH 04/13] test: startErrorFrom names the last fatal line's message, else the exit code or signal (#760) --- src/ports/daemon-launcher.test.ts | 52 ++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/src/ports/daemon-launcher.test.ts b/src/ports/daemon-launcher.test.ts index 668260437..b645ff70d 100644 --- a/src/ports/daemon-launcher.test.ts +++ b/src/ports/daemon-launcher.test.ts @@ -3,7 +3,7 @@ import { mkdtemp, readFile, readdir, rm, stat } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { NodeDaemonLauncher } from "./daemon-launcher.js"; +import { NodeDaemonLauncher, startErrorFrom } from "./daemon-launcher.js"; describe("NodeDaemonLauncher", () => { it("rejects asynchronous spawn failures", async () => { @@ -94,3 +94,53 @@ describe("NodeDaemonLauncher", () => { } }); }); + +describe("startErrorFrom", () => { + it("names the last fatal line's message, else the exit code or signal", () => { + const fatal = (message: string): string => + JSON.stringify({ message: "Daemon failed to start", fields: { message } }); + const info = JSON.stringify({ message: "Daemon listening", fields: { message: "ready" } }); + const exit1 = { code: 1, signal: null }; + const cases = [ + { + label: "the fatal line alone", + exit: exit1, + output: `${fatal("boom")}\n`, + error: "The daemon could not start: boom", + }, + { + label: "the fatal line after other lines", + exit: exit1, + output: `${info}\n${fatal("boom")}\n`, + error: "The daemon could not start: boom", + }, + { + label: "two fatal lines", + exit: exit1, + output: `${fatal("first")}\n${fatal("second")}\n`, + error: "The daemon could not start: second", + }, + { + label: "no fatal line, code 1", + exit: exit1, + output: `${info}\n`, + error: "The daemon exited with code 1 while starting; see `simlock daemon logs`", + }, + { + label: "no fatal line, SIGKILL", + exit: { code: null, signal: "SIGKILL" }, + output: "", + error: "The daemon exited with code SIGKILL while starting; see `simlock daemon logs`", + }, + { + label: "a non-JSON line before the fatal line", + exit: exit1, + output: `not json\n${fatal("boom")}\n`, + error: "The daemon could not start: boom", + }, + ]; + expect(cases.map((c) => ({ label: c.label, error: startErrorFrom(c.exit, c.output) }))).toEqual( + cases.map((c) => ({ label: c.label, error: c.error })), + ); + }); +}); From 94d99abba89496bfda3c055d82ea6bde4022ee57 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 18:41:37 +0200 Subject: [PATCH 05/13] test: NodeDaemonLauncher's exited gives the exit code and readOutput only the log bytes since the launch (#760) --- src/ports/daemon-launcher.test.ts | 34 ++++++++++++++++++++++++++++++- src/ports/daemon-launcher.ts | 2 +- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/ports/daemon-launcher.test.ts b/src/ports/daemon-launcher.test.ts index b645ff70d..4ed1a57c8 100644 --- a/src/ports/daemon-launcher.test.ts +++ b/src/ports/daemon-launcher.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { mkdtemp, readFile, readdir, rm, stat } from "node:fs/promises"; +import { mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -95,6 +95,38 @@ describe("NodeDaemonLauncher", () => { }); }); +describe("NodeDaemonLauncher's LaunchedDaemon", () => { + it("gives the exit code and only the log bytes written since the launch, across a rotation too", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-launcher-")); + const logPath = join(directory, "daemon.log"); + const older = `${JSON.stringify({ message: "Daemon failed to start", fields: { message: "older" } })}\n`; + const launch = async (script: string) => { + await rm(logPath, { force: true }); + await rm(`${logPath}.1`, { force: true }); + await writeFile(logPath, older); + const launched = await new NodeDaemonLauncher({ + args: ["-e", script, logPath], + command: process.execPath, + logPath, + simlockHome: directory, + }).launch(); + return { exit: await launched.exited, output: await launched.readOutput() }; + }; + try { + const plain = await launch("console.log('newer'); process.exit(1)"); + const rotated = await launch( + "const fs = require('node:fs'); const p = process.argv[1]; fs.renameSync(p, p + '.1'); console.log('tail'); fs.writeFileSync(p, 'fatal\\n'); process.exit(2)", + ); + expect({ plain, rotated }).toEqual({ + plain: { exit: { code: 1, signal: null }, output: "newer\n" }, + rotated: { exit: { code: 2, signal: null }, output: "tail\nfatal\n" }, + }); + } finally { + await rm(directory, { force: true, recursive: true }); + } + }); +}); + describe("startErrorFrom", () => { it("names the last fatal line's message, else the exit code or signal", () => { const fatal = (message: string): string => diff --git a/src/ports/daemon-launcher.ts b/src/ports/daemon-launcher.ts index 4e8346fae..0b35a05dc 100644 --- a/src/ports/daemon-launcher.ts +++ b/src/ports/daemon-launcher.ts @@ -92,7 +92,7 @@ export class NodeDaemonLauncher implements DaemonLauncher { } finally { await log.close(); } - return { exited: new Promise(() => undefined), readOutput: async () => "" }; + return { exited: Promise.resolve({ code: null, signal: null }), readOutput: async () => "" }; } } From a4f4ec705bbcf0edc809c883b3e8421b671cdd2f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 18:42:00 +0200 Subject: [PATCH 06/13] feat(ports): NodeDaemonLauncher reports the daemon's exit and the log since the launch (#760) --- src/ports/daemon-launcher.ts | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/src/ports/daemon-launcher.ts b/src/ports/daemon-launcher.ts index 0b35a05dc..ef3d5033e 100644 --- a/src/ports/daemon-launcher.ts +++ b/src/ports/daemon-launcher.ts @@ -1,5 +1,5 @@ import { spawn } from "node:child_process"; -import { mkdir, open } from "node:fs/promises"; +import { mkdir, open, readFile, stat } from "node:fs/promises"; import { dirname } from "node:path"; /** Starts the detached daemon owned by the operating system rather than the CLI. */ @@ -75,6 +75,8 @@ export class NodeDaemonLauncher implements DaemonLauncher { // this `open` is what first creates `daemon.log` for an auto-launched daemon -- the daemon's // own sink only appends to the file this one made. const log = await open(this.options.logPath, "a", 0o600); + const { ino, size } = await log.stat(); + const logPath = this.options.logPath; try { const child = spawn(this.options.command, this.options.args, { detached: true, @@ -84,15 +86,18 @@ export class NodeDaemonLauncher implements DaemonLauncher { env: { ...process.env, SIMLOCK_HOME: this.options.simlockHome }, stdio: ["ignore", log.fd, log.fd], }); + const exited = new Promise((resolve) => { + child.once("exit", (code, signal) => resolve({ code, signal })); + }); await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); }); child.unref(); + return { exited, readOutput: () => readLogSince(logPath, ino, size) }; } finally { await log.close(); } - return { exited: Promise.resolve({ code: null, signal: null }), readOutput: async () => "" }; } } @@ -114,3 +119,19 @@ export class FakeDaemonLauncher implements DaemonLauncher { }; } } + +const MAX_OUTPUT_BYTES = 64 * 1024; + +// why: `NodeFileLogSink` rotates by renaming the log to `.1`, so the bytes written since +// the launch can sit in either file; the inode noted at launch says which one is the old log. +async function readLogSince(logPath: string, ino: number, size: number): Promise { + const chunks: Buffer[] = []; + if ((await stat(logPath)).ino === ino) { + chunks.push((await readFile(logPath)).subarray(size)); + } else { + const rotatedPath = `${logPath}.1`; + if ((await stat(rotatedPath)).ino !== ino) throw new Error("daemon.log was replaced"); + chunks.push((await readFile(rotatedPath)).subarray(size), await readFile(logPath)); + } + return Buffer.concat(chunks).subarray(-MAX_OUTPUT_BYTES).toString("utf8"); +} From d981c217d87447ec8e2ae5ed8b657bdf5199399d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 18:42:38 +0200 Subject: [PATCH 07/13] test: a parent that launched a daemon and awaits nothing exits while the daemon keeps running (#760) --- src/ports/daemon-launcher.test.ts | 41 +++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/ports/daemon-launcher.test.ts b/src/ports/daemon-launcher.test.ts index 4ed1a57c8..457288c28 100644 --- a/src/ports/daemon-launcher.test.ts +++ b/src/ports/daemon-launcher.test.ts @@ -1,4 +1,6 @@ import { describe, expect, it } from "vitest"; +import { spawn } from "node:child_process"; +import { fileURLToPath } from "node:url"; import { mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -127,6 +129,45 @@ describe("NodeDaemonLauncher's LaunchedDaemon", () => { }); }); +describe("NodeDaemonLauncher in a parent that awaits nothing", () => { + it("lets the parent process exit while the launched daemon keeps running", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-launcher-")); + const launcherModule = fileURLToPath(new URL("./daemon-launcher.ts", import.meta.url)); + const parentScript = ` + const { NodeDaemonLauncher } = await import(${JSON.stringify(launcherModule)}); + const launcher = new NodeDaemonLauncher({ + args: ["-e", "console.log(process.pid); setTimeout(() => {}, 30000)"], + command: process.execPath, + logPath: ${JSON.stringify(join(directory, "daemon.log"))}, + simlockHome: ${JSON.stringify(directory)}, + }); + await launcher.launch(); + `; + const parent = spawn( + process.execPath, + ["--experimental-transform-types", "--input-type=module", "-e", parentScript], + { stdio: "ignore" }, + ); + let childPid: number | undefined; + try { + const outcome = await Promise.race([ + new Promise((resolve) => parent.once("exit", () => resolve("parent exited"))), + new Promise((resolve) => setTimeout(() => resolve("parent still running"), 8000)), + ]); + expect(outcome).toBe("parent exited"); + await expect + .poll(async () => (await readFile(join(directory, "daemon.log"), "utf8")).trim()) + .toMatch(/^\d+$/); + childPid = Number((await readFile(join(directory, "daemon.log"), "utf8")).trim()); + expect(() => process.kill(childPid as number, 0)).not.toThrow(); + } finally { + parent.kill(); + if (childPid !== undefined) process.kill(childPid); + await rm(directory, { force: true, recursive: true }); + } + }); +}); + describe("startErrorFrom", () => { it("names the last fatal line's message, else the exit code or signal", () => { const fatal = (message: string): string => From d5b5c80c10ad36f079bc3b535e4fb899e2338a37 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 18:43:46 +0200 Subject: [PATCH 08/13] test: connectWithAutoLaunch rejects with the start error as soon as the launched daemon exits (#760) --- src/mcp/connect.test.ts | 82 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 81 insertions(+), 1 deletion(-) diff --git a/src/mcp/connect.test.ts b/src/mcp/connect.test.ts index 2684e2193..abcd622aa 100644 --- a/src/mcp/connect.test.ts +++ b/src/mcp/connect.test.ts @@ -2,7 +2,7 @@ // default startup deadline it shares with the CLI's own loop (#663). import { describe, expect, it } from "vitest"; -import { FakeClock, FakeDaemonLauncher, MemoryIpcTransport } from "../ports/index.js"; +import { FakeClock, FakeDaemonLauncher, IpcError, MemoryIpcTransport } from "../ports/index.js"; import { connectWithAutoLaunch } from "./connect.js"; const settle = (): Promise => new Promise((resolve) => setImmediate(resolve)); @@ -57,3 +57,83 @@ describe("MCP: auto-launch's startup deadline (#663)", () => { expect(launcher.launches).toBe(1); }); }); + +describe("MCP: auto-launch's daemon that exits while starting (#760)", () => { + const fatal = (message: string): string => + `${JSON.stringify({ message: "Daemon failed to start", fields: { message } })}\n`; + + // why: the winner is not listening yet at the first poll after the launch, so the loop reaches + // the launched daemon's exit before it finds the winner. + class LateWinnerTransport extends MemoryIpcTransport { + connects = 0; + override async connect(endpoint: string): ReturnType { + this.connects += 1; + if (this.connects === 2) { + throw new IpcError("endpoint-not-found", `No IPC endpoint at ${endpoint}`, undefined); + } + return super.connect(endpoint); + } + } + + async function answerHello(ipc: MemoryIpcTransport): Promise { + await ipc.listen("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/simlock/daemon.sock", (connection) => { + connection.onData((chunk) => { + for (const line of chunk.split("\n").filter((value) => value !== "")) { + const frame = JSON.parse(line) as { id: number; type: string }; + if (frame.type !== "hello") continue; + void connection.write( + `${JSON.stringify({ + id: frame.id, + ok: true, + payload: { + daemonProtocolRange: { max: 3, min: 3 }, + principal: "agent-1", + protocolVersion: 3, + role: "agent", + version: "0.3.0", + }, + })}\n`, + ); + } + }); + }); + } + + it("rejects with the start error as soon as the launched daemon exits, and connects when another daemon answers", async () => { + const outcome = async (message: string, winner: boolean) => { + const clock = new FakeClock(0); + const ipc = new LateWinnerTransport(); + const launcher = new FakeDaemonLauncher(winner ? () => answerHello(ipc) : undefined, { + exit: { code: 1, signal: null }, + output: fatal(message), + }); + const result = await Promise.race([ + connectWithAutoLaunch({ + clock, + ipc, + launcher, + principal: "agent-1", + socketPath: "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/simlock/daemon.sock", + }).then( + (client) => `connected as ${client.role}`, + (error: unknown) => `${(error as { code: string }).code}: ${(error as Error).message}`, + ), + settle() + .then(settle) + .then(settle) + .then(() => "still waiting"), + ]); + return { result, elapsed: clock.now() }; + }; + expect({ + refused: await outcome("Found state.json", false), + raced: await outcome("Simlock daemon is already running", true), + }).toEqual({ + refused: { + result: "DAEMON_STARTUP_FAILED: The daemon could not start: Found state.json", + elapsed: 0, + }, + raced: { result: "connected as agent", elapsed: 0 }, + }); + }); +}); From 24227baf75afa247232a3533d94cf586b54acaff Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 18:43:57 +0200 Subject: [PATCH 09/13] feat(mcp): the MCP server's auto-start fails with the daemon's start error when it exits (#760) --- src/mcp/connect.ts | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/mcp/connect.ts b/src/mcp/connect.ts index a3b3f9f06..32042e3d9 100644 --- a/src/mcp/connect.ts +++ b/src/mcp/connect.ts @@ -17,7 +17,9 @@ import { import { DAEMON_STARTUP_TIMEOUT_MS, IpcError, + startErrorFrom, type Clock, + type DaemonExit, type DaemonLauncher, type IpcConnector, } from "../ports/index.js"; @@ -53,7 +55,11 @@ export async function connectWithAutoLaunch( } catch (error: unknown) { if (!isUnavailable(error)) throw error; } - await options.launcher.launch(); + const launched = await options.launcher.launch(); + let exit: DaemonExit | undefined; + void launched.exited.then((value) => { + exit = value; + }); const deadline = options.clock.now() + (options.startupTimeoutMs ?? DAEMON_STARTUP_TIMEOUT_MS); let lastError: unknown; while (options.clock.now() < deadline) { @@ -62,6 +68,20 @@ export async function connectWithAutoLaunch( } catch (error: unknown) { if (!isUnavailable(error)) throw error; lastError = error; + if (exit !== undefined) { + const output = await launched.readOutput().catch(() => ""); + try { + return await connectToRunningDaemon(options); + } catch (lastAttempt: unknown) { + if (!isUnavailable(lastAttempt)) throw lastAttempt; + } + throw new SimlockError( + "DAEMON_STARTUP_FAILED", + "transport", + startErrorFrom(exit, output), + {}, + ); + } await delay(options.clock, options.retryIntervalMs ?? 50); } } From e91a0b0fb233af404b03e629037a082312bb02b1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 18:44:50 +0200 Subject: [PATCH 10/13] test: simlock status prints the daemon's start error when the folder holds state.json (#760) --- e2e/start-refusal.test.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 e2e/start-refusal.test.ts diff --git a/e2e/start-refusal.test.ts b/e2e/start-refusal.test.ts new file mode 100644 index 000000000..bb42016bf --- /dev/null +++ b/e2e/start-refusal.test.ts @@ -0,0 +1,25 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { withDaemon } from "./helpers/index.js"; + +describe("an auto-started daemon that refuses to start (#760)", () => { + it("simlock status prints DAEMON_STARTUP_FAILED with the daemon's start error, exit 1, in under 5 s", async () => { + const env = await withDaemon({ mode: "auto" }); + const stateJson = join(env.home, "state.json"); + await writeFile(stateJson, "{}\n", "utf8"); + + const startedAt = Date.now(); + const result = await env.cli(["status"]); + const elapsedMs = Date.now() - startedAt; + + expect(result.code, result.stderr).toBe(1); + const failure = JSON.parse(result.stderr.trim().split("\n").at(-1) ?? "{}") as { + error: { code: string; message: string }; + }; + expect(failure.error.code).toBe("DAEMON_STARTUP_FAILED"); + expect(failure.error.message).toContain(`The daemon could not start: Found ${stateJson}, `); + expect(elapsedMs).toBeLessThan(5_000); + }); +}); From f10d892da8d208e71f5f59e55f7189438539fe5b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 18:45:03 +0200 Subject: [PATCH 11/13] docs(cli): the daemon's start error is shown when it exits during start (#760) --- docs/CLI.md | 8 ++++++-- src/cli/AGENTS.md | 3 ++- src/mcp/AGENTS.md | 2 ++ src/ports/AGENTS.md | 2 +- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 1deb30224..05f55265c 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -145,7 +145,7 @@ command starts it again) to bring the platform up. |---|---|---| | 0 | — | success (for a `lease` that stayed alive: the lease ended normally) | | 1 | `INTERNAL` | internal / unexpected error | -| 1 | `DAEMON_STARTUP_FAILED` | the daemon was started but did not accept connections before the startup timeout, or answered the handshake then closed before the CLI's startup status probe answered | +| 1 | `DAEMON_STARTUP_FAILED` | the daemon was started but did not accept connections before the startup timeout, or exited while starting (the message is the daemon's start error), or answered the handshake then closed before the CLI's startup status probe answered | | 1 | `PROVISION_FAILED` | creating a device for the request failed twice; the message is the driver's error | | 1 | `HISTORY_UNAVAILABLE` | `stats` while `history.db` could not be opened, so the usage figures cannot be read; the daemon's log says why | | 1 | `WORKER_UNREACHABLE` | the gateway cannot reach the worker this lease or request lives on (its uplink is down), or a worker named with `component install --worker` cannot be asked | @@ -2521,7 +2521,11 @@ Totals ## `simlock daemon ` -If a command auto-starts a daemon and it answers the handshake but closes +If a command auto-starts a daemon and that daemon exits before it accepts +connections, the command fails at once with `DAEMON_STARTUP_FAILED` and the +daemon's start error (`The daemon could not start: `, or the exit code +when it logged none); a daemon that exits because another one holds the socket +is not a failure, and the command goes on with that one. If it answers the handshake but closes before the CLI's startup status probe answers, the command reports `DAEMON_STARTUP_FAILED` (exit 1). The probe shares the launch timeout and runs before the command's operation, including after a rejected credential falls diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index c2a696ff7..305dbd7c3 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -63,7 +63,8 @@ Surface: [CLI.md](../../docs/CLI.md) — every command, flag and exit code. None, or a rejected one → an `agent` session and one stderr `notice` line. 3. **Auto-launch** (`AutoLaunchAdminConnector`) — when nothing listens: load the config first (a bad one fails on this stderr), launch the daemon detached, retry every 50 ms - for `DAEMON_STARTUP_TIMEOUT_MS`. After a launch, `status.get` probes the connection + for `DAEMON_STARTUP_TIMEOUT_MS`; a launched daemon that exits fails the command at once + with `startErrorFrom`'s text, unless another daemon answers a last connect. After a launch, `status.get` probes the connection before handing it to a command, within that same deadline. A connection loss during this probe becomes `DAEMON_STARTUP_FAILED`; a silent probe times out with that code and starts closing its client without waiting for the daemon to end its side. An answered probe ends the window, including a `starting` status: subsequent diff --git a/src/mcp/AGENTS.md b/src/mcp/AGENTS.md index 396ff3841..addfc4d78 100644 --- a/src/mcp/AGENTS.md +++ b/src/mcp/AGENTS.md @@ -42,6 +42,8 @@ Surface: [CLI.md](../../docs/CLI.md#simlock-mcp). - a tool call → `connectWithAutoLaunch`: launches the daemon only when nothing listens (`connection-refused`, `endpoint-not-found`), retries every 50 ms for `startupTimeoutMs` (default `DAEMON_STARTUP_TIMEOUT_MS`), else `DAEMON_STARTUP_FAILED`; + a launched daemon that exits fails at once with `startErrorFrom`'s text, unless another + daemon answers a last connect; - the renew timer → `connectToRunningDaemon`: never launches. The lease survives either way: the daemon released nothing. 7. **End** — stdin EOF, `SIGINT`/`SIGTERM` or transport close → `McpSession.close`: stop diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index 7f163dce5..5537d5cec 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -15,7 +15,7 @@ Uses: nothing from other components. Imported by: every component that touches t | (wrapper) | `logging-process-runner.ts` | `LoggingProcessRunner` | — | One `process` log line per command, at `debug` only | | `ProcessSupervisor` | `process-supervisor.ts` | `NodeProcessSupervisor` | `FakeProcessSupervisor` | Is a pid alive; signal it | | `ParentWatch` | `parent-watch.ts` | `NodeParentWatch` | `FakeParentWatch` | Call once when a pid exits (polls) | -| `DaemonLauncher` | `daemon-launcher.ts` | `NodeDaemonLauncher` | `FakeDaemonLauncher` | Detached daemon, its log, `DAEMON_STARTUP_TIMEOUT_MS` | +| `DaemonLauncher` | `daemon-launcher.ts` | `NodeDaemonLauncher` | `FakeDaemonLauncher` | Detached daemon, its log, `DAEMON_STARTUP_TIMEOUT_MS`; `launch()` answers a `LaunchedDaemon` (`exited`, `readOutput` of the log since the launch); `startErrorFrom` | | `IpcConnector`, `IpcListenerFactory` | `ipc.ts` | `NodeIpcTransport` | `MemoryIpcTransport` | The daemon's unix socket | | `UplinkConnector`, `UplinkListenerFactory` | `uplink.ts` | `WebSocketUplinkConnector`, `WebSocketUplinkListenerFactory` | `MemoryUplinkTransport` | A worker's uplink to its gateway | | `Logger`, `LogSink` | `logger.ts` | `JsonLinesLogger`, `NodeFileLogSink` | `NoopLogger`, `MemoryLogSink` | JSON-line logs, `child(module)`, rotation | From 62e45551979bed713128da1ffad6f9fc15c2f9c4 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 18:45:28 +0200 Subject: [PATCH 12/13] refactor(cli): the exited-daemon path is its own function in both frontends (#760) --- src/cli/environment.ts | 35 +++++++++++++++++++---------------- src/mcp/connect.ts | 30 ++++++++++++++++-------------- 2 files changed, 35 insertions(+), 30 deletions(-) diff --git a/src/cli/environment.ts b/src/cli/environment.ts index 8929ae992..8bf6171cf 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -12,6 +12,7 @@ import type { DaemonLauncher, Filesystem, IpcConnector, + LaunchedDaemon, ParentWatch, ParentWatchHandle, } from "../ports/index.js"; @@ -55,22 +56,8 @@ class AutoLaunchAdminConnector { } catch (error: unknown) { if (!(await isUnavailable(error))) throw error; lastError = error; - if (exit !== undefined) { - const output = await launched.readOutput().catch(() => ""); - try { - return await this.finishConnection(await this.connectClient(resolveCredential)); - } catch (lastAttempt: unknown) { - if (!(await isUnavailable(lastAttempt))) throw lastAttempt; - } - const { SimlockError } = await import("../contract/index.js"); - const { startErrorFrom } = await import("../ports/index.js"); - throw new SimlockError( - "DAEMON_STARTUP_FAILED", - "transport", - startErrorFrom(exit, output), - {}, - ); - } + if (exit !== undefined) + return await this.connectAfterExit(launched, exit, resolveCredential); await new Promise((resolve) => this.clock.setTimer(50, resolve)); } } @@ -83,6 +70,22 @@ class AutoLaunchAdminConnector { ); } + private async connectAfterExit( + launched: LaunchedDaemon, + exit: DaemonExit, + resolveCredential: () => Promise, + ): Promise { + const output = await launched.readOutput().catch(() => ""); + try { + return await this.finishConnection(await this.connectClient(resolveCredential)); + } catch (error: unknown) { + if (!(await isUnavailable(error))) throw error; + } + const { SimlockError } = await import("../contract/index.js"); + const { startErrorFrom } = await import("../ports/index.js"); + throw new SimlockError("DAEMON_STARTUP_FAILED", "transport", startErrorFrom(exit, output), {}); + } + private async finishConnection(client: SimlockAdminClient): Promise { if (this.startupDeadline === undefined) return client; const { isSimlockError, SimlockError } = await import("../contract/index.js"); diff --git a/src/mcp/connect.ts b/src/mcp/connect.ts index 32042e3d9..983b1e581 100644 --- a/src/mcp/connect.ts +++ b/src/mcp/connect.ts @@ -22,6 +22,7 @@ import { type DaemonExit, type DaemonLauncher, type IpcConnector, + type LaunchedDaemon, } from "../ports/index.js"; /** What it takes to reach a daemon that is already listening -- no launcher anywhere in it, @@ -68,20 +69,7 @@ export async function connectWithAutoLaunch( } catch (error: unknown) { if (!isUnavailable(error)) throw error; lastError = error; - if (exit !== undefined) { - const output = await launched.readOutput().catch(() => ""); - try { - return await connectToRunningDaemon(options); - } catch (lastAttempt: unknown) { - if (!isUnavailable(lastAttempt)) throw lastAttempt; - } - throw new SimlockError( - "DAEMON_STARTUP_FAILED", - "transport", - startErrorFrom(exit, output), - {}, - ); - } + if (exit !== undefined) return await connectAfterExit(options, launched, exit); await delay(options.clock, options.retryIntervalMs ?? 50); } } @@ -93,6 +81,20 @@ export async function connectWithAutoLaunch( ); } +async function connectAfterExit( + options: ConnectToRunningDaemonOptions, + launched: LaunchedDaemon, + exit: DaemonExit, +): Promise { + const output = await launched.readOutput().catch(() => ""); + try { + return await connectToRunningDaemon(options); + } catch (error: unknown) { + if (!isUnavailable(error)) throw error; + } + throw new SimlockError("DAEMON_STARTUP_FAILED", "transport", startErrorFrom(exit, output), {}); +} + /** * Connects only to a daemon that is already listening, and never launches one -- which is * exactly `connectWithAutoLaunch` minus its one extra power, so the latter is written in terms From b89dfcb9bca999e6dba2ca18588ea58c7b35843e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 19:04:48 +0200 Subject: [PATCH 13/13] test(launcher): the parent guard can fire, and the unreadable-output fallbacks are covered (#760) --- src/cli/index.test.ts | 35 +++++++++++++++++++++++++++++++ src/mcp/connect.test.ts | 23 ++++++++++++++++++++ src/ports/daemon-launcher.test.ts | 25 +++++++++++++++++++++- 3 files changed, 82 insertions(+), 1 deletion(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 8dc7c4be5..855ecca52 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1524,6 +1524,41 @@ describe("CLI: auto-launch's daemon that exits while starting (#760)", () => { }, }); }); + + it("status names the exit code when the launched daemon's output cannot be read", async () => { + const clock = new FakeClock(0); + const launcher = { + launch: async () => ({ + exited: Promise.resolve({ code: 3, signal: null }), + readOutput: async (): Promise => { + throw new Error("daemon.log was replaced"); + }, + }), + }; + const output = outputCapture({ + filesystem: new MemoryFilesystem(), + clock, + systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ipc: new MemoryIpcTransport(), + launcher, + daemonHome: { role: "worker", dataDirectory: "/simlock", gatewayPresent: false }, + }); + let settled = false; + const exitCode = runCli(["status"], output.environmentWith()).then((code) => { + settled = true; + return code; + }); + for (let tick = 0; tick < 100 && !settled; tick += 1) { + clock.advance(50); + await settle(); + await settle(); + } + expect(settled, "status had not settled by 5 s").toBe(true); + expect(await exitCode).toBe(1); + expect(JSON.parse(output.stderr).error.message).toBe( + "The daemon exited with code 3 while starting; see `simlock daemon logs`", + ); + }); }); describe("CLI: auto-launch's daemon that lost the socket to another daemon (#760)", () => { diff --git a/src/mcp/connect.test.ts b/src/mcp/connect.test.ts index abcd622aa..2adb9679c 100644 --- a/src/mcp/connect.test.ts +++ b/src/mcp/connect.test.ts @@ -136,4 +136,27 @@ describe("MCP: auto-launch's daemon that exits while starting (#760)", () => { raced: { result: "connected as agent", elapsed: 0 }, }); }); + + it("names the exit code when the launched daemon's output cannot be read", async () => { + const clock = new FakeClock(0); + const launcher = { + launch: async () => ({ + exited: Promise.resolve({ code: 3, signal: null }), + readOutput: async (): Promise => { + throw new Error("daemon.log was replaced"); + }, + }), + }; + const result = await connectWithAutoLaunch({ + clock, + ipc: new MemoryIpcTransport(), + launcher, + principal: "agent-1", + socketPath: "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/simlock/daemon.sock", + }).then( + () => "connected", + (error: unknown) => (error as Error).message, + ); + expect(result).toBe("The daemon exited with code 3 while starting; see `simlock daemon logs`"); + }); }); diff --git a/src/ports/daemon-launcher.test.ts b/src/ports/daemon-launcher.test.ts index 457288c28..9bb031865 100644 --- a/src/ports/daemon-launcher.test.ts +++ b/src/ports/daemon-launcher.test.ts @@ -127,6 +127,28 @@ describe("NodeDaemonLauncher's LaunchedDaemon", () => { await rm(directory, { force: true, recursive: true }); } }); + + it("refuses to read the log when neither file is the one the daemon was launched into", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-launcher-")); + const logPath = join(directory, "daemon.log"); + try { + await writeFile(logPath, "older\n"); + const launched = await new NodeDaemonLauncher({ + args: [ + "-e", + "require('node:fs').rmSync(process.argv[1]); require('node:fs').writeFileSync(process.argv[1], 'x'); require('node:fs').writeFileSync(process.argv[1] + '.1', 'y')", + logPath, + ], + command: process.execPath, + logPath, + simlockHome: directory, + }).launch(); + await launched.exited; + await expect(launched.readOutput()).rejects.toThrow("daemon.log was replaced"); + } finally { + await rm(directory, { force: true, recursive: true }); + } + }); }); describe("NodeDaemonLauncher in a parent that awaits nothing", () => { @@ -165,7 +187,8 @@ describe("NodeDaemonLauncher in a parent that awaits nothing", () => { if (childPid !== undefined) process.kill(childPid); await rm(directory, { force: true, recursive: true }); } - }); + // why: the 8 s guard above must be able to fire before vitest's own 5 s default does. + }, 20_000); }); describe("startErrorFrom", () => {