iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

cli: a daemon's file counts only when its daemon answers, never by its pid alone

A file outlives a daemon that crashed, and after a reboot its pid may be another
process's. start, stop and status now ask the daemon itself; stop sends a signal only
to a pid that the daemon answered with.

Session: claude 344f881f-d8ca-4d42-99c3-42f7b2516e6b on beelink

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Wq8CaUVTGJy72BCq2ioc3x

Jonas Templestein, 2026-11-28 20:53 UTC · 02d5288054877705c9805cec0c2c544a7ddc0f92 · parent 2f33f71

4 files changed

M core/lib/src/cli/cli.ts
@@ -68,8 +68,8 @@
 import { importProvidedFile, nameOfFile, type ProvidedFile, runProvide } from "./provide.ts";
 import { finalStateOf, type ProvideState } from "./provide-state.ts";
 import { runTunnel } from "./tunnel.ts";
-import { DAEMON_FILE, isRunning, readDaemonFile, startDaemon } from "./daemon.ts";
-import { connectDaemon } from "./daemon-client.ts";
+import { startDaemon } from "./daemon.ts";
+import { connectDaemon, DAEMON_FILE, readDaemonFile, runningDaemon } from "./daemon-client.ts";
 import { shareMyComputer } from "./share-my-computer.ts";
 import {
   CONFIG_DIR,
@@ -1025,8 +1025,8 @@
           "Start the daemon in the background, with its output in daemon.log of the CLI's config folder; the same on Linux and macOS",
       })
       .handler(async ({ input }) => {
-        const running = readDaemonFile();
-        if (running && isRunning(running.pid))
+        const running = await runningDaemon();
+        if (running)
           return { already: true, pid: running.pid, port: running.port, mind: running.mind };
         // the mind is read here, where a person sees the error of a profile that names none
         const mind = await resolveMind(input.mind);
@@ -1058,11 +1058,12 @@
       .input(z.object({}))
       .meta({ description: "Stop the daemon of this computer's user" })
       .handler(async () => {
-        const running = readDaemonFile();
-        if (!running || !isRunning(running.pid)) return { running: false };
+        // only a daemon that answered with this pid gets the signal (daemon-client.ts)
+        const running = await runningDaemon();
+        if (!running) return { running: false };
         process.kill(running.pid, "SIGTERM");
         for (const giveUpAt = Date.now() + 10_000; Date.now() < giveUpAt; await sleep(100))
-          if (!isRunning(running.pid)) return { stopped: running.pid };
+          if (!(await runningDaemon())) return { stopped: running.pid };
         throw new Error(`The daemon (pid ${running.pid}) did not stop in 10 s.`);
       }),
     status: os
@@ -1072,8 +1073,7 @@
         description: "The daemon's minds and their connections, the local programs and their lends",
       })
       .handler(async () => {
-        const running = readDaemonFile();
-        if (!running || !isRunning(running.pid)) return { running: false, file: DAEMON_FILE };
+        if (!(await runningDaemon())) return { running: false, file: DAEMON_FILE };
         using daemon = await connectDaemon({ name: "iterate daemon status" });
         return await daemon.status();
       }),
M core/lib/src/cli/daemon-client.ts
@@ -2,19 +2,57 @@
 // desktop app or a script imports as `connectDaemon` from `iterate/node`. It reads the daemon's
 // file for the port and the token, opens one WebSocket to localhost, and talks capnweb. It makes
 // no connection to the mind and holds no sign-in.
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
 import { newWebSocketRpcSession, RpcTarget, type RpcStub } from "capnweb";
 import WebSocket from "ws";
+import { z } from "zod";
 import type { MindItx } from "../node.ts";
-import {
-  DAEMON_FILE,
-  type DaemonApi,
-  type DaemonSessionApi,
-  type DaemonStatus,
-  isRunning,
-  readDaemonFile,
-} from "./daemon.ts";
+import { withTimeout } from "../lib.ts";
+import { CONFIG_DIR } from "./config.ts";
+import type { DaemonApi, DaemonSessionApi, DaemonStatus } from "./daemon.ts";
 import { rpcTargetOf } from "./provide.ts";
 
