Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add read-only `npm run doctor` install-prerequisite report (#5304)

[._.]/ Adam Eivyc9242dbf70fc
diff --git a/docs/README.md b/docs/README.md
index 667b1f0f6f..353dc8579a 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -2,6 +2,8 @@
Index of everything under `docs/`. Start with the [root README](../README.md) for the product overview and quick start.
+**Something won't start?** Run `npm run doctor` — a read-only report of every install prerequisite (Node/npm floors, submodule, workspace deps, PostgreSQL + pgvector, migrations, seeded `data/`, pm2, media toolchain, cert, ports). It runs before `npm install` and prints one pasteable block; add `--json` for machine-readable output. Then see [TROUBLESHOOTING.md](./TROUBLESHOOTING.md).
+
## Guides (living documents)
| Doc | Covers |
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 6267f886af..a54fee9260 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -4,6 +4,27 @@ Common issues and solutions when running PortOS.
## Startup Issues
+### Start Here: `npm run doctor`
+
+**Symptom**: anything won't start, and it isn't obvious which prerequisite is missing.
+
+```bash
+npm run doctor # human-readable table
+npm run doctor -- --json # { ok, facts: [{ name, status, detail, required }] }
+```
+
+It is read-only (no installs, no migrations, no DB writes) and loads from a bare
+checkout, so it works even before `npm install` has ever run. Each prerequisite
+is probed independently and separately bounded, so one unreachable service
+degrades to a single line instead of hanging the report. It exits non-zero when
+a **required** prerequisite is unavailable; optional facts (TLS cert, `gh`,
+ffmpeg/python3/uv, the port block) are reported but never fail the run — a
+running install legitimately occupies ports 5553–5561.
+
+Details name no hostnames, usernames, IPs, or home-directory paths, so the
+output is safe to paste into a bug report as-is.
+
+
### Port Already in Use
**Symptom**: Server fails to start with `EADDRINUSE` error.
diff --git a/package.json b/package.json
index ede36fa7ca..cf58ce71fb 100644
--- a/package.json
+++ b/package.json
@@ -25,6 +25,7 @@
"pm2:save": "node ./node_modules/pm2/bin/pm2 save",
"pm2:startup": "node ./node_modules/pm2/bin/pm2 startup",
"install:all": "npm run setup",
+ "doctor": "node scripts/doctor.js",
"migrations": "node scripts/run-migrations.js",
"setup": "node scripts/checkNodeVersion.js && node scripts/checkNpmVersion.js && git submodule update --init --recursive && npm install && npm install --prefix client && npm install --prefix server && npm install --prefix autofixer && node scripts/trusted-rebuilds.js server && node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-llm.js && node scripts/setup-browser.js",
"setup:data": "node scripts/setup-data.js",
diff --git a/scripts/doctor.js b/scripts/doctor.js
new file mode 100644
index 0000000000..10920bd3d3
--- /dev/null
+++ b/scripts/doctor.js
@@ -0,0 +1,460 @@
+#!/usr/bin/env node
+/**
+ * `npm run doctor` — one read-only, pasteable report of every install
+ * prerequisite (#5304).
+ *
+ * PortOS has a long prerequisite chain (Node/npm floors, an initialized
+ * `lib/slashdo` submodule, four workspace `node_modules` trees, a reachable
+ * Postgres with schema + pgvector, migrations applied, `data/` seeded from
+ * `data.reference/`, pm2, the media toolchain, an optional TLS cert, `gh`
+ * auth, the 5553–5561 port block) and until now the checks for it were
+ * scattered across places that only run once something else is already
+ * working: `checkNodeVersion.js`/`checkNpmVersion.js` fire inside
+ * `npm run dev|start|setup`, `GET /api/system/health/details` needs the server
+ * booted, `providerPrerequisites.js` covers only the AI CLIs, and
+ * `smoke-boot.js` proves the process stays up but never says why it didn't.
+ * When the server will not start there was no single thing to run.
+ *
+ * Three properties make this useful rather than just another status page:
+ *
+ * 1. **Read-only.** No installs, no migrations, no DB writes, no LLM calls
+ * (AGENTS.md "AI Provider Usage Policy"). Every probe is a SELECT, a stat,
+ * a `--version`, or a listen-and-close.
+ * 2. **Loads from a bare checkout.** Its static imports are Node builtins and
+ * builtin-only repo modules, so it runs *before* `npm install` — the very
+ * state it most needs to describe. Anything with a third-party dependency
+ * (`pg`) is loaded with a dynamic `import()` inside its own probe, so a
+ * missing dependency becomes an `unavailable` fact instead of a stack
+ * trace. `scripts/pre-install-entrypoints.test.js` enforces this.
+ * 3. **Pasteable.** Details name no hostnames, usernames, IPs, home-directory
+ * paths, or DB passwords: paths are repo-relative or scrubbed through
+ * `scrubHomePath`, and Postgres is reported by host-class (`system :5432` /
+ * `docker :5561`) rather than by connection string.
+ *
+ * Every fact is independent and separately bounded, so one hung probe degrades
+ * to a single `unavailable` line instead of hanging the report.
+ *
+ * Usage:
+ * npm run doctor # human-readable table
+ * npm run doctor -- --json # { ok, facts: [{ name, status, detail, required }] }
+ * Exits 1 when any REQUIRED fact is unavailable, 0 otherwise.
+ */
+
+import { existsSync } from 'fs';
+import { readdir } from 'fs/promises';
+import { createRequire } from 'module';
+import { createServer } from 'net';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+import { certPaths } from '../lib/certPaths.js';
+import { commandExists } from '../server/lib/commandExists.js';
+import { scrubHomePath } from '../server/lib/homePath.js';
+import { MIN_NODE, compareVersions, satisfiesMinNode } from './checkNodeVersion.js';
+import { MIN_NPM, parseNpmUserAgent, readBundledNpmVersion } from './checkNpmVersion.js';
+import { isDirectlyInvoked } from './lib/directInvocation.js';
+import { listPendingMigrations } from './run-migrations.js';
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+/**
+ * Per-probe bound. Generous enough for a cold Postgres connection (db.js allows
+ * 10s to establish one) while still capping the whole report — the probes run
+ * concurrently, so this is roughly the report's own ceiling, not a per-fact
+ * tax.
+ */
+export const PROBE_TIMEOUT_MS = 12_000;
+
+/** Shorter bound for the cheap local probes (stat, listen, `--version`). */
+const FAST_TIMEOUT_MS = 6_000;
+
+/** The workspaces `scripts/ensure-deps.js` installs — each needs node_modules. */
+const WORKSPACES = ['', 'client', 'server', 'autofixer'];
+
+/**
+ * The PortOS-owned port block from `ecosystem.config.cjs` (docs/PORTS.md).
+ * Anything outside it in `PORTS` belongs to something the operator starts by
+ * hand (whisper, llama.cpp, the vLLM/SGLang containers) and is none of a fresh
+ * install's business.
+ */
+const PORT_BLOCK = { min: 5553, max: 5561 };
+
+/**
+ * Read `PORTS` out of the CJS ecosystem config. Isolated (and defensive) so a
+ * malformed `.env` or a config the caller has edited degrades to "couldn't read
+ * the port list" rather than taking the whole report down.
+ * @returns {number[]} sorted, deduped ports inside the PortOS block
+ */
+export function portBlock(root = ROOT) {
+ const require = createRequire(import.meta.url);
+ const { PORTS } = require(join(root, 'ecosystem.config.cjs'));
+ const inBlock = Object.values(PORTS)
+ .filter((p) => Number.isInteger(p) && p >= PORT_BLOCK.min && p <= PORT_BLOCK.max);
+ return [...new Set(inBlock)].sort((a, b) => a - b);
+}
+
+// ---------------------------------------------------------------------------
+// Probe runner
+// ---------------------------------------------------------------------------
+
+/**
+ * Run one probe into a fact, bounded and total.
+ *
+ * A probe reports `{ available, detail }`. It may also throw or hang: both
+ * become an `unavailable` fact carrying the reason, because a doctor that
+ * crashes on the first broken prerequisite is a doctor that can't diagnose a
+ * broken install. Details are scrubbed on the way out so a thrown ENOENT
+ * (which embeds an absolute path) can't leak a username into the report.
+ *
+ * @param {{name: string, required?: boolean, timeoutMs?: number, run: function}} probe
+ * @returns {Promise<{name: string, status: 'available'|'unavailable', detail: string, required: boolean}>}
+ */
+export async function runProbe(probe) {
+ const required = probe.required !== false;
+ const timeoutMs = probe.timeoutMs ?? PROBE_TIMEOUT_MS;
+
+ let timer;
+ const timeout = new Promise((resolve) => {
+ timer = setTimeout(() => resolve({ available: false, detail: `probe timed out after ${timeoutMs}ms` }), timeoutMs);
+ // Never hold the event loop open on the timer itself — if every probe has
+ // settled, the report should print immediately.
+ timer.unref?.();
+ });
+
+ const result = await Promise.race([
+ Promise.resolve()
+ .then(() => probe.run())
+ .catch((err) => ({ available: false, detail: `probe failed: ${err?.message || err}` })),
+ timeout,
+ ]);
+ clearTimeout(timer);
+
+ return {
+ name: probe.name,
+ status: result?.available ? 'available' : 'unavailable',
+ detail: scrubHomePath(String(result?.detail ?? '')),
+ required,
+ };
+}
+
+/**
+ * Run every probe concurrently. Order of the returned facts follows the probe
+ * list, not completion order, so two runs of the same install produce a
+ * byte-identical report and a user can diff them.
+ */
+export async function collectFacts(probes) {
+ return Promise.all(probes.map((probe) => runProbe(probe)));
+}
+
+/**
+ * `ok` is true only when every REQUIRED fact is available. Optional facts (the
+ * cert, `gh`, the media toolchain, the port block) are reported but never fail
+ * the run — none of them stops PortOS from booting.
+ */
+export function summarize(facts) {
+ return { ok: facts.every((f) => !f.required || f.status === 'available'), facts };
+}
+
+/** Human-readable table. Aligned on the longest name so it scans vertically. */
+export function formatReport({ ok, facts }) {
+ const width = facts.reduce((max, f) => Math.max(max, f.name.length), 0);
+ const lines = facts.map((f) => {
+ const icon = f.status === 'available' ? '✅' : f.required ? '❌' : '⚠️ ';
+ return `${icon} ${f.name.padEnd(width)} ${f.detail}`;
+ });
+ const missing = facts.filter((f) => f.required && f.status === 'unavailable');
+ lines.push('');
+ lines.push(ok
+ ? '✅ All required prerequisites are available'
+ : `❌ ${missing.length} required prerequisite${missing.length === 1 ? '' : 's'} unavailable: ${missing.map((f) => f.name).join(', ')}`);
+ return lines.join('\n');
+}
+
+// ---------------------------------------------------------------------------
+// Probes
+// ---------------------------------------------------------------------------
+
+/** `existsSync` on a repo-relative path — detail names the path, never the root. */
+function probePath(root, relativePath, { presentDetail, missingDetail }) {
+ const available = existsSync(join(root, relativePath));
+ return { available, detail: available ? presentDetail : missingDetail };
+}
+
+async function probeNode() {
+ const version = process.versions.node;
+ return satisfiesMinNode(version)
+ ? { available: true, detail: `v${version} (floor ${MIN_NODE})` }
+ : { available: false, detail: `v${version} is below the ${MIN_NODE} floor — see .nvmrc` };
+}
+
+/**
+ * npm is ADVISORY, never required: no Node release bundles npm 12 yet, so an
+ * older npm is a correct install that merely churns the lockfiles. Same
+ * reasoning as `checkNpmVersion.js`, which warns rather than exits.
+ */
+async function probeNpm() {
+ const version = parseNpmUserAgent();
+ if (!version) {
+ const bundled = readBundledNpmVersion();
+ return bundled
+ ? { available: true, detail: `not running under npm; Node bundles npm ${bundled}` }
+ : { available: true, detail: 'not running under npm' };
+ }
+ return compareVersions(version, MIN_NPM) >= 0
+ ? { available: true, detail: `${version}` }
+ : { available: false, detail: `${version} is below ${MIN_NPM} — installs rewrite package-lock.json (npm install -g npm@latest)` };
+}
+
+async function probeSubmodule(root) {
+ return probePath(root, join('lib', 'slashdo', 'package.json'), {
+ presentDetail: 'lib/slashdo checked out',
+ missingDetail: 'lib/slashdo is empty — run: git submodule update --init --recursive',
+ });
+}
+
+async function probeWorkspaceDeps(root, workspace) {
+ const relative = workspace ? join(workspace, 'node_modules') : 'node_modules';
+ return probePath(root, relative, {
+ presentDetail: `${relative.replace(/\\/g, '/')} present`,
+ missingDetail: `${relative.replace(/\\/g, '/')} missing — run: npm run install:all`,
+ });
+}
+
+/**
+ * `scripts/setup-data.js` copies every top-level `data.reference/` entry into
+ * `data/`, so a missing entry means setup never ran (or ran before that entry
+ * shipped). Names come from the repo, never from the user's records, so they
+ * are safe to print.
+ */
+async function probeDataSeeded(root) {
+ const reference = join(root, 'data.reference');
+ if (!existsSync(reference)) return { available: false, detail: 'data.reference/ missing — incomplete checkout' };
+ const entries = await readdir(reference);
+ const missing = entries.filter((entry) => !existsSync(join(root, 'data', entry)));
+ return missing.length === 0
+ ? { available: true, detail: `data/ seeded (${entries.length} reference entries)` }
+ : { available: false, detail: `${missing.length}/${entries.length} entries missing (${missing.slice(0, 5).join(', ')}) — run: npm run setup:data` };
+}
+
+/**
+ * The Postgres connection, reported by HOST CLASS only.
+ *
+ * `db.js` opens a pool on import and pulls in `pg`, so it is loaded lazily:
+ * that keeps doctor runnable before `npm install`, and it means an install
+ * with no dependencies reports "unavailable" here rather than failing to
+ * start. The pool is memoized across the two DB probes and closed once, in
+ * `runDoctor`, so a single connection serves both and the process still exits.
+ */
+let dbStatePromise = null;
+function loadDbState() {
+ dbStatePromise ??= (async () => {
+ // A checkout with no `server/node_modules` cannot resolve `pg`. That is a
+ // dependency fact the deps: probes already report, so translate it here
+ // rather than surfacing a module-resolution stack trace as if the database
+ // itself were broken.
+ const db = await import('../server/lib/db.js').catch((err) => {
+ if (err?.code === 'ERR_MODULE_NOT_FOUND') return null;
+ throw err;
+ });
+ if (!db) return { db: null, health: { connected: false, hasSchema: false }, vector: false, depsMissing: true };
+ const health = await db.checkHealth();
+ // Only ask about pgvector once we know the connection works — otherwise the
+ // extension probe would just re-report the same connection failure.
+ const vector = health.connected
+ ? await db.query("SELECT 1 FROM pg_extension WHERE extname = 'vector'").then((r) => r.rowCount > 0).catch(() => false)
+ : false;
+ return { db, health, vector, depsMissing: false };
+ })();
+ return dbStatePromise;
+}
+
+/** `system :5432` / `docker :5561` — never a host, user, or password. */
+function pgHostClass() {
+ const port = parseInt(process.env.PGPORT || '5432', 10);
+ return `${port === 5561 ? 'docker' : 'system'} :${port}`;
+}
+
+async function probePostgres() {
+ const { health, depsMissing } = await loadDbState();
+ if (depsMissing) return { available: false, detail: 'not checked — server dependencies missing; run: npm run install:all' };
+ if (!health.connected) return { available: false, detail: `unreachable on ${pgHostClass()} — run: npm run setup:db` };
+ if (!health.hasSchema) return { available: false, detail: `connected on ${pgHostClass()} but schema is missing — run: npm run setup:db` };
+ return { available: true, detail: `connected on ${pgHostClass()}, schema present` };
+}
+
+async function probePgvector() {
+ const { health, vector, depsMissing } = await loadDbState();
+ if (depsMissing) return { available: false, detail: 'not checked — server dependencies missing; run: npm run install:all' };
+ if (!health.connected) return { available: false, detail: 'not checked — database unreachable' };
+ return vector
+ ? { available: true, detail: 'extension installed' }
+ : { available: false, detail: 'extension missing — the creative catalog needs pgvector; run: npm run setup:db' };
+}
+
+/**
+ * Reads `data/migrations.applied.json` only — `listPendingMigrations` is the
+ * documented pure-read half of the migration runner and never applies anything.
+ */
+async function probeMigrations(root) {
+ const pending = await listPendingMigrations({
+ rootDir: root,
+ migrationsDir: join(root, 'scripts', 'migrations'),
+ });
+ return pending.length === 0
+ ? { available: true, detail: 'all migrations applied' }
+ : { available: false, detail: `${pending.length} pending (${pending.slice(0, 3).join(', ')}) — run: npm run migrations` };
+}
+
+/**
+ * A capability probe, not a PATH lookup: `commandExists` actually invokes the
+ * binary, so a broken shim on PATH reports unavailable.
+ */
+async function probeCommand(cmd, args, { presentDetail, missingDetail }) {
+ const available = await commandExists(cmd, args, { timeoutMs: FAST_TIMEOUT_MS });
+ return { available, detail: available ? presentDetail : missingDetail };
+}
+
+async function probeCert(root) {
+ const { cert, key } = certPaths(join(root, 'data'));
+ const available = existsSync(cert) && existsSync(key);
+ return {
+ available,
+ detail: available
+ ? 'data/certs/{cert,key}.pem present — server boots HTTPS on :5555'
+ : 'no cert — server boots HTTP (optional; run: npm run setup:cert)',
+ };
+}
+
+/** Can we bind this port on loopback? Closes immediately either way. */
+export function isPortFree(port, { timeoutMs = FAST_TIMEOUT_MS } = {}) {
+ return new Promise((resolve) => {
+ const server = createServer();
+ const settle = (free) => {
+ server.removeAllListeners();
+ server.close(() => resolve(free));
+ };
+ const guard = setTimeout(() => settle(false), timeoutMs);
+ guard.unref?.();
+ server.once('error', () => { clearTimeout(guard); settle(false); });
+ server.once('listening', () => { clearTimeout(guard); settle(true); });
+ server.listen(port, '127.0.0.1');
+ });
+}
+
+/**
+ * OPTIONAL, deliberately. A healthy install that is currently RUNNING occupies
+ * most of this block, so failing the report on an occupied port would make
+ * `npm run doctor` exit non-zero on every working machine — the opposite of
+ * the signal it exists to give. Occupancy is reported as a fact for the case it
+ * actually diagnoses (a foreign process squatting on :5555 before PortOS
+ * starts) and left for the reader to interpret.
+ */
+async function probePorts(root) {
+ const ports = portBlock(root);
+ // Concurrently: serialized, nine ports at the per-port bound could outlast
+ // this probe's own budget and report a timeout instead of the occupancy.
+ const free = await Promise.all(ports.map((port) => isPortFree(port)));
+ const taken = ports.filter((_, i) => !free[i]);
+ return taken.length === 0
+ ? { available: true, detail: `${ports.length} ports free (${PORT_BLOCK.min}–${PORT_BLOCK.max})` }
+ : { available: false, detail: `in use: ${taken.join(', ')} — expected when PortOS is already running` };
+}
+
+/**
+ * The full prerequisite list, in report order: toolchain, then checkout, then
+ * data, then services, then the optional extras.
+ * @returns {Array<{name: string, required: boolean, run: function}>}
+ */
+export function defaultProbes({ root = ROOT } = {}) {
+ return [
+ { name: 'node', required: true, run: probeNode },
+ { name: 'npm', required: false, run: probeNpm },
+ { name: 'submodule:slashdo', required: true, run: () => probeSubmodule(root) },
+ ...WORKSPACES.map((workspace) => ({
+ name: `deps:${workspace || 'root'}`,
+ required: true,
+ run: () => probeWorkspaceDeps(root, workspace),
+ })),
+ { name: 'data:seeded', required: true, run: () => probeDataSeeded(root) },
+ { name: 'postgres', required: true, run: probePostgres },
+ { name: 'postgres:pgvector', required: true, run: probePgvector },
+ { name: 'migrations', required: true, run: () => probeMigrations(root) },
+ {
+ name: 'pm2',
+ required: true,
+ run: () => probeCommand('pm2', ['--version'], {
+ presentDetail: 'available — npm start manages apps through it',
+ missingDetail: 'not runnable — run: npm run install:all',
+ }),
+ },
+ {
+ name: 'ffmpeg',
+ required: false,
+ run: () => probeCommand('ffmpeg', ['-version'], {
+ presentDetail: 'available',
+ missingDetail: 'not runnable — media transcode/thumbnail jobs will fail',
+ }),
+ },
+ {
+ name: 'python3',
+ required: false,
+ run: () => probeCommand('python3', ['--version'], {
+ presentDetail: 'available',
+ missingDetail: 'not runnable — local image/audio/video generators will fail',
+ }),
+ },
+ {
+ name: 'uv',
+ required: false,
+ run: () => probeCommand('uv', ['--version'], {
+ presentDetail: 'available',
+ missingDetail: 'not runnable — the Python generators resolve their envs with it',
+ }),
+ },
+ {
+ name: 'gh',
+ required: false,
+ run: () => probeCommand('gh', ['auth', 'status'], {
+ presentDetail: 'authenticated',
+ missingDetail: 'not installed or not authenticated — run: gh auth login',
+ }),
+ },
+ { name: 'tls-cert', required: false, run: () => probeCert(root) },
+ { name: 'ports', required: false, run: () => probePorts(root) },
+ ];
+}
+
+// ---------------------------------------------------------------------------
+// CLI
+// ---------------------------------------------------------------------------
+
+/**
+ * Collect, format, and report. Injectable end to end so the test exercises the
+ * real assembly without spawning a second interpreter or touching a database.
+ *
+ * @returns {Promise<{ok: boolean, facts: object[], exitCode: number}>}
+ */
+export async function runDoctor({ probes = defaultProbes(), json = false, log = console.log } = {}) {
+ const report = summarize(await collectFacts(probes));
+ log(json ? JSON.stringify(report, null, 2) : formatReport(report));
+ return { ...report, exitCode: report.ok ? 0 : 1 };
+}
+
+/**
+ * Close anything a probe opened (today: the `pg` pool the database probes
+ * share), so the process exits on its own. Exported because a programmatic
+ * caller running `defaultProbes()` inherits the same open pool.
+ */
+export async function closeProbeResources() {
+ if (!dbStatePromise) return;
+ await dbStatePromise.then(({ db }) => db?.close()).catch(() => {});
+ dbStatePromise = null;
+}
+
+// Runnable directly: `node scripts/doctor.js [--json]` — see
+// lib/directInvocation.js for why this is not a plain string equality.
+if (isDirectlyInvoked(import.meta.url)) {
+ const { exitCode } = await runDoctor({ json: process.argv.includes('--json') });
+ await closeProbeResources();
+ process.exitCode = exitCode;
+}
diff --git a/scripts/doctor.test.js b/scripts/doctor.test.js
new file mode 100644
index 0000000000..bdb22a6eb9
--- /dev/null
+++ b/scripts/doctor.test.js
@@ -0,0 +1,206 @@
+/**
+ * `npm run doctor` contract (#5304).
+ *
+ * The probes themselves are thin delegations to helpers that have their own
+ * tests (`checkNodeVersion`, `commandExists`, `listPendingMigrations`), so what
+ * is worth pinning here is the part unique to the doctor: its totality. A
+ * diagnostic that crashes, hangs, or leaks the user's username into the block
+ * they are about to paste into a bug report is worse than no diagnostic, and
+ * each of those is a behavior no caller-level test would catch.
+ */
+import { describe, expect, it, vi } from 'vitest';
+import { homedir } from 'os';
+
+import {
+ PROBE_TIMEOUT_MS,
+ collectFacts,
+ defaultProbes,
+ formatReport,
+ portBlock,
+ runDoctor,
+ runProbe,
+ summarize,
+} from './doctor.js';
+
+const fact = (name, status, { required = true } = {}) => ({ name, status, detail: '', required });
+
+describe('summarize', () => {
+ it('is ok only when every required fact is available', () => {
+ expect(summarize([fact('a', 'available'), fact('b', 'available')]).ok).toBe(true);
+ expect(summarize([fact('a', 'available'), fact('b', 'unavailable')]).ok).toBe(false);
+ });
+
+ it('never lets an optional fact fail the run', () => {
+ // The cert, gh, the media toolchain and the port block are all reported but
+ // none of them stops PortOS from booting — see the probe list.
+ const report = summarize([
+ fact('postgres', 'available'),
+ fact('tls-cert', 'unavailable', { required: false }),
+ fact('ports', 'unavailable', { required: false }),
+ ]);
+ expect(report.ok).toBe(true);
+ });
+
+ it('is ok on an empty fact list rather than throwing', () => {
+ expect(summarize([]).ok).toBe(true);
+ });
+});
+
+describe('runProbe', () => {
+ it('turns a thrown probe into an unavailable fact instead of rejecting', async () => {
+ const result = await runProbe({
+ name: 'postgres',
+ run: () => { throw new Error('connection refused'); },
+ });
+ expect(result).toMatchObject({ name: 'postgres', status: 'unavailable', required: true });
+ expect(result.detail).toContain('connection refused');
+ });
+
+ it('turns a rejected async probe into an unavailable fact', async () => {
+ const result = await runProbe({ name: 'x', run: async () => { throw new Error('boom'); } });
+ expect(result.status).toBe('unavailable');
+ expect(result.detail).toContain('boom');
+ });
+
+ it('times out a probe that never settles rather than hanging the report', async () => {
+ // Injected time, not a production sleep: the point is the state machine,
+ // and a real 12s wait in the suite would be the actual defect.
+ vi.useFakeTimers();
+ try {
+ const pending = runProbe({ name: 'hung', timeoutMs: 1_000, run: () => new Promise(() => {}) });
+ await vi.advanceTimersByTimeAsync(1_000);
+ const result = await pending;
+ expect(result.status).toBe('unavailable');
+ expect(result.detail).toContain('timed out after 1000ms');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('scrubs the home-directory prefix out of the detail it reports', async () => {
+ // The whole value proposition is a block the user pastes into a bug report,
+ // and a thrown ENOENT embeds an absolute path — so the username must be
+ // gone before the fact is built, not at print time.
+ const home = homedir();
+ const result = await runProbe({
+ name: 'deps:server',
+ run: () => { throw new Error(`ENOENT: no such file ${home}/github.com/example/server/node_modules`); },
+ });
+ expect(result.detail).not.toContain(home);
+ expect(result.detail).toContain('~/github.com/example/server/node_modules');
+ });
+
+ it('defaults a probe to required, and honors an explicit required:false', async () => {
+ const available = async () => ({ available: true, detail: 'ok' });
+ expect((await runProbe({ name: 'a', run: available })).required).toBe(true);
+ expect((await runProbe({ name: 'b', required: false, run: available })).required).toBe(false);
+ });
+
+ it('reports a probe that returns nothing as unavailable with an empty detail', async () => {
+ const result = await runProbe({ name: 'silent', run: async () => undefined });
+ expect(result).toMatchObject({ status: 'unavailable', detail: '' });
+ });
+});
+
+describe('collectFacts', () => {
+ it('keeps probe-list order regardless of completion order, so two runs diff cleanly', async () => {
+ const slow = { name: 'slow', run: () => new Promise((r) => setTimeout(() => r({ available: true, detail: '' }), 20)) };
+ const fast = { name: 'fast', run: async () => ({ available: true, detail: '' }) };
+ const facts = await collectFacts([slow, fast]);
+ expect(facts.map((f) => f.name)).toEqual(['slow', 'fast']);
+ });
+});
+
+describe('formatReport', () => {
+ it('names every missing required fact in the closing line', () => {
+ const out = formatReport(summarize([
+ fact('postgres', 'unavailable'),
+ fact('migrations', 'unavailable'),
+ fact('node', 'available'),
+ ]));
+ expect(out).toContain('2 required prerequisites unavailable: postgres, migrations');
+ });
+
+ it('marks an unavailable optional fact as a warning, not a failure', () => {
+ const out = formatReport(summarize([fact('tls-cert', 'unavailable', { required: false })]));
+ expect(out).toContain('⚠️');
+ expect(out).not.toContain('❌');
+ expect(out).toContain('All required prerequisites are available');
+ });
+});
+
+describe('portBlock', () => {
+ it('returns only the PortOS-owned 5553-5561 block, deduped and sorted', () => {
+ // PORTS also carries whisper/llama/vLLM ports the operator starts by hand,
+ // and lists POSTGRES twice (its own key plus the docker one).
+ const ports = portBlock();
+ expect(ports.length).toBeGreaterThan(0);
+ expect(ports).toEqual([...new Set(ports)].sort((a, b) => a - b));
+ expect(ports.every((p) => p >= 5553 && p <= 5561)).toBe(true);
+ expect(ports).toContain(5555);
+ });
+});
+
+describe('defaultProbes', () => {
+ it('gives every prerequisite a unique name and a runnable probe', () => {
+ const probes = defaultProbes();
+ expect(new Set(probes.map((p) => p.name)).size).toBe(probes.length);
+ expect(probes.every((p) => typeof p.run === 'function')).toBe(true);
+ });
+
+ it('requires the boot-blocking prerequisites and leaves the rest advisory', () => {
+ const required = Object.fromEntries(defaultProbes().map((p) => [p.name, p.required]));
+ // Without these the server cannot start.
+ expect(required).toMatchObject({
+ node: true,
+ 'submodule:slashdo': true,
+ 'deps:server': true,
+ 'data:seeded': true,
+ postgres: true,
+ 'postgres:pgvector': true,
+ migrations: true,
+ });
+ // These do not block boot. `ports` in particular is advisory on purpose: a
+ // running install legitimately occupies the block, and failing on that
+ // would make doctor exit 1 on every healthy machine.
+ expect(required).toMatchObject({ npm: false, ffmpeg: false, gh: false, 'tls-cert': false, ports: false });
+ });
+});
+
+describe('runDoctor', () => {
+ it('prints parseable JSON and exits 0 when every required fact is available', async () => {
+ const log = vi.fn();
+ const result = await runDoctor({
+ probes: [
+ { name: 'node', run: async () => ({ available: true, detail: 'v24' }) },
+ { name: 'gh', required: false, run: async () => ({ available: false, detail: 'not authenticated' }) },
+ ],
+ json: true,
+ log,
+ });
+ expect(result.exitCode).toBe(0);
+ const printed = JSON.parse(log.mock.calls[0][0]);
+ expect(printed.ok).toBe(true);
+ expect(printed.facts).toHaveLength(2);
+ expect(printed.facts[0]).toEqual({ name: 'node', status: 'available', detail: 'v24', required: true });
+ });
+
+ it('exits 1 when a required fact is unavailable, and still prints the whole report', async () => {
+ const log = vi.fn();
+ const result = await runDoctor({
+ probes: [
+ { name: 'postgres', run: async () => ({ available: false, detail: 'unreachable' }) },
+ { name: 'node', run: async () => ({ available: true, detail: 'v24' }) },
+ ],
+ log,
+ });
+ expect(result.exitCode).toBe(1);
+ expect(log.mock.calls[0][0]).toContain('postgres');
+ expect(log.mock.calls[0][0]).toContain('node');
+ });
+
+ it('bounds each probe by default so one hung prerequisite cannot hang the report', () => {
+ expect(PROBE_TIMEOUT_MS).toBeGreaterThan(0);
+ expect(PROBE_TIMEOUT_MS).toBeLessThanOrEqual(30_000);
+ });
+});
diff --git a/scripts/pre-install-entrypoints.test.js b/scripts/pre-install-entrypoints.test.js
index bac125e79e..c42b3b5eca 100644
--- a/scripts/pre-install-entrypoints.test.js
+++ b/scripts/pre-install-entrypoints.test.js
@@ -27,6 +27,20 @@ const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
/** Run by the CI `impact` job before any dependency install. */
const PRE_INSTALL_ENTRYPOINTS = ['scripts/ci-base-sha.js', 'scripts/ci-test-plan.js'];
+/**
+ * Scripts that must ALSO load from a bare checkout, but for their own reason
+ * rather than because CI runs them first — so they get the builtin-only
+ * assertion without the CI-wiring one.
+ *
+ * `doctor.js` is here because a missing `node_modules` is precisely the
+ * failure it exists to explain (#5304): if it needed `npm install` to have
+ * succeeded, the one install state that most needs a diagnostic would get a
+ * module-resolution stack trace instead. Its `pg` import is a dynamic
+ * `import()` inside the database probe for the same reason, which is why it
+ * does not show up in this static walk.
+ */
+const BARE_CHECKOUT_SCRIPTS = ['scripts/doctor.js'];
+
const BUILTINS = new Set(builtinModules);
const isBuiltin = (specifier) => BUILTINS.has(specifier.replace(/^node:/, ''));
@@ -55,7 +69,7 @@ function bareSpecifiersReachableFrom(entry) {
return [...bare];
}
-describe('CI pre-install entrypoints load from a bare checkout', () => {
+describe('scripts that must load from a bare checkout', () => {
// The walker decides whether the assertions below mean anything, so it is
// verified against this file's own known imports rather than trusted.
it('bareSpecifiersReachableFrom follows relative imports and collects bare ones', () => {
@@ -72,8 +86,11 @@ describe('CI pre-install entrypoints load from a bare checkout', () => {
expect(workflow).toContain(`node ${entry}`);
});
- it.each(PRE_INSTALL_ENTRYPOINTS)('%s imports only Node builtins, transitively', (entry) => {
- const nonBuiltins = bareSpecifiersReachableFrom(entry).filter((s) => !isBuiltin(s));
- expect(nonBuiltins).toEqual([]);
- });
+ it.each([...PRE_INSTALL_ENTRYPOINTS, ...BARE_CHECKOUT_SCRIPTS])(
+ '%s imports only Node builtins, transitively',
+ (entry) => {
+ const nonBuiltins = bareSpecifiersReachableFrom(entry).filter((s) => !isBuiltin(s));
+ expect(nonBuiltins).toEqual([]);
+ },
+ );
});
diff --git a/server/lib/README.md b/server/lib/README.md
index 8404a89498..9c6c5ef0f9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -203,6 +203,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. |
| `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, directory helpers, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. |
| `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |
+| `homePath.js` | `scrubHomePath(value)` — replace the running user's home-directory prefix with `~` anywhere in a string, so `/Users/<name>/…` never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting `/` as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: `agentRunEvents.js` re-exports it for the CoS ledger, and `scripts/doctor.js` imports it statically because it must load from a bare checkout with no `node_modules` (`scripts/pre-install-entrypoints.test.js` enforces that). |
| `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore`. |
| `mimeTypes.js` | MIME tables and extension allowlists, image format detection, and filename sanitization. |
| `paths.js` | Canonical source/install `PATHS`, `dataPath`, and home-directory expansion. |
diff --git a/server/lib/agentRunEvents.js b/server/lib/agentRunEvents.js
index 8af8df0757..eeab5a6887 100644
--- a/server/lib/agentRunEvents.js
+++ b/server/lib/agentRunEvents.js
@@ -29,7 +29,7 @@
*/
import { z } from 'zod';
-import { homedir } from 'os';
+import { scrubHomePath } from './homePath.js';
import { sha256Text } from './fileUtils.js';
import { canonicalStringify, POLLUTING_KEYS } from './objects.js';
import { redactOutput } from './commandSecurity.js';
@@ -176,22 +176,10 @@ const isSafeImagePath = (key, value) => (
&& /^\/api\/screenshots\/[A-Za-z0-9][A-Za-z0-9._-]*\.(?:png|jpg|jpeg|gif|webp)$/i.test(value)
);
-/**
- * Replace the user's home directory prefix with `~` anywhere in a string.
- *
- * Workspace paths are the most common thing a lifecycle payload carries, and
- * `/Users/<name>/…` embeds the OS username. The ledger is machine-local, but a
- * diagnostic is exactly the thing a user pastes into a bug report, so the
- * username never gets written down in the first place.
- */
-export function scrubHomePath(value) {
- const home = homedir();
- // A root-user container reports `/` as the home directory. Substituting on
- // that would rewrite every separator in every path (`/var/log` → `~var~log`),
- // destroying the diagnostic to protect a username that isn't in the string.
- if (typeof value !== 'string' || !home || home === '/' || home === '\\') return value;
- return value.split(home).join('~');
-}
+// Re-exported so the ledger stays the one import site callers already know,
+// while the definition lives in a builtin-only module `scripts/doctor.js` can
+// also load from a bare checkout. See server/lib/homePath.js.
+export { scrubHomePath };
/**
* Scrub + bound one free-form string: home path, then the shared secret filter,
diff --git a/server/lib/agentRunEvents.test.js b/server/lib/agentRunEvents.test.js
index 175f20febe..bc9c834dae 100644
--- a/server/lib/agentRunEvents.test.js
+++ b/server/lib/agentRunEvents.test.js
@@ -177,6 +177,11 @@ describe('redactRunEventData — privacy', () => {
vi.doMock('os', async (importOriginal) => ({ ...(await importOriginal()), homedir: () => '/' }));
const { scrubHomePath: rootScrub } = await import('./agentRunEvents.js');
expect(rootScrub('/var/log/example.log')).toBe('/var/log/example.log');
+ // Bypass probe: on a real machine the line above passes whether or not the
+ // `os` mock took, since the real home is not `/`. This one only passes when
+ // the mock actually reached the scrubber — otherwise the REAL home prefix
+ // would still be substituted.
+ expect(rootScrub(`${homedir()}/a`)).toBe(`${homedir()}/a`);
vi.doUnmock('os');
vi.resetModules();
});
diff --git a/server/lib/homePath.js b/server/lib/homePath.js
new file mode 100644
index 0000000000..31740d850a
--- /dev/null
+++ b/server/lib/homePath.js
@@ -0,0 +1,41 @@
+/**
+ * scrubHomePath — replace the running user's home-directory prefix with `~`.
+ *
+ * Lives in its own zero-dependency module, rather than beside the other
+ * redaction helpers in `agentRunEvents.js`, because two callers need it from
+ * opposite ends of the dependency graph:
+ *
+ * - the CoS run ledger (`agentRunEvents.js`), which re-exports this symbol so
+ * every existing `import { scrubHomePath } from './agentRunEvents.js'`
+ * caller is unchanged, and
+ * - `scripts/doctor.js`, whose whole job is explaining an install that will
+ * not start — including one where `server/node_modules` was never installed.
+ * Everything doctor imports statically therefore has to load from a bare
+ * checkout using Node builtins only (`scripts/pre-install-entrypoints.test.js`
+ * enforces that). Reaching for the scrubber through `agentRunEvents.js`
+ * would drag in zod and the trajectory schemas, and the diagnostic would
+ * crash on exactly the installs it exists to diagnose.
+ *
+ * Builtins only. Keep it that way — see the guard test above.
+ */
+import { homedir } from 'os';
+
+/**
+ * Replace the user's home directory prefix with `~` anywhere in a string.
+ *
+ * Workspace paths are the most common thing a lifecycle payload carries, and
+ * `/Users/<name>/…` embeds the OS username. The ledger is machine-local, but a
+ * diagnostic is exactly the thing a user pastes into a bug report, so the
+ * username never gets written down in the first place.
+ *
+ * @param {*} value - any value; non-strings pass through untouched
+ * @returns {*} the scrubbed string, or `value` unchanged
+ */
+export function scrubHomePath(value) {
+ const home = homedir();
+ // A root-user container reports `/` as the home directory. Substituting on
+ // that would rewrite every separator in every path (`/var/log` → `~var~log`),
+ // destroying the diagnostic to protect a username that isn't in the string.
+ if (typeof value !== 'string' || !home || home === '/' || home === '\\') return value;
+ return value.split(home).join('~');
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index 0e9ea6e012..f7171e6804 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -192,6 +192,7 @@ export * from './agentInstructionsFile.js';
export * from './fileCore.js';
export * as fileUtils from './fileUtils.js';
export * from './fileWriteQueue.js';
+export * from './homePath.js';
export * from './jsonIo.js';
export * from './mimeTypes.js';
export * from './paths.js';