Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

feat(cli): background daemon by default + status/stop/logs + launchd autostart

Yuting Zhong3fc24dc08458
diff --git a/README.md b/README.md
index acbeb08e..3a6d7610 100644
--- a/README.md
+++ b/README.md
@@ -80,8 +80,12 @@ notfair
```
```
-notfair Launch local server + open UI (default)
-notfair start Same, with --port <n>, --no-open, --data-dir <path>
+notfair Start in the background + open UI (default)
+notfair start Same, with --port <n>, --no-open, --foreground, --data-dir <path>
+notfair status Running? pid, port, uptime, autostart state
+notfair stop Stop the background server
+notfair logs Show / follow the server log (-n N, -f)
+notfair autostart enable | disable | status — start at login (macOS launchd)
notfair doctor Preflight checks with a Fix: line per failure
```
diff --git a/notfair/CHANGELOG.md b/notfair/CHANGELOG.md
index b434ec8f..0b12d22d 100644
--- a/notfair/CHANGELOG.md
+++ b/notfair/CHANGELOG.md
@@ -1,5 +1,9 @@
# NotFair
+## Unreleased
+
+**NotFair now runs in the background — and survives reboots.** `notfair` (or `notfair start`) detaches the server, waits for it to answer, and opens the UI; your terminal stays free and closing it no longer kills the loop. New lifecycle commands: `notfair status` (pid, port, uptime, health), `notfair stop` (finally implemented), and `notfair logs -f` (server log lives at `~/.notfair/logs/server.log`). `notfair autostart enable` installs a macOS LaunchAgent that starts NotFair at login and restarts it if it crashes — launchd becomes the single owner, so `start`/`stop` delegate to it instead of racing it for the port, the agent captures your shell's PATH so `claude`/`codex` stay reachable at login, and `start` self-heals the entry when an upgrade moves the package on disk. `--foreground` keeps the old attached behavior.
+
## 0.9.5 — 2026-07-21
**The "Needs you" panel is now the single source of truth for repeated asks.** Agents were told to repeat user-action asks in every check summary, but nothing told them when an ask was closed — so asks you'd already handled kept echoing from summary to summary forever. Every tick brief now mirrors the panel's live list of open escalations: the agent repeats exactly those, and only those. A handled-but-still-broken problem comes back as a fresh escalation with new evidence, so the panel and the diary can never drift apart again.
diff --git a/notfair/README.md b/notfair/README.md
index 8b54d4e7..18fba0dc 100644
--- a/notfair/README.md
+++ b/notfair/README.md
@@ -42,28 +42,42 @@ Run `notfair doctor` to check Node, both harness binaries, the data directory, a
```bash
# One-shot, no install:
npx notfair@latest doctor # verify env
-npx notfair@latest # launch UI on http://127.0.0.1:3327
+npx notfair@latest # start in the background + open http://127.0.0.1:3327
# Or install globally:
npm install -g notfair
notfair
```
-The UI opens in your browser. Sidebar is project-scoped; create one to start.
+The server runs as a background process (state in `~/.notfair/server.json`, log in `~/.notfair/logs/server.log`) and the UI opens in your browser — your terminal stays free, and closing it doesn't kill the loop. Sidebar is project-scoped; create one to start.
+
+To survive reboots, enable autostart (macOS):
+
+```bash
+notfair autostart enable # launchd: starts at login, restarts on crash
+```
## CLI
```
-notfair Launch local server + open UI (default)
-notfair start Same as above
-notfair doctor Run preflight checks (see below)
+notfair Start in the background + open UI (default)
+notfair start Same as above (--foreground to stay attached)
+notfair status Running? pid, port, uptime, autostart state
+notfair stop Stop the background server
+notfair logs [-n N] [-f] Show / follow the server log
+notfair autostart enable Start automatically at login (macOS launchd)
+notfair autostart disable Remove the LaunchAgent + stop the server
+notfair autostart status Is the LaunchAgent installed and loaded?
+notfair doctor Run preflight checks (see below)
notfair --version
notfair --help
```
-Options on `start`: `--port <n>` (default 3327), `--no-open`, `--data-dir <path>`.
+Options on `start`: `--port <n>` (default 3327), `--no-open`, `--foreground`, `--data-dir <path>`.
Options on `doctor`: `--port <n>`, `--data-dir <path>`.
+When autostart is enabled, launchd owns the server: `notfair start` delegates to it (never spawns a competing copy), `notfair stop` stops it until your next login, and `notfair autostart disable` removes it entirely. The LaunchAgent captures your shell's PATH so the `claude` / `codex` binaries stay reachable at login, and `notfair start` self-heals the entry if an upgrade moved the package on disk. Global install is recommended for autostart — the npx cache can be cleared at any time.
+
`doctor` checks Node ≥ 20 (24 recommended), Claude Code on PATH, Codex on PATH, at least one harness ready, a writable data directory, and a free preferred port. It exits 0 if every check is passing and 1 otherwise, with a `Fix:` line under each failure naming the exact command to run.
## What happens when you create a goal
diff --git a/notfair/bin/cli.mjs b/notfair/bin/cli.mjs
index 584663c1..afa16df5 100755
--- a/notfair/bin/cli.mjs
+++ b/notfair/bin/cli.mjs
@@ -2,29 +2,39 @@
// NotFair CLI entry point.
// Compiled-free: stays as plain ESM JS so it works straight from npm without a build step
// for the CLI surface. The Next.js app itself is built and shipped under .next/standalone.
+//
+// Process model: `notfair start` runs the server as a detached background
+// process (state in <data-dir>/server.json, log in <data-dir>/logs/server.log);
+// `--foreground` stays attached and is what launchd runs. When autostart is
+// enabled, launchd is the single owner — start/stop delegate to launchctl so
+// KeepAlive never fights the CLI over the same port.
import { spawn } from "node:child_process";
import {
+ closeSync,
+ cpSync,
existsSync,
mkdirSync,
+ openSync,
readFileSync,
- cpSync,
- writeFileSync,
unlinkSync,
+ writeFileSync,
} from "node:fs";
import { homedir } from "node:os";
-import { dirname, join, resolve } from "node:path";
+import { dirname, join, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { createServer } from "node:net";
import { Command } from "commander";
import open from "open";
-const __dirname = dirname(fileURLToPath(import.meta.url));
+const CLI_PATH = fileURLToPath(import.meta.url);
+const __dirname = dirname(CLI_PATH);
const PKG_ROOT = dirname(__dirname);
// Resolved to absolute: the value is forwarded as NOTFAIR_DATA_DIR to the
// standalone server, whose cwd is the package dir — a relative path would
// silently land the database inside the npm/npx cache.
const DATA_DIR = resolve(process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair"));
+const LAUNCHD_LABEL = "co.notfair.server";
const program = new Command();
program
@@ -34,17 +44,12 @@ program
program
.command("start", { isDefault: true })
- .description("Start the local server and open the UI in your browser.")
+ .description("Start NotFair in the background and open the UI in your browser.")
.option("-p, --port <port>", "Port to bind", "3327")
.option("--no-open", "Do not auto-open the browser")
+ .option("--foreground", "Stay attached to this terminal instead of running in the background")
.option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)
.action(async (opts) => {
- const desired = Number.parseInt(opts.port, 10);
- const port = await findFreePort(desired);
- if (port !== desired) {
- console.log(`Port ${desired} was busy, using ${port} instead.`);
- }
-
ensureDataDir(opts.dataDir);
const standalonePath = join(PKG_ROOT, ".next", "standalone", "server.js");
@@ -55,36 +60,231 @@ program
process.exit(2);
}
+ // When autostart owns the server, starting it by hand would race launchd
+ // onto the same port — delegate to launchctl instead.
+ if (!opts.foreground && process.platform === "darwin" && existsSync(plistPath())) {
+ await startViaLaunchd(opts);
+ return;
+ }
+
+ if (!opts.foreground) {
+ const running = getState(opts.dataDir);
+ if (running && (await isHealthy(running.url))) {
+ console.log(`NotFair is already running on ${running.url} (pid ${running.pid}).`);
+ if (opts.open !== false) await open(running.url).catch(() => {});
+ return;
+ }
+ if (running) {
+ console.log(
+ `A NotFair process (pid ${running.pid}) exists but isn't answering on ${running.url} yet.`,
+ );
+ console.log("Check `notfair status` / `notfair logs`, or `notfair stop` and retry.");
+ process.exit(1);
+ }
+ }
+
+ const desired = Number.parseInt(opts.port, 10);
+ const port = await findFreePort(desired);
+ if (port !== desired) {
+ console.log(`Port ${desired} was busy, using ${port} instead.`);
+ }
+
// Next.js standalone output omits .next/static and public by default; copy
// them in if they're missing so the server can serve CSS/JS chunks.
ensureStandaloneAssets();
const url = `http://127.0.0.1:${port}`;
+ const env = {
+ ...process.env,
+ PORT: String(port),
+ HOSTNAME: "127.0.0.1",
+ NOTFAIR_DATA_DIR: opts.dataDir,
+ };
+
+ if (opts.foreground) {
+ const child = spawn("node", [standalonePath], { stdio: "inherit", env });
+ writeState(opts.dataDir, {
+ pid: child.pid,
+ port,
+ url,
+ data_dir: opts.dataDir,
+ version: readPackageVersion(),
+ started_at: new Date().toISOString(),
+ managed: process.env.NOTFAIR_MANAGED ?? "foreground",
+ });
+
+ console.log(`NotFair running on ${url}`);
+
+ if (opts.open !== false) {
+ setTimeout(() => {
+ open(url).catch(() => {
+ console.log(`Open ${url} in your browser.`);
+ });
+ }, 800);
+ }
+
+ const shutdown = () => {
+ child.kill("SIGTERM");
+ };
+ process.on("SIGINT", shutdown);
+ process.on("SIGTERM", shutdown);
+ child.on("close", (code) => {
+ clearState(opts.dataDir);
+ process.exit(code ?? 0);
+ });
+ return;
+ }
+
+ // Background mode: detach, log to a file, and only report success once
+ // the server actually answers HTTP.
+ mkdirSync(dirname(logFile(opts.dataDir)), { recursive: true });
+ const fd = openSync(logFile(opts.dataDir), "a");
const child = spawn("node", [standalonePath], {
- stdio: "inherit",
- env: {
- ...process.env,
- PORT: String(port),
- HOSTNAME: "127.0.0.1",
- NOTFAIR_DATA_DIR: opts.dataDir,
- },
+ detached: true,
+ stdio: ["ignore", fd, fd],
+ env,
+ });
+ child.unref();
+ closeSync(fd);
+ writeState(opts.dataDir, {
+ pid: child.pid,
+ port,
+ url,
+ data_dir: opts.dataDir,
+ version: readPackageVersion(),
+ started_at: new Date().toISOString(),
+ managed: "daemon",
});
- console.log(`NotFair running on ${url}`);
+ const healthy = await waitFor(() => isHealthy(url), 30_000, 500);
+ if (!healthy) {
+ console.error(`NotFair did not answer on ${url} within 30s. Last log lines:`);
+ printLogTail(opts.dataDir, 20);
+ console.error(`Full log: ${logFile(opts.dataDir)}`);
+ try {
+ process.kill(child.pid, "SIGTERM");
+ } catch {}
+ clearState(opts.dataDir);
+ process.exit(1);
+ }
+ console.log(`NotFair running in the background on ${url} (pid ${child.pid}).`);
+ console.log(" notfair status check health");
+ console.log(" notfair logs -f follow the server log");
+ console.log(" notfair stop stop the background server");
+ if (process.platform === "darwin" && !existsSync(plistPath())) {
+ console.log(" notfair autostart enable start automatically at login");
+ }
if (opts.open !== false) {
- setTimeout(() => {
- open(url).catch(() => {
- console.log(`Open ${url} in your browser.`);
- });
- }, 800);
+ await open(url).catch(() => {
+ console.log(`Open ${url} in your browser.`);
+ });
}
+ });
- const shutdown = () => {
- child.kill("SIGTERM");
- };
- process.on("SIGINT", shutdown);
- process.on("SIGTERM", shutdown);
+program
+ .command("stop")
+ .description("Stop the background NotFair server.")
+ .option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)
+ .action(async (opts) => {
+ // launchd-managed: stop through launchctl, or KeepAlive resurrects the
+ // process the moment we kill it.
+ if (process.platform === "darwin" && (await launchAgentLoaded())) {
+ await runCheck("launchctl", ["bootout", launchdServiceTarget()]);
+ const state = getState(opts.dataDir);
+ if (state) {
+ await waitFor(() => !isPidAlive(state.pid), 10_000);
+ clearState(opts.dataDir);
+ }
+ console.log("Stopped NotFair (launchd-managed).");
+ if (existsSync(plistPath())) {
+ console.log(
+ "Autostart stays enabled — it starts again at your next login. `notfair autostart disable` turns that off.",
+ );
+ }
+ return;
+ }
+
+ const state = getState(opts.dataDir);
+ if (!state || !isPidAlive(state.pid)) {
+ clearState(opts.dataDir);
+ console.log("NotFair is not running.");
+ return;
+ }
+ try {
+ process.kill(state.pid, "SIGTERM");
+ } catch {}
+ let dead = await waitFor(() => !isPidAlive(state.pid), 10_000);
+ if (!dead) {
+ try {
+ process.kill(state.pid, "SIGKILL");
+ } catch {}
+ dead = await waitFor(() => !isPidAlive(state.pid), 3_000);
+ }
+ clearState(opts.dataDir);
+ if (!dead) {
+ console.error(`Could not stop pid ${state.pid} — kill it manually.`);
+ process.exit(1);
+ }
+ console.log(`Stopped NotFair (pid ${state.pid}).`);
+ });
+
+program
+ .command("status")
+ .description("Show whether NotFair is running, where, and its autostart state.")
+ .option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)
+ .action(async (opts) => {
+ const state = getState(opts.dataDir);
+ const alive = state ? isPidAlive(state.pid) : false;
+ const healthy = alive ? await isHealthy(state.url) : false;
+
+ if (!alive) {
+ if (state) clearState(opts.dataDir);
+ console.log("NotFair is not running.");
+ } else {
+ console.log(
+ healthy
+ ? "NotFair is running."
+ : "NotFair process is alive but not answering HTTP (starting up, or wedged — see logs).",
+ );
+ console.log(` url ${state.url}`);
+ console.log(` pid ${state.pid}`);
+ console.log(` version ${state.version ?? "unknown"}`);
+ console.log(` mode ${state.managed ?? "unknown"}`);
+ console.log(` started ${state.started_at ?? "unknown"}${formatUptime(state.started_at)}`);
+ console.log(` log ${logFile(opts.dataDir)}`);
+ }
+
+ if (process.platform === "darwin") {
+ const enabled = existsSync(plistPath());
+ const loaded = enabled && (await launchAgentLoaded());
+ console.log(
+ ` autostart ${enabled ? (loaded ? "enabled (loaded)" : "enabled (loads at next login)") : "disabled"}`,
+ );
+ }
+
+ process.exit(alive && healthy ? 0 : 1);
+ });
+
+program
+ .command("logs")
+ .description("Show the background server's log.")
+ .option("-n, --lines <n>", "Number of trailing lines to print", "100")
+ .option("-f, --follow", "Keep following the log (like tail -f)")
+ .option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)
+ .action((opts) => {
+ const file = logFile(opts.dataDir);
+ if (!existsSync(file)) {
+ console.log(`No log yet at ${file} — has the server been started in the background?`);
+ return;
+ }
+ const lines = Number.parseInt(opts.lines, 10) || 100;
+ if (opts.follow) {
+ const tail = spawn("tail", ["-n", String(lines), "-F", file], { stdio: "inherit" });
+ tail.on("close", (code) => process.exit(code ?? 0));
+ return;
+ }
+ printLogTail(opts.dataDir, lines);
});
program
@@ -135,13 +335,75 @@ program
process.exit(failed === 0 ? 0 : 1);
});
-program
- .command("stop")
- .description("Stop any running NotFair instances on this machine.")
- .action(() => {
- console.log("Stop is not implemented yet. Use Ctrl+C in the running terminal,");
- console.log("or kill the node process bound to your NotFair port.");
- process.exit(1);
+const autostart = program
+ .command("autostart")
+ .description("Start NotFair automatically at login (macOS launchd).");
+
+autostart
+ .command("enable")
+ .description("Install a launchd LaunchAgent: starts at login, restarts on crash.")
+ .option("-p, --port <port>", "Port the login server binds", "3327")
+ .option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)
+ .action(async (opts) => {
+ requireDarwin();
+ if (PKG_ROOT.includes(`${sep}_npx${sep}`)) {
+ console.log("Warning: you're running from the npx cache, which npm may clear at any time.");
+ console.log("For a reliable autostart, install globally first: npm install -g notfair");
+ }
+ ensureDataDir(opts.dataDir);
+ mkdirSync(dirname(logFile(opts.dataDir)), { recursive: true });
+
+ // Hand the port over: a CLI-started daemon would collide with the
+ // launchd copy the moment it boots.
+ const state = getState(opts.dataDir);
+ if (state && isPidAlive(state.pid)) {
+ console.log(`Stopping the current NotFair (pid ${state.pid}) so launchd can own it…`);
+ try {
+ process.kill(state.pid, "SIGTERM");
+ } catch {}
+ await waitFor(() => !isPidAlive(state.pid), 10_000);
+ clearState(opts.dataDir);
+ }
+
+ writeFileSync(plistPath(), renderPlist(Number.parseInt(opts.port, 10), opts.dataDir));
+ await reloadLaunchAgent();
+
+ const url = `http://127.0.0.1:${opts.port}`;
+ const healthy = await waitFor(() => isHealthy(url), 30_000, 500);
+ if (healthy) {
+ console.log(`Autostart enabled — NotFair is running on ${url} and starts at every login.`);
+ } else {
+ console.log("Autostart enabled, but the server hasn't answered yet.");
+ console.log("Check `notfair status` and `notfair logs`.");
+ process.exit(1);
+ }
+ });
+
+autostart
+ .command("disable")
+ .description("Remove the LaunchAgent and stop the launchd-managed server.")
+ .action(async () => {
+ requireDarwin();
+ await runCheck("launchctl", ["bootout", launchdServiceTarget()]);
+ try {
+ unlinkSync(plistPath());
+ } catch {}
+ console.log("Autostart disabled; the launchd-managed server (if any) was stopped.");
+ });
+
+autostart
+ .command("status")
+ .description("Show whether the LaunchAgent is installed and loaded.")
+ .action(async () => {
+ requireDarwin();
+ const enabled = existsSync(plistPath());
+ if (!enabled) {
+ console.log("Autostart is disabled. Enable with: notfair autostart enable");
+ process.exit(1);
+ }
+ const loaded = await launchAgentLoaded();
+ console.log(`Autostart is enabled (${plistPath()}).`);
+ console.log(loaded ? "LaunchAgent is loaded." : "LaunchAgent loads at next login.");
});
program.parseAsync(process.argv).catch((err) => {
@@ -149,6 +411,248 @@ program.parseAsync(process.argv).catch((err) => {
process.exit(1);
});
+// --- daemon state helpers ---
+
+function stateFile(dataDir) {
+ return join(dataDir, "server.json");
+}
+
+function logFile(dataDir) {
+ return join(dataDir, "logs", "server.log");
+}
+
+function getState(dataDir) {
+ try {
+ const state = JSON.parse(readFileSync(stateFile(dataDir), "utf8"));
+ if (!isPidAlive(state.pid)) {
+ clearState(dataDir);
+ return null;
+ }
+ return state;
+ } catch {
+ return null;
+ }
+}
+
+function writeState(dataDir, state) {
+ writeFileSync(stateFile(dataDir), `${JSON.stringify(state, null, 2)}\n`);
+}
+
+function clearState(dataDir) {
+ try {
+ unlinkSync(stateFile(dataDir));
+ } catch {}
+}
+
+function isPidAlive(pid) {
+ if (!Number.isInteger(pid) || pid <= 0) return false;
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (err) {
+ return err.code === "EPERM";
+ }
+}
+
+async function isHealthy(url) {
+ try {
+ const res = await fetch(url, {
+ signal: AbortSignal.timeout(2_500),
+ redirect: "manual",
+ });
+ return res.status < 500;
+ } catch {
+ return false;
+ }
+}
+
+function sleep(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+}
+
+async function waitFor(fn, timeoutMs, stepMs = 300) {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ if (await fn()) return true;
+ if (Date.now() >= deadline) return false;
+ await sleep(stepMs);
+ }
+}
+
+function printLogTail(dataDir, n) {
+ try {
+ const lines = readFileSync(logFile(dataDir), "utf8").trimEnd().split("\n");
+ for (const line of lines.slice(-n)) console.log(line);
+ } catch {}
+}
+
+function formatUptime(startedAt) {
+ if (!startedAt) return "";
+ const ms = Date.now() - new Date(startedAt).getTime();
+ if (!Number.isFinite(ms) || ms < 0) return "";
+ const min = Math.floor(ms / 60_000);
+ if (min < 1) return " (just now)";
+ if (min < 60) return ` (up ${min}m)`;
+ const h = Math.floor(min / 60);
+ if (h < 48) return ` (up ${h}h ${min % 60}m)`;
+ return ` (up ${Math.floor(h / 24)}d)`;
+}
+
+// --- launchd helpers (macOS autostart) ---
+
+function requireDarwin() {
+ if (process.platform === "darwin") return;
+ console.error("Autostart is only supported on macOS today (launchd).");
+ console.error(
+ "On Linux, create a systemd user unit that runs: notfair start --foreground --no-open",
+ );
+ process.exit(1);
+}
+
+function plistPath() {
+ return join(homedir(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
+}
+
+function launchdServiceTarget() {
+ return `gui/${process.getuid()}/${LAUNCHD_LABEL}`;
+}
+
+async function launchAgentLoaded() {
+ if (process.platform !== "darwin") return false;
+ const r = await runCheck("launchctl", ["print", launchdServiceTarget()]);
+ return r.ok;
+}
+
+async function reloadLaunchAgent() {
+ await runCheck("launchctl", ["bootout", launchdServiceTarget()]);
+ const boot = await runCheck("launchctl", ["bootstrap", `gui/${process.getuid()}`, plistPath()]);
+ if (!boot.ok) {
+ // Older macOS without bootstrap/bootout semantics.
+ await runCheck("launchctl", ["load", "-w", plistPath()]);
+ }
+}
+
+function xmlEscape(s) {
+ return String(s)
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;");
+}
+
+/**
+ * The LaunchAgent runs the CLI itself in --foreground so launchd supervises
+ * a real process tree (RunAtLoad = start at login, KeepAlive = restart on
+ * crash). PATH is captured from the enabling shell — launchd's default PATH
+ * would hide the claude/codex binaries the agents need.
+ */
+function renderPlist(port, dataDir) {
+ const args = [
+ process.execPath,
+ CLI_PATH,
+ "start",
+ "--foreground",
+ "--no-open",
+ "--port",
+ String(port),
+ "--data-dir",
+ dataDir,
+ ];
+ const argStrings = args.map((a) => ` <string>${xmlEscape(a)}</string>`).join("\n");
+ return `<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key><string>${LAUNCHD_LABEL}</string>
+ <key>ProgramArguments</key>
+ <array>
+${argStrings}
+ </array>
+ <key>RunAtLoad</key><true/>
+ <key>KeepAlive</key><true/>
+ <key>WorkingDirectory</key><string>${xmlEscape(PKG_ROOT)}</string>
+ <key>StandardOutPath</key><string>${xmlEscape(logFile(dataDir))}</string>
+ <key>StandardErrorPath</key><string>${xmlEscape(logFile(dataDir))}</string>
+ <key>EnvironmentVariables</key>
+ <dict>
+ <key>PATH</key><string>${xmlEscape(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin")}</string>
+ <key>HOME</key><string>${xmlEscape(homedir())}</string>
+ <key>NOTFAIR_MANAGED</key><string>launchd</string>
+ </dict>
+</dict>
+</plist>
+`;
+}
+
+/** Pull port/data-dir back out of the installed plist (regex, not a parser —
+ * we wrote the file, so the shape is known). */
+function readPlistConfig() {
+ try {
+ const xml = readFileSync(plistPath(), "utf8");
+ const strings = [...xml.matchAll(/<string>([^<]*)<\/string>/g)].map((m) => m[1]);
+ const port = Number.parseInt(strings[strings.indexOf("--port") + 1] ?? "", 10);
+ const dataDir = strings[strings.indexOf("--data-dir") + 1] ?? DATA_DIR;
+ // Anchor on the "start" argument: ProgramArguments is [node, cli, "start",
+ // ...], but document order puts the Label's <string> first.
+ const startIdx = strings.indexOf("start");
+ return {
+ port: Number.isFinite(port) ? port : 3327,
+ dataDir,
+ execPath: startIdx >= 2 ? strings[startIdx - 2] : null,
+ cliPath: startIdx >= 1 ? strings[startIdx - 1] : null,
+ };
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * `notfair start` while autostart is enabled: launchd owns the server.
+ * Heal a plist that points at a previous install (npx cache paths and
+ * global-install realpaths move on upgrade), make sure the agent is
+ * loaded, and wait for health — never spawn a competing daemon.
+ */
+async function startViaLaunchd(opts) {
+ const cfg = readPlistConfig();
+ const port = cfg?.port ?? 3327;
+ const url = `http://127.0.0.1:${port}`;
+ const desired = Number.parseInt(opts.port, 10);
+ if (Number.isFinite(desired) && desired !== port && opts.port !== "3327") {
+ console.log(
+ `Autostart is enabled on port ${port}; ignoring --port ${desired}. Re-run \`notfair autostart enable --port ${desired}\` to move it.`,
+ );
+ }
+
+ const stale =
+ (cfg?.cliPath && cfg.cliPath !== CLI_PATH) ||
+ (cfg?.execPath && cfg.execPath !== process.execPath);
+ if (stale) {
+ writeFileSync(plistPath(), renderPlist(port, cfg.dataDir));
+ console.log("Refreshed the login autostart entry to this NotFair install.");
+ await reloadLaunchAgent();
+ } else if (await isHealthy(url)) {
+ console.log(`NotFair is already running on ${url} (launchd-managed).`);
+ if (opts.open !== false) await open(url).catch(() => {});
+ return;
+ } else if (await launchAgentLoaded()) {
+ await runCheck("launchctl", ["kickstart", launchdServiceTarget()]);
+ } else {
+ await reloadLaunchAgent();
+ }
+
+ const healthy = await waitFor(() => isHealthy(url), 30_000, 500);
+ if (!healthy) {
+ console.error(`launchd did not bring NotFair up on ${url} within 30s.`);
+ console.error(`Check \`notfair logs\` (${logFile(cfg?.dataDir ?? DATA_DIR)}).`);
+ process.exit(1);
+ }
+ console.log(`NotFair running on ${url} (launchd-managed).`);
+ if (opts.open !== false) {
+ await open(url).catch(() => {
+ console.log(`Open ${url} in your browser.`);
+ });
+ }
+}
+
// --- helpers ---
function ensureStandaloneAssets() {