+/** Where a daemon says how to reach it, for as long as it runs. */
+export const DAEMON_FILE = join(CONFIG_DIR, "daemon.json");
+
+/** `daemon.json`: written once the server listens, removed when the daemon ends. */
+export const DaemonFile = z.object({
+  pid: z.number().int(),
+  port: z.number().int(),
+  /** what `authenticate` takes: 32 random bytes, new at each start */
+  token: z.string(),
+  /** the mind that a call names none for */
+  mind: z.string(),
+  version: z.string(),
+  startedAt: z.string(),
+});
+export type DaemonFile = z.infer<typeof DaemonFile>;
+
+/** The file of a daemon, or null when there is none or it does not parse (a stale one's). */
+export function readDaemonFile(path = DAEMON_FILE): DaemonFile | null {
+  if (!existsSync(path)) return null;
+  try {
+    return DaemonFile.parse(JSON.parse(readFileSync(path, "utf8")));
+  } catch {
+    return null;
+  }
+}
+
+/** THE DAEMON THAT ANSWERS NOW, as its file says it, or null. Only an answer counts: a file
+ *  outlives a daemon that crashed, and its pid may by then be another process's, so nothing
+ *  is ever told from the pid, and no signal is sent to it, before the daemon has answered with it. */
+export async function runningDaemon(path = DAEMON_FILE): Promise<DaemonFile | null> {
+  const file = readDaemonFile(path);
+  if (!file) return null;
+  try {
+    using daemon = await connectDaemon({ name: "iterate daemon", file: path });
+    return (await daemon.status()).pid === file.pid ? file : null;
+  } catch {
+    return null;
+  }
+}
+
 export type DaemonConnection = Disposable & {
   status(): Promise<DaemonStatus>;
   /** THE MIND'S ROOT CONTEXT over the daemon's connection (`mind`: another mind than the
@@ -43,8 +81,8 @@
 ): Promise<DaemonConnection> {
   const path = input.file || DAEMON_FILE;
   const file = readDaemonFile(path);
-  if (!file || !isRunning(file.pid))
-    throw new Error(`No iterate daemon runs here (${path}). Start one: iterate daemon start.`);
+  const none = `No iterate daemon runs here (${path}). Start one: iterate daemon start.`;
+  if (!file) throw new Error(none);
   const socket = new WebSocket(`ws://127.0.0.1:${file.port}/`, { handshakeTimeout: 5_000 });
   const closed = new Promise<{ code: number; reason: string }>((resolve) => {
     socket.once("close", (code, reason) => resolve({ code, reason: reason.toString() }));
@@ -62,14 +100,16 @@
     return promise.dup() as unknown as RpcStub<DaemonSessionApi>;
   })();
   try {
-    // the first call proves the socket and the token
-    await session.status();
+    // the first call proves the socket and the token; a port that something else took never answers
+    await withTimeout(Promise.resolve(session.status()), 5_000, "The iterate daemon's answer");
   } catch (error) {
     socket.terminate();
-    throw new Error(
-      `Could not connect to the iterate daemon on port ${file.port}: ${error instanceof Error ? error.message : String(error)}`,
-      { cause: error },
-    );
+    const why = error instanceof Error ? error.message : String(error);
+    // nothing listens on the file's port: its daemon is gone
+    if (/ECONNREFUSED|closed|WebSocket/i.test(why)) throw new Error(none, { cause: error });
+    throw new Error(`Could not connect to the iterate daemon on port ${file.port}: ${why}`, {
+      cause: error,
+    });
   }
   return {
     status: async () => await session.status(),
M core/lib/src/cli/daemon.test.ts
@@ -1,15 +1,15 @@
 // daemon.test.ts — `iterate daemon` (daemon.ts) and a program's connection to it
 // (daemon-client.ts), over real sockets and real capnweb sessions on localhost. The mind is a
 // stand-in: a WebSocket server whose root keeps what is lent to it, as a mind's `provide` does.
-import { mkdtempDisposableSync, existsSync, statSync } from "node:fs";
+import { existsSync, mkdtempDisposableSync, statSync, writeFileSync } from "node:fs";
 import { tmpdir } from "node:os";
 import { join } from "node:path";
 import { newWebSocketRpcSession, RpcTarget, type RpcStub } from "capnweb";
 import { expect, test, vi } from "vitest";
 import WebSocket, { WebSocketServer } from "ws";
 import type { MindConnection, MindItx } from "../node.ts";
-import { connectDaemon } from "./daemon-client.ts";
-import { readDaemonFile, startDaemon } from "./daemon.ts";
+import { connectDaemon, readDaemonFile, runningDaemon } from "./daemon-client.ts";
+import { startDaemon } from "./daemon.ts";
 
 type Lent = RpcStub<RpcTarget> & {
   deliverEvent(event: { type: string }): Promise<string>;
@@ -229,6 +229,37 @@
       page.on("error", () => {});
     });
     expect(refused).toBe(403);
+  } finally {
+    daemon.stop();
+  }
+});
+
+test("a file that a dead daemon left is no daemon: its pid may be another process's, so only an answer counts, and a new daemon writes over it", async () => {
+  using folder = mkdtempDisposableSync(join(tmpdir(), "iterate-daemon-"));
+  using mind = await standInMind();
+  const file = join(folder.path, "daemon.json");
+  // a port that nothing listens on, and the pid of a process that runs (this test's parent)
+  const unused = new WebSocketServer({ port: 0, host: "127.0.0.1" });
+  await new Promise((resolve) => unused.once("listening", resolve));
+  const { port } = unused.address() as { port: number };
+  await new Promise((resolve) => unused.close(resolve));
+  writeFileSync(
+    file,
+    JSON.stringify({
+      pid: process.ppid,
+      port,
+      token: "left-behind",
+      mind: "iterate.example.com",
+      version: "0.0.0-test",
+      startedAt: new Date().toISOString(),
+    }),
+  );
+  expect(await runningDaemon(file)).toBe(null);
+  await expect(connectDaemon({ file })).rejects.toThrow("No iterate daemon runs here");
+
+  const daemon = await daemonFor(mind, folder.path);
+  try {
+    expect(await runningDaemon(file)).toMatchObject({ pid: process.pid, port: daemon.file.port });
   } finally {
     daemon.stop();
   }
M core/lib/src/cli/daemon.ts
@@ -17,52 +17,15 @@
 // `authenticate(token)`, and a request that a browser's page made (it carries `Origin`) is refused
 // before that. The daemon acts as the sign-in's person, so a program that connects does too.
 import { randomBytes, timingSafeEqual } from "node:crypto";
-import { existsSync, readFileSync, rmSync } from "node:fs";
+import { rmSync } from "node:fs";
 import { createServer, type Server } from "node:http";
 import type { AddressInfo } from "node:net";
-import { join } from "node:path";
 import { newWebSocketRpcSession, RpcTarget, type RpcStub } from "capnweb";
 import { WebSocketServer } from "ws";
-import { z } from "zod";
 import type { MindConnection, MindItx } from "../node.ts";
-import { CONFIG_DIR, writePrivateJson } from "./config.ts";
+import { writePrivateJson } from "./config.ts";
+import { DAEMON_FILE, type DaemonFile, readDaemonFile, runningDaemon } from "./daemon-client.ts";
 
-/** Where a daemon says how to reach it, for as long as it runs. */
-export const DAEMON_FILE = join(CONFIG_DIR, "daemon.json");
-
-/** `daemon.json`: written once the server listens, removed when the daemon ends. */
-export const DaemonFile = z.object({
-  pid: z.number().int(),
-  port: z.number().int(),
-  /** what `authenticate` takes: 32 random bytes, new at each start */
-  token: z.string(),
-  /** the mind that a call names none for */
-  mind: z.string(),
-  version: z.string(),
-  startedAt: z.string(),
-});
-export type DaemonFile = z.infer<typeof DaemonFile>;
-
-/** The file of a daemon, or null when there is none or it does not parse (a stale one's). */
-export function readDaemonFile(path = DAEMON_FILE): DaemonFile | null {
-  if (!existsSync(path)) return null;
-  try {
-    return DaemonFile.parse(JSON.parse(readFileSync(path, "utf8")));
-  } catch {
-    return null;
-  }
-}
-
-/** Whether a process with this pid runs (a signal 0 reaches it, or is refused as another user's). */
-export function isRunning(pid: number): boolean {
-  try {
-    process.kill(pid, 0);
-    return true;
-  } catch (error) {
-    return error instanceof Error && "code" in error && error.code === "EPERM";
-  }
-}
-
 /** A capability's name: `itx.<name>`, dotted segments allowed (`beelink.codex`), as provide.ts. */
 const NAME = /^[a-zA-Z][a-zA-Z0-9]*(\.[a-zA-Z][a-zA-Z0-9]*)*$/;
 
@@ -164,8 +127,10 @@
 }): Promise<Daemon> {
   const path = input.file || DAEMON_FILE;
   const log = input.log || ((line) => console.error(`${new Date().toISOString()} ${line}`));
-  const earlier = readDaemonFile(path);
-  if (earlier && earlier.pid !== process.pid && isRunning(earlier.pid))
+  // ONE DAEMON FOR A FILE. A file whose daemon no longer answers is a dead one's (a crash, a
+  // reboot: its pid may be another process's by now) and is written over.
+  const earlier = await runningDaemon(path);
+  if (earlier && earlier.pid !== process.pid)
     throw new Error(
       `An iterate daemon already runs here (pid ${earlier.pid}, port ${earlier.port}). Stop it first: iterate daemon stop.`,
     );