Rule inputs
A Rule reads its file through ctx.file and the Project Inventory through ctx.project. Any other file, directory listing, or path check goes through ctx.fs:
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
create(ctx) {
const pkg = ctx.fs.readJson("package.json");
if (!isRecord(pkg) || !isRecord(pkg.dependencies) || !pkg.dependencies.acme) return;
const config = ctx.fs.readText("acme.config.ts");
// ...
}
ctx.fs has readText, readJson, exists, stat, readDir, readDirRecursive, realpath, and glob. Relative paths resolve from the project root, and missing files return undefined instead of throwing. readJson returns unknown, so validate the value before you use it. Doctor records every read as an input of the Rule, so don't import node:fs or read process.env in Rule code; built-in Rule Packs enforce this with a lint rule.
ctx.cache is memory shared by all Rules for one Doctor Run. A value stored with ctx.cache.set carries the ctx.fs reads made since the matching ctx.cache.get missed, so another Rule that reuses it depends on the same inputs. Derive cached values only from the key, ctx.fs, and ctx.project, never from the current file.
Caching between runs
Doctor caches each Rule's Diagnostics per file and replays them while the file, the Project Inventory, the Rule config, and every input the Rule read are unchanged. The cache key includes the Rule Pack name and version, the Rule's meta (prefilter included), and the source of its create function, so bump the Rule Pack version when a Rule's helpers change.
Doctor runs these Rules every time:
meta.cacheScope: "none", for a Rule that reads anythingctx.fscannot see;meta.determinism: "env-dependent"or"runtime-dependent", for a Rule whose result depends on the environment or a network call;- a Rule that changes the Project Inventory, such as adding evidence gaps.
Read the import graph
A workspace or manifest Rule (meta.execution: "workspace" or "manifest") can read inventory built from every source file in the run through ctx.inventory: sourcePaths(), componentUsage() for which Vue SFCs render which components, and importGraph() for which files import which. Doctor builds each once per run and shares it between Rules.
A file Rule can call componentUsage() or importGraph() only with meta.requires.crossFile: true and meta.cacheScope: "none", and cannot call sourcePaths(). Doctor never replays a Rule that read this inventory from the cache.
createRule({
meta: { id: "acme/store-imports-page", execution: "workspace" /* ... */ },
create(ctx) {
return {
async onWorkspaceEnd() {
const imports = await ctx.inventory.importGraph();
for (const edge of imports.importsOf("src/stores/cart.ts")) {
if (!edge.to?.includes("/pages/") || edge.typeOnly) continue;
ctx.report(diagnostics.ACME0003(), { file: edge.from, range: edge.range });
}
},
};
},
});
importGraph() resolves the specifiers Doctor resolves for --analyses dead-code: relative paths and the ~/, @/, and ~~/ aliases. Paths are absolute, and importsOf and importersOf also take paths relative to the project root.
files: every source file with File Facts.edges: one entry perimportdeclaration,export ... fromre-export,import()with a string literal, and Nuxt or Nitro auto-import of a project file. Each edge hasfrom;towhen the specifier resolves to a file in the run;specifieras written;kind("import","re-export","dynamic-import", or"auto-import");typeOnlyforimport typeandexport type ... from; andrange. A file's written edges come in source order, then its auto-import edges.importsOf(file)andimportersOf(file): the edges from a file, and the edges that resolve to it.cycles: groups of two or more files joined by static runtime imports, re-exports, and auto-imports. Each has sortedfilesandpath, one shortest loop through the group. A loop never combines Nuxt app and Nitro auto-imports, and type-only edges and dynamic imports never form one. These are the cycles--analyses graphreports asDOC0001.
Auto-import edges
In a Nuxt app, composables, utils, stores, and server utils call each other through auto-imports with no import statement. An "auto-import" edge goes from a script that reads an auto-imported value to the project file Nuxt or Nitro imports it from. specifier is the identifier, such as useCart; range is the file's first runtime read of it; autoImportBundle is "nuxt" or "nitro".
Doctor adds one edge per identifier, file, and bundle, only for reads that no local declaration or import shadows, and only for sources inside the run, never packages such as vue or #app. A file reached from both app and Nitro entry points can have edges in both bundles. typeof type queries and assignment targets are not reads. Vue SFCs contribute their <script> and <script setup> references, and a <script setup> local doesn't shadow a name in <script>. Template expressions add no edges; rendered components are in componentUsage().
Files in a layer's serverDir, resolved Nitro handlers and plugins, and their resolved dependencies use Nitro's registry, subject to Nitro's injection settings, file filters, and opt-out markers. A scan directory alone doesn't prove a file runs in Nitro, and Doctor reports an evidence gap for Nitro-scanned files it cannot place in either bundle. The app and Nitro enablement settings are independent.
Doctor reads the resolved registries from .nuxt/doctor.manifest.json; raw app collision candidates create no edges. The Nuxt bridge checks Nitro's cached registry against a fresh scan with Nitro's installed Unimport, and Doctor rechecks the scan's export results, including star re-exports and symlinks. Custom scan filters are recorded as decisions for the paths Nitro saw, so a new path needs a fresh prepare. A custom Nitro auto-import resolver can change the target for each importer, so Doctor withholds Nitro edges rather than replaying it.
When the manifest or registry evidence is missing, stale, or unverifiable, Doctor withholds that registry's edges and reports an evidence gap. Run nuxt prepare again to refresh it. The standalone CLI uses its own scanner only when the versions match. If Nitro uses another version, run nuxt doctor, or pass --host-extensions on a project you trust, to replay Nitro's installed scanner.
Report scope
A file Rule reports into the file it analyzes: the reported file and every related location must be ctx.file.path. That is the default meta.reportScope: "file", and Doctor enforces it. A file Rule that reports anywhere else stops the run with DOC0030, naming the Rule, the analyzed file, and the other file. Evidence file entries are not report locations and are not checked.
A file Rule that reports into other files, such as the module an import resolves to, declares it:
createRule({
meta: {
id: "acme/imported-legacy",
title: "Legacy module",
category: "imports",
severity: "warn",
reportScope: "project",
},
create(ctx) {
// ...
ctx.report(diagnostics.ACME0002(), {
file: target,
related: [{ file: ctx.file.path, message: "Imported here" }],
});
},
});
Manifest and workspace Rules (execution: "manifest" or "workspace") always report on the project; reportScope doesn't apply to them.
The scope decides what a --changed run analyzes. A file-scoped Rule's Diagnostics can only land in the file it analyzed, so --changed runs file-scoped Rules on changed files only, and doesn't parse unchanged files unless something needs them. Project-scoped file Rules, manifest Rules, workspace Rules, and --analyses still see the whole project. Either way the report equals a full run filtered to the changed lines, so declare "project" whenever a Rule can report outside its file. The affectedFiles run option scopes a run the same way, to whole files instead of changed lines; the Vite Plugin Surface passes the files a dev server saw saved.
Activation scope
In a workspace, an activated Rule Pack runs its Rules on the files of the workspace packages that activate it. A Rule about integration code, such as a Vite plugin or Nuxt module that registers Nitro handlers for an app elsewhere, declares meta.activationScope: "workspace" to check every workspace package once its Rule Pack activates for any of them.
Evidence Sources
An Evidence Source reads Runtime Evidence the source tree doesn't hold, such as a saved toolchain report. Doctor calls it only when the run is given an input for it. Declare it on the extension, not in setup, so the CLI can discover its flags without running setup:
import { defineDoctorConfig } from "vite-doctor/config";
import { defineDoctorExtension, type EvidenceSource } from "vite-doctor/extension";
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
const build: EvidenceSource<string> = {
name: "build",
label: "build report",
options: {
report: { help: "Read a saved build report.", value: "path" },
},
fromOptions: ({ report }) => report![0]!,
toOptions: (report) => ({ report: [report] }),
async collect(report, { project }) {
try {
const data = JSON.parse(await readFile(resolve(project.root, report), "utf8"));
return { evidence: { data }, targets: [report] };
} catch {
return { evidence: {}, gaps: [{ message: `Could not read build report ${report}.` }] };
}
},
};
export default defineDoctorConfig({
extensions: [defineDoctorExtension({ name: "acme/build", sources: [build] })],
});
- Flags. Each option becomes
--<source>-<option>, here--build-report. A flag must be unique across sources and must not overlap a built-in flag. The CLI reads flag values as strings once--confighas loaded. Use--flag=valuewhen the value starts with a dash. - Inputs.
fromOptionsturns the flag values into the source's input. Inputs can carry tokens, so Doctor never reads them fromdoctor.config.*. - Evidence. Doctor waits for every input's
validatebefore it runs any contributor or collector, then stores whatcollectreturns asproject.runtimeEvidence.buildfor Rules to read. Each gap makes the reportincomplete(exit3). - Reports.
sourcesin the JSON report lists each source with itstargets. Rerun commands repeat the original CLI flags, or usetoOptionsfor programmatic input. Values markedsecretare redacted.
A source the run reads can't share its name with a Runtime Evidence contributor, because both write project.runtimeEvidence.<name>.
Doctor never connects to a running server. To check a running MCP server, use is-mcp-ok as the MCP guide describes.