From e16c9e290b1cfb951ce3fb9cc8cda85fe80a68ba Mon Sep 17 00:00:00 2001 From: HomeLab Agent Date: Thu, 5 Nov 2026 03:24:24 -0500 Subject: [PATCH 1/5] =?UTF-8?q?feat(cli):=20paddock=20doctor=20[--json]=20?= =?UTF-8?q?[--offline]=20(CLI=20contract=20SPEC=20=C2=A71)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The contract's eight checks with the shared ids, then Paddock's own (config, projects, claude-login, claude-cli). ✓/!/✗/- lines with a fix: under every warning and failure, exit 1 on a failure, --json matching schemas/doctor.schema.json, the update notice on stderr. --offline is scoped to doctor. The update check writes update-check.json only into a data dir that already exists, so doctor never creates an instance. Co-Authored-By: Claude Opus 5.5 --- .changeset/cli-contract-doctor.md | 10 + packages/server/src/cli/args.ts | 79 +- packages/server/src/cli/doctor.ts | 694 ++++++++++++++++++ packages/server/src/cli/paddock.ts | 18 +- packages/server/src/cli/service/index.ts | 7 +- packages/server/test/unit/cli-doctor.test.ts | 466 ++++++++++++ .../docs/guides/running-as-a-service.md | 4 + website/src/content/docs/guides/updating.md | 35 + 8 files changed, 1309 insertions(+), 4 deletions(-) create mode 100644 .changeset/cli-contract-doctor.md create mode 100644 packages/server/src/cli/doctor.ts create mode 100644 packages/server/test/unit/cli-doctor.test.ts diff --git a/.changeset/cli-contract-doctor.md b/.changeset/cli-contract-doctor.md new file mode 100644 index 00000000..34446297 --- /dev/null +++ b/.changeset/cli-contract-doctor.md @@ -0,0 +1,10 @@ +--- +"@paddock/server": minor +--- + +**`paddock doctor [--json] [--offline]` — check that Paddock can run here, with a fix for each problem.** The `--help` and the updating guide already named it; now it exists. One line per check, starting `✓`, `!` (a warning), `✗` (a failure) or `-` (doesn't apply here), with a `fix:` line under every warning and failure. + +- **The CLI contract's eight checks**, with the ids every tool uses: `node-engines`, `install-method`, `unit` (installed, running and answering; its Node and CLI still there; the same install as this CLI), `running-version`, `port` (free, or held by Paddock), `linger` (Linux), `data-home` and `update`. Then Paddock's own: `config` (the config loads as `serve` would load it), `projects` (the projects folder is writable), `claude-login` (which kind of Claude login it would use — never the login itself) and `claude-cli` (a `claude` on PATH, which the sweeper always needs and `driveMode: batch` needs for every turn). +- **What a script can see:** exit **1** if any check failed, **0** otherwise (warnings don't count), **2** for a usage error. `--json` prints one document on stdout, `{ ok, version, checks: [{ id, status, message, fix? }] }`, matching the contract's `schemas/doctor.schema.json`; the update notice goes to stderr. +- **The update check asks the npm registry** — only because you ran it — and writes `/update-check.json` the way `update --check` does, so `service status` repeats it — into a data dir that's already there only, so `doctor` never creates an instance. An unreachable registry is a warning, not a failure. `--offline` skips it. `doctor` writes nothing else. +- **`--offline` is a usage error (exit 2) on every other command**, like `--force`, `--check` and `--refresh`. diff --git a/packages/server/src/cli/args.ts b/packages/server/src/cli/args.ts index 90af8918..bf177798 100644 --- a/packages/server/src/cli/args.ts +++ b/packages/server/src/cli/args.ts @@ -115,6 +115,11 @@ export interface CliOptions { * `--port 9000` service comes back on 7233. */ refresh?: boolean; + /** + * `doctor --offline`: skip the one check that asks the npm registry + * (SPEC §1). Every other check is local. + */ + offline?: boolean; } /** @@ -188,7 +193,7 @@ export type ConfigAction = (typeof CONFIG_ACTIONS)[number]; * Paddock and Managers, every existing service unit's `ExecStart` names it, and * it is in two years of other people's scripts. They parse to the same command. */ -export const VERBS = ["serve", "start", "service", "config", "busy", "update", "upgrade"] as const; +export const VERBS = ["serve", "start", "service", "config", "busy", "update", "upgrade", "doctor"] as const; /** * A parsed invocation: which verb, plus the flags that followed it. @@ -209,7 +214,9 @@ export type Command = * the documentation, two that work, so nobody has to remember which word this * tool chose. */ - | { verb: "update"; opts: CliOptions }; + | { verb: "update"; opts: CliOptions } + /** `doctor` (SPEC §1): the checks, with a fix for each failure. */ + | { verb: "doctor"; opts: CliOptions }; /** * Split an action off a verb's argv, then parse what follows as flags. @@ -317,6 +324,12 @@ const SCOPED_FLAGS: readonly { where: ["update"], why: "`update` is the only command that asks a question.", }, + { + flag: "--offline", + read: (o) => o.offline === true, + where: ["doctor"], + why: "It skips doctor's one check that asks the npm registry.", + }, { flag: "--refresh", read: (o) => o.refresh === true, @@ -366,6 +379,9 @@ function dispatch(argv: string[]): Command { // `update`, with `upgrade` accepted and undocumented (SPEC §1). if (first === "update" || first === "upgrade") return { verb: "update", opts: parseArgs(rest) }; + // `doctor` (SPEC §1). + if (first === "doctor") return { verb: "doctor", opts: parseArgs(rest) }; + // `serve` and `start` are one command: see VERBS. if (first === "serve" || first === "start") return { verb: "serve", opts: parseArgs(rest) }; @@ -462,6 +478,10 @@ export function parseArgs(argv: string[]): CliOptions { case "--refresh": opts.refresh = true; break; + // `doctor --offline` (SPEC §1). + case "--offline": + opts.offline = true; + break; // `service logs` flags, the names `tail`, `journalctl` and every other // log reader uses — this is not the place to be original. case "-f": @@ -545,6 +565,7 @@ export const USAGE_SYNOPSIS = `Usage paddock service [options] install|uninstall|status|start|stop|restart|logs paddock busy [--json] is the running instance busy? paddock update [--check] [--to ] install a newer Paddock + paddock doctor [--json] [--offline] checks, with a fix for each problem paddock config [options] what this instance's config resolved to paddock -v | --version print the version and exit paddock -h | --help the full help`; @@ -569,6 +590,9 @@ Usage paddock update [--check] [--to ] install a newer Paddock and restart the service (\`paddock update --help\`) + paddock doctor [--json] [--offline] check this install, with a fix for + each problem + (\`paddock doctor --help\`) paddock config show [--resolved] what this instance's config resolved to, and where each value came from paddock config eject [--write] freeze that resolution into @@ -1058,3 +1082,54 @@ Asking the registry else https://registry.npmjs.org. Docs: https://github.com/edspencer/paddock`; + +export const DOCTOR_USAGE = `paddock doctor — check that Paddock can run here, with a fix for each problem + +Usage + paddock doctor run the checks, one line each + paddock doctor --json the same checks as one JSON document + paddock doctor --offline don't ask the npm registry for a newer version + +Options + --json One JSON document on stdout: ok, version, checks (each + with an id, a status, a message and, for a warning or + a failure, a fix). The update notice goes to stderr + --offline Skip the update check, the only one that uses the + network + -d, --data-dir Which instance to check (default: the service's, else + $PADDOCK_DATA_DIR, else ~/.paddock) + -h, --help Show this help + +What it checks + node-engines this Node satisfies the package's engines + install-method how Paddock was installed, and whether \`paddock update\` + can update it + unit the service: installed, running and answering, its Node + and CLI still there, the same install as this CLI + running-version the running Paddock is the installed version + port the port is free, or held by Paddock + linger on Linux, whether the service keeps running after you log out + data-home the data dir is writable + config paddock.config.yaml and the environment load, as \`serve\` + would load them + projects the projects folder is writable + claude-login a Claude login Paddock can use (which kind; never its value) + claude-cli a \`claude\` on PATH, which the sweeper always runs, and + chats and triggers do on driveMode: batch + update a newer version on the registry (skipped with --offline) + + Each line starts ✓ (fine), ! (a warning), ✗ (a failure) or - (doesn't apply + here), and every warning and failure has a fix: line under it. + +Exit codes + 0 nothing failed (warnings don't count) + 1 a check failed + 2 usage: an unknown flag, or a bad value + +Asking the registry + The update check is the only one that leaves this machine, and only because + you ran it. Like \`paddock update --check\`, it writes what it found to + /update-check.json, which \`paddock service status\` repeats. It + writes nothing else, and never creates the data dir. + +Docs: https://github.com/edspencer/paddock`; diff --git a/packages/server/src/cli/doctor.ts b/packages/server/src/cli/doctor.ts new file mode 100644 index 00000000..c22a46f6 --- /dev/null +++ b/packages/server/src/cli/doctor.ts @@ -0,0 +1,694 @@ +/** + * `paddock doctor [--json] [--offline]` (CLI contract SPEC §1). + * + * One `✓` / `!` / `✗` line a check (`-` for one that doesn't apply here), with a + * `fix:` line under every failure and warning. Exit 1 if any check failed; + * warnings don't change the code. + * + * The contract's eight come first, with the ids every tool uses so a script can + * read any of them: `node-engines`, `install-method`, `unit`, + * `running-version`, `port`, `linger`, `data-home` and `update`. Then Paddock's + * own: the config loads (`config`), the projects folder (`projects`), a Claude + * login it can use (`claude-login`) and a `claude` on PATH (`claude-cli`). + * + * It only reads, with one exception: like `update --check`, the `update` check + * writes what it found to `/update-check.json`, so `service status` + * can repeat it (SPEC §3) — but only into a data dir that's already there, so + * `doctor` never creates an instance. It asks the npm registry only because a + * person ran it, and `--offline` doesn't. It never prints a credential: the + * login check says which KIND of login it found. + * + * The service checks reuse `service status`'s own report (`buildStatus`), so the + * two cannot disagree about what is installed and what is running. + */ +import fs from "node:fs"; +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { MIN_NODE_MAJOR, type CliOptions } from "./args.js"; +import { EXIT } from "./exit-codes.js"; +import { + buildStatus, + serviceBackend, + type ServiceContext, + type StatusReport, +} from "./service/index.js"; +import { defaultDataDir, DEFAULT_PORT } from "./service/spec.js"; +import { missingPaths, which } from "./service/path-env.js"; +import type { LingerState, ServiceManager } from "./service/manager.js"; +import { fetchHealth } from "./service/ready.js"; +import { describeInstall, detectInstall, updateCommand, type InstallInfo } from "./update/install-method.js"; +import { npmConfigGet, npmGlobalRoot } from "./update/package-manager.js"; +import { RegistryError, resolveRegistry, resolveTarget } from "./update/registry.js"; +import { compareVersions, isPrerelease, satisfiesEngines } from "./update/semver.js"; +import { updateNotice, writeUpdateCheck } from "./update/update-check.js"; +import { readLiveRuntimeFile } from "../runtime-file.js"; +import { PADDOCK_NAME, PADDOCK_VERSION } from "../version.js"; +import { + PADDOCK_IMAGE, + PADDOCK_PACKAGE, + paddockChangelogUrl, +} from "./update-command.js"; + +export type CheckStatus = "pass" | "warn" | "fail" | "skip"; + +/** One line of the report, and one entry of `--json`'s `checks` (`schemas/doctor.schema.json`). */ +export interface Check { + /** Stable, for scripts. */ + id: string; + status: CheckStatus; + message: string; + /** What to do about it. Every `fail` has one, and so does every `warn`. */ + fix?: string; +} + +const MARK: Record = { pass: "✓", warn: "!", fail: "✗", skip: "-" }; + +/** The variables that log Claude Code in without a file (the same list `claude-home.ts` checks at boot). */ +const TOKEN_ENV_VARS = ["CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"] as const; + +/** What `doctor` reads of the instance's resolved config. */ +export interface InstanceConfig { + projectsRoot: string; + claudeHome: string; + credentials: "own" | "host"; + driveMode: "session" | "batch"; +} + +export interface DoctorInput { + ctx: ServiceContext; + /** `--data-dir`, when it was given. */ + dataDir?: string; + offline?: boolean; + /** `process.argv[1]`, for SPEC §6's walk-up. */ + entry: string; + env?: NodeJS.ProcessEnv; + /** Injected for tests. Everything below defaults to the real thing. */ + nodeVersion?: string; + npmGlobalRoot?: () => string | undefined; + registry?: string; + registryFetch?: typeof fetch; + /** Is anything accepting connections at host:port? */ + isListening?: (host: string, port: number) => Promise; + /** Is what answers at `url` a Paddock, and which version? Undefined if nothing answers HTTP there. */ + identify?: (url: string) => Promise<{ paddock: boolean; version?: string } | undefined>; + /** Load the instance's config for `dataDir`. Throws what `paddock serve` would fail with. */ + loadConfig?: (dataDir: string) => Promise; + /** The macOS Keychain probe `claude-home.ts` runs at boot. */ + keychain?: () => Promise<"found" | "unknown">; + /** `~/.claude`, the machine's own Claude home. */ + userClaudeHome?: string; +} + +export interface DoctorResult { + checks: Check[]; + /** SPEC §3's update notice, for stderr. */ + notice?: string; +} + +/** `/home/me/x` → `~/x`, for lines a person reads. */ +function tildify(p: string, home: string): string { + if (p === home) return "~"; + return p.startsWith(`${home}${path.sep}`) ? `~${p.slice(home.length)}` : p; +} + +export async function diagnose(i: DoctorInput): Promise { + const checks: Check[] = []; + const add = (c: Check): void => void checks.push(c); + const ctx = i.ctx; + const env = i.env ?? process.env; + const t = (p: string): string => tildify(p, ctx.homeDir); + let notice: string | undefined; + + // ---- how it was installed (SPEC §6). First, because the engines check reads + // the package root it finds. + const info: InstallInfo = detectInstall({ + packageName: PADDOCK_PACKAGE, + envPrefix: "PADDOCK", + entry: i.entry, + env, + npmGlobalRoot: i.npmGlobalRoot ?? (() => npmGlobalRoot({ env })), + }); + + // ---- this Node against the package's `engines` + const nodeVersion = i.nodeVersion ?? process.versions.node; + const engines = enginesOf(info.packageRoot) ?? `>=${MIN_NODE_MAJOR}`; + if (satisfiesEngines(nodeVersion, { node: engines }).ok === false) { + add({ + id: "node-engines", + status: "fail", + message: `Node ${nodeVersion} is too old: Paddock ${PADDOCK_VERSION} needs Node ${engines}`, + fix: `install Node ${engines} (nvm, fnm, Homebrew, nodejs.org), then run paddock with it`, + }); + } else { + add({ id: "node-engines", status: "pass", message: `Node ${nodeVersion} (Paddock needs ${engines})` }); + } + + const how = describeInstall(info, PADDOCK_PACKAGE); + if (info.canUpdate) { + add({ + id: "install-method", + status: "pass", + message: `Paddock ${PADDOCK_VERSION}, ${how}: \`paddock update\` can update it`, + }); + } else { + const cmd = updateCommand(info, { packageName: PADDOCK_PACKAGE, image: PADDOCK_IMAGE }); + add({ + id: "install-method", + status: "warn", + message: `Paddock ${PADDOCK_VERSION}, ${how}: \`paddock update\` can't update it`, + fix: `${cmd.command}${cmd.note !== undefined ? ` (${cmd.note})` : ""}`, + }); + } + + // ---- the unit: present, its Node and CLI still there, the same install as this CLI + let backend: ServiceManager | undefined; + let report: StatusReport | undefined; + try { + backend = serviceBackend(ctx); + report = await buildStatus(ctx, backend); + } catch (err) { + add({ + id: "unit", + status: "skip", + message: `there's no service here: ${firstLine((err as Error).message)}`, + }); + } + if (report !== undefined && !report.installed) { + add({ + id: "unit", + status: "skip", + message: "Paddock isn't installed as a service (`paddock service install` runs it from login)", + }); + } else if (report !== undefined) { + const before = checks.length; + for (const gone of missingPaths([report.node ?? undefined, report.cli ?? undefined])) { + add({ + id: "unit", + status: "fail", + message: `the service runs ${t(gone)}, which isn't there any more (a Node version removed with nvm, fnm or volta, or Paddock reinstalled elsewhere)`, + fix: "paddock service install --refresh (re-writes the unit for this Node and this install, keeping its port, host and data dir)", + }); + } + if (report.warnings.some((w) => w.includes("#872"))) { + add({ + id: "unit", + status: "warn", + message: "the unit predates a fix (#872): a clean stop (sleep, logout, a stray kill) leaves Paddock down until it's started by hand", + fix: "paddock service install --refresh", + }); + } + if (report.cli !== null && fs.existsSync(report.cli) && !samePath(report.cli, ctx.scriptPath)) { + add({ + id: "unit", + status: "warn", + message: `the service runs a different Paddock install (${t(report.cli)}) from this one (${t(ctx.scriptPath)})`, + fix: "run `paddock service install --refresh` from the install the service should run", + }); + } + if (!report.running) { + add({ + id: "unit", + status: "warn", + message: `the service is installed (${report.manager}) but not running`, + fix: "paddock service start (and `paddock service logs` if it doesn't stay up)", + }); + } else if (!report.answering) { + add({ + id: "unit", + status: "warn", + message: `the service is running, but ${report.url ?? "its URL"} isn't answering`, + fix: "paddock service logs", + }); + } + if (checks.length === before) { + add({ + id: "unit", + status: "pass", + message: `the service is installed (${report.manager}), running and answering at ${report.url ?? "?"}: ${t(report.unit)}`, + }); + } + } + + // The instance this run is about: an explicit --data-dir, else the unit's, + // else PADDOCK_DATA_DIR, else ~/.paddock. It's where `update-check.json` goes, + // and where `service status` reads it back from. + const home = path.resolve( + i.dataDir ?? + (report?.installed === true && report.dataDir !== null ? report.dataDir : undefined) ?? + ctx.envDataDir ?? + defaultDataDir(ctx.homeDir), + ); + + // ---- the running version is the installed one: the service's, or a `serve` in a terminal + const live = readLiveRuntimeFile(home); + const running = + report?.answering === true + ? { version: report.runningVersion, where: report.url ?? "the service", installed: report.installedVersion, via: "service" as const } + : live !== null + ? { version: live.version, where: live.url, installed: PADDOCK_VERSION, via: "serve" as const } + : undefined; + if (running === undefined) { + add({ id: "running-version", status: "skip", message: "Paddock isn't running" }); + } else if (running.version !== null && running.installed !== null && running.version !== running.installed) { + add({ + id: "running-version", + status: "fail", + message: `${running.where} is running ${running.version}, but ${running.installed} is installed: it's still running the code it started with`, + fix: + running.via === "service" + ? "paddock service restart" + : "stop the `paddock serve` in its terminal (Ctrl-C) and start it again", + }); + } else { + add({ + id: "running-version", + status: "pass", + message: `${running.where} is running ${running.version ?? "an unknown version"}${running.via === "serve" ? " (in a terminal)" : ""}`, + }); + } + + // ---- the port: free, or held by Paddock + const port = Number( + report?.installed === true && report.port !== null + ? report.port + : (live?.port ?? env.PORT ?? DEFAULT_PORT), + ); + const host = loopbackFor(report?.installed === true && report.host !== null ? report.host : "127.0.0.1"); + const listening = await (i.isListening ?? isListening)(host, port); + if (!listening) { + add({ id: "port", status: "pass", message: `port ${port} is free` }); + } else { + const who = await (i.identify ?? identify)(`http://${urlHost(host)}:${port}`); + if (who?.paddock === true) { + add({ + id: "port", + status: "pass", + message: `port ${port} is Paddock's${who.version !== undefined ? ` (${who.version})` : ""}`, + }); + } else { + add({ + id: "port", + status: "fail", + // Something answered /api/health but not /api/busy: another tool, or a + // Paddock from before the busy check, which can't be told apart. + message: + who !== undefined + ? `something that isn't Paddock (or is a Paddock older than 0.81) is listening on port ${port}` + : `something that isn't Paddock is listening on port ${port}`, + fix: + report?.installed === true + ? "stop it, or move the service: `paddock service install --port `" + : "stop it, or run Paddock on another port: `paddock --port `", + }); + } + } + + // ---- linger, on Linux: without it the service stops when you log out + let linger: LingerState | undefined; + try { + linger = backend?.linger(); + } catch { + linger = undefined; + } + if (linger === undefined || !linger.applies) { + add({ id: "linger", status: "skip", message: "linger only applies to Linux" }); + } else { + const user = linger.user ?? "$USER"; + if (linger.enabled === true) { + add({ id: "linger", status: "pass", message: `linger is on for ${user}: the service keeps running when you log out` }); + } else if (linger.enabled === false && report?.installed === true) { + add({ + id: "linger", + status: "warn", + message: `linger is off for ${user}: the service stops when you log out, and starts only when you log in`, + fix: `sudo loginctl enable-linger ${user} (Paddock never runs sudo itself)`, + }); + } else if (linger.enabled === false) { + add({ + id: "linger", + status: "pass", + message: `linger is off for ${user}, which only matters once Paddock runs as a service`, + }); + } else { + add({ id: "linger", status: "skip", message: "couldn't ask loginctl about linger" }); + } + } + + // ---- the data home is writable + const writable = writableOrCreatable(home); + if (writable === true) { + add({ id: "data-home", status: "pass", message: `the data dir ${t(home)} is writable` }); + } else if (writable === "creatable") { + add({ + id: "data-home", + status: "pass", + message: `the data dir ${t(home)} doesn't exist yet; Paddock makes it the first time it runs`, + }); + } else { + add({ + id: "data-home", + status: "fail", + message: `the data dir ${t(home)} isn't writable: ${writable}`, + fix: `check the permissions of ${t(home)}: it holds your projects, chats and settings`, + }); + } + + // ---- Paddock's own: the config loads, and what it resolves to + let cfg: InstanceConfig | undefined; + try { + cfg = await (i.loadConfig ?? loadInstanceConfig)(home); + add({ id: "config", status: "pass", message: "the config loads" }); + } catch (err) { + add({ + id: "config", + status: "fail", + message: `the config doesn't load, so \`paddock serve\` would fail too: ${firstLine((err as Error).message)}`, + fix: "fix what it names (`paddock config show` prints the same error)", + }); + } + + if (cfg === undefined) { + add({ id: "projects", status: "skip", message: "the config didn't load, so the projects folder is unknown" }); + } else { + const projects = writableOrCreatable(cfg.projectsRoot); + if (projects === true) { + add({ id: "projects", status: "pass", message: `the projects folder ${t(cfg.projectsRoot)} is writable` }); + } else if (projects === "creatable") { + add({ + id: "projects", + status: "pass", + message: `the projects folder ${t(cfg.projectsRoot)} doesn't exist yet; Paddock makes it the first time it runs`, + }); + } else { + add({ + id: "projects", + status: "fail", + message: `the projects folder ${t(cfg.projectsRoot)} isn't writable: ${projects}`, + fix: "fix its permissions, or point PADDOCK_PROJECTS_DIR (or `projectsRoot:` in paddock.config.yaml) somewhere writable", + }); + } + } + + // ---- a Claude login it can use. Which KIND, never the value. + if (cfg !== undefined) add(await loginCheck(cfg, env, i, t, report?.installed === true)); + else add({ id: "claude-login", status: "skip", message: "the config didn't load, so Paddock's Claude home is unknown" }); + + // ---- a `claude` on PATH: the sweeper always shells out to it, and on + // driveMode: batch so do chats and triggers. + const claude = which("claude", env.PATH ?? ""); + if (claude !== undefined) { + add({ id: "claude-cli", status: "pass", message: `claude is on PATH (${t(claude)})` }); + } else { + const batch = cfg?.driveMode === "batch"; + add({ + id: "claude-cli", + status: batch ? "fail" : "warn", + message: batch + ? "there's no `claude` on PATH, and driveMode is batch: every chat turn and trigger runs it, so they'll all fail" + : "there's no `claude` on PATH: chats work (they use the SDK's own), but the sweeper that keeps OVERVIEW.md and CHANGELOG.md current runs `claude` and will fail", + fix: "npm install -g @anthropic-ai/claude-code (then re-run `paddock service install --refresh` if it's a service, so the unit's PATH has it)", + }); + } + + // ---- a newer version (SPEC §1). The only check that asks the network, and --offline skips it. + if (i.offline === true) { + add({ id: "update", status: "skip", message: "not asking the registry for a newer version (--offline)" }); + } else { + try { + const target = await resolveTarget({ + packageName: PADDOCK_PACKAGE, + registry: i.registry ?? resolveRegistry(env, (k) => npmConfigGet(k, { env })), + ...(i.registryFetch !== undefined ? { fetch: i.registryFetch } : {}), + }); + const cmp = compareVersions(target.version, PADDOCK_VERSION); + const available = cmp > 0 && !isPrerelease(target.version); + const cmd = info.canUpdate + ? { command: "paddock update" } + : updateCommand(info, { packageName: PADDOCK_PACKAGE, target: target.version, image: PADDOCK_IMAGE }); + // Only into a data dir that's there. Making it here would make the instance: + // `serve` prints its first-run welcome only when the data dir is new, and + // `config show` stays out of it for the same reason. + if (fs.existsSync(home)) writeUpdateCheck(home, { + name: PADDOCK_PACKAGE, + current: PADDOCK_VERSION, + target: target.version, + tag: target.tag, + updateAvailable: available, + installMethod: info.method, + canUpdate: info.canUpdate, + command: available ? cmd.command : null, + engines: target.engines, + nodeOk: satisfiesEngines(nodeVersion, target.engines !== null ? { node: target.engines } : undefined).ok !== false, + changelog: paddockChangelogUrl(target.version), + checkedAt: new Date().toISOString(), + }); + if (available) { + notice = updateNotice({ + name: PADDOCK_NAME, + current: PADDOCK_VERSION, + target: target.version, + command: cmd.command, + ...("note" in cmd && cmd.note !== undefined ? { note: cmd.note } : {}), + changelog: paddockChangelogUrl(target.version), + }); + add({ + id: "update", + status: "warn", + message: `Paddock ${target.version} is available (you have ${PADDOCK_VERSION})`, + fix: cmd.command, + }); + } else { + add({ + id: "update", + status: "pass", + message: + cmp < 0 + ? `${PADDOCK_VERSION} is newer than the registry's latest (${target.version})` + : `${PADDOCK_VERSION} is the latest`, + }); + } + } catch (err) { + add({ + id: "update", + status: "warn", + message: `couldn't ask the registry for a newer version: ${ + err instanceof RegistryError ? `${err.message} (${err.url})` : firstLine((err as Error).message) + }`, + fix: "check the network (or npm_config_registry), or skip this check with --offline", + }); + } + } + + return { checks, ...(notice !== undefined ? { notice } : {}) }; +} + +/** The `claude-login` check: what kind of login Paddock would find, never its value. */ +async function loginCheck( + cfg: InstanceConfig, + env: NodeJS.ProcessEnv, + i: DoctorInput, + t: (p: string) => string, + service: boolean, +): Promise { + const tokenVar = TOKEN_ENV_VARS.find((v) => (env[v] ?? "").trim() !== ""); + if (tokenVar !== undefined) { + return { + id: "claude-login", + status: "pass", + message: + `${tokenVar} is set in this shell` + + (service ? " (the service doesn't inherit this shell's environment, so it needs a login of its own)" : ""), + }; + } + if (fs.existsSync(path.join(cfg.claudeHome, ".credentials.json"))) { + return { id: "claude-login", status: "pass", message: `a Claude login is in Paddock's Claude home (${t(cfg.claudeHome)})` }; + } + const userHome = i.userClaudeHome ?? path.join(os.homedir(), ".claude"); + if (cfg.credentials === "host") { + if (fs.existsSync(path.join(userHome, ".credentials.json"))) { + return { + id: "claude-login", + status: "pass", + message: `Paddock shares this machine's Claude Code login (${t(userHome)}, claude.credentials: host)`, + }; + } + if (i.ctx.platform === "darwin") { + const keychain = await (i.keychain ?? probeKeychain)(); + if (keychain === "found") { + return { + id: "claude-login", + status: "pass", + message: "Paddock shares this machine's Claude Code login, from the macOS Keychain (claude.credentials: host)", + }; + } + } + } + return { + id: "claude-login", + status: "warn", + message: + `no Claude login found for Paddock: none in its Claude home (${t(cfg.claudeHome)}), no ${TOKEN_ENV_VARS.join("/")} in the environment` + + (cfg.credentials === "host" ? ", and none on this machine to share" : ", and claude.credentials: own shares none of this machine's") + + ". Chats will fail with \"Not logged in\"", + fix: `CLAUDE_CONFIG_DIR=${t(cfg.claudeHome)} claude login (or \`claude setup-token\` and put the token in CLAUDE_CODE_OAUTH_TOKEN)`, + }; +} + +/** The checklist, for a person. */ +export function renderChecks(checks: readonly Check[]): string { + return ( + checks + .map( + (c) => + `${MARK[c.status]} ${c.message}` + + (c.fix !== undefined && (c.status === "fail" || c.status === "warn") ? `\n fix: ${c.fix}` : ""), + ) + .join("\n") + "\n" + ); +} + +/** 1 if any check failed (SPEC §1); warnings don't change it. */ +export function doctorExit(checks: readonly Check[]): number { + return checks.some((c) => c.status === "fail") ? EXIT.FAILED : EXIT.OK; +} + +/** `paddock doctor`: run the checks, print them, and hand back the exit code. */ +export async function runDoctor(opts: CliOptions, ctx: ServiceContext): Promise { + const { checks, notice } = await diagnose({ + ctx, + ...(opts.dataDir !== undefined ? { dataDir: opts.dataDir } : {}), + ...(opts.offline === true ? { offline: true } : {}), + entry: process.argv[1] ?? ctx.scriptPath, + }); + const code = doctorExit(checks); + if (opts.json === true) { + process.stdout.write( + `${JSON.stringify({ ok: code === EXIT.OK, version: PADDOCK_VERSION, checks }, null, 2)}\n`, + ); + } else { + process.stdout.write(renderChecks(checks)); + } + // The update notice goes to stderr (SPEC §3), with or without --json. + if (notice !== undefined) process.stderr.write(`\n${notice}\n`); + return code; +} + +// ---- the real implementations of the injected seams + +/** The package's `engines.node`, read from the package root §6's walk-up found. */ +function enginesOf(packageRoot: string | undefined): string | undefined { + if (packageRoot === undefined) return undefined; + try { + const raw = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8")) as { + engines?: { node?: unknown }; + }; + return typeof raw.engines?.node === "string" ? raw.engines.node : undefined; + } catch { + return undefined; + } +} + +/** + * Load the instance's config the way `paddock serve` would, without creating + * anything. `loadPaddockConfig` reads `PADDOCK_DATA_DIR`, so it's set for the + * call and put back. + */ +async function loadInstanceConfig(dataDir: string): Promise { + const before = process.env.PADDOCK_DATA_DIR; + process.env.PADDOCK_DATA_DIR = dataDir; + try { + const { loadPaddockConfig } = await import("../config.js"); + const cfg = loadPaddockConfig({ createDataDir: false }); + return { + projectsRoot: cfg.projectsRoot, + claudeHome: cfg.claudeHome, + credentials: cfg.claude.credentials, + driveMode: cfg.driveMode, + }; + } finally { + if (before === undefined) delete process.env.PADDOCK_DATA_DIR; + else process.env.PADDOCK_DATA_DIR = before; + } +} + +async function probeKeychain(): Promise<"found" | "unknown"> { + const { probeMacosKeychainLogin } = await import("../claude-home.js"); + return probeMacosKeychainLogin(); +} + +/** True if `dir` is writable; "creatable" if it doesn't exist but its nearest existing parent is; else why not. */ +export function writableOrCreatable(dir: string): true | "creatable" | string { + let probe = dir; + while (!fs.existsSync(probe)) { + const parent = path.dirname(probe); + if (parent === probe) return "no part of it exists"; + probe = parent; + } + try { + if (!fs.statSync(probe).isDirectory()) return `${probe} isn't a folder`; + fs.accessSync(probe, fs.constants.W_OK); + return probe === dir ? true : "creatable"; + } catch (err) { + return (err as Error).message; + } +} + +function samePath(a: string, b: string): boolean { + const real = (p: string): string => { + try { + return fs.realpathSync(p); + } catch { + return path.resolve(p); + } + }; + return real(a) === real(b); +} + +/** A wildcard bind is reached on loopback. */ +function loopbackFor(host: string): string { + if (host === "0.0.0.0" || host === "") return "127.0.0.1"; + if (host === "::" || host === "[::]") return "::1"; + return host; +} + +function urlHost(host: string): string { + return host.includes(":") ? `[${host}]` : host; +} + +function firstLine(s: string): string { + return s.split("\n")[0] ?? s; +} + +function isListening(host: string, port: number): Promise { + return new Promise((resolve) => { + const s = net.connect({ host, port }); + s.setTimeout(1000); + s.once("connect", () => { + s.destroy(); + resolve(true); + }); + s.once("timeout", () => { + s.destroy(); + resolve(false); + }); + s.once("error", () => resolve(false)); + }); +} + +/** + * Is this a Paddock? `/api/health`'s `{ ok, version }` is the contract's, so + * every tool answers it; `/api/busy`'s `counts.chat` is Paddock's own. + */ +async function identify(url: string): Promise<{ paddock: boolean; version?: string } | undefined> { + const health = await fetchHealth(url); + if (health === undefined) return undefined; + try { + const res = await fetch(`${url}/api/busy`, { signal: AbortSignal.timeout(2_000) }); + const body = (await res.json()) as { counts?: Record }; + const paddock = health.ok && typeof body.counts?.chat === "number" && "background" in (body.counts ?? {}); + return { paddock, ...(health.version !== undefined ? { version: health.version } : {}) }; + } catch { + return { paddock: false, ...(health.version !== undefined ? { version: health.version } : {}) }; + } +} diff --git a/packages/server/src/cli/paddock.ts b/packages/server/src/cli/paddock.ts index 2bf71d66..ff769d62 100644 --- a/packages/server/src/cli/paddock.ts +++ b/packages/server/src/cli/paddock.ts @@ -34,6 +34,7 @@ import { CONFIG_USAGE, BUSY_USAGE, UPDATE_USAGE, + DOCTOR_USAGE, parseCommand, nodeVersionProblem, explainListenError, @@ -307,7 +308,9 @@ async function main(): Promise { ? BUSY_USAGE : command.verb === "update" ? UPDATE_USAGE - : USAGE, + : command.verb === "doctor" + ? DOCTOR_USAGE + : USAGE, ); return EXIT.OK; } @@ -348,6 +351,19 @@ async function main(): Promise { } } + // `doctor` (SPEC §1). Dynamic for the same reason `busy` and `update` are; it + // loads the config only to check it, and starts nothing. + if (command.verb === "doctor") { + const { runDoctor } = await import("./doctor.js"); + try { + return await runDoctor(opts, serviceContext()); + } catch (err) { + if (err instanceof CliError) return fail(err.message, err.exitCode); + if (err instanceof Error) return fail(err.message); + throw err; + } + } + addBundledBinsToPath(); // NOTHING here reads `process.cwd()`, and that is the point (#798). `--here` diff --git a/packages/server/src/cli/service/index.ts b/packages/server/src/cli/service/index.ts index f57d0601..2489878b 100644 --- a/packages/server/src/cli/service/index.ts +++ b/packages/server/src/cli/service/index.ts @@ -112,6 +112,10 @@ export interface ServiceContext { * either of these without a scheduled task or a service wrapper, and shipping * an untested third writer would be worse than saying so. */ +export function serviceBackend(ctx: ServiceContext): ServiceBackend { + return backendFor(ctx); +} + function backendFor(ctx: ServiceContext): ServiceBackend { const run = ctx.run ?? spawnRunner; if (ctx.platform === "darwin") return createLaunchd(PADDOCK_SERVICE, { run, homeDir: ctx.homeDir }); @@ -490,7 +494,8 @@ function withUpdate(home: string): { update?: UpdateSummary } { return summary !== undefined ? { update: summary } : {}; } -async function buildStatus(ctx: ServiceContext, backend: ServiceBackend): Promise { +/** What `status` reports, and what `doctor`'s service checks read: one report, so the two agree. */ +export async function buildStatus(ctx: ServiceContext, backend: ServiceBackend): Promise { const state = backend.status(); const base = { installed: state.registered, diff --git a/packages/server/test/unit/cli-doctor.test.ts b/packages/server/test/unit/cli-doctor.test.ts new file mode 100644 index 00000000..528abab7 --- /dev/null +++ b/packages/server/test/unit/cli-doctor.test.ts @@ -0,0 +1,466 @@ +/** + * `paddock doctor [--json] [--offline]` (CLI contract SPEC §1). + * + * Everything that touches the machine is injected — the service manager's + * commands, the port probe, the registry, the config loader — so each check's + * pass, warning and failure can be arranged on one box. What these do NOT prove + * is that a real systemd or launchd agrees: `service status`'s own tests and the + * real-service CI cover the report `doctor` reads. + */ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { parseCommand, UsageError, DOCTOR_USAGE, USAGE, USAGE_SYNOPSIS } from "../../src/cli/args.js"; +import { EXIT } from "../../src/cli/exit-codes.js"; +import { + diagnose, + doctorExit, + renderChecks, + type Check, + type DoctorInput, + type InstanceConfig, +} from "../../src/cli/doctor.js"; +import type { Runner } from "../../src/cli/service/manager.js"; +import { createSystemd } from "../../src/cli/service/systemd.js"; +import { buildSpec, PADDOCK_SERVICE } from "../../src/cli/service/spec.js"; +import { readUpdateCheck } from "../../src/cli/update/update-check.js"; +import { writeRuntimeFile } from "../../src/runtime-file.js"; +import { PADDOCK_VERSION } from "../../src/version.js"; +// The contract's own validator and schema, from the conformance runner this repo +// already uses: a `--json` that drifts from `schemas/doctor.schema.json` fails here. +import { validate, loadSchema, formatErrors } from "@edspencer/cli-conformance/dist/src/schema.js"; + +const SPEC_IDS = [ + "node-engines", + "install-method", + "unit", + "running-version", + "port", + "linger", + "data-home", + "update", +]; + +let home: string; +let cli: string; +let node: string; + +beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), "paddock-doctor-")); + // A pretend global install, so the walk-up finds a named package with engines. + const pkg = path.join(home, "lib", "node_modules", "@edspencer", "paddock"); + cli = path.join(pkg, "packages", "server", "dist", "cli", "paddock.js"); + fs.mkdirSync(path.dirname(cli), { recursive: true }); + fs.writeFileSync(cli, ""); + fs.writeFileSync( + path.join(pkg, "package.json"), + JSON.stringify({ name: "@edspencer/paddock", version: PADDOCK_VERSION, engines: { node: ">=22" } }), + ); + node = path.join(home, "bin", "node"); + fs.mkdirSync(path.dirname(node), { recursive: true }); + fs.writeFileSync(node, ""); +}); + +afterEach(() => { + fs.rmSync(home, { recursive: true, force: true }); +}); + +/** A systemd that answers: is-active, MainPID and linger as given. */ +function systemd(o: { active?: boolean; linger?: "yes" | "no" | "none" } = {}): Runner { + return (cmd, args) => { + if (cmd === "systemctl" && args.includes("is-active")) + return { status: o.active ? 0 : 3, stdout: o.active ? "active\n" : "inactive\n", stderr: "" }; + if (cmd === "systemctl" && args.includes("MainPID")) + return { status: 0, stdout: o.active ? "4242\n" : "0\n", stderr: "" }; + if (cmd === "loginctl") + return o.linger === "none" || o.linger === undefined + ? { status: null, stdout: "", stderr: "" } + : { status: 0, stdout: `Linger=${o.linger}\n`, stderr: "" }; + return { status: 0, stdout: "", stderr: "" }; + }; +} + +const CONFIG = (dataDir: string): InstanceConfig => ({ + projectsRoot: path.join(dataDir, "projects"), + claudeHome: path.join(dataDir, "claude-home"), + credentials: "own", + driveMode: "session", +}); + +/** A registry that serves `latest` and its manifest. */ +function registry(latest: string): typeof fetch { + return (async (url: string | URL) => { + const u = String(url); + if (u.includes("dist-tags")) return new Response(JSON.stringify({ latest }), { status: 200 }); + return new Response(JSON.stringify({ name: "@edspencer/paddock", version: latest, engines: { node: ">=22" } }), { + status: 200, + }); + }) as typeof fetch; +} + +function input(over: Partial & { run?: Runner } = {}): DoctorInput { + const { run, ...rest } = over; + return { + ctx: { + platform: "linux", + nodePath: node, + scriptPath: cli, + packageRoot: path.dirname(cli), + homeDir: home, + run: run ?? systemd(), + probeHealth: async () => undefined, + }, + entry: cli, + env: { PATH: path.join(home, "bin") }, + nodeVersion: "22.23.4", + npmGlobalRoot: () => path.join(home, "lib", "node_modules"), + registry: "http://registry.test", + registryFetch: registry(PADDOCK_VERSION), + isListening: async () => false, + identify: async () => undefined, + loadConfig: async (d) => CONFIG(d), + userClaudeHome: path.join(home, ".claude"), + ...rest, + }; +} + +const byId = (checks: Check[], id: string): Check[] => checks.filter((c) => c.id === id); +const one = (checks: Check[], id: string): Check => { + const found = byId(checks, id); + expect(found, id).toHaveLength(1); + return found[0]; +}; + +function installUnit(o: { port?: string } = {}): void { + createSystemd(PADDOCK_SERVICE, { run: systemd(), homeDir: home }).install( + buildSpec({ + nodePath: node, + scriptPath: cli, + dataDir: path.join(home, ".paddock"), + ...(o.port !== undefined ? { port: o.port } : {}), + }), + ); +} + +describe("paddock doctor: parsing", () => { + it("is a verb, and takes --json and --offline", () => { + const c = parseCommand(["doctor", "--json", "--offline"]); + expect(c.verb).toBe("doctor"); + expect(c.opts.json).toBe(true); + expect(c.opts.offline).toBe(true); + }); + + it.each([ + ["busy", "--offline"], + ["update", "--offline"], + ["serve", "--offline"], + ["service", "status", "--offline"], + ["config", "show", "--offline"], + ])("--offline is a usage error anywhere else: %s", (...argv) => { + expect(() => parseCommand(argv)).toThrow(UsageError); + try { + parseCommand(argv); + } catch (err) { + expect((err as UsageError).exitCode).toBe(EXIT.USAGE); + expect((err as Error).message).toContain("--offline applies to `doctor` only"); + } + }); + + it.each([["--force"], ["--check"], ["--refresh"], ["--yes"]])("doctor %s is a usage error", (flag) => { + expect(() => parseCommand(["doctor", flag])).toThrow(UsageError); + }); + + it("the help and the synopsis name it", () => { + expect(USAGE).toContain("paddock doctor [--json] [--offline]"); + expect(USAGE_SYNOPSIS).toContain("paddock doctor"); + for (const id of [...SPEC_IDS, "config", "projects", "claude-login", "claude-cli"]) { + expect(DOCTOR_USAGE).toContain(id); + } + }); +}); + +describe("paddock doctor: the checks", () => { + it("runs the contract's eight checks with their ids, then Paddock's own, and its --json fits the schema", async () => { + const { checks } = await diagnose(input()); + const ids = [...new Set(checks.map((c) => c.id))]; + expect(ids).toEqual([ + "node-engines", + "install-method", + "unit", + "running-version", + "port", + "linger", + "data-home", + "config", + "projects", + "claude-login", + "claude-cli", + "update", + ]); + const doc = { ok: doctorExit(checks) === 0, version: PADDOCK_VERSION, checks }; + expect(formatErrors(validate(loadSchema("doctor"), doc))).toBe(""); + }); + + it("a fresh machine: nothing failed, and nothing was created", async () => { + const { checks, notice } = await diagnose(input()); + expect(doctorExit(checks)).toBe(EXIT.OK); + expect(one(checks, "install-method").status).toBe("pass"); + expect(one(checks, "unit").status).toBe("skip"); + expect(one(checks, "running-version").status).toBe("skip"); + expect(one(checks, "port")).toMatchObject({ status: "pass", message: "port 7233 is free" }); + expect(one(checks, "data-home").message).toContain("doesn't exist yet"); + expect(one(checks, "update")).toMatchObject({ status: "pass", message: `${PADDOCK_VERSION} is the latest` }); + expect(notice).toBeUndefined(); + // Not even update-check.json: writing it would create the data dir, and with + // it the instance (serve's first-run welcome keys on the dir being new). + expect(fs.existsSync(path.join(home, ".paddock"))).toBe(false); + }); + + it("every warning and every failure has a fix, and the rendering puts it under the line", async () => { + installUnit(); + fs.rmSync(node); + const { checks } = await diagnose( + input({ + run: systemd({ active: false, linger: "no" }), + isListening: async () => true, + identify: async () => ({ paddock: false }), + registryFetch: registry("99.0.0"), + }), + ); + for (const c of checks) if (c.status === "fail" || c.status === "warn") expect(c.fix, c.id).toBeTruthy(); + const text = renderChecks(checks); + for (const line of text.trimEnd().split("\n")) expect(line).toMatch(/^([✓!✗-] | fix: )/); + expect(text).toMatch(/^✗ the service runs .*node, which isn't there any more.*\n fix: paddock service install --refresh/m); + }); + + describe("unit", () => { + it("passes for an installed, running, answering service", async () => { + installUnit(); + const i = input({ run: systemd({ active: true, linger: "yes" }) }); + i.ctx.probeHealth = async () => ({ ok: true, version: PADDOCK_VERSION }); + const r = await diagnose({ ...i, isListening: async () => true, identify: async () => ({ paddock: true, version: PADDOCK_VERSION }) }); + expect(one(r.checks, "unit")).toMatchObject({ status: "pass" }); + expect(one(r.checks, "unit").message).toContain("running and answering at http://127.0.0.1:7233"); + expect(one(r.checks, "running-version").status).toBe("pass"); + expect(one(r.checks, "port")).toMatchObject({ status: "pass", message: `port 7233 is Paddock's (${PADDOCK_VERSION})` }); + expect(one(r.checks, "linger").status).toBe("pass"); + expect(doctorExit(r.checks)).toBe(EXIT.OK); + }); + + it("fails when the Node it runs has gone", async () => { + installUnit(); + fs.rmSync(node); + const { checks } = await diagnose(input({ run: systemd({ active: true }) })); + const unit = byId(checks, "unit").find((c) => c.status === "fail"); + expect(unit?.message).toContain("isn't there any more"); + expect(doctorExit(checks)).toBe(EXIT.FAILED); + }); + + it("warns when the unit runs a different install from this CLI", async () => { + installUnit(); + const other = path.join(home, "other", "paddock.js"); + fs.mkdirSync(path.dirname(other), { recursive: true }); + fs.writeFileSync(other, ""); + const i = input({ run: systemd({ active: true }) }); + i.ctx.scriptPath = other; + i.ctx.probeHealth = async () => ({ ok: true, version: PADDOCK_VERSION }); + const { checks } = await diagnose(i); + const w = byId(checks, "unit").find((c) => c.status === "warn"); + expect(w?.message).toContain("a different Paddock install"); + expect(w?.fix).toContain("--refresh"); + }); + + it("warns when it's installed but not running", async () => { + installUnit(); + const { checks } = await diagnose(input({ run: systemd({ active: false }) })); + expect(one(checks, "unit")).toMatchObject({ status: "warn", fix: expect.stringContaining("paddock service start") }); + }); + + it("skips, rather than failing, where there's no service manager (Windows)", async () => { + const i = input(); + i.ctx.platform = "win32"; + const { checks } = await diagnose(i); + expect(one(checks, "unit").status).toBe("skip"); + expect(one(checks, "linger").status).toBe("skip"); + }); + }); + + describe("running-version", () => { + it("fails when the service runs an older version than is installed", async () => { + installUnit(); + const i = input({ run: systemd({ active: true }) }); + i.ctx.probeHealth = async () => ({ ok: true, version: "0.0.1" }); + const { checks } = await diagnose(i); + expect(one(checks, "running-version")).toMatchObject({ status: "fail", fix: "paddock service restart" }); + }); + + it("finds a foreground serve through runtime.json", async () => { + const dataDir = path.join(home, ".paddock"); + writeRuntimeFile(dataDir, { pid: process.pid, port: 7300, url: "http://127.0.0.1:7300", version: "0.0.1" }); + const { checks } = await diagnose(input()); + expect(one(checks, "running-version")).toMatchObject({ + status: "fail", + fix: expect.stringContaining("Ctrl-C"), + }); + // …and the port check follows it to 7300. + expect(one(checks, "port").message).toBe("port 7300 is free"); + }); + }); + + describe("port", () => { + it("fails when something that isn't Paddock holds it, and names the unit's port", async () => { + installUnit({ port: "7299" }); + const { checks } = await diagnose( + input({ isListening: async (_h, p) => p === 7299, identify: async () => undefined }), + ); + expect(one(checks, "port")).toMatchObject({ + status: "fail", + message: "something that isn't Paddock is listening on port 7299", + fix: expect.stringContaining("paddock service install --port"), + }); + }); + }); + + describe("linger", () => { + it("warns only when there is a service for it to matter to", async () => { + expect(one((await diagnose(input({ run: systemd({ linger: "no" }) }))).checks, "linger").status).toBe("pass"); + installUnit(); + const c = one((await diagnose(input({ run: systemd({ linger: "no" }) }))).checks, "linger"); + expect(c.status).toBe("warn"); + expect(c.fix).toMatch(/^sudo loginctl enable-linger /); + }); + }); + + describe("data-home", () => { + it("fails when the data dir can't be written", async () => { + if (process.getuid?.() === 0) return; // root writes anywhere + const dir = path.join(home, "ro"); + fs.mkdirSync(dir, { mode: 0o500 }); + const { checks } = await diagnose(input({ dataDir: dir })); + expect(one(checks, "data-home").status).toBe("fail"); + }); + + it("--data-dir picks the instance", async () => { + const dir = path.join(home, "elsewhere"); + fs.mkdirSync(dir); + const { checks } = await diagnose(input({ dataDir: dir })); + expect(one(checks, "data-home").message).toBe("the data dir ~/elsewhere is writable"); + expect(readUpdateCheck(dir)).not.toBeNull(); + }); + }); + + describe("Paddock's own", () => { + it("config: a config that won't load fails, and the checks that need it skip", async () => { + const { checks } = await diagnose( + input({ + loadConfig: async () => { + throw new Error("Failed to parse Paddock config file /x/paddock.config.yaml as YAML: bad\nmore"); + }, + }), + ); + expect(one(checks, "config")).toMatchObject({ status: "fail" }); + expect(one(checks, "config").message).toContain("as YAML: bad"); + expect(one(checks, "config").message).not.toContain("more"); + expect(one(checks, "projects").status).toBe("skip"); + expect(one(checks, "claude-login").status).toBe("skip"); + }); + + it("config: the real loader reads a real data dir without creating it", async () => { + const dir = path.join(home, "never-made"); + const { checks } = await diagnose(input({ dataDir: dir, loadConfig: undefined, offline: true })); + expect(one(checks, "config").status).toBe("pass"); + expect(fs.existsSync(dir)).toBe(false); + }); + + it("claude-login: names the kind of login, never its value", async () => { + // Plainly not a token, so no secret scanner mistakes the fixture for one. + const secret = "placeholder-value-doctor-must-not-print"; + const { checks } = await diagnose(input({ env: { PATH: "", CLAUDE_CODE_OAUTH_TOKEN: secret } })); + const c = one(checks, "claude-login"); + expect(c).toMatchObject({ status: "pass", message: "CLAUDE_CODE_OAUTH_TOKEN is set in this shell" }); + expect(JSON.stringify(checks)).not.toContain(secret); + }); + + it("claude-login: a host login is found when credentials is host, and not when it's own", async () => { + fs.mkdirSync(path.join(home, ".claude")); + fs.writeFileSync(path.join(home, ".claude", ".credentials.json"), "{}"); + const own = one((await diagnose(input())).checks, "claude-login"); + expect(own.status).toBe("warn"); + expect(own.message).toContain("claude.credentials: own"); + const host = one( + (await diagnose(input({ loadConfig: async (d) => ({ ...CONFIG(d), credentials: "host" }) }))).checks, + "claude-login", + ); + expect(host).toMatchObject({ status: "pass" }); + expect(host.message).toContain("shares this machine's Claude Code login"); + }); + + it("claude-login: the macOS Keychain counts on darwin", async () => { + const i = input({ + keychain: async () => "found", + loadConfig: async (d) => ({ ...CONFIG(d), credentials: "host" }), + }); + i.ctx.platform = "darwin"; + expect(one((await diagnose(i)).checks, "claude-login").message).toContain("macOS Keychain"); + }); + + it("claude-cli: no claude is a warning on session, a failure on batch", async () => { + expect(one((await diagnose(input())).checks, "claude-cli").status).toBe("warn"); + const batch = await diagnose(input({ loadConfig: async (d) => ({ ...CONFIG(d), driveMode: "batch" }) })); + expect(one(batch.checks, "claude-cli").status).toBe("fail"); + expect(doctorExit(batch.checks)).toBe(EXIT.FAILED); + + const claude = path.join(home, "bin", "claude"); + fs.writeFileSync(claude, "#!/bin/sh\n", { mode: 0o755 }); + expect(one((await diagnose(input())).checks, "claude-cli")).toMatchObject({ status: "pass" }); + }); + }); + + describe("update", () => { + it("a newer version is a warning with the notice, and update-check.json is written for status", async () => { + fs.mkdirSync(path.join(home, ".paddock")); + const r = await diagnose(input({ registryFetch: registry("99.0.0") })); + expect(one(r.checks, "update")).toMatchObject({ status: "warn", fix: "paddock update" }); + expect(r.notice).toContain(`Paddock 99.0.0 is available (you have ${PADDOCK_VERSION}).`); + expect(r.notice).toContain("Run: paddock update"); + expect(doctorExit(r.checks)).toBe(EXIT.OK); + const cache = readUpdateCheck(path.join(home, ".paddock")); + expect(cache).toMatchObject({ current: PADDOCK_VERSION, target: "99.0.0", updateAvailable: true, command: "paddock update" }); + }); + + it("an install that can't update itself gets its own command", async () => { + const r = await diagnose(input({ registryFetch: registry("99.0.0"), env: { PATH: "", PADDOCK_IN_DOCKER: "1" } })); + expect(one(r.checks, "install-method").status).toBe("warn"); + expect(one(r.checks, "update").fix).toBe("docker compose pull && docker compose up -d"); + }); + + it("a registry that doesn't answer is a warning, not a failure", async () => { + const r = await diagnose( + input({ + registryFetch: (async () => { + throw new Error("connect ECONNREFUSED"); + }) as typeof fetch, + }), + ); + expect(one(r.checks, "update")).toMatchObject({ status: "warn", fix: expect.stringContaining("--offline") }); + expect(doctorExit(r.checks)).toBe(EXIT.OK); + }); + + it("--offline asks nothing and writes nothing", async () => { + let asked = false; + const r = await diagnose( + input({ + offline: true, + registryFetch: (async () => { + asked = true; + throw new Error("asked"); + }) as typeof fetch, + }), + ); + expect(asked).toBe(false); + expect(one(r.checks, "update").status).toBe("skip"); + expect(fs.existsSync(path.join(home, ".paddock"))).toBe(false); + }); + }); +}); diff --git a/website/src/content/docs/guides/running-as-a-service.md b/website/src/content/docs/guides/running-as-a-service.md index 557efbf7..abd0ec08 100644 --- a/website/src/content/docs/guides/running-as-a-service.md +++ b/website/src/content/docs/guides/running-as-a-service.md @@ -94,6 +94,10 @@ fnm and volta do the moment you remove a version. The symptom without the warnin is Paddock being absent one morning with an *empty* log, because it never got as far as running. +For everything around the service as well — the Node it runs, the port, linger, the data +dir, your Claude login, a newer version — run `paddock doctor` +([Checking an install](/guides/updating/#checking-an-install-paddock-doctor)). + ## Reading the logs ```bash diff --git a/website/src/content/docs/guides/updating.md b/website/src/content/docs/guides/updating.md index 804dc048..8a3b4cce 100644 --- a/website/src/content/docs/guides/updating.md +++ b/website/src/content/docs/guides/updating.md @@ -162,6 +162,41 @@ Worth knowing if you are automating around it, or if it stops half way: The registry it asks is `npm_config_registry`, else `npm config get registry`, else `https://registry.npmjs.org`. +## Checking an install: `paddock doctor` + +`paddock doctor` runs every check an update depends on, and a few Paddock needs to work at +all, one line each, with a `fix:` under anything that's wrong: + +``` +✓ Node 22.23.4 (Paddock needs >=22) +✓ Paddock 0.82.1, installed globally with npm: `paddock update` can update it +! the service is installed (systemd) but not running + fix: paddock service start (and `paddock service logs` if it doesn't stay up) +- Paddock isn't running +✓ port 7233 is free +! linger is off for ed: the service stops when you log out, and starts only when you log in + fix: sudo loginctl enable-linger ed (Paddock never runs sudo itself) +✓ the data dir ~/.paddock is writable +✓ the config loads +✓ the projects folder ~/.paddock/projects is writable +✓ Paddock shares this machine's Claude Code login (~/.claude, claude.credentials: host) +✓ claude is on PATH (/usr/local/bin/claude) +! Paddock 0.83.0 is available (you have 0.82.1) + fix: paddock update +``` + +`✓` is fine, `!` a warning, `✗` a failure, and `-` a check that doesn't apply here. It +exits **1** if anything failed; warnings don't change the exit code. The checks are the +ones every tool built on the same CLI contract runs (`node-engines`, `install-method`, +`unit`, `running-version`, `port`, `linger`, `data-home`, `update`), then Paddock's own: +`config`, `projects`, `claude-login` (which *kind* of login it found, never the login +itself) and `claude-cli`. + +`--json` prints the same checks as one document, for a script; `--offline` skips the +update check, the only one that leaves the machine. Like `update --check`, that check +writes what it found to `/update-check.json`, so `paddock service status` +repeats it. + ## Updating by hand There is nothing magic about `update` — it runs the commands you would: From 07f51128c42b9558b9c83fda1c5c13243a21efd5 Mon Sep 17 00:00:00 2001 From: HomeLab Agent Date: Thu, 5 Nov 2026 03:24:00 -0500 Subject: [PATCH 2/5] feat(cli): service install --dry-run, the checkout and port refusals, --json on the service actions, serve --quiet; re-sync service/ and runtime-file with the reference (WIP) Co-Authored-By: Claude Opus 5.5 --- packages/server/src/cli/args.ts | 87 ++++- packages/server/src/cli/doctor.ts | 36 +- packages/server/src/cli/paddock.ts | 8 +- packages/server/src/cli/service/index.ts | 154 +++++++- packages/server/src/cli/service/launchd.ts | 10 +- packages/server/src/cli/service/ready.ts | 45 +++ packages/server/src/cli/service/systemd.ts | 16 +- packages/server/src/runtime-file.ts | 27 +- .../test/unit/cli-service-shoulds.test.ts | 337 ++++++++++++++++++ 9 files changed, 658 insertions(+), 62 deletions(-) create mode 100644 packages/server/test/unit/cli-service-shoulds.test.ts diff --git a/packages/server/src/cli/args.ts b/packages/server/src/cli/args.ts index bf177798..fd9516d8 100644 --- a/packages/server/src/cli/args.ts +++ b/packages/server/src/cli/args.ts @@ -120,6 +120,20 @@ export interface CliOptions { * (SPEC §1). Every other check is local. */ offline?: boolean; + /** + * `service install --dry-run`: print the unit it would write, and write + * nothing — not the unit, not a folder (SPEC §1). + */ + dryRun?: boolean; + /** + * `service install --from-checkout`: install a unit that runs THIS copy even + * though it is a git checkout (SPEC §1). Without it, `install` refuses: a unit + * pointing into a working tree breaks the next time it is rebuilt, switched + * to another branch or moved. + */ + fromCheckout?: boolean; + /** `serve --quiet` / `-q`: print the `Paddock : ` line and nothing else (SPEC §3). */ + quiet?: boolean; } /** @@ -324,6 +338,41 @@ const SCOPED_FLAGS: readonly { where: ["update"], why: "`update` is the only command that asks a question.", }, + { + flag: "--json", + read: (o) => o.json === true, + where: [ + "service status", + "service install", + "service uninstall", + "service start", + "service stop", + "service restart", + "busy", + "update", + "doctor", + "config show", + ], + why: "It prints one JSON document on stdout, and those are the commands that have one.", + }, + { + flag: "--dry-run", + read: (o) => o.dryRun === true, + where: ["service install"], + why: "It prints the unit `install` would write, and writes nothing.", + }, + { + flag: "--from-checkout", + read: (o) => o.fromCheckout === true, + where: ["service install"], + why: "It lets `install` write a unit that runs a git checkout.", + }, + { + flag: "--quiet", + read: (o) => o.quiet === true, + where: ["serve"], + why: "It keeps `serve` to its one `Paddock : ` line.", + }, { flag: "--offline", read: (o) => o.offline === true, @@ -478,6 +527,18 @@ export function parseArgs(argv: string[]): CliOptions { case "--refresh": opts.refresh = true; break; + // `service install` (SPEC §1). + case "--dry-run": + opts.dryRun = true; + break; + case "--from-checkout": + opts.fromCheckout = true; + break; + // `serve --quiet` (SPEC §3). + case "-q": + case "--quiet": + opts.quiet = true; + break; // `doctor --offline` (SPEC §1). case "--offline": opts.offline = true; @@ -577,6 +638,7 @@ Usage paddock serve [options] the same thing, said out loud (\`paddock start\` is a permanent alias) paddock service install [options] run it in the background from login + (--dry-run prints the unit instead) paddock service uninstall stop it and remove the unit paddock service status [--json] installed? running? which version? paddock service start start an installed service @@ -604,6 +666,7 @@ Options --host Bind address (default 127.0.0.1) -d, --data-dir Projects + state (default ~/.paddock, or $PADDOCK_DATA_DIR) -o, --open Open the app in your browser once it is listening + -q, --quiet Print only the first line, \`Paddock : \` --verbose Show the server's own logs (quiet by default) -v, --version Print the Paddock version and exit -h, --help Show this help @@ -723,6 +786,7 @@ export const SERVICE_USAGE = `paddock service — keep Paddock running in the ba Usage paddock service install [options] register it and start it now paddock service install --refresh re-write the unit, keeping its settings + paddock service install --dry-run print the unit it would write; write nothing paddock service uninstall stop it and deregister it paddock service status [--json] is it registered, is it running, which version, where are the logs @@ -738,7 +802,18 @@ Options (logs) Options (stop, restart) --force stop it even though it is busy +Options (install, uninstall, start, stop, restart, status) + --json One JSON document on stdout: ok, action, and the + service's status afterwards (the same fields as + \`status --json\`), plus error on a failure. All + prose goes to stderr. The exit code is unchanged + Options (install) + --dry-run Print the unit (and where it would go) and write + nothing — not the unit, not a folder + --from-checkout Install from a git checkout anyway. Without it, + install refuses: a unit that runs a working tree + breaks when you rebuild, switch branch or move it --refresh Re-render the unit from the settings the EXISTING one carries — its port, host, data dir and verbosity — rather than from this shell's flags and environment. @@ -799,20 +874,26 @@ Where it lives itself at 8 MB, keeping three older generations beside it. Exit codes - 0 it is installed, running and answering + 0 it is installed, running and answering (status), or done 3 installed, but not running or not answering 4 not installed: there is no unit (status, logs, start, stop, restart) 1 something failed 2 usage: an unknown action or flag, or a bad value 75 busy, and --force was not given (stop, restart) -Installed from npx? +Installed from npx, or running from a checkout? \`service install\` refuses. An npx cache path is hash-keyed and npm may prune it, so the unit would work until it silently didn't, at some future login. - Install properly first: + A checkout is yours to rebuild, switch and move, and the unit would follow + it. Install properly first: npm i -g @edspencer/paddock && paddock service install + (--from-checkout installs from the checkout anyway, for working on Paddock.) + + It also refuses when something that isn't Paddock holds the port: pick + another with --port. + A note on access Paddock binds loopback with authentication off, which is right for a laptop. A service is up for as long as you are logged in rather than as long as a diff --git a/packages/server/src/cli/doctor.ts b/packages/server/src/cli/doctor.ts index c22a46f6..82732ab2 100644 --- a/packages/server/src/cli/doctor.ts +++ b/packages/server/src/cli/doctor.ts @@ -22,7 +22,6 @@ * two cannot disagree about what is installed and what is running. */ import fs from "node:fs"; -import net from "node:net"; import os from "node:os"; import path from "node:path"; import { MIN_NODE_MAJOR, type CliOptions } from "./args.js"; @@ -36,7 +35,7 @@ import { import { defaultDataDir, DEFAULT_PORT } from "./service/spec.js"; import { missingPaths, which } from "./service/path-env.js"; import type { LingerState, ServiceManager } from "./service/manager.js"; -import { fetchHealth } from "./service/ready.js"; +import { identifyPaddock as identify, isListening } from "./service/ready.js"; import { describeInstall, detectInstall, updateCommand, type InstallInfo } from "./update/install-method.js"; import { npmConfigGet, npmGlobalRoot } from "./update/package-manager.js"; import { RegistryError, resolveRegistry, resolveTarget } from "./update/registry.js"; @@ -659,36 +658,3 @@ function urlHost(host: string): string { function firstLine(s: string): string { return s.split("\n")[0] ?? s; } - -function isListening(host: string, port: number): Promise { - return new Promise((resolve) => { - const s = net.connect({ host, port }); - s.setTimeout(1000); - s.once("connect", () => { - s.destroy(); - resolve(true); - }); - s.once("timeout", () => { - s.destroy(); - resolve(false); - }); - s.once("error", () => resolve(false)); - }); -} - -/** - * Is this a Paddock? `/api/health`'s `{ ok, version }` is the contract's, so - * every tool answers it; `/api/busy`'s `counts.chat` is Paddock's own. - */ -async function identify(url: string): Promise<{ paddock: boolean; version?: string } | undefined> { - const health = await fetchHealth(url); - if (health === undefined) return undefined; - try { - const res = await fetch(`${url}/api/busy`, { signal: AbortSignal.timeout(2_000) }); - const body = (await res.json()) as { counts?: Record }; - const paddock = health.ok && typeof body.counts?.chat === "number" && "background" in (body.counts ?? {}); - return { paddock, ...(health.version !== undefined ? { version: health.version } : {}) }; - } catch { - return { paddock: false, ...(health.version !== undefined ? { version: health.version } : {}) }; - } -} diff --git a/packages/server/src/cli/paddock.ts b/packages/server/src/cli/paddock.ts index ff769d62..7037af6a 100644 --- a/packages/server/src/cli/paddock.ts +++ b/packages/server/src/cli/paddock.ts @@ -391,7 +391,9 @@ async function main(): Promise { // Precedence is explicit flag > existing env > our default. const dataDir = resolveDataDir(opts); - noteFirstRun(dataDir); + // `--quiet` (SPEC §3): the banner line and nothing else, so not the + // first-run note either (it is prose on stderr, but prose all the same). + if (opts.quiet !== true) noteFirstRun(dataDir); process.env.PADDOCK_DATA_DIR = dataDir; @@ -445,6 +447,10 @@ async function main(): Promise { // runner, and by anything that wants the URL without guessing the port — so // the friendly block below it stays, but below it. console.log(`${PADDOCK_NAME} ${PADDOCK_VERSION}: ${url}`); + if (opts.quiet === true) { + if (opts.open) openBrowser(url); + return EXIT.OK; + } // Still name the data dir, even though it no longer varies with cwd: "which // instance am I looking at" is a real question the moment anyone passes // `--data-dir`, and the answer should be readable off the two lines the tool diff --git a/packages/server/src/cli/service/index.ts b/packages/server/src/cli/service/index.ts index 2489878b..1021cf30 100644 --- a/packages/server/src/cli/service/index.ts +++ b/packages/server/src/cli/service/index.ts @@ -46,8 +46,9 @@ import { type ServiceSpec, type ServiceState, } from "./manager.js"; -import { createLaunchd } from "./launchd.js"; -import { createSystemd } from "./systemd.js"; +import { createLaunchd, renderPlist } from "./launchd.js"; +import { createSystemd, renderUnit } from "./systemd.js"; +import { underNodeModules } from "../update/install-method.js"; import { missingPaths } from "./path-env.js"; import { DEFAULT_LOG_LINES, followFile, sizeOf, tailFile } from "./logs.js"; import { readLiveRuntimeFile } from "../../runtime-file.js"; @@ -56,6 +57,8 @@ import { updateSummary, type UpdateSummary } from "../update/update-check.js"; import { waitForReady, fetchHealth, + identifyPaddock, + isListening, READY_TIMEOUT_LABEL, type HealthAnswer, type Readiness, @@ -103,6 +106,41 @@ export interface ServiceContext { home: string, opts: { force?: boolean; json?: boolean }, ) => Promise; + /** + * Who holds `host:port` — nothing, a Paddock, or something else — asked by + * `install` before it writes a unit (SPEC §1). Injected so a test's answer + * does not depend on what happens to be listening on the box running it. + */ + portOwner?: (host: string, port: number) => Promise; +} + +export type PortOwner = "free" | "paddock" | "other"; + +/** The real {@link ServiceContext.portOwner}: a TCP connect, then `/api/health` and `/api/busy`. */ +export async function portOwner(host: string, port: number): Promise { + const probe = host === "0.0.0.0" || host === "" ? "127.0.0.1" : host === "::" ? "::1" : host; + if (!(await isListening(probe, port))) return "free"; + const who = await identifyPaddock(`http://${probe.includes(":") ? `[${probe}]` : probe}:${port}`); + return who?.paddock === true ? "paddock" : "other"; +} + +/** + * Why `install` won't write a unit that runs a checkout (SPEC §1, §6). + * + * A checkout (or an `npm link`) is a working tree: it gets rebuilt, switched to + * another branch, cleaned and moved, and a unit that runs it follows every one + * of those — half-built `dist/` included — at the next login, unattended. The + * flag is there for working on Paddock itself, where that is the point. + */ +export function checkoutRefusal(packageRoot: string): string { + return ( + "`service install` would write a unit that runs this checkout\n" + + ` (${packageRoot}), which follows every rebuild, branch switch and\n` + + " move of the working tree, at your next login, unattended.\n\n" + + " npm i -g @edspencer/paddock && paddock service install\n\n" + + " Or, to run this checkout as the service anyway (working on Paddock):\n" + + " paddock service install --from-checkout\n" + ); } /** @@ -284,6 +322,12 @@ async function install( backend: ServiceBackend, ): Promise { if (isNpxPath(ctx.packageRoot)) throw new CliError(NPX_REFUSAL); + // A checkout is a package root that isn't under any `node_modules` (SPEC §6): + // `packages/server` in the repo, `/lib/node_modules/@edspencer/paddock/ + // packages/server` from npm. `npm link` reads the same, on purpose. + if (!underNodeModules(ctx.packageRoot) && opts.fromCheckout !== true) { + throw new CliError(checkoutRefusal(ctx.packageRoot)); + } // `--refresh` (SPEC §5 step 11): re-render an EXISTING unit, keeping what it // records. With nothing installed there is nothing to refresh — exit 4, the @@ -297,7 +341,13 @@ async function install( if (refreshing) { existing = backend.status(); if (!existing.registered) { - console.log(notInstalled(backend)); + if (opts.dryRun === true && opts.json === true) { + // `--dry-run --json` prints its own document (runService leaves it be). + console.error(notInstalled(backend)); + console.log(JSON.stringify({ ok: false, action: "install", dryRun: true, error: "not installed", unit: backend.unitPath }, null, 2)); + } else { + console.log(notInstalled(backend)); + } return EXIT.NOT_INSTALLED; } } @@ -309,6 +359,41 @@ async function install( ); const url = `http://${hostFromArgv(spec.args)}:${portFromArgv(spec.args)}`; + // `--dry-run` (SPEC §1): the unit, on stdout, and nothing written — not the + // unit, not the service or log folders `backend.install` would make. The + // where-it-would-go line is on stderr, so `> paddock.service` captures the + // unit alone. + if (opts.dryRun === true) { + const contents = + backend.platform === "darwin" ? renderPlist(PADDOCK_SERVICE, spec) : renderUnit(PADDOCK_SERVICE, spec); + if (opts.json === true) { + console.log( + JSON.stringify({ ok: true, action: "install", dryRun: true, unit: backend.unitPath, contents }, null, 2), + ); + } else { + console.error(`paddock: dry run: this is the unit \`service install\` would write to ${backend.unitPath}. Nothing was written.`); + console.log(contents.trimEnd()); + } + return EXIT.OK; + } + + // Refuse a port something else holds (SPEC §1): the service would start, + // fail to bind, and restart every ten seconds, for good. A Paddock holding it + // is fine — that's the reinstall this replaces — and so is the unit's own + // running service when it's too old to say it's Paddock (before 0.81). + const port = Number(portFromArgv(spec.args)); + const owner = await (ctx.portOwner ?? portOwner)(hostFromArgv(spec.args), port); + if (owner === "other") { + const current = existing ?? backend.status(); + const itsOwn = current.registered && current.running && portFromArgv(current.argv) === String(port); + if (!itsOwn) { + throw new CliError( + `port ${port} is held by something that isn't Paddock, so the service could not start.\n` + + ` Stop it, or pick another port: paddock service install --port ${port + 1}`, + ); + } + } + if (refreshing) { console.log( `\n Re-writing ${backend.unitPath}\n Keeping: paddock ${spec.args.join(" ")}`, @@ -916,6 +1001,69 @@ export async function runService( // `--force` is rejected on every action but `stop` and `restart` — in // `parseCommand`, once, for every verb. See the note there. const backend = backendFor(ctx); + // `--json` on the actions that change something (SPEC §1): their prose goes + // to stderr, and stdout gets one document — what was done, and the status + // afterwards. `status` has its own; `--dry-run` prints its own. + if (opts.json === true && action !== "status" && action !== "logs" && opts.dryRun !== true) { + return withJson(action, () => act(action, opts, ctx, backend), ctx, backend); + } + return act(action, opts, ctx, backend); +} + +/** + * Run `act` with its prose on stderr, then print `{ ok, action, error?, + * ...status }` on stdout (SPEC §1, §3) — the shape Hallway's `service … --json` + * prints, and `status --json`'s fields after `ok` and `action`, so a script + * reads one shape whatever it asked. + * + * Every line in this file goes through `console.log`, so the prose is moved by + * pointing that at stderr for the duration, rather than by threading a writer + * through every function. A failure still prints its document, and is then + * re-thrown, so `paddock: ` and the exit code are what they are + * without `--json`. + */ +async function withJson( + action: ServiceAction, + run: () => Promise, + ctx: ServiceContext, + backend: ServiceBackend, +): Promise { + const log = console.log; + console.log = (...a: unknown[]) => console.error(...a); + let code: number; + let failure: unknown; + try { + code = await run(); + } catch (err) { + failure = err; + code = err instanceof CliError ? err.exitCode : EXIT.FAILED; + } finally { + console.log = log; + } + const error = + failure !== undefined + ? (failure instanceof Error ? failure.message : String(failure)).split("\n")[0] + : code === EXIT.BUSY + ? "busy" + : code === EXIT.NOT_INSTALLED + ? "not installed" + : code !== EXIT.OK + ? "failed" + : undefined; + const report = await buildStatus(ctx, backend); + console.log( + JSON.stringify({ ok: code === EXIT.OK, action, ...(error !== undefined ? { error } : {}), ...report }, null, 2), + ); + if (failure !== undefined) throw failure; + return code; +} + +async function act( + action: ServiceAction, + opts: CliOptions, + ctx: ServiceContext, + backend: ServiceBackend, +): Promise { if (action === "install") return install(opts, ctx, backend); if (action === "uninstall") return uninstall(ctx, backend); if (action === "start" || action === "restart") return startOrRestart(action, opts, ctx, backend); diff --git a/packages/server/src/cli/service/launchd.ts b/packages/server/src/cli/service/launchd.ts index 2c41af77..bcbbd3fd 100644 --- a/packages/server/src/cli/service/launchd.ts +++ b/packages/server/src/cli/service/launchd.ts @@ -154,6 +154,7 @@ export function createLaunchd(id: ServiceIdentity, o: LaunchdOptions): ServiceMa kind: 'a launchd LaunchAgent', install(spec) { + const existed = fs.existsSync(file); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.mkdirSync(spec.workingDirectory, { recursive: true }); // launchd doesn't create the log's folder; without it the job fails to spawn, and says nothing. @@ -161,7 +162,14 @@ export function createLaunchd(id: ServiceIdentity, o: LaunchdOptions): ServiceMa fs.writeFileSync(file, renderPlist(id, spec), 'utf8'); // A bootout first, because bootstrap refuses a label that's loaded. It fails on a first install, as expected. bootoutAndWait(); - bootstrap(); + try { + bootstrap(); + } catch (err) { + // A first install launchd refused mustn't leave a plist behind: `status` would then say it's installed, and + // the next login would try it again. A reinstall keeps its plist. + if (!existed) fs.rmSync(file, { force: true }); + throw err; + } run('launchctl', ['kickstart', '-k', target]); }, diff --git a/packages/server/src/cli/service/ready.ts b/packages/server/src/cli/service/ready.ts index 95a67295..3af98353 100644 --- a/packages/server/src/cli/service/ready.ts +++ b/packages/server/src/cli/service/ready.ts @@ -21,6 +21,7 @@ * same claim as "it failed". Callers print it as a caveat, not an error, and * point at the logs. */ +import net from "node:net"; /** Where the poll got to when it stopped. */ export type Readiness = "ready" | "timeout"; @@ -185,3 +186,47 @@ export async function waitForVersion(opts: ReadyOptions & { version: string }): await sleep(intervalMs); } } + +/** Is anything accepting connections at host:port? A second at most. */ +export function isListening(host: string, port: number): Promise { + return new Promise((resolve) => { + const s = net.connect({ host, port }); + s.setTimeout(1000); + s.once("connect", () => { + s.destroy(); + resolve(true); + }); + s.once("timeout", () => { + s.destroy(); + resolve(false); + }); + s.once("error", () => resolve(false)); + }); +} + +/** + * Is what answers at `url` a Paddock, and which version? Undefined when nothing + * answers `/api/health` there. + * + * `/api/health`'s `{ ok, version }` is the CLI contract's, so every one of the + * six tools answers it alike; `/api/busy`'s `counts.chat` and + * `counts.background` are Paddock's own. A Paddock older than 0.81 has no + * `/api/busy`, and reads as not-Paddock here — callers that can tell it apart + * some other way (an installed unit on that port) should. + */ +export async function identifyPaddock( + url: string, + fetchImpl: typeof fetch = fetch, +): Promise<{ paddock: boolean; version?: string } | undefined> { + const health = await fetchHealth(url, { fetchImpl }); + if (health === undefined) return undefined; + const version = health.version !== undefined ? { version: health.version } : {}; + try { + const res = await fetchImpl(`${url}/api/busy`, { signal: AbortSignal.timeout(2_000) }); + const body = (await res.json()) as { counts?: Record }; + const counts = body.counts ?? {}; + return { paddock: health.ok && typeof counts.chat === "number" && "background" in counts, ...version }; + } catch { + return { paddock: false, ...version }; + } +} diff --git a/packages/server/src/cli/service/systemd.ts b/packages/server/src/cli/service/systemd.ts index 52f368a5..fef3e371 100644 --- a/packages/server/src/cli/service/systemd.ts +++ b/packages/server/src/cli/service/systemd.ts @@ -126,14 +126,26 @@ export function createSystemd(id: ServiceIdentity, o: SystemdOptions): ServiceMa install(spec) { // Asked before the unit is overwritten, while it still describes what's running. - const wasActive = fs.existsSync(file) && isActive(); + const existed = fs.existsSync(file); + const wasActive = existed && isActive(); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.mkdirSync(spec.workingDirectory, { recursive: true }); fs.mkdirSync(path.dirname(spec.logPath), { recursive: true }); fs.writeFileSync(file, renderUnit(id, spec), 'utf8'); // Without a reload the manager keeps serving its cached copy of the old unit. run('systemctl', ['--user', 'daemon-reload']); - systemctl('enable', '--now', id.unit); + try { + systemctl('enable', '--now', id.unit); + } catch (err) { + // A first install systemd refused (no systemd here, no user bus) mustn't leave a unit behind: `status` would + // then say it's installed. A reinstall keeps its unit, which is what's installed either way. + if (!existed) { + run('systemctl', ['--user', 'disable', id.unit]); + fs.rmSync(file, { force: true }); + run('systemctl', ['--user', 'daemon-reload']); + } + throw err; + } // `enable --now` doesn't touch a unit that's already active: a reinstall over a running service would leave the // old process serving and report success. That's the state `update`'s rollback refreshes in, while the failed // version is still up. So restart, but only then: on a stopped unit it would be two starts milliseconds apart, diff --git a/packages/server/src/runtime-file.ts b/packages/server/src/runtime-file.ts index a75a1e6d..53211593 100644 --- a/packages/server/src/runtime-file.ts +++ b/packages/server/src/runtime-file.ts @@ -1,8 +1,4 @@ -// From edspencer/cli-contract reference/runtime-file.ts @ SPEC 0.1; local changes: `node:fs` / `node:path` imports -// unchanged, nothing else — the module is Node built-ins only and Paddock's `` is its data dir, so it needed -// no adaptation. Kept verbatim on purpose: wave C4 re-syncs it, and a divergence here would be a divergence in the -// one file every tool's `busy`, `service status` and `update` agree on. -// +// From edspencer/cli-contract reference/runtime-file.ts @ 0.2; local changes: none. // `/runtime.json`: what a running instance tells its own CLI (SPEC §4, ROADMAP). `serve` writes it once it's // listening and removes it on a clean exit; `busy`, `service status` and `update` read it to find the instance. // @@ -10,8 +6,8 @@ // is settled; the file is written 0600 already, so adding one later changes nothing about who can read it. // Node built-ins only. -import fs from "node:fs"; -import path from "node:path"; +import fs from 'node:fs'; +import path from 'node:path'; export interface RuntimeInfo { pid: number; @@ -23,17 +19,14 @@ export interface RuntimeInfo { startedAt: string; } -export const RUNTIME_FILE = "runtime.json"; +export const RUNTIME_FILE = 'runtime.json'; export function runtimeFilePath(home: string): string { return path.join(home, RUNTIME_FILE); } /** Writes the file atomically (a temporary file, then a rename), readable only by this user. */ -export function writeRuntimeFile( - home: string, - info: Omit & { startedAt?: string }, -): RuntimeInfo { +export function writeRuntimeFile(home: string, info: Omit & { startedAt?: string }): RuntimeInfo { const full: RuntimeInfo = { pid: info.pid, port: info.port, @@ -58,7 +51,7 @@ export function writeRuntimeFile( export function readRuntimeFile(home: string): RuntimeInfo | null { let raw: string; try { - raw = fs.readFileSync(runtimeFilePath(home), "utf8"); + raw = fs.readFileSync(runtimeFilePath(home), 'utf8'); } catch { return null; } @@ -67,9 +60,9 @@ export function readRuntimeFile(home: string): RuntimeInfo | null { if ( Number.isInteger(v.pid) && Number.isInteger(v.port) && - typeof v.url === "string" && - typeof v.version === "string" && - typeof v.startedAt === "string" + typeof v.url === 'string' && + typeof v.version === 'string' && + typeof v.startedAt === 'string' ) { return v as RuntimeInfo; } @@ -97,7 +90,7 @@ export function isPidAlive(pid: number): boolean { process.kill(pid, 0); return true; } catch (err) { - return (err as NodeJS.ErrnoException).code === "EPERM"; + return (err as NodeJS.ErrnoException).code === 'EPERM'; } } diff --git a/packages/server/test/unit/cli-service-shoulds.test.ts b/packages/server/test/unit/cli-service-shoulds.test.ts new file mode 100644 index 00000000..fb3f0a7e --- /dev/null +++ b/packages/server/test/unit/cli-service-shoulds.test.ts @@ -0,0 +1,337 @@ +/** + * The CLI contract's §1/§3 "should"s, and the one "must" that came with them: + * `service install --dry-run`, the checkout refusal and `--from-checkout`, the + * refusal of a port something else holds, `--json` on the service actions that + * change something, `serve --quiet`, and the flags that belong to one command. + * + * Like cli-service.test.ts, every subprocess call goes through an injected + * Runner: what these prove is the flow and the output, not that a real systemd + * or launchd agrees (scripts/service-real.mjs does that on CI). + */ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { parseCommand, UsageError, type CliOptions } from "../../src/cli/args.js"; +import { CliError } from "../../src/cli/args.js"; +import { EXIT } from "../../src/cli/exit-codes.js"; +import { runService, type ServiceContext } from "../../src/cli/service/index.js"; +import { createLaunchd, plistPath } from "../../src/cli/service/launchd.js"; +import { createSystemd, unitPath } from "../../src/cli/service/systemd.js"; +import { buildSpec, PADDOCK_SERVICE } from "../../src/cli/service/spec.js"; +import type { Runner, RunResult } from "../../src/cli/service/manager.js"; + +const OPTS: CliOptions = { open: false, verbose: false, help: false, version: false }; +const GLOBAL = "/usr/local/lib/node_modules/@edspencer/paddock/packages/server"; +const CLI = `${GLOBAL}/dist/cli/paddock.js`; + +let home: string; +beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), "paddock-shoulds-")); +}); +afterEach(() => { + fs.rmSync(home, { recursive: true, force: true }); +}); + +/** A runner that records, answers "active" to is-active when `active`, and says launchd has nothing loaded. */ +function recorder(o: { active?: boolean; fail?: (cmd: string, args: string[]) => boolean } = {}) { + const calls: string[][] = []; + const run: Runner = (cmd, args): RunResult => { + calls.push([cmd, ...args]); + if (o.fail?.(cmd, args) === true) return { status: 1, stdout: "", stderr: "refused" }; + if (cmd === "systemctl" && args.includes("is-active")) + return { status: o.active ? 0 : 3, stdout: o.active ? "active\n" : "inactive\n", stderr: "" }; + if (cmd === "launchctl" && args[0] === "print") return { status: 113, stdout: "", stderr: "Could not find service" }; + return { status: 0, stdout: "", stderr: "" }; + }; + return { run, calls }; +} + +function ctxFor(platform: "linux" | "darwin", run: Runner, over: Partial = {}): ServiceContext { + return { + platform, + nodePath: "/opt/node/bin/node", + scriptPath: CLI, + packageRoot: GLOBAL, + homeDir: home, + pathEnv: "/usr/bin:/bin", + run, + checkReady: async () => "ready", + probeHealth: async () => ({ ok: true, version: "0.82.1" }), + portOwner: async () => "free", + guardBusy: async () => null, + ...over, + }; +} + +/** Everything written to stdout and to stderr, through console.log and console.error, separately. */ +async function streams(body: () => Promise): Promise<{ out: string; err: string; value: unknown; thrown?: unknown }> { + const out: string[] = []; + const err: string[] = []; + const log = console.log; + const error = console.error; + console.log = (...a: unknown[]) => void out.push(a.map(String).join(" ")); + console.error = (...a: unknown[]) => void err.push(a.map(String).join(" ")); + let value: unknown; + let thrown: unknown; + try { + value = await body(); + } catch (e) { + thrown = e; + } finally { + console.log = log; + console.error = error; + } + return { out: out.join("\n"), err: err.join("\n"), value, ...(thrown !== undefined ? { thrown } : {}) }; +} + +const installed = (port = "7233") => + createSystemd(PADDOCK_SERVICE, { run: recorder().run, homeDir: home }).install( + buildSpec({ nodePath: "/opt/node/bin/node", scriptPath: CLI, dataDir: path.join(home, ".paddock"), port }), + ); + +describe("flags belong to their commands (SPEC §1)", () => { + it.each([ + [["service", "install", "--dry-run"]], + [["service", "install", "--from-checkout"]], + [["service", "install", "--dry-run", "--json"]], + [["serve", "--quiet"]], + [["serve", "-q"]], + [["-q"]], + ...["install", "uninstall", "start", "stop", "restart", "status"].map((a) => [["service", a, "--json"]]), + [["busy", "--json"]], + [["update", "--json"]], + [["doctor", "--json"]], + [["config", "show", "--json"]], + ])("accepted: %j", (argv) => { + expect(() => parseCommand(argv)).not.toThrow(); + }); + + it.each([ + [["service", "start", "--dry-run"], "--dry-run"], + [["update", "--dry-run"], "--dry-run"], + [["service", "status", "--from-checkout"], "--from-checkout"], + [["serve", "--from-checkout"], "--from-checkout"], + [["busy", "--quiet"], "--quiet"], + [["service", "install", "-q"], "--quiet"], + [["service", "logs", "--json"], "--json"], + [["serve", "--json"], "--json"], + [["--json"], "--json"], + [["config", "eject", "--json"], "--json"], + ])("refused with exit 2: %j", (argv, flag) => { + let err: unknown; + try { + parseCommand(argv); + } catch (e) { + err = e; + } + expect(err).toBeInstanceOf(UsageError); + expect((err as UsageError).exitCode).toBe(EXIT.USAGE); + expect((err as Error).message.startsWith(`${flag} applies to`)).toBe(true); + }); + + it("serve -q sets quiet", () => { + expect(parseCommand(["serve", "-q"]).opts.quiet).toBe(true); + }); +}); + +describe("service install --dry-run", () => { + it("prints the systemd unit on stdout, says where on stderr, and writes nothing at all", async () => { + const { run, calls } = recorder(); + const r = await streams(() => runService("install", { ...OPTS, dryRun: true, port: "7300" }, ctxFor("linux", run))); + expect(r.value).toBe(EXIT.OK); + expect(r.out).toMatch(/^\[Unit\]$/m); + expect(r.out).toContain("ExecStart=/opt/node/bin/node"); + expect(r.out).toContain("--port 7300"); + expect(r.err).toContain(unitPath(PADDOCK_SERVICE, home)); + expect(r.err).toContain("Nothing was written"); + // Not the unit, not the data dir, not the logs folder — nothing in the home at all. + expect(fs.readdirSync(home)).toEqual([]); + // And nothing asked of systemd. + expect(calls).toEqual([]); + }); + + it("prints the plist on macOS", async () => { + const r = await streams(() => runService("install", { ...OPTS, dryRun: true }, ctxFor("darwin", recorder().run))); + expect(r.out).toMatch(/^<\?xml/); + expect(r.out).toContain("net.edspencer.paddock"); + expect(fs.existsSync(plistPath(PADDOCK_SERVICE, home))).toBe(false); + }); + + it("with --refresh, prints the unit re-rendered from the installed one's settings", async () => { + installed("9123"); + const unit = unitPath(PADDOCK_SERVICE, home); + const before = fs.readFileSync(unit, "utf8"); + const mtime = fs.statSync(unit).mtimeMs; + const r = await streams(() => + runService("install", { ...OPTS, dryRun: true, refresh: true }, ctxFor("linux", recorder().run)), + ); + expect(r.out).toContain("--port 9123"); + expect(fs.readFileSync(unit, "utf8")).toBe(before); + expect(fs.statSync(unit).mtimeMs).toBe(mtime); + }); + + it("--json prints one document with the unit in it", async () => { + const r = await streams(() => + runService("install", { ...OPTS, dryRun: true, json: true }, ctxFor("linux", recorder().run)), + ); + const doc = JSON.parse(r.out) as Record; + expect(doc).toMatchObject({ ok: true, action: "install", dryRun: true, unit: unitPath(PADDOCK_SERVICE, home) }); + expect(String(doc.contents)).toMatch(/^\[Unit\]$/m); + expect(fs.readdirSync(home)).toEqual([]); + }); + + it("--refresh --json with nothing installed: 4, and still one document", async () => { + const r = await streams(() => + runService("install", { ...OPTS, dryRun: true, refresh: true, json: true }, ctxFor("linux", recorder().run)), + ); + expect(r.value).toBe(EXIT.NOT_INSTALLED); + expect(JSON.parse(r.out)).toMatchObject({ ok: false, error: "not installed" }); + }); +}); + +describe("service install refuses a checkout (SPEC §1, §6)", () => { + const CHECKOUT = "/home/ed/src/paddock/packages/server"; + + it("refuses with exit 1, names the way out, and writes nothing", async () => { + const { run, calls } = recorder(); + const r = await streams(() => runService("install", OPTS, ctxFor("linux", run, { packageRoot: CHECKOUT }))); + expect(r.thrown).toBeInstanceOf(CliError); + expect((r.thrown as CliError).exitCode).toBe(EXIT.FAILED); + expect((r.thrown as Error).message).toContain(CHECKOUT); + expect((r.thrown as Error).message).toContain("--from-checkout"); + expect((r.thrown as Error).message).toContain("npm i -g @edspencer/paddock"); + expect(calls).toEqual([]); + expect(fs.existsSync(unitPath(PADDOCK_SERVICE, home))).toBe(false); + }); + + it("--dry-run is refused the same way: it previews what install would do", async () => { + const r = await streams(() => + runService("install", { ...OPTS, dryRun: true }, ctxFor("linux", recorder().run, { packageRoot: CHECKOUT })), + ); + expect(r.thrown).toBeInstanceOf(CliError); + }); + + it("--from-checkout installs anyway", async () => { + const r = await streams(() => + runService("install", { ...OPTS, fromCheckout: true }, ctxFor("linux", recorder().run, { packageRoot: CHECKOUT })), + ); + expect(r.value).toBe(EXIT.OK); + expect(fs.existsSync(unitPath(PADDOCK_SERVICE, home))).toBe(true); + }); + + it("the control: a global install is not a checkout", async () => { + const r = await streams(() => runService("install", OPTS, ctxFor("linux", recorder().run))); + expect(r.value).toBe(EXIT.OK); + }); +}); + +describe("service install refuses a port something else holds (SPEC §1)", () => { + it("refuses when the port is held by something that isn't Paddock", async () => { + const { run, calls } = recorder(); + const r = await streams(() => + runService("install", { ...OPTS, port: "7300" }, ctxFor("linux", run, { portOwner: async () => "other" })), + ); + expect((r.thrown as CliError).exitCode).toBe(EXIT.FAILED); + expect((r.thrown as Error).message).toContain("port 7300 is held by something that isn't Paddock"); + expect(calls.filter((c) => c.includes("enable"))).toEqual([]); + expect(fs.existsSync(unitPath(PADDOCK_SERVICE, home))).toBe(false); + }); + + it("goes ahead over a Paddock (a reinstall), and over its own running service even when that can't say it's Paddock", async () => { + expect( + (await streams(() => runService("install", OPTS, ctxFor("linux", recorder().run, { portOwner: async () => "paddock" })))).value, + ).toBe(EXIT.OK); + installed("7233"); + const r = await streams(() => + runService("install", OPTS, ctxFor("linux", recorder({ active: true }).run, { portOwner: async () => "other" })), + ); + expect(r.thrown).toBeUndefined(); + expect(r.value).toBe(EXIT.OK); + }); +}); + +describe("--json on the service actions (SPEC §1, §3)", () => { + it("install: one document on stdout — ok, action and the status after — and every word of prose on stderr", async () => { + const r = await streams(() => runService("install", { ...OPTS, json: true }, ctxFor("linux", recorder({ active: true }).run))); + expect(r.value).toBe(EXIT.OK); + const doc = JSON.parse(r.out) as Record; + expect(doc).toMatchObject({ ok: true, action: "install", installed: true, running: true, answering: true, runningVersion: "0.82.1" }); + expect(doc).not.toHaveProperty("error"); + expect(r.err).toContain("Paddock is installed as a systemd --user service"); + }); + + it("uninstall: installed is false afterwards", async () => { + installed(); + const r = await streams(() => runService("uninstall", { ...OPTS, json: true }, ctxFor("linux", recorder().run))); + expect(JSON.parse(r.out)).toMatchObject({ ok: true, action: "uninstall", installed: false }); + expect(r.err).toContain("stopped and removed"); + }); + + it("start with nothing installed: 4, and the document says why", async () => { + const r = await streams(() => runService("start", { ...OPTS, json: true }, ctxFor("linux", recorder().run))); + expect(r.value).toBe(EXIT.NOT_INSTALLED); + expect(JSON.parse(r.out)).toMatchObject({ ok: false, action: "start", error: "not installed", installed: false }); + }); + + it("stop refused as busy: 75, and error is busy", async () => { + installed(); + const r = await streams(() => + runService( + "stop", + { ...OPTS, json: true }, + ctxFor("linux", recorder({ active: true }).run, { guardBusy: async () => EXIT.BUSY }), + ), + ); + expect(r.value).toBe(EXIT.BUSY); + expect(JSON.parse(r.out)).toMatchObject({ ok: false, action: "stop", error: "busy", running: true }); + }); + + it("restart that fails: the document is printed, then the failure is re-thrown for paddock: and its code", async () => { + installed(); + const r = await streams(() => + runService( + "restart", + { ...OPTS, json: true }, + ctxFor("linux", recorder({ active: true, fail: (c, a) => c === "systemctl" && a.includes("restart") }).run), + ), + ); + expect(r.thrown).toBeInstanceOf(Error); + const doc = JSON.parse(r.out) as Record; + expect(doc).toMatchObject({ ok: false, action: "restart" }); + expect(String(doc.error)).toContain("systemctl --user restart paddock.service failed"); + }); + + it("a refused install (the checkout) still prints its document", async () => { + const r = await streams(() => + runService("install", { ...OPTS, json: true }, ctxFor("linux", recorder().run, { packageRoot: "/src/paddock/packages/server" })), + ); + expect((r.thrown as CliError).exitCode).toBe(EXIT.FAILED); + expect(JSON.parse(r.out)).toMatchObject({ ok: false, action: "install", installed: false }); + }); +}); + +describe("a first install the service manager refuses leaves no unit behind (cli-contract d5ddc0e)", () => { + it("systemd", () => { + const { run, calls } = recorder({ fail: (c, a) => c === "systemctl" && a.includes("enable") }); + const backend = createSystemd(PADDOCK_SERVICE, { run, homeDir: home }); + expect(() => backend.install(buildSpec({ nodePath: "/n", scriptPath: CLI, dataDir: path.join(home, ".paddock") }))).toThrow(); + expect(fs.existsSync(unitPath(PADDOCK_SERVICE, home))).toBe(false); + expect(calls.some((c) => c.includes("disable"))).toBe(true); + }); + + it("systemd: a REinstall that fails keeps the unit that's there", () => { + installed(); + const { run } = recorder({ fail: (c, a) => c === "systemctl" && a.includes("enable") }); + const backend = createSystemd(PADDOCK_SERVICE, { run, homeDir: home }); + expect(() => backend.install(buildSpec({ nodePath: "/n", scriptPath: CLI, dataDir: path.join(home, ".paddock") }))).toThrow(); + expect(fs.existsSync(unitPath(PADDOCK_SERVICE, home))).toBe(true); + }); + + it("launchd", () => { + const { run } = recorder({ fail: (c, a) => c === "launchctl" && a[0] === "bootstrap" }); + const backend = createLaunchd(PADDOCK_SERVICE, { run, homeDir: home, sleep: () => undefined }); + expect(() => backend.install(buildSpec({ nodePath: "/n", scriptPath: CLI, dataDir: path.join(home, ".paddock") }))).toThrow(); + expect(fs.existsSync(plistPath(PADDOCK_SERVICE, home))).toBe(false); + }); +}); From b137e925b131d8c329fbab63ec27466621c9846b Mon Sep 17 00:00:00 2001 From: HomeLab Agent Date: Thu, 5 Nov 2026 03:28:02 -0500 Subject: [PATCH 3/5] feat(cli): changeset; service-real gains --dry-run, install --json and doctor steps Co-Authored-By: Claude Opus 5.5 --- .changeset/cli-contract-shoulds.md | 13 +++++++++++++ scripts/service-real.mjs | 29 +++++++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 .changeset/cli-contract-shoulds.md diff --git a/.changeset/cli-contract-shoulds.md b/.changeset/cli-contract-shoulds.md new file mode 100644 index 00000000..9e779ccb --- /dev/null +++ b/.changeset/cli-contract-shoulds.md @@ -0,0 +1,13 @@ +--- +"@paddock/server": minor +--- + +**The CLI contract's remaining `service` and `serve` options (SPEC §1, §3).** What a script can see: + +- **`paddock service install --dry-run`** prints the unit it would write (the systemd unit or the launchd plist) on stdout, says where it would go on stderr, and writes nothing — not the unit, not a folder. It works with `--refresh` too, and with `--json` (`{ ok, action, dryRun, unit, contents }`). +- **`service install` refuses to run from a git checkout** (or an `npm link`), exit **1**, unless you add **`--from-checkout`**: a unit that runs a working tree follows every rebuild, branch switch and move of it. A global install is unaffected. +- **`service install` refuses a port something else holds**, exit **1**, rather than writing a service that can only crash-loop. A Paddock on the port (a reinstall) is fine, and so is the unit's own running service. +- **`--json` on `service install`, `uninstall`, `start`, `stop` and `restart`**: one document on stdout, `{ ok, action, error?, …the service's status afterwards }` (the same fields as `service status --json`), with every word of prose on stderr. The exit codes don't change; `error` is `busy` for a 75 and `not installed` for a 4. +- **`paddock serve --quiet` (`-q`)** prints only the first line, `Paddock : `. +- **Flags belong to their commands:** `--dry-run` and `--from-checkout` (`service install` only), `--quiet` (`serve` only) and **`--json` on a command that has no JSON document — `serve`, `service logs`, `config eject` — now exit 2**. They used to be accepted and ignored. +- A first `service install` that systemd or launchd refuses no longer leaves its unit behind (re-synced with cli-contract's `reference/service/`); a reinstall that fails keeps the unit that was there. diff --git a/scripts/service-real.mjs b/scripts/service-real.mjs index 447e5753..74a18dde 100644 --- a/scripts/service-real.mjs +++ b/scripts/service-real.mjs @@ -276,10 +276,24 @@ try { assert.ok(!fs.existsSync(unit), "nothing written"); const port = await freePort(); - step(`service install --port ${port}`); + step(`service install --dry-run --port ${port}: the unit on stdout, nothing written`); + const dry = expectExit(0, "service", "install", "--dry-run", "--port", String(port)); + assert.ok(dry.stdout.includes(cli), `the dry run prints the unit, which runs ${cli}:\n${dry.stdout}`); + assert.ok(dry.stdout.includes(String(port)), "with the port"); + assert.match(dry.stderr, /Nothing was written/); + assert.ok(!fs.existsSync(unit), "--dry-run wrote no unit"); + + step(`service install --port ${port} --json: one document on stdout, the prose on stderr`); installed = true; - const out = expectExit(0, "service", "install", "--port", String(port)).stdout; + const inst = expectExit(0, "service", "install", "--port", String(port), "--json"); + const out = inst.stderr; assert.match(out, new RegExp(`running at http://127\\.0\\.0\\.1:${port}`)); + const doc = JSON.parse(inst.stdout); + assert.equal(doc.ok, true); + assert.equal(doc.action, "install"); + assert.equal(doc.installed, true); + assert.equal(doc.answering, true, `answering after install: ${inst.stdout}`); + assert.equal(doc.port, port); const answer = await until("health", () => health(port)); assert.equal(answer.ok, true); assert.equal(answer.version, version, "/api/health reports the version it is running (SPEC §8)"); @@ -303,6 +317,17 @@ try { fs.readFileSync(logFile, "utf8").includes(`Paddock ${version}: http://127.0.0.1:${port}`), ); + step("doctor --offline --json against the real service: the service checks pass"); + { + const r = paddock("doctor", "--offline", "--json"); + const d = JSON.parse(r.stdout); + const by = (id) => d.checks.filter((c) => c.id === id); + for (const id of ["unit", "running-version", "port", "data-home", "node-engines"]) { + assert.deepEqual(by(id).map((c) => c.status), ["pass"], `doctor ${id}: ${JSON.stringify(by(id))}`); + } + assert.equal(by("update")[0].status, "skip", "--offline skips the registry"); + } + step("status: exit 0, running, answering, versions agree"); console.log(expectExit(0, "service", "status").stdout); let s = statusJson(0); From 21ee8fcf16a66ac4540f21a44c432a25633e9f2d Mon Sep 17 00:00:00 2001 From: HomeLab Agent Date: Thu, 5 Nov 2026 03:30:03 -0500 Subject: [PATCH 4/5] fix(cli): the checkout refusal's first line says what it is Co-Authored-By: Claude Opus 5.5 --- packages/server/src/cli/service/index.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/server/src/cli/service/index.ts b/packages/server/src/cli/service/index.ts index 1021cf30..f4cc67f0 100644 --- a/packages/server/src/cli/service/index.ts +++ b/packages/server/src/cli/service/index.ts @@ -134,11 +134,11 @@ export async function portOwner(host: string, port: number): Promise */ export function checkoutRefusal(packageRoot: string): string { return ( - "`service install` would write a unit that runs this checkout\n" + - ` (${packageRoot}), which follows every rebuild, branch switch and\n` + - " move of the working tree, at your next login, unattended.\n\n" + + `this copy of Paddock is a checkout (${packageRoot}), so \`service install\` won't use it.\n` + + " A unit that runs a checkout follows every rebuild, branch switch and move of\n" + + " it, at your next login, unattended. Install it properly first:\n\n" + " npm i -g @edspencer/paddock && paddock service install\n\n" + - " Or, to run this checkout as the service anyway (working on Paddock):\n" + + " Or run this checkout as the service anyway (when working on Paddock):\n" + " paddock service install --from-checkout\n" ); } From 4227e8f2fc880e53a735cd146a063798726807df Mon Sep 17 00:00:00 2001 From: HomeLab Agent Date: Thu, 5 Nov 2026 03:31:11 -0500 Subject: [PATCH 5/5] =?UTF-8?q?fix(cli):=20a=20reinstall=20keeps=20the=20u?= =?UTF-8?q?nit's=20settings=20unless=20a=20flag=20says=20otherwise=20(SPEC?= =?UTF-8?q?=20=C2=A71)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .changeset/cli-contract-shoulds.md | 1 + packages/server/src/cli/args.ts | 6 +++++- packages/server/src/cli/service/index.ts | 14 ++++++++----- .../test/unit/cli-service-shoulds.test.ts | 21 +++++++++++++++++++ scripts/service-real.mjs | 9 ++++++++ 5 files changed, 45 insertions(+), 6 deletions(-) diff --git a/.changeset/cli-contract-shoulds.md b/.changeset/cli-contract-shoulds.md index 9e779ccb..36f92f61 100644 --- a/.changeset/cli-contract-shoulds.md +++ b/.changeset/cli-contract-shoulds.md @@ -8,6 +8,7 @@ - **`service install` refuses to run from a git checkout** (or an `npm link`), exit **1**, unless you add **`--from-checkout`**: a unit that runs a working tree follows every rebuild, branch switch and move of it. A global install is unaffected. - **`service install` refuses a port something else holds**, exit **1**, rather than writing a service that can only crash-loop. A Paddock on the port (a reinstall) is fine, and so is the unit's own running service. - **`--json` on `service install`, `uninstall`, `start`, `stop` and `restart`**: one document on stdout, `{ ok, action, error?, …the service's status afterwards }` (the same fields as `service status --json`), with every word of prose on stderr. The exit codes don't change; `error` is `busy` for a 75 and `not installed` for a 4. +- **Running `service install` again keeps the installed unit's settings** — its port, host, data dir and verbosity — unless a flag says otherwise (SPEC §1). It used to do that only with `--refresh`, so a plain reinstall over a `--port 9000` service moved it to 7233. - **`paddock serve --quiet` (`-q`)** prints only the first line, `Paddock : `. - **Flags belong to their commands:** `--dry-run` and `--from-checkout` (`service install` only), `--quiet` (`serve` only) and **`--json` on a command that has no JSON document — `serve`, `service logs`, `config eject` — now exit 2**. They used to be accepted and ignored. - A first `service install` that systemd or launchd refuses no longer leaves its unit behind (re-synced with cli-contract's `reference/service/`); a reinstall that fails keeps the unit that was there. diff --git a/packages/server/src/cli/args.ts b/packages/server/src/cli/args.ts index fd9516d8..b025c335 100644 --- a/packages/server/src/cli/args.ts +++ b/packages/server/src/cli/args.ts @@ -816,7 +816,7 @@ Options (install) breaks when you rebuild, switch branch or move it --refresh Re-render the unit from the settings the EXISTING one carries — its port, host, data dir and verbosity — - rather than from this shell's flags and environment. + and never from PADDOCK_DATA_DIR in this shell. This is what \`paddock update\` runs, through the new version's CLI, so the unit is written in the format that version writes. Exit 4 with nothing installed: @@ -824,6 +824,10 @@ Options (install) install with defaults instead is how a --port 9000 service comes back on 7233. + Running install again is safe: it keeps the port, host, data dir and + verbosity the installed unit records, unless you give new ones, and + restarts the running service onto the new unit. + Busy \`stop\` and \`restart\` ask the running instance whether it is busy first, and refuse with exit 75 if it is — a chat turn in flight, a background task, a diff --git a/packages/server/src/cli/service/index.ts b/packages/server/src/cli/service/index.ts index f4cc67f0..7bb71920 100644 --- a/packages/server/src/cli/service/index.ts +++ b/packages/server/src/cli/service/index.ts @@ -337,10 +337,15 @@ async function install( // CLI, and a silent fallback would move a `--port 9000` service to 7233 on // the one run nobody is watching. const refreshing = opts.refresh === true; - let existing: ServiceState | undefined; + // A reinstall keeps what the installed unit records — its port, host, data + // dir and verbosity — unless a flag says otherwise (SPEC §1). It used to do + // that only with `--refresh`, so `service install` over a `--port 9000` + // service quietly moved it to 7233. `--refresh` still differs in two ways: + // it ignores `PADDOCK_DATA_DIR` in this shell, and with no unit it exits 4. + const current = backend.status(); + const existing: ServiceState | undefined = current.registered ? current : undefined; if (refreshing) { - existing = backend.status(); - if (!existing.registered) { + if (existing === undefined) { if (opts.dryRun === true && opts.json === true) { // `--dry-run --json` prints its own document (runService leaves it be). console.error(notInstalled(backend)); @@ -384,7 +389,6 @@ async function install( const port = Number(portFromArgv(spec.args)); const owner = await (ctx.portOwner ?? portOwner)(hostFromArgv(spec.args), port); if (owner === "other") { - const current = existing ?? backend.status(); const itsOwn = current.registered && current.running && portFromArgv(current.argv) === String(port); if (!itsOwn) { throw new CliError( @@ -394,7 +398,7 @@ async function install( } } - if (refreshing) { + if (existing !== undefined) { console.log( `\n Re-writing ${backend.unitPath}\n Keeping: paddock ${spec.args.join(" ")}`, ); diff --git a/packages/server/test/unit/cli-service-shoulds.test.ts b/packages/server/test/unit/cli-service-shoulds.test.ts index fb3f0a7e..5fee9de8 100644 --- a/packages/server/test/unit/cli-service-shoulds.test.ts +++ b/packages/server/test/unit/cli-service-shoulds.test.ts @@ -251,6 +251,27 @@ describe("service install refuses a port something else holds (SPEC §1)", () => }); }); +describe("a reinstall keeps the unit's settings (SPEC §1)", () => { + it("service install with no flags over a --port 9123 unit keeps 9123; a flag still wins", async () => { + installed("9123"); + const unit = unitPath(PADDOCK_SERVICE, home); + const r = await streams(() => runService("install", OPTS, ctxFor("linux", recorder().run))); + expect(r.value).toBe(EXIT.OK); + expect(r.out).toContain("Keeping: paddock serve --port 9123"); + expect(fs.readFileSync(unit, "utf8")).toContain("--port 9123"); + + await streams(() => runService("install", { ...OPTS, port: "9200" }, ctxFor("linux", recorder().run))); + expect(fs.readFileSync(unit, "utf8")).toContain("--port 9200"); + expect(fs.readFileSync(unit, "utf8")).not.toContain("9123"); + }); + + it("the control: a first install takes the defaults", async () => { + const r = await streams(() => runService("install", OPTS, ctxFor("linux", recorder().run))); + expect(r.out).not.toContain("Keeping:"); + expect(fs.readFileSync(unitPath(PADDOCK_SERVICE, home), "utf8")).not.toContain("--port"); + }); +}); + describe("--json on the service actions (SPEC §1, §3)", () => { it("install: one document on stdout — ok, action and the status after — and every word of prose on stderr", async () => { const r = await streams(() => runService("install", { ...OPTS, json: true }, ctxFor("linux", recorder({ active: true }).run))); diff --git a/scripts/service-real.mjs b/scripts/service-real.mjs index 74a18dde..bac48815 100644 --- a/scripts/service-real.mjs +++ b/scripts/service-real.mjs @@ -328,6 +328,15 @@ try { assert.equal(by("update")[0].status, "skip", "--offline skips the registry"); } + step("service install again, with no flags: keeps the port, and replaces the running process (SPEC §1)"); + { + const pidBefore = statusJson(0).pid; + const again = JSON.parse(expectExit(0, "service", "install", "--json").stdout); + assert.equal(again.port, port, "a reinstall keeps the port the unit records"); + assert.equal(again.answering, true); + assert.notEqual(again.pid, pidBefore, `the old process was replaced (pid ${pidBefore})`); + } + step("status: exit 0, running, answering, versions agree"); console.log(expectExit(0, "service", "status").stdout); let s = statusJson(0);