Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
3d40291
test: the CLI's status fails at once with the daemon's start error wh…
V3RON Oct 20, 2026
8b59da6
feat(cli): an auto-started daemon that exits while starting fails the…
V3RON Oct 20, 2026
554a669
test: the CLI's status goes on with the winner when the launched daem…
V3RON Oct 20, 2026
c2722a1
test: startErrorFrom names the last fatal line's message, else the ex…
V3RON Oct 20, 2026
94d99ab
test: NodeDaemonLauncher's exited gives the exit code and readOutput …
V3RON Oct 20, 2026
a4f4ec7
feat(ports): NodeDaemonLauncher reports the daemon's exit and the log…
V3RON Oct 20, 2026
d981c21
test: a parent that launched a daemon and awaits nothing exits while …
V3RON Oct 20, 2026
d5b5c80
test: connectWithAutoLaunch rejects with the start error as soon as t…
V3RON Oct 20, 2026
24227ba
feat(mcp): the MCP server's auto-start fails with the daemon's start …
V3RON Oct 20, 2026
e91a0b0
test: simlock status prints the daemon's start error when the folder …
V3RON Oct 20, 2026
f10d892
docs(cli): the daemon's start error is shown when it exits during sta…
V3RON Oct 20, 2026
62e4555
refactor(cli): the exited-daemon path is its own function in both fro…
V3RON Oct 20, 2026
e0567de
Merge remote-tracking branch 'origin/task/757' into task/760
V3RON Oct 20, 2026
b89dfcb
test(launcher): the parent guard can fire, and the unreadable-output …
V3RON Oct 20, 2026
96f5395
Merge remote-tracking branch 'origin/task/758' into task/760
V3RON Oct 20, 2026
f177074
Merge remote-tracking branch 'origin/task/758' into task/760
V3RON Oct 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -2521,7 +2521,11 @@ Totals

## `simlock daemon <start|stop|status|logs [--follow]>`

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: <error>`, 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
Expand Down
25 changes: 25 additions & 0 deletions e2e/start-refusal.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
3 changes: 2 additions & 1 deletion src/cli/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 25 additions & 1 deletion src/cli/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import type { SimlockAdminClient } from "../admin/index.js";
import type { ConfigOverrides, ModuleConfigEntry } from "../core/index.js";
import type {
Clock,
DaemonExit,
DaemonLauncher,
Filesystem,
IpcConnector,
LaunchedDaemon,
ParentWatch,
ParentWatchHandle,
} from "../ports/index.js";
Expand Down Expand Up @@ -38,7 +40,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;
Expand All @@ -50,6 +56,8 @@ class AutoLaunchAdminConnector {
} catch (error: unknown) {
if (!(await isUnavailable(error))) throw error;
lastError = error;
if (exit !== undefined)
return await this.connectAfterExit(launched, exit, resolveCredential);
await new Promise<void>((resolve) => this.clock.setTimer(50, resolve));
}
}
Expand All @@ -62,6 +70,22 @@ class AutoLaunchAdminConnector {
);
}

private async connectAfterExit(
launched: LaunchedDaemon,
exit: DaemonExit,
resolveCredential: () => Promise<string | undefined>,
): Promise<SimlockAdminClient> {
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<SimlockAdminClient> {
if (this.startupDeadline === undefined) return client;
const { isSimlockError, SimlockError } = await import("../contract/index.js");
Expand Down
135 changes: 135 additions & 0 deletions src/cli/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1486,6 +1486,141 @@ 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",
},
});
});

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<string> => {
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)", () => {
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<MemoryIpcTransport["connect"]> {
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: "/simlock/admin.token",
filesystem,
ipcTransport,
socketPath: "/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 },
Expand Down
2 changes: 2 additions & 0 deletions src/mcp/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
105 changes: 104 additions & 1 deletion src/mcp/connect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> => new Promise((resolve) => setImmediate(resolve));
Expand Down Expand Up @@ -57,3 +57,106 @@ 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<MemoryIpcTransport["connect"]> {
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<void> {
await ipc.listen("/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: "/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 },
});
});

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<string> => {
throw new Error("daemon.log was replaced");
},
}),
};
const result = await connectWithAutoLaunch({
clock,
ipc: new MemoryIpcTransport(),
launcher,
principal: "agent-1",
socketPath: "/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`");
});
});
Loading
Loading