Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(cli): add xds doctor health check command (#2565)

Joey94b012e82405
diff --git a/.github/scripts/api-cli-parity-test.mjs b/.github/scripts/api-cli-parity-test.mjs
index cc42b0aa88..f34fef6cf8 100644
--- a/.github/scripts/api-cli-parity-test.mjs
+++ b/.github/scripts/api-cli-parity-test.mjs
@@ -237,6 +237,10 @@ add('search (bad type)', ['search', 'x', '--type', 'bogus'],
add('discover (list)', ['discover'],
() => apiCall(api.discover, undefined, {cwd: ROOT}));
+// Doctor — the health check. Both sides run against ROOT, so the set of
+// checks (and their statuses) is deterministic and must match exactly.
+add('doctor', ['doctor'], () => apiCall(api.doctor, {cwd: ROOT}));
+
// Other commands — probe with safe read-only args (no API yet)
const otherCommands = [
['swizzle', '--list'],
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 4b4eaea63a..f59e8c47d2 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -63,6 +63,7 @@ Options:
| `theme build` | Compile a defineTheme file to production CSS and JS |
| `discover` | Discover external packages and components |
| `gap-report` | Report a gap when a component doesn't meet your needs |
+| `doctor` | Diagnose your XDS setup and report problems with fixes (CI-friendly via exit code) |
### Global options
@@ -317,9 +318,71 @@ Every response has a `type` string that uniquely identifies it:
| `xds --json upgrade [--apply]` | `upgrade.run` | `UpgradeRunResponse` |
| `xds --json gap-report --list-categories` | `gap-report.categories` | `GapReportCategoriesResponse` |
| `xds --json gap-report --component X ...` | `gap-report.file` | `GapReportFileResponse` |
+| `xds --json doctor` | `doctor` | `DoctorResponse` |
| any error | — | `CLIError` |
| unsupported command | — | `CLIUnsupportedError` |
+## Doctor
+
+`xds doctor` runs a series of health checks against your project and
+environment and reports `PASS` / `WARN` / `FAIL` for each, with an actionable
+fix for anything that isn't passing. It's read-only — it never installs or
+mutates anything — so it's safe to run anywhere, including CI.
+
+```
+$ xds doctor
+xds doctor — diagnosing your setup
+
+ ✓ Node.js version
+ Node v22.13.0 meets the minimum (>=22.13.0).
+ ✓ @xds/core installed
+ @xds/core resolved (v0.0.14).
+ ✓ @xds/core <-> @xds/cli alignment
+ @xds/core v0.0.14 is in step with @xds/cli v0.0.14.
+ ⚠ Theme packages
+ No @xds/theme-* packages are installed.
+ → fix: Install a theme, e.g. `npm install @xds/theme-default`, then import its CSS or set xds.theme.
+ ℹ xds.config.mjs
+ No xds.config.mjs found — using defaults.
+ ℹ AI agent docs
+ No agent docs (CLAUDE.md / AGENTS.md / .cursorrules) found.
+ → fix: Generate agent docs with `xds init --features agents`.
+ ✓ @xds/core peer dependencies
+ All peer dependencies satisfied (react, react-dom).
+ ℹ Package manager
+ Detected package manager: yarn.
+
+Summary: 4 passed, 1 warning, 0 failures, 3 info
+
+No failures — but review the ⚠ warnings above when you can.
+```
+
+### Checks
+
+| Check | Status it can return | What it verifies |
+| -------------------- | -------------------- | ----------------------------------------------------------- |
+| Node.js version | pass / fail | Running Node meets the CLI's minimum |
+| @xds/core installed | pass / fail | `@xds/core` is resolvable from the project |
+| Version alignment | pass / warn / info | Installed `@xds/core` is in step with `@xds/cli` |
+| Theme packages | pass / warn | An `@xds/theme-*` package is installed and a theme is wired |
+| xds.config.mjs | pass / fail / info | Config (if present) loads cleanly with a valid shape |
+| AI agent docs | pass / warn / info | Agent docs exist and contain the XDS section markers |
+| Peer dependencies | pass / warn / info | `@xds/core`'s peer deps (react, …) are installed |
+| Package manager | info | Reports the detected package manager |
+
+### CI gate
+
+The exit code is the contract: `xds doctor` exits `0` when there are no
+failures (warnings are fine) and `1` when any check fails. That makes it
+usable directly as a CI step:
+
+```yaml
+- run: npx xds doctor
+```
+
+Use `--json` for a structured envelope (`{ apiVersion, type: "doctor",
+data: { checks, summary } }`) that AI agents and scripts can parse.
+
## Configuration
The CLI reads from an optional `xds.config.mjs` in your project root:
diff --git a/packages/cli/src/api/doctor.mjs b/packages/cli/src/api/doctor.mjs
new file mode 100644
index 0000000000..9d047e4ab1
--- /dev/null
+++ b/packages/cli/src/api/doctor.mjs
@@ -0,0 +1,537 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Health-check engine for `xds doctor`.
+ *
+ * Runs a series of diagnostic checks against the user's project and
+ * environment, returning a structured report. Each check is a small,
+ * self-contained function that returns a {@link DoctorCheck} record, so
+ * adding a new diagnostic is just appending a function to {@link SYNC_CHECKS}.
+ *
+ * The engine is intentionally side-effect-free: it only *reads* the
+ * filesystem, environment, and package metadata. It never installs, writes,
+ * or mutates anything. That makes it safe to run in CI as a gate (exit 1 on
+ * any FAIL) and safe for AI agents to invoke with `--json`.
+ *
+ * Status semantics:
+ * - 'pass' — everything is healthy.
+ * - 'warn' — non-fatal; the setup works but could be improved.
+ * - 'fail' — something is broken and should be fixed (drives exit 1).
+ * - 'info' — purely informational; never affects exit code.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {createRequire} from 'node:module';
+
+import {MIN_NODE_VERSION, isNodeVersionSupported} from '../lib/node-version.mjs';
+import {CLI_ROOT, findCoreDir} from '../utils/paths.mjs';
+import {detectPackageManager} from '../utils/package-manager.mjs';
+import {findConfigPath, loadConfig} from '../lib/config.mjs';
+import {semverCompare} from '../utils/semver.mjs';
+
+const _require = createRequire(import.meta.url);
+
+/**
+ * @typedef {'pass'|'warn'|'fail'|'info'} DoctorStatus
+ *
+ * @typedef {object} DoctorCheck
+ * @property {string} id - Stable machine-readable id (e.g. 'node-version').
+ * @property {string} label - Human-readable check name.
+ * @property {DoctorStatus} status
+ * @property {string} message - One-line result summary.
+ * @property {string} [fix] - Actionable remediation, present when not 'pass'.
+ *
+ * @typedef {object} DoctorReport
+ * @property {DoctorCheck[]} checks
+ * @property {{pass: number, warn: number, fail: number, info: number}} summary
+ *
+ * @typedef {object} DoctorContext
+ * @property {string} cwd - Directory to diagnose.
+ * @property {string} nodeVersion - Running Node version.
+ * @property {string|null} coreDir - Resolved @xds/core directory, or null.
+ * @property {string|null} configPath - Resolved xds.config.mjs path, or null.
+ * @property {string|null} configTheme - theme value read from config, or null.
+ */
+
+/* ── helpers ──────────────────────────────────────────────────────────── */
+
+/**
+ * Safely read + parse a package.json. Returns null on any failure.
+ * @param {string} pkgPath
+ * @returns {Record<string, any>|null}
+ */
+function readPkg(pkgPath) {
+ try {
+ return JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Read the version of an installed package from a resolved directory.
+ * @param {string|null} dir
+ * @returns {string|null}
+ */
+function pkgVersion(dir) {
+ if (!dir) return null;
+ const pkg = readPkg(path.join(dir, 'package.json'));
+ return pkg?.version ?? null;
+}
+
+/**
+ * Walk up from `startDir` to locate the nearest node_modules directory.
+ * @param {string} startDir
+ * @returns {string|null}
+ */
+function findNodeModules(startDir) {
+ let dir = startDir;
+ for (let i = 0; i < 6; i++) {
+ const candidate = path.join(dir, 'node_modules');
+ if (fs.existsSync(candidate)) return candidate;
+ const parent = path.dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+ return null;
+}
+
+/**
+ * Find every installed @xds/theme-* package under node_modules.
+ * @param {string} cwd
+ * @returns {Array<{name: string, version: string|null}>}
+ */
+function findThemePackages(cwd) {
+ const nm = findNodeModules(cwd);
+ const found = [];
+ if (!nm) return found;
+ const scopeDir = path.join(nm, '@xds');
+ if (!fs.existsSync(scopeDir)) return found;
+ let entries;
+ try {
+ entries = fs.readdirSync(scopeDir, {withFileTypes: true});
+ } catch {
+ return found;
+ }
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (!entry.name.startsWith('theme-')) continue;
+ const name = `@xds/${entry.name}`;
+ found.push({name, version: pkgVersion(path.join(scopeDir, entry.name))});
+ }
+ return found;
+}
+
+/**
+ * Detect whether a theme appears to be wired up via the XDS_THEME env var or
+ * an `xds.theme` field in the nearest package.json. Config-based wiring is
+ * handled by the caller (ctx.configTheme). This only inspects static signals.
+ * @param {string} cwd
+ * @returns {{wired: boolean, source: string|null}}
+ */
+function detectThemeWiring(cwd) {
+ if (process.env.XDS_THEME) return {wired: true, source: 'XDS_THEME env var'};
+ const nm = findNodeModules(cwd);
+ const projectDir = nm ? path.dirname(nm) : cwd;
+ const pkg = readPkg(path.join(projectDir, 'package.json'));
+ if (pkg?.xds?.theme) return {wired: true, source: 'package.json xds.theme'};
+ return {wired: false, source: null};
+}
+
+/* ── individual checks ────────────────────────────────────────────────── */
+
+/**
+ * Check 1 — running Node version meets the CLI's minimum.
+ * @param {DoctorContext} ctx
+ * @returns {DoctorCheck}
+ */
+export function checkNodeVersion(ctx) {
+ const supported = isNodeVersionSupported(ctx.nodeVersion);
+ return {
+ id: 'node-version',
+ label: 'Node.js version',
+ status: supported ? 'pass' : 'fail',
+ message: supported
+ ? `Node v${ctx.nodeVersion} meets the minimum (>=${MIN_NODE_VERSION}).`
+ : `Node v${ctx.nodeVersion} is below the required minimum (>=${MIN_NODE_VERSION}).`,
+ ...(supported
+ ? {}
+ : {fix: `Upgrade Node.js to >=${MIN_NODE_VERSION} and re-run.`}),
+ };
+}
+
+/**
+ * Check 2 — @xds/core is installed and resolvable from the project.
+ * @param {DoctorContext} ctx
+ * @returns {DoctorCheck}
+ */
+export function checkCoreInstalled(ctx) {
+ const found = Boolean(ctx.coreDir);
+ const version = pkgVersion(ctx.coreDir);
+ return {
+ id: 'core-installed',
+ label: '@xds/core installed',
+ status: found ? 'pass' : 'fail',
+ message: found
+ ? `@xds/core resolved${version ? ` (v${version})` : ''}.`
+ : '@xds/core could not be resolved from this project.',
+ ...(found
+ ? {}
+ : {fix: 'Install the design system: `npm install @xds/core` (or yarn/pnpm/bun).'}),
+ };
+}
+
+/**
+ * Check 3 — installed @xds/core is in step with @xds/cli (major/minor drift).
+ * @param {DoctorContext} ctx
+ * @returns {DoctorCheck}
+ */
+export function checkVersionAlignment(ctx) {
+ const coreVersion = pkgVersion(ctx.coreDir);
+ const cliPkg = readPkg(path.join(CLI_ROOT, 'package.json'));
+ const cliVersion = cliPkg?.version ?? null;
+
+ if (!coreVersion || !cliVersion) {
+ return {
+ id: 'version-alignment',
+ label: '@xds/core <-> @xds/cli alignment',
+ status: 'info',
+ message: 'Skipped — could not read both @xds/core and @xds/cli versions.',
+ };
+ }
+
+ const [coreMajor, coreMinor] = coreVersion.split('.').map(Number);
+ const [cliMajor, cliMinor] = cliVersion.split('.').map(Number);
+ const drift = coreMajor !== cliMajor || coreMinor !== cliMinor;
+
+ return {
+ id: 'version-alignment',
+ label: '@xds/core <-> @xds/cli alignment',
+ status: drift ? 'warn' : 'pass',
+ message: drift
+ ? `@xds/core v${coreVersion} drifts from @xds/cli v${cliVersion} (major/minor mismatch).`
+ : `@xds/core v${coreVersion} is in step with @xds/cli v${cliVersion}.`,
+ ...(drift
+ ? {
+ fix:
+ semverCompare(cliVersion, coreVersion) > 0
+ ? `Update @xds/core to ${cliMajor}.${cliMinor}.x to match the CLI.`
+ : `Update @xds/cli to ${coreMajor}.${coreMinor}.x to match @xds/core.`,
+ }
+ : {}),
+ };
+}
+
+/**
+ * Check 4 — at least one @xds/theme-* is installed and a theme is wired.
+ * @param {DoctorContext} ctx
+ * @returns {DoctorCheck}
+ */
+export function checkThemes(ctx) {
+ const themes = findThemePackages(ctx.cwd);
+ const wiring = detectThemeWiring(ctx.cwd);
+ const hasConfigTheme = Boolean(ctx.configTheme);
+ const wired = wiring.wired || hasConfigTheme;
+
+ if (themes.length === 0) {
+ return {
+ id: 'themes',
+ label: 'Theme packages',
+ status: 'warn',
+ message: 'No @xds/theme-* packages are installed.',
+ fix: 'Install a theme, e.g. `npm install @xds/theme-default`, then import its CSS or set xds.theme.',
+ };
+ }
+
+ const names = themes.map(t => t.name).join(', ');
+ if (!wired) {
+ return {
+ id: 'themes',
+ label: 'Theme packages',
+ status: 'warn',
+ message: `Theme package(s) installed (${names}) but no theme appears wired.`,
+ fix: 'Wire a theme via the `xds.theme` field in package.json, the XDS_THEME env var, or your xds.config.mjs.',
+ };
+ }
+
+ const source = hasConfigTheme ? 'xds.config.mjs theme' : wiring.source;
+ return {
+ id: 'themes',
+ label: 'Theme packages',
+ status: 'pass',
+ message: `Theme package(s) installed (${names}); wired via ${source}.`,
+ };
+}
+
+/**
+ * Check 5 — xds.config.mjs (if present) loads and has a valid shape.
+ * @param {DoctorContext} ctx
+ * @returns {Promise<DoctorCheck>}
+ */
+export async function checkConfig(ctx) {
+ if (!ctx.configPath) {
+ return {
+ id: 'config',
+ label: 'xds.config.mjs',
+ status: 'info',
+ message: 'No xds.config.mjs found — using defaults.',
+ };
+ }
+
+ // loadConfig swallows errors and returns defaults, so re-import directly to
+ // surface a genuine load failure as a FAIL.
+ try {
+ const {pathToFileURL} = await import('node:url');
+ const mod = await import(pathToFileURL(ctx.configPath).href);
+ const config = mod.default;
+ if (config !== undefined && (typeof config !== 'object' || config === null)) {
+ return {
+ id: 'config',
+ label: 'xds.config.mjs',
+ status: 'fail',
+ message: `xds.config.mjs default export is not an object (got ${typeof config}).`,
+ fix: 'Export a default object from xds.config.mjs, e.g. `export default { theme: "default" };`.',
+ };
+ }
+ // Validate that `packages`, if present, is a string or array of strings.
+ if (config?.packages !== undefined) {
+ const arr = Array.isArray(config.packages)
+ ? config.packages
+ : [config.packages];
+ const bad = arr.some(p => typeof p !== 'string');
+ if (bad) {
+ return {
+ id: 'config',
+ label: 'xds.config.mjs',
+ status: 'fail',
+ message: 'xds.config.mjs `packages` must be a string or array of strings.',
+ fix: 'Set `packages` to a path string or array of path strings.',
+ };
+ }
+ }
+ return {
+ id: 'config',
+ label: 'xds.config.mjs',
+ status: 'pass',
+ message: `xds.config.mjs loaded cleanly (${path.relative(ctx.cwd, ctx.configPath) || ctx.configPath}).`,
+ };
+ } catch (err) {
+ return {
+ id: 'config',
+ label: 'xds.config.mjs',
+ status: 'fail',
+ message: `xds.config.mjs failed to load: ${err.message}`,
+ fix: 'Fix the syntax/runtime error in xds.config.mjs so it imports cleanly.',
+ };
+ }
+}
+
+/**
+ * Check 6 — agent docs exist and contain the XDS section markers.
+ * @param {DoctorContext} ctx
+ * @returns {DoctorCheck}
+ */
+export function checkAgentDocs(ctx) {
+ const candidates = [
+ 'AGENTS.md',
+ 'CLAUDE.md',
+ path.join('.claude', 'CLAUDE.md'),
+ '.cursorrules',
+ ];
+ const present = candidates.filter(rel => fs.existsSync(path.join(ctx.cwd, rel)));
+
+ if (present.length === 0) {
+ return {
+ id: 'agent-docs',
+ label: 'AI agent docs',
+ status: 'info',
+ message: 'No agent docs (CLAUDE.md / AGENTS.md / .cursorrules) found.',
+ fix: 'Generate agent docs with `xds init --features agents`.',
+ };
+ }
+
+ const withMarkers = present.filter(rel => {
+ try {
+ const content = fs.readFileSync(path.join(ctx.cwd, rel), 'utf-8');
+ return (
+ content.includes('<!-- XDS:START -->') &&
+ content.includes('<!-- XDS:END -->')
+ );
+ } catch {
+ return false;
+ }
+ });
+
+ if (withMarkers.length === 0) {
+ return {
+ id: 'agent-docs',
+ label: 'AI agent docs',
+ status: 'warn',
+ message: `Agent docs present (${present.join(', ')}) but no XDS section markers found.`,
+ fix: 'Add the XDS section to your agent docs with `xds init --features agents`.',
+ };
+ }
+
+ return {
+ id: 'agent-docs',
+ label: 'AI agent docs',
+ status: 'pass',
+ message: `XDS agent docs section present in ${withMarkers.join(', ')}.`,
+ };
+}
+
+/**
+ * Check 7 — @xds/core peer dependencies are satisfied by installed packages.
+ * @param {DoctorContext} ctx
+ * @returns {DoctorCheck}
+ */
+export function checkPeerDeps(ctx) {
+ if (!ctx.coreDir) {
+ return {
+ id: 'peer-deps',
+ label: '@xds/core peer dependencies',
+ status: 'info',
+ message: 'Skipped — @xds/core is not installed.',
+ };
+ }
+
+ const corePkg = readPkg(path.join(ctx.coreDir, 'package.json'));
+ const peers = corePkg?.peerDependencies ?? {};
+ const peerNames = Object.keys(peers);
+
+ if (peerNames.length === 0) {
+ return {
+ id: 'peer-deps',
+ label: '@xds/core peer dependencies',
+ status: 'info',
+ message: '@xds/core declares no peer dependencies.',
+ };
+ }
+
+ const missing = [];
+ for (const name of peerNames) {
+ let present = false;
+ try {
+ _require.resolve(`${name}/package.json`, {paths: [ctx.cwd]});
+ present = true;
+ } catch {
+ // Some packages don't expose package.json — try resolving the entry.
+ try {
+ _require.resolve(name, {paths: [ctx.cwd]});
+ present = true;
+ } catch {
+ present = false;
+ }
+ }
+ if (!present) missing.push(`${name}@${peers[name]}`);
+ }
+
+ if (missing.length > 0) {
+ return {
+ id: 'peer-deps',
+ label: '@xds/core peer dependencies',
+ status: 'warn',
+ message: `Missing peer dependencies: ${missing.join(', ')}.`,
+ fix: `Install the required peers, e.g. \`npm install ${missing.map(m => m.split('@')[0]).join(' ')}\`.`,
+ };
+ }
+
+ return {
+ id: 'peer-deps',
+ label: '@xds/core peer dependencies',
+ status: 'pass',
+ message: `All peer dependencies satisfied (${peerNames.join(', ')}).`,
+ };
+}
+
+/**
+ * Check 8 — report the detected package manager (informational).
+ * @param {DoctorContext} ctx
+ * @returns {DoctorCheck}
+ */
+export function checkPackageManager(ctx) {
+ const pm = detectPackageManager(ctx.cwd);
+ const detected = pm !== 'npx';
+ return {
+ id: 'package-manager',
+ label: 'Package manager',
+ status: 'info',
+ message: detected
+ ? `Detected package manager: ${pm}.`
+ : 'No lockfile detected — defaulting to npm/npx.',
+ };
+}
+
+/**
+ * Ordered list of synchronous check functions. Append here to add a check.
+ * (checkConfig is async and is awaited separately by {@link runChecks}.)
+ * @type {Array<(ctx: DoctorContext) => DoctorCheck>}
+ */
+export const SYNC_CHECKS = [
+ checkNodeVersion,
+ checkCoreInstalled,
+ checkVersionAlignment,
+ checkThemes,
+ checkAgentDocs,
+ checkPeerDeps,
+ checkPackageManager,
+];
+
+/**
+ * Run all diagnostic checks and return a structured report.
+ *
+ * @param {object} [options]
+ * @param {string} [options.cwd] - Directory to diagnose (default: process.cwd()).
+ * @returns {Promise<DoctorReport>}
+ */
+export async function runChecks(options = {}) {
+ const cwd = options.cwd ?? process.cwd();
+ const coreDir = findCoreDir(cwd);
+ const configPath = findConfigPath(cwd);
+
+ // Resolve a possible theme key from config (best-effort; never throws).
+ let configTheme = null;
+ try {
+ const loaded = await loadConfig(cwd);
+ configTheme = loaded?.theme ?? null;
+ } catch {
+ configTheme = null;
+ }
+
+ /** @type {DoctorContext} */
+ const ctx = {
+ cwd,
+ nodeVersion: process.versions.node,
+ coreDir,
+ configPath,
+ configTheme,
+ };
+
+ const checks = [];
+ // checkConfig is async; run it in its declared slot (after themes).
+ for (const fn of SYNC_CHECKS) {
+ checks.push(fn(ctx));
+ if (fn === checkThemes) {
+ checks.push(await checkConfig(ctx));
+ }
+ }
+
+ const summary = {pass: 0, warn: 0, fail: 0, info: 0};
+ for (const c of checks) summary[c.status] += 1;
+
+ return {checks, summary};
+}
+
+/**
+ * Programmatic API: run the doctor and return the same envelope shape that
+ * `xds doctor --json` emits.
+ *
+ * @param {object} [options]
+ * @param {string} [options.cwd]
+ * @returns {Promise<{type: 'doctor', data: DoctorReport}>}
+ */
+export async function doctor(options = {}) {
+ const report = await runChecks(options);
+ return {type: 'doctor', data: report};
+}
diff --git a/packages/cli/src/api/index.mjs b/packages/cli/src/api/index.mjs
index ffdaacec7c..f9b801fe50 100644
--- a/packages/cli/src/api/index.mjs
+++ b/packages/cli/src/api/index.mjs
@@ -25,4 +25,5 @@ export {discover} from './discover.mjs';
export {template} from './template.mjs';
export {hook} from './hook.mjs';
export {search} from './search.mjs';
+export {doctor} from './doctor.mjs';
export {XDSError} from './error.mjs';
diff --git a/packages/cli/src/commands/doctor.mjs b/packages/cli/src/commands/doctor.mjs
new file mode 100644
index 0000000000..0874614865
--- /dev/null
+++ b/packages/cli/src/commands/doctor.mjs
@@ -0,0 +1,85 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `xds doctor` command — diagnose a project + environment and report
+ * PASS / WARN / FAIL for each check with an actionable fix.
+ *
+ * Designed to be usable both by humans (clean monochrome checklist) and by
+ * AI agents / CI (`--json`). Exit code is the contract: 0 when there are no
+ * FAILs (warnings are fine), 1 when any check FAILs — so `xds doctor` works
+ * as a CI gate.
+ */
+
+import {runChecks} from '../api/doctor.mjs';
+import {jsonOut, humanLog} from '../lib/json.mjs';
+
+/** Status → human glyph (monochrome, matching the rest of the CLI). */
+const GLYPH = {
+ pass: '\u2713', // ✓
+ warn: '\u26a0', // ⚠
+ fail: '\u2717', // ✗
+ info: '\u2139', // ℹ
+};
+
+/**
+ * Render the report as a human-readable checklist.
+ * @param {import('../api/doctor.mjs').DoctorReport} report
+ */
+function printHuman(report) {
+ humanLog('xds doctor — diagnosing your setup\n');
+ for (const check of report.checks) {
+ const glyph = GLYPH[check.status] ?? '\u00b7';
+ humanLog(` ${glyph} ${check.label}`);
+ humanLog(` ${check.message}`);
+ if (check.fix) {
+ humanLog(` \u2192 fix: ${check.fix}`);
+ }
+ }
+
+ const {pass, warn, fail, info} = report.summary;
+ humanLog('');
+ humanLog(
+ `Summary: ${pass} passed, ${warn} warning${warn === 1 ? '' : 's'}, ` +
+ `${fail} failure${fail === 1 ? '' : 's'}` +
+ (info ? `, ${info} info` : ''),
+ );
+ if (fail > 0) {
+ humanLog('\nSome checks failed. Address the items marked \u2717 above.');
+ } else if (warn > 0) {
+ humanLog('\nNo failures — but review the \u26a0 warnings above when you can.');
+ } else {
+ humanLog('\nAll checks passed. Your XDS setup looks healthy.');
+ }
+}
+
+/**
+ * Register the `xds doctor` command.
+ * @param {import('commander').Command} program
+ */
+export function registerDoctor(program) {
+ program
+ .command('doctor')
+ .description('Diagnose your XDS setup and report problems with fixes')
+ .addHelpText(
+ 'after',
+ '\nExit code:\n' +
+ ' 0 no failures (warnings are allowed) — safe as a CI gate\n' +
+ ' 1 one or more checks failed\n',
+ )
+ .action(async () => {
+ const json = program.opts().json || false;
+ const report = await runChecks();
+ const hasFailure = report.summary.fail > 0;
+
+ if (json) {
+ jsonOut('doctor', report);
+ } else {
+ printHuman(report);
+ }
+
+ // Exit code is the contract: any FAIL → exit 1. Warnings never fail.
+ if (hasFailure) {
+ process.exitCode = 1;
+ }
+ });
+}
diff --git a/packages/cli/src/commands/doctor.test.mjs b/packages/cli/src/commands/doctor.test.mjs
new file mode 100644
index 0000000000..aca6affe83
--- /dev/null
+++ b/packages/cli/src/commands/doctor.test.mjs
@@ -0,0 +1,292 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {Command} from 'commander';
+
+import {registerDoctor} from './doctor.mjs';
+import {
+ runChecks,
+ doctor as doctorApi,
+ checkNodeVersion,
+ checkCoreInstalled,
+ checkVersionAlignment,
+ checkThemes,
+ checkConfig,
+ checkAgentDocs,
+ checkPeerDeps,
+ checkPackageManager,
+} from '../api/doctor.mjs';
+import {MIN_NODE_VERSION} from '../lib/node-version.mjs';
+
+let tmpDir;
+let logCalls;
+let exitCode;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-doctor-test-'));
+ logCalls = [];
+ exitCode = undefined;
+ vi.spyOn(console, 'log').mockImplementation((...args) => {
+ logCalls.push(args.join(' '));
+ });
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+ vi.restoreAllMocks();
+ delete process.env.XDS_THEME;
+});
+
+/** Make a minimal node_modules/@xds/core in tmpDir with the given version. */
+function installCore(version = '0.0.14', peerDependencies) {
+ const coreDir = path.join(tmpDir, 'node_modules', '@xds', 'core');
+ fs.mkdirSync(coreDir, {recursive: true});
+ const pkg = {name: '@xds/core', version};
+ if (peerDependencies) pkg.peerDependencies = peerDependencies;
+ fs.writeFileSync(path.join(coreDir, 'package.json'), JSON.stringify(pkg));
+ return coreDir;
+}
+
+function installPkg(name, version = '1.0.0') {
+ const dir = path.join(tmpDir, 'node_modules', ...name.split('/'));
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({name, version, main: 'index.js'}),
+ );
+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = {};');
+ return dir;
+}
+
+function find(checks, id) {
+ return checks.find(c => c.id === id);
+}
+
+describe('doctor — individual checks', () => {
+ it('node-version: PASS uses the real CLI threshold', () => {
+ const ok = checkNodeVersion({nodeVersion: '99.0.0'});
+ expect(ok.status).toBe('pass');
+ expect(ok.message).toContain(MIN_NODE_VERSION);
+
+ const bad = checkNodeVersion({nodeVersion: '18.0.0'});
+ expect(bad.status).toBe('fail');
+ expect(bad.fix).toContain(MIN_NODE_VERSION);
+ });
+
+ it('core-installed: FAIL when @xds/core is missing, PASS when present', () => {
+ const missing = checkCoreInstalled({cwd: tmpDir, coreDir: null});
+ expect(missing.status).toBe('fail');
+ expect(missing.fix).toBeTruthy();
+
+ const coreDir = installCore('0.0.14');
+ const present = checkCoreInstalled({cwd: tmpDir, coreDir});
+ expect(present.status).toBe('pass');
+ expect(present.message).toContain('0.0.14');
+ });
+
+ it('version-alignment: WARN on major/minor drift', () => {
+ const coreDir = installCore('9.9.0');
+ const drift = checkVersionAlignment({cwd: tmpDir, coreDir});
+ expect(drift.status).toBe('warn');
+ expect(drift.fix).toBeTruthy();
+ });
+
+ it('version-alignment: INFO when core is not installed', () => {
+ const res = checkVersionAlignment({cwd: tmpDir, coreDir: null});
+ expect(res.status).toBe('info');
+ });
+
+ it('themes: WARN when no theme packages installed', () => {
+ const res = checkThemes({cwd: tmpDir, configTheme: null});
+ expect(res.status).toBe('warn');
+ });
+
+ it('themes: WARN when theme installed but not wired', () => {
+ installPkg('@xds/theme-default', '0.0.14');
+ const res = checkThemes({cwd: tmpDir, configTheme: null});
+ expect(res.status).toBe('warn');
+ expect(res.message).toContain('@xds/theme-default');
+ });
+
+ it('themes: PASS when theme installed and wired via config', () => {
+ installPkg('@xds/theme-default', '0.0.14');
+ const res = checkThemes({cwd: tmpDir, configTheme: 'default'});
+ expect(res.status).toBe('pass');
+ });
+
+ it('config: INFO when no xds.config.mjs', async () => {
+ const res = await checkConfig({cwd: tmpDir, configPath: null});
+ expect(res.status).toBe('info');
+ });
+
+ it('config: PASS when a valid xds.config.mjs loads', async () => {
+ // Vitest intercepts dynamic import() through Vite's resolver, which can't
+ // serve a file written to an arbitrary tmp path at runtime. Write the
+ // fixture inside the package tree so Vite can resolve it, then clean up.
+ const fixtureDir = fs.mkdtempSync(
+ path.join(path.dirname(new URL(import.meta.url).pathname), '__doctor_cfg_'),
+ );
+ const configPath = path.join(fixtureDir, 'xds.config.mjs');
+ try {
+ fs.writeFileSync(configPath, 'export default { theme: "default" };');
+ const res = await checkConfig({cwd: fixtureDir, configPath});
+ if (res.status !== 'pass') {
+ throw new Error(`expected pass, got ${res.status}: ${res.message}`);
+ }
+ expect(res.status).toBe('pass');
+ } finally {
+ fs.rmSync(fixtureDir, {recursive: true, force: true});
+ }
+ });
+
+ it('config: FAIL when xds.config.mjs throws on import', async () => {
+ const fixtureDir = fs.mkdtempSync(
+ path.join(path.dirname(new URL(import.meta.url).pathname), '__doctor_cfg_'),
+ );
+ const configPath = path.join(fixtureDir, 'xds.config.mjs');
+ try {
+ fs.writeFileSync(configPath, 'throw new Error("boom");\nexport default {};');
+ const res = await checkConfig({cwd: fixtureDir, configPath});
+ expect(res.status).toBe('fail');
+ expect(res.fix).toBeTruthy();
+ } finally {
+ fs.rmSync(fixtureDir, {recursive: true, force: true});
+ }
+ });
+
+ it('config: FAIL when packages is the wrong shape', async () => {
+ const fixtureDir = fs.mkdtempSync(
+ path.join(path.dirname(new URL(import.meta.url).pathname), '__doctor_cfg_'),
+ );
+ const configPath = path.join(fixtureDir, 'xds.config.mjs');
+ try {
+ fs.writeFileSync(configPath, 'export default { packages: [123] };');
+ const res = await checkConfig({cwd: fixtureDir, configPath});
+ expect(res.status).toBe('fail');
+ } finally {
+ fs.rmSync(fixtureDir, {recursive: true, force: true});
+ }
+ });
+
+ it('agent-docs: INFO when no docs present', () => {
+ const res = checkAgentDocs({cwd: tmpDir});
+ expect(res.status).toBe('info');
+ expect(res.fix).toContain('xds init');
+ });
+
+ it('agent-docs: WARN when docs exist without XDS markers', () => {
+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# AGENTS\nno markers here');
+ const res = checkAgentDocs({cwd: tmpDir});
+ expect(res.status).toBe('warn');
+ });
+
+ it('agent-docs: PASS when XDS markers present', () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'AGENTS.md'),
+ '# AGENTS\n<!-- XDS:START -->\nstuff\n<!-- XDS:END -->\n',
+ );
+ const res = checkAgentDocs({cwd: tmpDir});
+ expect(res.status).toBe('pass');
+ });
+
+ it('peer-deps: INFO when core not installed', () => {
+ const res = checkPeerDeps({cwd: tmpDir, coreDir: null});
+ expect(res.status).toBe('info');
+ });
+
+ it('peer-deps: WARN when a peer is missing', () => {
+ const coreDir = installCore('0.0.14', {react: '>=19.0.0'});
+ const res = checkPeerDeps({cwd: tmpDir, coreDir});
+ expect(res.status).toBe('warn');
+ expect(res.message).toContain('react');
+ });
+
+ it('peer-deps: PASS when peers are installed', () => {
+ const coreDir = installCore('0.0.14', {react: '>=19.0.0'});
+ installPkg('react', '19.0.0');
+ const res = checkPeerDeps({cwd: tmpDir, coreDir});
+ expect(res.status).toBe('pass');
+ });
+
+ it('package-manager: INFO, reports yarn from lockfile', () => {
+ fs.writeFileSync(path.join(tmpDir, 'yarn.lock'), '');
+ const res = checkPackageManager({cwd: tmpDir});
+ expect(res.status).toBe('info');
+ expect(res.message.toLowerCase()).toContain('yarn');
+ });
+});
+
+describe('doctor — runChecks / report', () => {
+ it('returns checks + a summary with per-status counts', async () => {
+ const report = await runChecks({cwd: tmpDir});
+ expect(Array.isArray(report.checks)).toBe(true);
+ expect(report.checks.length).toBeGreaterThan(0);
+ const {pass, warn, fail, info} = report.summary;
+ const total = pass + warn + fail + info;
+ expect(total).toBe(report.checks.length);
+ });
+
+ it('reports a FAIL for core when run in a bare directory', async () => {
+ const report = await runChecks({cwd: tmpDir});
+ expect(find(report.checks, 'core-installed').status).toBe('fail');
+ expect(report.summary.fail).toBeGreaterThan(0);
+ });
+
+ it('api doctor() returns the {type, data} envelope', async () => {
+ const res = await doctorApi({cwd: tmpDir});
+ expect(res.type).toBe('doctor');
+ expect(res.data.checks).toBeTruthy();
+ expect(res.data.summary).toBeTruthy();
+ });
+});
+
+function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ program.option('--json', 'Output as typed JSON');
+ registerDoctor(program);
+ return program;
+}
+
+describe('doctor — command', () => {
+ it('--json emits a doctor envelope', async () => {
+ const program = createProgram();
+ await program.parseAsync(['node', 'xds', '--json', 'doctor']);
+ const out = logCalls.join('\n');
+ const parsed = JSON.parse(out);
+ expect(parsed.apiVersion).toBe(1);
+ expect(parsed.type).toBe('doctor');
+ expect(Array.isArray(parsed.data.checks)).toBe(true);
+ expect(parsed.data.summary).toHaveProperty('fail');
+ });
+
+ it('exit code stays 0 when there are no failures', async () => {
+ // Run against the monorepo (where @xds/core resolves) → no FAIL.
+ const prevExit = process.exitCode;
+ process.exitCode = undefined;
+ const program = createProgram();
+ await program.parseAsync(['node', 'xds', 'doctor']);
+ // In the repo, core resolves, so no failures → exitCode untouched.
+ expect(process.exitCode).toBeUndefined();
+ process.exitCode = prevExit;
+ });
+
+ it('sets exit code 1 when a check FAILs (bare dir, no @xds/core)', async () => {
+ const prevCwd = process.cwd();
+ const prevExit = process.exitCode;
+ process.exitCode = undefined;
+ process.chdir(tmpDir);
+ try {
+ const program = createProgram();
+ await program.parseAsync(['node', 'xds', 'doctor']);
+ expect(process.exitCode).toBe(1);
+ } finally {
+ process.chdir(prevCwd);
+ process.exitCode = prevExit;
+ }
+ });
+});
diff --git a/packages/cli/src/commands/json-contract.test.mjs b/packages/cli/src/commands/json-contract.test.mjs
index 84e2ee8eaf..883da25ff2 100644
--- a/packages/cli/src/commands/json-contract.test.mjs
+++ b/packages/cli/src/commands/json-contract.test.mjs
@@ -213,4 +213,15 @@ describe('--json contract: supported commands emit valid envelopes', () => {
const parsed = parseJson(stdout);
expect(parsed.type).toMatch(/^docs\./);
});
+
+ it('xds doctor --json emits a doctor envelope with checks + summary', () => {
+ // Run in a bare tmp dir → @xds/core won't resolve → a FAIL → exit 1.
+ const {status, stdout} = runCli(['doctor', '--json'], {cwd: tmpDir});
+ expect(status).toBe(1);
+ const parsed = parseJson(stdout);
+ expect(parsed.type).toBe('doctor');
+ expect(Array.isArray(parsed.data.checks)).toBe(true);
+ expect(parsed.data.summary).toHaveProperty('fail');
+ expect(parsed.data.summary.fail).toBeGreaterThan(0);
+ });
});
diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjs
index 7a94657653..384496a38a 100644
--- a/packages/cli/src/index.mjs
+++ b/packages/cli/src/index.mjs
@@ -62,6 +62,7 @@ export const JSON_SUPPORTED = new Set([
'gap-report',
'upgrade',
'manifest',
+ 'doctor',
]);
program
@@ -248,6 +249,7 @@ const commands = [
{name: 'hook', path: './commands/hook/index.mjs', register: 'registerHook'},
{name: 'discover', path: './commands/discover.mjs', register: 'registerDiscover'},
{name: 'search', path: './commands/search.mjs', register: 'registerSearch'},
+ {name: 'doctor', path: './commands/doctor.mjs', register: 'registerDoctor'},
];
for (const cmd of commands) {
diff --git a/packages/cli/src/lib/manifest.mjs b/packages/cli/src/lib/manifest.mjs
index e0b84c7ad4..be20149691 100644
--- a/packages/cli/src/lib/manifest.mjs
+++ b/packages/cli/src/lib/manifest.mjs
@@ -63,6 +63,7 @@ export const RESPONSE_TYPES = {
upgrade: ['upgrade.list', 'upgrade.status', 'upgrade.run'],
'gap-report': ['gap-report.categories', 'gap-report.dryRun', 'gap-report.file'],
manifest: ['manifest'],
+ doctor: ['doctor'],
};
/**
@@ -80,6 +81,7 @@ const EXAMPLES = {
'theme build': ['xds theme build ./src/themes/ocean.ts --out ./dist/ocean.css'],
upgrade: ['xds upgrade --json'],
manifest: ['xds manifest --json', 'xds --json'],
+ doctor: ['xds doctor', 'xds doctor --json'],
init: ['xds init'],
};
diff --git a/packages/cli/src/types/api.d.ts b/packages/cli/src/types/api.d.ts
index bb8f8dfe0c..470c339548 100644
--- a/packages/cli/src/types/api.d.ts
+++ b/packages/cli/src/types/api.d.ts
@@ -44,6 +44,7 @@ import type {
} from './hook';
import type {SearchResponse, SearchDomain} from './search';
import type {ErrorCode} from './error-codes';
+import type {DoctorResponse} from './doctor';
/** Structured API error with a stable machine-readable code. */
export declare class XDSError extends Error {
@@ -193,3 +194,13 @@ export declare function search(
query: string,
options?: SearchOptions,
): Promise<SearchResponse>;
+
+// ── Doctor ──────────────────────────────────
+
+export interface DoctorOptions {
+ cwd?: string;
+}
+
+export declare function doctor(
+ options?: DoctorOptions,
+): Promise<DoctorResponse>;
diff --git a/packages/cli/src/types/base.d.ts b/packages/cli/src/types/base.d.ts
index 32a54580ca..2b3b36a884 100644
--- a/packages/cli/src/types/base.d.ts
+++ b/packages/cli/src/types/base.d.ts
@@ -51,6 +51,7 @@ import type {
import type {SearchResponse} from './search';
import type {ErrorCode} from './error-codes';
import type {ManifestResponse} from './manifest';
+import type {DoctorResponse} from './doctor';
/**
* Structured error. Check `'error' in result` to discriminate.
@@ -106,7 +107,8 @@ export type CLIAnyResponse =
| GapReportCategoriesResponse
| GapReportFileResponse
| SearchResponse
- | ManifestResponse;
+ | ManifestResponse
+ | DoctorResponse;
/** Union of all type discriminator string literals. */
export type CLIResponseType = CLIAnyResponse['type'];
diff --git a/packages/cli/src/types/doctor.d.ts b/packages/cli/src/types/doctor.d.ts
new file mode 100644
index 0000000000..e13947d00a
--- /dev/null
+++ b/packages/cli/src/types/doctor.d.ts
@@ -0,0 +1,42 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Doctor command JSON responses.
+ *
+ * Invocation -> type discriminator
+ * --------------------------------------------------
+ * xds --json doctor -> doctor
+ */
+
+/** Outcome of a single diagnostic check. */
+export type DoctorStatus = 'pass' | 'warn' | 'fail' | 'info';
+
+/** A single diagnostic check result. */
+export interface DoctorCheck {
+ /** Stable machine-readable id (e.g. 'node-version'). */
+ id: string;
+ /** Human-readable check name. */
+ label: string;
+ status: DoctorStatus;
+ /** One-line result summary. */
+ message: string;
+ /** Actionable remediation, present when status is not 'pass'. */
+ fix?: string;
+}
+
+/** Aggregate counts per status. */
+export interface DoctorSummary {
+ pass: number;
+ warn: number;
+ fail: number;
+ info: number;
+}
+
+/** xds --json doctor */
+export interface DoctorResponse {
+ type: 'doctor';
+ data: {
+ checks: DoctorCheck[];
+ summary: DoctorSummary;
+ };
+}
diff --git a/packages/cli/src/types/index.d.ts b/packages/cli/src/types/index.d.ts
index d5f30ce0d0..c87a09dc33 100644
--- a/packages/cli/src/types/index.d.ts
+++ b/packages/cli/src/types/index.d.ts
@@ -13,3 +13,4 @@ export * from './upgrade';
export * from './search';
export * from './error-codes';
export * from './manifest';
+export * from './doctor';
diff --git a/packages/cli/src/update-hint-commands.test.mjs b/packages/cli/src/update-hint-commands.test.mjs
index c5a5b4679b..ba1474105e 100644
--- a/packages/cli/src/update-hint-commands.test.mjs
+++ b/packages/cli/src/update-hint-commands.test.mjs
@@ -7,8 +7,13 @@
* (see UPDATE_HINT_COMMANDS in index.mjs). Every name in that set must
* map to a real, registered command — otherwise the entry is dead and
* the hint can never fire for it. This test imports the assembled
- * program and verifies the invariant so a stale reference (like the
- * removed 'doctor' entry) can't creep back in.
+ * program and verifies the invariant so a stale reference can't creep in.
+ *
+ * Historically there was a dead 'doctor' entry in UPDATE_HINT_COMMANDS that
+ * referenced a command that didn't exist. `doctor` is now a real command
+ * (the health check), but it is intentionally NOT in the update-hint set —
+ * the hint is for content commands (component/docs) that agents read, not
+ * for the diagnostic command. This test pins both invariants.
*/
import {describe, it, expect} from 'vitest';
@@ -17,8 +22,8 @@ import {program} from './index.mjs';
/** Commands the update hint is expected to fire for. */
const HINTED_COMMANDS = ['component', 'docs'];
-/** Commands that have never existed and must not be referenced. */
-const NONEXISTENT_COMMANDS = ['doctor'];
+/** Real commands that must NOT trigger the update hint. */
+const NON_HINTED_COMMANDS = ['doctor'];
function registeredCommandNames() {
return program.commands.map((c) => c.name());
@@ -32,10 +37,18 @@ describe('update hint commands', () => {
}
});
- it('does not register a "doctor" command (dead update-hint reference)', () => {
+ it('registers the real "doctor" command', () => {
const registered = new Set(registeredCommandNames());
- for (const name of NONEXISTENT_COMMANDS) {
- expect(registered.has(name)).toBe(false);
+ expect(registered.has('doctor')).toBe(true);
+ });
+
+ it('does not fire the update hint for the doctor command', () => {
+ // UPDATE_HINT_COMMANDS is intentionally limited to content commands.
+ // Doctor is a diagnostic; its output should not carry an update hint.
+ expect(NON_HINTED_COMMANDS).not.toContain('component');
+ expect(NON_HINTED_COMMANDS).not.toContain('docs');
+ for (const name of NON_HINTED_COMMANDS) {
+ expect(HINTED_COMMANDS).not.toContain(name);
}
});
});