Skip to main content

fallow_types/
workspace.rs

1//! Workspace and source-discovery diagnostic data types.
2//!
3//! The serializable `WorkspaceDiagnostic` / `WorkspaceDiagnosticKind` pair
4//! lives here, upstream of both `fallow-config` (which owns the registry and
5//! emission logic and re-exports these types for back-compat) and
6//! `fallow-output` (which embeds `Vec<WorkspaceDiagnostic>` in its JSON
7//! envelopes). Keeping the data types in `fallow-types` lets the output layer
8//! reference the real, schema-bearing type instead of an opaque
9//! `serde_json::Value` newtype, so `workspace_diagnostics[]` keeps its typed
10//! `kind`/`path`/`message` shape (and the typed `kind` oneOf) in
11//! `docs/output-schema.json` without coupling output contracts to config
12//! loading.
13
14use std::path::{Path, PathBuf};
15
16#[cfg(feature = "schema")]
17use schemars::JsonSchema;
18use serde::{Deserialize, Serialize};
19
20use crate::path_util::display_relative;
21use crate::serde_path;
22
23#[path = "workspace_config_entry.rs"]
24mod config_entry;
25#[path = "workspace_health_text.rs"]
26mod health_text;
27#[path = "workspace_merge.rs"]
28mod merge;
29#[path = "workspace_plugin_text.rs"]
30mod plugin_text;
31#[path = "workspace_production_text.rs"]
32mod production_text;
33
34pub use config_entry::{OVERRIDE_REASON_BASE_RULE_OFF, OVERRIDE_REASON_PROJECT_LEVEL};
35pub use merge::{dedupe_workspace_diagnostics, merge_workspace_diagnostics};
36
37/// Why the declared pnpm version ignores the `overrides` section of
38/// `pnpm-workspace.yaml`.
39#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
40#[cfg_attr(feature = "schema", derive(JsonSchema))]
41#[serde(rename_all = "kebab-case")]
42pub enum PnpmWorkspaceOverridesIgnoredCause {
43    /// pnpm 10 or earlier, and the root `package.json` declares non-empty
44    /// `pnpm.overrides` or `resolutions`. pnpm uses these entries in place
45    /// of the `pnpm-workspace.yaml` overrides.
46    PackageJsonOverrides,
47    /// pnpm before 10.5.1, which does not read the `overrides` section of
48    /// `pnpm-workspace.yaml`.
49    PnpmVersion,
50}
51
52/// Whether the project had a `node_modules` directory at a point in time.
53///
54/// A dead-code baseline records this when it is saved, so a later run in a
55/// different install state can say that its results can differ.
56#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
57#[cfg_attr(feature = "schema", derive(JsonSchema))]
58#[serde(rename_all = "kebab-case")]
59pub enum NodeModulesState {
60    /// `node_modules` existed, or the project legitimately runs without it.
61    Present,
62    /// `node_modules` did not exist.
63    Missing,
64}
65
66impl NodeModulesState {
67    /// The wire token, as it appears in JSON.
68    #[must_use]
69    pub const fn as_str(self) -> &'static str {
70        match self {
71            Self::Present => "present",
72            Self::Missing => "missing",
73        }
74    }
75}
76
77/// Why a workspace-discovery candidate was rejected, or why a sibling
78/// directory looked workspace-like but was not declared.
79///
80/// Wire-format names are kebab-case so JSON consumers (CI integrations, MCP
81/// agents, LSP clients) get a stable, language-neutral identifier.
82#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
83#[cfg_attr(feature = "schema", derive(JsonSchema))]
84#[serde(tag = "kind", rename_all = "kebab-case")]
85pub enum WorkspaceDiagnosticKind {
86    /// A directory contains `package.json` but is not declared as a workspace
87    /// in `package.json` `workspaces`, `pnpm-workspace.yaml`, or
88    /// `tsconfig.json` `references`. Surfaced by
89    /// `find_undeclared_workspaces`.
90    UndeclaredWorkspace,
91    /// A declared workspace's `package.json` failed to parse. The directory is
92    /// dropped from discovery, but analysis still proceeds (degraded).
93    MalformedPackageJson {
94        /// `serde_json` parse error text.
95        error: String,
96    },
97    /// A workspace glob pattern matched a directory that contains no
98    /// `package.json`. Honors the extended skip list and `ignorePatterns`
99    /// before emitting.
100    GlobMatchedNoPackageJson {
101        /// The glob pattern that matched the directory.
102        pattern: String,
103    },
104    /// A workspace entry is an absolute path or has `..` segments that lead
105    /// above the project root, so it can name directories outside the root. Fallow skips the entry
106    /// before it reads the disk and analyzes no package from it. `path` is
107    /// the file that declares the entry (`package.json`,
108    /// `pnpm-workspace.yaml`, `deno.json` or `deno.jsonc`), or the project
109    /// root for an entry of the fallow config `workspaces.patterns`. The
110    /// diagnostic never names a directory outside the root.
111    ///
112    /// npm, pnpm and yarn accept such an entry, so fallow does not exit with
113    /// an error on it. The project root is the security boundary of a run.
114    WorkspaceGlobOutsideRoot {
115        /// The workspace entry, as written in the file.
116        pattern: String,
117    },
118    /// A positive workspace pattern names a directory that does not exist.
119    /// The check reads the literal part of the pattern before the first
120    /// segment with a glob character (`vite` for `vite/packages/*`). A pattern
121    /// without a literal part (`**/pkg`) never gets this diagnostic, and a
122    /// literal directory that exists but holds no package does not get it
123    /// either. `path` is the file that declares the pattern, or the project
124    /// root for an entry of the fallow config `workspaces.patterns`.
125    ///
126    /// A repository that clones other repositories into the workspace in CI
127    /// declares such patterns. The packages there can consume catalog
128    /// entries, so the run does not report `unused-catalog-entries` while a
129    /// pattern of this kind exists. For a `packages` entry of the
130    /// `pnpm-workspace.yaml` of a nested pnpm project, the pattern is
131    /// relative to that file, and the run does not report the unused entries
132    /// of that catalog only.
133    WorkspacePatternDirMissing {
134        /// The workspace pattern, as written in the file.
135        pattern: String,
136    },
137    /// A directory has its own `package.json` and `pnpm-workspace.yaml`, and
138    /// no workspace pattern of the root manifests declares it. pnpm installs
139    /// it as an independent project. Fallow analyzes it as a workspace, so its
140    /// `package.json` owns its files and dependencies. The members that the
141    /// `packages` list of its `pnpm-workspace.yaml` declares are workspaces
142    /// too. The `catalog:` references of the project and its members resolve
143    /// against its own catalog, not against the root catalog.
144    ///
145    /// Information only: nothing is lost from the analysis, so
146    /// `degrades_analysis` is false.
147    NestedProjectRoot,
148    /// The root `tsconfig.json`, or a config in its `extends` chain, exists
149    /// but failed to parse. `path` names the file that failed. Fallow ignores
150    /// the project references, path aliases and compiler options of that file.
151    MalformedTsconfig {
152        /// JSONC parse error text.
153        error: String,
154    },
155    /// `tsconfig.json` lists a `references[].path` that does not point to an
156    /// existing directory.
157    TsconfigReferenceDirMissing,
158    /// `pnpm-workspace.yaml` exists but failed to parse as YAML. The catalog
159    /// checks are skipped and dependency-override analysis proceeds without
160    /// the file's entries (degraded) until the syntax is fixed.
161    MalformedPnpmWorkspaceYaml {
162        /// YAML parse error text.
163        error: String,
164    },
165    /// A source file was skipped at discovery because it exceeds the configured
166    /// per-file size limit (`--max-file-size` / `FALLOW_MAX_FILE_SIZE`, default
167    /// 5 MB). The file is never read, parsed, or analyzed, guarding against the
168    /// out-of-memory blowup a single multi-MB generated/vendored/bundled file
169    /// causes (issue #1086). Surfaced by source discovery, not workspace
170    /// discovery, but shares this channel so the skip is visible in
171    /// `workspace_diagnostics[]` on `fallow dead-code / dupes / health` JSON.
172    SkippedLargeFile {
173        /// On-disk size of the skipped file in bytes.
174        size_bytes: u64,
175    },
176    /// A large JavaScript bundle was skipped at discovery because it appears to
177    /// be minified generated output. The file is never parsed or analyzed,
178    /// guarding against sub-limit bundles that can still create very large ASTs
179    /// and extraction payloads (issue #1086). Use `--max-file-size 0` when the
180    /// bundled file really should be analyzed.
181    SkippedMinifiedFile {
182        /// On-disk size of the skipped file in bytes.
183        size_bytes: u64,
184    },
185    /// A dot-prefixed directory was not traversed by source discovery even
186    /// though it contains at least one source file the project has not
187    /// excluded. Hidden directories are skipped by default apart from a small
188    /// convention allowlist (`.storybook`, `.vitepress`, `.well-known`,
189    /// `.changeset`, `.github`) and the directories an active framework plugin
190    /// or a `package.json` script reference contributes, so files inside are
191    /// never parsed and their imports and exports are invisible to every
192    /// analysis. A file, export or dependency that only the directory uses can
193    /// be reported as unused. A `!<dir>/**` entry in `ignorePatterns` adds the
194    /// directory to traversal (issue #2452). Or add the file to `entry`, the
195    /// export to `ignoreExports` or the dependency to `ignoreDependencies` to
196    /// stop that false positive, or add the directory to `ignorePatterns` to
197    /// silence this (issue #461). Running
198    /// fallow with `--root` against the directory analyzes it on its own and
199    /// does not fix the main run (issue #2797).
200    ///
201    /// "Not excluded" is measured the way the run measures it: a directory
202    /// whose contents are gitignored, or excluded by `ignorePatterns`, or (on
203    /// a `--production` run) excluded as test or story files, never earns this
204    /// diagnostic, because the advertised remedies would find nothing there
205    /// either. Generated tool output and non-git VCS metadata are excluded by
206    /// name.
207    ///
208    /// The advisory is best-effort and bounded: one run inspects a fixed
209    /// number of skipped directories with a fixed I/O budget, in sorted path
210    /// order, so a pathological tree yields a deterministic prefix rather than
211    /// an unbounded array or an unbounded scan. The stderr note says "at
212    /// least" when a ceiling bound the run.
213    ///
214    /// Surfaced by source discovery, not workspace discovery, but shares this
215    /// channel so the skip is visible in `workspace_diagnostics[]` on
216    /// `fallow dead-code / dupes / health` JSON.
217    ///
218    /// Unlike the two skipped-file kinds beside it, this one is CAPPED. To
219    /// bound the directory reads the check costs, a run classifies at most 64
220    /// candidate directories and spends at most 1024 directory entries across
221    /// all of them, so on a project that exceeds either ceiling the array is a
222    /// prefix of the skipped directories rather than all of them, and the
223    /// stderr note says "at least N". No measured repository comes close to
224    /// either ceiling. A consumer needing an exact total should run fallow
225    /// with `--root` against the tree rather than infer one from this array.
226    SkippedSourceDotdir,
227    /// A source discovered with a stable [`FileId`](crate::discover::FileId)
228    /// could not be read before parsing. Analysis continues with the remaining
229    /// sparse module IDs and reports the underlying filesystem or UTF-8 error.
230    SourceReadFailure {
231        /// Filesystem or UTF-8 decoding error from `read_to_string`.
232        error: String,
233    },
234    /// A source file was read but parsed with diagnostics, so the module
235    /// extracted from it may be missing imports, exports, or references after
236    /// the first error. Analysis proceeds with the partial module, which is why
237    /// this is reported: an import the parser never saw credits nothing, and its
238    /// target can surface as a confident `unused-file` or `unused-export`
239    /// finding with a `delete-file` or `remove-export` action on it.
240    ///
241    /// Recorded by the parse stage, alongside `source-read-failure`, and never
242    /// used to withhold a finding. oxc reports recoverable errors for valid
243    /// syntax newer than the parser as well as for genuinely broken files, so
244    /// gating findings on this would mute real results project-wide instead of
245    /// just the affected file.
246    ///
247    /// A file that `ignoreFindings` covers is not reported. The user marked it
248    /// as broken on purpose, so its partial parse also adds no caveat to other
249    /// findings and does not count for the parse-error gate.
250    SourceParseDegraded {
251        /// Number of parser diagnostics reported for the file.
252        error_count: u32,
253        /// `true` when the parser abandoned the file instead of recovering, so
254        /// the extracted module is a fragment at best.
255        panicked: bool,
256    },
257    /// A source file nests brackets deeper than the parser cap, or needs more
258    /// stack than fallow reserves, so it was not parsed at all. The file can be
259    /// valid code, so this is not reported as a syntax error, but it degrades
260    /// the run in the same way: its imports credit nothing. It counts for the
261    /// parse-error gate and adds the same caveats as `source-parse-degraded`.
262    SourceNestingTooDeep {
263        /// The bracket nesting cap of the pre-parse scan.
264        limit: u32,
265    },
266    /// Dependency-override resolution was skipped because bun's legacy binary
267    /// `bun.lockb` sits next to this `package.json`, fallow cannot read the
268    /// binary format, and no parseable text lockfile was found to use
269    /// instead: no `bun.lock` that parses, and no readable `pnpm-lock.yaml`,
270    /// `package-lock.json`, or `npm-shrinkwrap.json`. A `yarn.lock` is never
271    /// consulted (yarn ignores `overrides`), so it does not prevent the skip
272    /// either. The manifest declares overrides, so the
273    /// `unused-dependency-overrides` check would otherwise have run; without
274    /// resolution ground truth it would flag every transitive-only pin, so no
275    /// unused-override findings are reported at all (issue #2358). Surfaced
276    /// by the override analysis, not workspace discovery, but shares this
277    /// channel so the skip is visible in `workspace_diagnostics[]` JSON and
278    /// as a stderr warning.
279    BunLockbOverrideResolutionSkipped,
280    /// Dependency-override resolution was skipped because bun's text
281    /// `bun.lock` exists but could not be parsed and no readable pnpm or npm
282    /// lockfile was available as independent resolution ground truth.
283    BunLockOverrideResolutionSkipped,
284    /// Dependency-override resolution was skipped because `pnpm-lock.yaml`
285    /// exists but could not be parsed, for example because it still holds
286    /// unresolved merge-conflict markers, and no other parseable lockfile was
287    /// available as independent resolution ground truth.
288    PnpmLockOverrideResolutionSkipped,
289    /// Dependency-override resolution was skipped because `package-lock.json`
290    /// or `npm-shrinkwrap.json` exists but could not be parsed, for example
291    /// because it still holds unresolved merge-conflict markers, and no other
292    /// parseable lockfile was available as independent resolution ground
293    /// truth.
294    NpmLockOverrideResolutionSkipped,
295    /// A bun manifest declares both `overrides` and a non-empty `resolutions`
296    /// object. Bun applies `overrides` and ignores `resolutions`, so fallow
297    /// reports the shadowed configuration without offering removal advice.
298    BunResolutionsShadowedByOverrides,
299    /// The declared pnpm version ignores the `overrides` section of
300    /// `pnpm-workspace.yaml`. pnpm does not print a warning. Fallow reports
301    /// no findings for the ignored entries. `cause` tells why pnpm ignores
302    /// the section.
303    PnpmWorkspaceOverridesIgnored {
304        /// Why pnpm ignores the section. The cause decides the remedy.
305        cause: PnpmWorkspaceOverridesIgnoredCause,
306    },
307    /// The project has no `node_modules` directory and is not a Deno project
308    /// that legitimately runs without one. Analysis proceeds, but three things
309    /// degrade silently: package `exports` and conditional exports cannot be
310    /// read, so imports into a dependency's subpaths resolve less precisely;
311    /// framework plugins that activate on an installed package stay inactive,
312    /// so their entry points and path aliases are missing; and a dependency's
313    /// installed shape cannot be inspected, so type-only dependency
314    /// classification falls back to declaration-based heuristics.
315    ///
316    /// Recorded once per run by the source walk, anchored at the missing
317    /// `node_modules` directory so the reported path is a real location rather
318    /// than the empty string a root-anchored diagnostic would render. This used
319    /// to be a bare `tracing::warn!` duplicated in two pipelines, so it never
320    /// reached JSON output and never reached `fallow doctor`, which reported
321    /// `pass` on a tree that had never been installed.
322    NodeModulesMissing,
323    /// `boundaries` is empty while `boundary-violation` is not `off`, so the
324    /// boundary detector never ran. Its summary counters are therefore
325    /// structurally zero and say nothing about the project.
326    ///
327    /// This is the UNCONFIGURED zero, not the user-chosen one: a project that
328    /// sets `boundary-violation: off` asked for silence and can see that
329    /// choice in `fallow config`. A project that left `boundaries` empty
330    /// cannot distinguish "no violations" from "nothing was measured".
331    BoundariesNotConfigured,
332    /// `rulePacks` is empty while `policy-violation` is not `off`, so the
333    /// policy detector never ran and its summary counters are structurally
334    /// zero. The unconfigured counterpart of
335    /// [`Self::BoundariesNotConfigured`].
336    RulePacksNotConfigured,
337    /// `client-server-leak` is not `off`, but no analyzed file has a
338    /// top-level `"use client"` directive and no framework plugin supplies a
339    /// client root. The detector starts only from those files, so it had no
340    /// starting point and its zero count measures nothing. A plain Vite SPA
341    /// is a typical project of this shape. The React Router plugin supplies
342    /// its route modules and `.client` modules as client roots.
343    ///
344    /// Like [`Self::BoundariesNotConfigured`], an analyze pass with the rule
345    /// `off` does not report it. `fallow security` raises a top-level `off`
346    /// to `warn` before the pass, so that command always reports it.
347    ClientServerLeakNoClientRoots,
348    /// In production mode, a built-in production pattern (for example
349    /// `**/test/**`) excluded at least one source file that a production file
350    /// imports (issue #4498). Fallow does not analyze an excluded file, so an
351    /// export or a parameter that only this file uses can show up in a
352    /// finding.
353    ///
354    /// One entry per pattern. `path` is the first excluded file in path
355    /// order. The dead-code pass records the entry from the resolved imports
356    /// of the analyzed files. It reads no excluded file. The production
357    /// patterns do not change.
358    ProductionExcludedFileImported {
359        /// The built-in production pattern that matched, verbatim.
360        pattern: String,
361        /// Excluded files that this pattern matched and that a production
362        /// file imports. Exact.
363        file_count: u32,
364        /// The first excluded files in path order, project-root-relative
365        /// with forward slashes. Capped at five entries.
366        files: Vec<String>,
367    },
368    /// One of fallow's built-in discovery ignore patterns (`**/dist/**`,
369    /// `**/build/**`, `**/coverage/**`, and the four minified-bundle globs)
370    /// removed at least one candidate source file from this walk. The files
371    /// are never read, so their imports and exports are invisible to every
372    /// analysis, and until issue #2638 the drop was completely silent:
373    /// pointing fallow at a directory a built-in pattern matches returned a
374    /// clean report with exit 0 and nothing said why.
375    ///
376    /// `**/node_modules/**` is carved out and never appears in `pattern`:
377    /// installed dependencies are not the first-party source this diagnostic
378    /// is about, and a project that does not gitignore them would get a
379    /// five-figure count with no useful remedy. `**/.git/**` cannot fire,
380    /// because hidden directories are not traversed.
381    ///
382    /// One entry per pattern, never per file or per directory, so the array
383    /// grows by at most the number of built-in patterns on a project of any
384    /// size. `path` anchors at the matched directory holding the most excluded
385    /// files for that pattern, ties broken by the lexicographically first
386    /// path, so two runs on one tree report the same location. On a nested
387    /// match it is the DEEPEST segment the pattern matched
388    /// (`build/tools/build`, not `build`), because that is the directory the
389    /// `--root` remedy names and re-rooting at a shallower one would leave a
390    /// matching segment behind. That directory is the
391    /// largest group and not a majority: a flat monorepo can spread ten
392    /// excluded files over ten sibling `dist/` directories and every one of
393    /// them is then "the largest". `file_count` spans all of them, and
394    /// `directory_count` says how many there were, so a reader can tell a
395    /// single tree from a scattered one without a directory list in the
396    /// payload.
397    ///
398    /// Three properties of the population are load-bearing and easy to
399    /// misread:
400    ///
401    /// - **Gitignored trees count zero.** Source discovery honors
402    ///   `.gitignore`, `.git/info/exclude`, and the global gitignore, and
403    ///   prunes those directories before this check runs. The honest reading
404    ///   is "candidate source files git did not already hide and a built-in
405    ///   pattern then dropped", which is why a repository that gitignores its
406    ///   own `dist/` never sees this diagnostic.
407    /// - **A user `ignorePatterns` entry is not a surprise.** The compiled
408    ///   ignore set is the union of `ignorePatterns` and the built-ins, so a
409    ///   file both matched was an explicit project choice and is attributed to
410    ///   no pattern here. A `!` entry in `ignorePatterns` lifts a built-in for
411    ///   the paths it matches (issue #2940), and a lifted file is discovered,
412    ///   so it is never counted here.
413    /// - **The remedy depends on the pattern's shape.** A directory-shaped
414    ///   built-in (`**/dist/**`) is matched against the path relative to the
415    ///   run root, so re-rooting inside the matched directory removes the
416    ///   matched segment and the files become visible: the message advertises
417    ///   `fallow --root <dir>`. A file-shaped built-in (`**/*.min.js` and the
418    ///   three other bundle globs) matches on the file name and keeps matching
419    ///   at any root, so the message says so and points at renaming instead of
420    ///   handing out a command that provably does nothing.
421    ///
422    /// Deliberately NOT one of the [`Self::source_never_analyzed`] kinds. These
423    /// exclusions are the product's designed behavior on generated output, not
424    /// a degraded run: answering `true` would attach `IncompleteFileAnalysis`
425    /// and `IncompleteImportGraph` caveats to findings on nearly every project
426    /// that keeps a non-gitignored `dist/` or `coverage/`, and make `fallow
427    /// fix` withhold `delete-file` and `remove-export` actions project-wide.
428    ExcludedByDefaultIgnore {
429        /// The built-in glob that matched, verbatim (for example
430        /// `**/build/**`).
431        pattern: String,
432        /// Candidate source files this pattern excluded in this walk, across
433        /// every directory it matched, not just the one `path` anchors at.
434        /// Exact: the walk counts each excluded candidate once.
435        file_count: u32,
436        /// Distinct directories this pattern matched at, `path` included, and
437        /// not the number of directories that held the files. A
438        /// directory-shaped pattern (`**/dist/**`) matches at the directory it
439        /// names, so an excluded subtree counts once however many nested
440        /// directories inside it held source: a `dist/` holding files in three
441        /// sub-directories reports `1`. A file-shaped pattern (`**/*.min.js`)
442        /// has no directory to collapse to and counts each matched file's own
443        /// parent. Exact either way, and anything above `1` says `path` names
444        /// one matched location out of several.
445        directory_count: u32,
446    },
447    /// The walk finished with no source file to analyze at all, so every
448    /// finding count this run reports is zero because nothing was measured
449    /// rather than because the project is clean (issue #2686).
450    ///
451    /// Distinct from [`Self::ExcludedByDefaultIgnore`], which reports one
452    /// pattern's exclusions and is designed behavior on generated output. The
453    /// alarm is not the exclusion, it is having nothing left afterwards, and
454    /// that condition also fires with no exclusion at all: a docs-only
455    /// repository, a workspace member with no TypeScript, or a path filter that
456    /// matched nothing. `excluded_file_count` names the built-in-ignore
457    /// contribution so the common cause is still attributable, and is `0` when
458    /// no built-in pattern took part.
459    ///
460    /// This is the kind a CI consumer reads to tell "measured zero" from
461    /// "measured nothing": the human report has said so since 3.26.0, but only
462    /// in human format and only under the built-in-ignore cause, so `--quiet
463    /// --format json` saw a clean green either way.
464    NoSourceFilesAnalyzed {
465        /// Candidate source files the built-in ignore patterns removed from
466        /// this walk, summed across every pattern. `0` when the walk found no
467        /// candidate to exclude in the first place.
468        excluded_file_count: u32,
469    },
470    /// Per-file health scoring failed, so the score list is empty and the
471    /// scored-file count is `0` because nothing was measured rather than
472    /// because the project has no files worth scoring. Every score-derived
473    /// number (the average maintainability index, the refactoring targets, the
474    /// hotspot complexity half) is then structurally zero (issue #2689).
475    FileScoresUnavailable {
476        /// Scoring error text.
477        error: String,
478    },
479    /// Churn-based hotspot analysis was skipped, so the hotspots, churn and
480    /// ownership sections report nothing at all. The remaining health sections
481    /// are unaffected.
482    HotspotsSkipped {
483        /// Which input stopped it, as a kebab-case token: `not-a-repository`,
484        /// `no-commits`, `invalid-since` or `churn-file-unreadable`. The set is
485        /// open.
486        ///
487        /// The cause decides the remedy, which is why it is on the wire: a run
488        /// outside a repository is fixed by running fallow inside one, a
489        /// branch without a commit by committing, a malformed `--since` by
490        /// respelling the flag, and a churn file that changed under the run by
491        /// rerunning it. A consumer reading only the kind would offer the first
492        /// remedy for all four.
493        cause: String,
494    },
495    /// Change coupling found no pairs because the history cannot show them.
496    /// The `change_coupling` section is present with an empty `pairs` list,
497    /// and this entry tells why the list is empty.
498    ChangeCouplingSkipped {
499        /// Kebab-case token: `shallow-clone` (the fetched history is
500        /// incomplete) or `too-few-commits` (fewer analyzed commits than the
501        /// minimum revisions of one file). The set is open.
502        cause: String,
503    },
504    /// The repository is a shallow clone, so churn is measured over the fetched
505    /// history only and every hotspot figure is incomplete.
506    ShallowClone {
507        /// `true` when the run also asked for ownership attribution, which a
508        /// shallow clone skews further by inflating single-author dominance.
509        ownership_requested: bool,
510    },
511    /// No commit timestamp was available, so churn recency and ownership
512    /// staleness were measured against the wall clock and drift between two
513    /// runs over the same commit.
514    UnpinnedClock,
515    /// Ownership attribution was requested but its inputs did not load, so
516    /// hotspot entries carry degraded or absent owner signals.
517    OwnershipUnavailable {
518        /// Which input failed, as a kebab-case token: `invalid-bot-pattern` or
519        /// `codeowners-parse-failed`. The set is open.
520        cause: String,
521        /// Underlying error text.
522        error: String,
523    },
524    /// A saved health snapshot could not be read or parsed, so the trend is
525    /// computed over fewer snapshots than the project has on disk and a
526    /// direction can flip on the missing point alone.
527    TrendSnapshotUnreadable {
528        /// Filesystem or JSON error text.
529        error: String,
530    },
531    /// A grouped health run asked for a trend, but the baseline snapshot holds
532    /// no group data that matches this run, so the groups carry no trend. The
533    /// project trend is not affected. `path` names the baseline snapshot.
534    TrendGroupBaselineUnavailable {
535        /// Why the groups have no baseline, as a kebab-case token:
536        /// `snapshot-has-no-groups` or `grouped-by-mismatch`. The set is open.
537        cause: String,
538    },
539    /// A framework plugin read a build config and could not read one of its
540    /// keys in full, so part of what the key declares never reached the
541    /// analysis. `path` names the config file.
542    ///
543    /// The reader is syntactic, so a key whose value is computed at build time
544    /// is invisible to it: a Module Federation `exposes: makeExposes()` or a
545    /// `remotes` map spread from an environment module declares entries this
546    /// run does not know about. The consequence is a finding, not a missing
547    /// number: an unread `exposes` target is not registered as an entry point
548    /// and its file can surface as `unused-file`, and an unread `remotes` alias
549    /// is not treated as provided by a remote container and its import can
550    /// surface as an unlisted dependency.
551    ///
552    /// Recorded by the plugin stage, which runs before analysis and is not
553    /// cached, so the entry is present on a warm cache too. A bare
554    /// `tracing::warn!` from inside the plugin reaches no envelope and no CI
555    /// consumer (issue #2736).
556    ///
557    /// A source file that calls the Module Federation runtime API gets the same
558    /// entry: `path` names the source file, `key` names the runtime function
559    /// (`registerRemotes`, `loadRemote`, `init`, `createInstance`) and
560    /// `reason` is `dynamic-argument` when the call receives a value that is
561    /// not a static literal. The analysis records it from the facts of the
562    /// parse, which a warm cache restores (issue #2795). A `.vue` or `.svelte`
563    /// file gets it for a call in its `<script>` blocks (issue #2876).
564    PluginConfigUnreadable {
565        /// The plugin that read the config, as it labels itself:
566        /// `module-federation` for a standalone `module-federation.config.*`,
567        /// or the bundler plugin (`webpack`, `rspack`, `rsbuild`, `vite`) that
568        /// read the same options inline from its own config.
569        plugin: String,
570        /// The config key that was present and not fully readable (`exposes`,
571        /// `remotes`), or the Module Federation runtime function whose
572        /// argument was not readable (`registerRemotes`, `loadRemote`, `init`,
573        /// `createInstance`). The set is open.
574        key: String,
575        /// Why it could not be read, as a kebab-case token:
576        /// `not-object-literal`, `array-form`, `spread`,
577        /// `unreadable-entries`, `unrecognized-call`,
578        /// `import-target-unreadable` or `dynamic-argument`. The set is open.
579        ///
580        /// The reason decides the remedy, which is why it is on the wire: a
581        /// value that is not an object literal is fixed by writing one, while
582        /// unreadable entries are fixed by naming those entries in the config
583        /// option the message points at.
584        reason: String,
585    },
586    /// A framework plugin read a config key it understands, does not model
587    /// that key's effect, and therefore stood a modeled default down. `path`
588    /// names the config file.
589    ///
590    /// A file can also be the `path`: a Nuxt file that reads `#components` or
591    /// `#imports` in a way fallow cannot narrow to names, such as a spread of
592    /// a namespace import, has `key` set to that module and `reason` set to
593    /// `key-effect-not-modeled`. Every name of the module then counts as used.
594    ///
595    /// The Nuxt auto-import gate is the case this exists for. With
596    /// `autoImports` enabled fallow drops the Nuxt convention entry patterns
597    /// so a genuinely unreferenced convention file is reported, and a
598    /// `components:` or `imports:` block whose effect it cannot model keeps
599    /// them, which silently costs the user the findings they opted in for.
600    ///
601    /// Deliberately NOT one of the [`Self::warns_on_stderr`] kinds. Nothing
602    /// was lost that the run could have measured: the patterns stayed, so
603    /// findings are suppressed rather than invented, and a project in this
604    /// state would otherwise warn on every run forever with "write different
605    /// config" as the only remedy, which is the reason
606    /// `boundaries-not-configured` is off stderr as well.
607    PluginEffectNotModeled {
608        /// The plugin that read the config, as it labels itself (`nuxt`).
609        plugin: String,
610        /// The config key whose effect is not modeled (`components`,
611        /// `imports`), or the virtual module a file reads (`#components`,
612        /// `#imports`). The set is open.
613        key: String,
614        /// Why the effect is not modeled, as a kebab-case token:
615        /// `key-effect-not-modeled` when the key's own value is the reason,
616        /// `config-property-unreadable` when a top-level property of the same
617        /// config file could not be read statically, so no surface in it can
618        /// be classified at all. The set is open.
619        reason: String,
620    },
621    /// Test coverage was auto-detected on disk rather than passed with
622    /// `--coverage`, and `path` names the file that fed the CRAP scores.
623    ///
624    /// Deliberately NOT one of the [`Self::warns_on_stderr`] kinds: nothing
625    /// degraded, the run measured exactly what it found. It is provenance, and
626    /// it is on the wire because a score computed against a file the user did
627    /// not name is not reproducible and nothing else says which file it was.
628    CoverageAutoDetected,
629    /// `fallow flags --retirement` asked for flag age, but the repository is
630    /// a shallow clone. Blame and pickaxe see the fetched history only, so
631    /// every age would be too young. The report gives no age.
632    FlagAgeShallowClone,
633    /// `fallow flags --retirement` asked for flag age, but git history is
634    /// not available. The report gives no age.
635    FlagAgeUnavailable {
636        /// Why no history is available, as a kebab-case token:
637        /// `not-a-repository` or `no-commits`. The set is open.
638        cause: String,
639    },
640    /// A glob in `ignoreDependencies` matched no dependency that a
641    /// `package.json` of the project declares, so the entry had no effect in
642    /// this run. The usual cause is a typo in the scope or the name.
643    ///
644    /// The dead-code run records it only when the unused-dependency check ran
645    /// and the run reports dependency findings. A run filtered to other issue
646    /// types (`--unused-files`) or scoped to files (`--file`) does not record
647    /// it. An exact-name entry never produces it. `path` is the project root.
648    ///
649    /// Not a degraded run: the analysis measured what it was asked to, so
650    /// `degrades_analysis` is false and no finding carries a caveat.
651    IgnoreDependenciesGlobUnmatched {
652        /// The `ignoreDependencies` entry, as written in the config.
653        pattern: String,
654    },
655    /// A pattern in `ignoreFindings` matched no finding of the dead-code run,
656    /// so the entry had no effect in this run. The usual cause is a typo in
657    /// the path.
658    ///
659    /// The pattern is compared with every finding the analysis produced,
660    /// before issue-type filters and scope filters, so a filtered run does not
661    /// make a pattern look unused. `path` is the project root.
662    ///
663    /// Not a degraded run, for the same reason as
664    /// [`Self::IgnoreDependenciesGlobUnmatched`].
665    IgnoreFindingsPatternUnmatched {
666        /// The `ignoreFindings` entry, as written in the config.
667        pattern: String,
668    },
669    /// An `entry` pattern matched only files that another source (a
670    /// `package.json` field or script, a plugin, `dynamicallyLoaded`) makes
671    /// runtime entry points (issue #3824). Not for a pattern that matches no
672    /// file, nor a `--production` run. `path` is the root. Not degraded.
673    EntryPatternRedundant {
674        /// The `entry` pattern, as written in the config.
675        pattern: String,
676    },
677    /// An `ignoreDependencies` entry hid no dependency finding (issue #3824).
678    /// A glob that matches no declared dependency is
679    /// [`Self::IgnoreDependenciesGlobUnmatched`] instead. Same conditions as
680    /// that kind, and not a `--production` run. `path` is the root.
681    IgnoreDependenciesEntryRedundant {
682        /// The `ignoreDependencies` entry, as written in the config.
683        pattern: String,
684    },
685    /// An `ignorePatterns` glob excluded no file that the run would otherwise
686    /// analyze (issue #3824). Never a `!` exception, a glob that names a
687    /// hidden directory, or a `--production` run. A glob for build output has
688    /// an effect only after a build. `path` is the root. Not degraded.
689    IgnorePatternsEntryRedundant {
690        /// The `ignorePatterns` glob, as written in the config.
691        pattern: String,
692    },
693    /// A `circularDependencies.allow` entry matched no cycle of the run
694    /// (issue #4623): no cycle has exactly these files in this order, from
695    /// any start file. The usual cause is a cycle that the code no longer
696    /// has, or a path that is not relative to the project root. Not for a
697    /// `--production` run, nor a run with the `circular-dependencies` rule
698    /// off. `path` is the root. Not degraded.
699    CircularDependenciesAllowUnmatched {
700        /// The entry as one line: the files joined by `, ` in brackets.
701        pattern: String,
702        /// The files of the entry, as written in the config.
703        files: Vec<String>,
704    },
705    /// An `overrides` rule cannot change the result (issue #4065). `reason` is
706    /// `project-level` (fallow reads only the top-level severity of the rule)
707    /// or `base-rule-off` (the top-level rule is off after CLI flags, so its
708    /// detector does not run). The token set is open. `path` is the root. Not
709    /// degraded, and no finding or exit code changes.
710    OverrideRuleIneffective {
711        /// The canonical rule name, also when the config uses an alias.
712        rule: String,
713        /// The `overrides[].files` globs, as written in the config.
714        files: Vec<String>,
715        /// Why the rule has no effect, as a kebab-case token.
716        reason: String,
717    },
718    /// An explicit issue-type selection asked for a rule that the config sets
719    /// to `off`, so that check did not run (issue #4067). One entry per rule.
720    /// The opt-in flags that turn their rule on and a run with no selection
721    /// never report it. `path` is the root. Not degraded: the run measured
722    /// what the config asked for, and no finding or exit code changes.
723    RequestedRuleOff {
724        /// The canonical rule name in `rules`.
725        rule: String,
726        /// The canonical CLI selector of the request, such as `--unused-deps`.
727        /// A typed API or MCP request reports the same selector.
728        flag: String,
729    },
730    /// The dead-code baseline was saved in a different install state than
731    /// this run: one of the two runs had `node_modules` and the other did not.
732    /// Findings that need installed packages (dependency, unlisted,
733    /// unresolved-import and script-binary findings) can differ, so the run
734    /// can report baseline findings as new. `path` is the baseline file.
735    ///
736    /// Only a baseline that records its install state can report this. A
737    /// legacy baseline has no record, so the state is unknown.
738    BaselineInstallStateMismatch {
739        /// The install state when the baseline was saved.
740        baseline_node_modules: NodeModulesState,
741        /// The install state of this run.
742        run_node_modules: NodeModulesState,
743    },
744}
745
746impl WorkspaceDiagnosticKind {
747    /// Stable kebab-case identifier used in dedupe keys and tracing payloads.
748    #[must_use]
749    pub const fn id(&self) -> &'static str {
750        match self {
751            Self::UndeclaredWorkspace => "undeclared-workspace",
752            Self::MalformedPackageJson { .. } => "malformed-package-json",
753            Self::GlobMatchedNoPackageJson { .. } => "glob-matched-no-package-json",
754            Self::WorkspaceGlobOutsideRoot { .. } => "workspace-glob-outside-root",
755            Self::WorkspacePatternDirMissing { .. } => "workspace-pattern-dir-missing",
756            Self::NestedProjectRoot => "nested-project-root",
757            Self::MalformedTsconfig { .. } => "malformed-tsconfig",
758            Self::TsconfigReferenceDirMissing => "tsconfig-reference-dir-missing",
759            Self::MalformedPnpmWorkspaceYaml { .. } => "malformed-pnpm-workspace-yaml",
760            Self::SkippedLargeFile { .. } => "skipped-large-file",
761            Self::SkippedMinifiedFile { .. } => "skipped-minified-file",
762            Self::SkippedSourceDotdir => "skipped-source-dotdir",
763            Self::SourceReadFailure { .. } => "source-read-failure",
764            Self::SourceParseDegraded { .. } => "source-parse-degraded",
765            Self::SourceNestingTooDeep { .. } => "source-nesting-too-deep",
766            Self::BunLockbOverrideResolutionSkipped => "bun-lockb-override-resolution-skipped",
767            Self::BunLockOverrideResolutionSkipped => "bun-lock-override-resolution-skipped",
768            Self::PnpmLockOverrideResolutionSkipped => "pnpm-lock-override-resolution-skipped",
769            Self::NpmLockOverrideResolutionSkipped => "npm-lock-override-resolution-skipped",
770            Self::BunResolutionsShadowedByOverrides => "bun-resolutions-shadowed-by-overrides",
771            Self::PnpmWorkspaceOverridesIgnored { .. } => "pnpm-workspace-overrides-ignored",
772            Self::NodeModulesMissing => "node-modules-missing",
773            Self::BoundariesNotConfigured => "boundaries-not-configured",
774            Self::RulePacksNotConfigured => "rule-packs-not-configured",
775            Self::ClientServerLeakNoClientRoots => "client-server-leak-no-client-roots",
776            Self::ProductionExcludedFileImported { .. } => "production-excluded-file-imported",
777            Self::ExcludedByDefaultIgnore { .. } => "excluded-by-default-ignore",
778            Self::NoSourceFilesAnalyzed { .. } => "no-source-files-analyzed",
779            Self::FileScoresUnavailable { .. } => "file-scores-unavailable",
780            Self::HotspotsSkipped { .. } => "hotspots-skipped",
781            Self::ChangeCouplingSkipped { .. } => "change-coupling-skipped",
782            Self::ShallowClone { .. } => "shallow-clone",
783            Self::UnpinnedClock => "unpinned-clock",
784            Self::OwnershipUnavailable { .. } => "ownership-unavailable",
785            Self::TrendSnapshotUnreadable { .. } => "trend-snapshot-unreadable",
786            Self::TrendGroupBaselineUnavailable { .. } => "trend-group-baseline-unavailable",
787            Self::PluginConfigUnreadable { .. } => "plugin-config-unreadable",
788            Self::PluginEffectNotModeled { .. } => "plugin-effect-not-modeled",
789            Self::CoverageAutoDetected => "coverage-auto-detected",
790            Self::FlagAgeShallowClone => "flag-age-shallow-clone",
791            Self::FlagAgeUnavailable { .. } => "flag-age-unavailable",
792            Self::IgnoreDependenciesGlobUnmatched { .. } => "ignore-dependencies-glob-unmatched",
793            Self::IgnoreFindingsPatternUnmatched { .. } => "ignore-findings-pattern-unmatched",
794            Self::EntryPatternRedundant { .. } => "entry-pattern-redundant",
795            Self::IgnoreDependenciesEntryRedundant { .. } => "ignore-dependencies-entry-redundant",
796            Self::IgnorePatternsEntryRedundant { .. } => "ignore-patterns-entry-redundant",
797            Self::CircularDependenciesAllowUnmatched { .. } => {
798                "circular-dependencies-allow-unmatched"
799            }
800            Self::OverrideRuleIneffective { .. } => "override-rule-ineffective",
801            Self::RequestedRuleOff { .. } => "requested-rule-off",
802            Self::BaselineInstallStateMismatch { .. } => "baseline-install-state-mismatch",
803        }
804    }
805
806    /// Whether this diagnostic is worth a `tracing::warn!` line on stderr, on
807    /// top of its permanent entry in `workspace_diagnostics[]`.
808    ///
809    /// A warning is for a run whose RESULTS are degraded: something the user
810    /// installed, wrote, or expected did not reach the analysis. The two
811    /// unconfigured-check kinds are not that. They fire in the product's
812    /// default state, on every project that never opted into boundaries or
813    /// rule packs, and they will keep firing forever, because the remedy they
814    /// offer is to write configuration in order to silence a warning about not
815    /// having written configuration. They stay in the structured array, where a
816    /// consumer that wants to distinguish "measured zero" from "measured
817    /// nothing" can read them, and off the stderr surface that every other
818    /// command shares.
819    ///
820    /// `coverage-auto-detected` answers false for a third reason: it reports
821    /// the provenance of an input that DID load, so a consumer sentence about a
822    /// degraded run would state something untrue about it. Its own note is
823    /// printed by the health pipeline.
824    ///
825    /// `plugin-effect-not-modeled` answers false for the first reason: the
826    /// config was readable and nothing the run could have measured was lost,
827    /// so it would warn forever on a project whose `nuxt.config` fallow does
828    /// not model. Its sibling `plugin-config-unreadable` answers true, because
829    /// there a declaration the user wrote did not reach the analysis and
830    /// findings can be wrong in either direction.
831    #[must_use]
832    pub const fn warns_on_stderr(&self) -> bool {
833        match self {
834            Self::BoundariesNotConfigured
835            | Self::RulePacksNotConfigured
836            | Self::ClientServerLeakNoClientRoots
837            | Self::ExcludedByDefaultIgnore { .. }
838            | Self::PluginEffectNotModeled { .. }
839            | Self::CoverageAutoDetected
840            | Self::TrendGroupBaselineUnavailable { .. }
841            | Self::ChangeCouplingSkipped { .. }
842            | Self::IgnoreDependenciesGlobUnmatched { .. }
843            | Self::IgnoreFindingsPatternUnmatched { .. }
844            | Self::EntryPatternRedundant { .. }
845            | Self::IgnoreDependenciesEntryRedundant { .. }
846            | Self::IgnorePatternsEntryRedundant { .. }
847            | Self::CircularDependenciesAllowUnmatched { .. }
848            | Self::OverrideRuleIneffective { .. }
849            | Self::RequestedRuleOff { .. }
850            | Self::NestedProjectRoot => false,
851            Self::UndeclaredWorkspace
852            | Self::MalformedPackageJson { .. }
853            | Self::GlobMatchedNoPackageJson { .. }
854            | Self::WorkspaceGlobOutsideRoot { .. }
855            | Self::WorkspacePatternDirMissing { .. }
856            | Self::MalformedTsconfig { .. }
857            | Self::TsconfigReferenceDirMissing
858            | Self::MalformedPnpmWorkspaceYaml { .. }
859            | Self::SkippedLargeFile { .. }
860            | Self::SkippedMinifiedFile { .. }
861            | Self::SkippedSourceDotdir
862            | Self::SourceReadFailure { .. }
863            | Self::SourceParseDegraded { .. }
864            | Self::SourceNestingTooDeep { .. }
865            | Self::BunLockbOverrideResolutionSkipped
866            | Self::BunLockOverrideResolutionSkipped
867            | Self::PnpmLockOverrideResolutionSkipped
868            | Self::NpmLockOverrideResolutionSkipped
869            | Self::BunResolutionsShadowedByOverrides
870            | Self::PnpmWorkspaceOverridesIgnored { .. }
871            | Self::NodeModulesMissing
872            | Self::NoSourceFilesAnalyzed { .. }
873            | Self::FileScoresUnavailable { .. }
874            | Self::HotspotsSkipped { .. }
875            | Self::ShallowClone { .. }
876            | Self::UnpinnedClock
877            | Self::OwnershipUnavailable { .. }
878            | Self::TrendSnapshotUnreadable { .. }
879            | Self::PluginConfigUnreadable { .. }
880            | Self::FlagAgeShallowClone
881            | Self::FlagAgeUnavailable { .. }
882            | Self::ProductionExcludedFileImported { .. }
883            | Self::BaselineInstallStateMismatch { .. } => true,
884        }
885    }
886
887    /// Whether this diagnostic is produced by SOURCE discovery (the file walk in
888    /// `discover_files`) rather than WORKSPACE discovery (config load). Source-
889    /// discovery diagnostics are APPENDED to the registry after config load, so
890    /// `stash_workspace_diagnostics` must preserve them when it replaces the
891    /// workspace-discovery set, otherwise the per-analysis config re-loads in
892    /// combined-mode (`fallow` with no subcommand re-loads config for check,
893    /// dupes, and health) wipe them before the JSON envelope is built (issue
894    /// #1086).
895    #[must_use]
896    pub const fn is_source_discovery(&self) -> bool {
897        matches!(
898            self,
899            Self::SkippedLargeFile { .. }
900                | Self::SkippedMinifiedFile { .. }
901                | Self::SkippedSourceDotdir
902                | Self::SourceReadFailure { .. }
903                | Self::SourceParseDegraded { .. }
904                | Self::SourceNestingTooDeep { .. }
905                | Self::NodeModulesMissing
906                | Self::ExcludedByDefaultIgnore { .. }
907                | Self::NoSourceFilesAnalyzed { .. }
908        )
909    }
910
911    /// Whether this diagnostic is written by the source file WALK
912    /// (`discover_files`), the subset of [`Self::is_source_discovery`] that a
913    /// walk replaces wholesale for its root. `source-read-failure` is the
914    /// other source-discovery kind and is NOT one of these: the parse stage
915    /// records it after the walk, so it has to keep reaching consumers through
916    /// the registry.
917    ///
918    /// A walk-recorded entry must reach an analysis from its OWN walk's return
919    /// value. Combined mode runs the dead-code and duplication walks under
920    /// `rayon::join` whenever a per-analysis `production` split stops them from
921    /// sharing a file list, so a registry read answers "whichever walk wrote
922    /// last" and varies between runs of the same command (issue #2366).
923    #[must_use]
924    pub const fn is_source_walk_recorded(&self) -> bool {
925        matches!(
926            self,
927            Self::SkippedLargeFile { .. }
928                | Self::SkippedMinifiedFile { .. }
929                | Self::SkippedSourceDotdir
930                | Self::NodeModulesMissing
931                | Self::ExcludedByDefaultIgnore { .. }
932                | Self::NoSourceFilesAnalyzed { .. }
933        )
934    }
935
936    /// Whether this diagnostic reports a source file whose contents this run
937    /// never analyzed, so every import and export the file holds is invisible
938    /// to the module graph.
939    ///
940    /// This is the class `reachability_caveats[]` exists for. A file the run
941    /// never read credits nothing, so the modules it imports surface as
942    /// confident `unused-file` and `unused-export` findings carrying
943    /// `delete-file` and `remove-export` actions, and `fallow fix` would
944    /// otherwise apply the removal against source that still imports the
945    /// target.
946    ///
947    /// All four discovery-side kinds qualify, for the same reason and with the
948    /// same consequence:
949    ///
950    /// - `skipped-large-file` and `skipped-minified-file`: the file is in the
951    ///   project tree and was never opened, so its import list is unknown.
952    /// - `skipped-source-dotdir`: the directory holds at least one source file
953    ///   the project did not exclude, and none of them were traversed. The
954    ///   diagnostic is capped, so it under-reports rather than over-reports;
955    ///   its presence still proves unseen source exists.
956    /// - `source-read-failure`: the file was discovered and then could not be
957    ///   read, so nothing was extracted from it at all.
958    ///
959    /// `source-parse-degraded` is deliberately NOT one of these, though it
960    /// belongs to the same family. Neither is `excluded-by-default-ignore`,
961    /// for a different reason: that one reports designed behavior on generated
962    /// output rather than a degraded run, and its own doc comment carries the
963    /// argument.
964    ///
965    /// `source-parse-degraded`: that file WAS read, so it has a module and
966    /// a graph node and its reachability is observable, which lets the caveat
967    /// pass narrow it: a degraded module that is itself unreachable cannot
968    /// change a reachability verdict. Every kind above has no node to ask (a
969    /// read failure has one with nothing extracted into it), so no narrowing
970    /// is available and the caveat they raise is run-level.
971    ///
972    /// The match is exhaustive on purpose: a new "the run did not see this
973    /// file" kind has to be classified here, and answering `true` is the only
974    /// wiring its findings need in order to inherit both the caveat and the
975    /// `fallow fix` withholding that follows it.
976    #[must_use]
977    pub const fn source_never_analyzed(&self) -> bool {
978        match self {
979            Self::SkippedLargeFile { .. }
980            | Self::SkippedMinifiedFile { .. }
981            | Self::SkippedSourceDotdir
982            | Self::SourceReadFailure { .. } => true,
983            Self::UndeclaredWorkspace
984            | Self::MalformedPackageJson { .. }
985            | Self::GlobMatchedNoPackageJson { .. }
986            | Self::WorkspaceGlobOutsideRoot { .. }
987            | Self::WorkspacePatternDirMissing { .. }
988            | Self::NestedProjectRoot
989            | Self::MalformedTsconfig { .. }
990            | Self::TsconfigReferenceDirMissing
991            | Self::MalformedPnpmWorkspaceYaml { .. }
992            | Self::SourceParseDegraded { .. }
993            | Self::SourceNestingTooDeep { .. }
994            | Self::BunLockbOverrideResolutionSkipped
995            | Self::BunLockOverrideResolutionSkipped
996            | Self::PnpmLockOverrideResolutionSkipped
997            | Self::NpmLockOverrideResolutionSkipped
998            | Self::BunResolutionsShadowedByOverrides
999            | Self::PnpmWorkspaceOverridesIgnored { .. }
1000            | Self::NodeModulesMissing
1001            | Self::BoundariesNotConfigured
1002            | Self::RulePacksNotConfigured
1003            | Self::ClientServerLeakNoClientRoots
1004            | Self::ProductionExcludedFileImported { .. }
1005            | Self::ExcludedByDefaultIgnore { .. }
1006            | Self::NoSourceFilesAnalyzed { .. }
1007            | Self::FileScoresUnavailable { .. }
1008            | Self::HotspotsSkipped { .. }
1009            | Self::ChangeCouplingSkipped { .. }
1010            | Self::ShallowClone { .. }
1011            | Self::UnpinnedClock
1012            | Self::OwnershipUnavailable { .. }
1013            | Self::TrendSnapshotUnreadable { .. }
1014            | Self::TrendGroupBaselineUnavailable { .. }
1015            | Self::PluginConfigUnreadable { .. }
1016            | Self::PluginEffectNotModeled { .. }
1017            | Self::CoverageAutoDetected
1018            | Self::FlagAgeShallowClone
1019            | Self::FlagAgeUnavailable { .. }
1020            | Self::IgnoreDependenciesGlobUnmatched { .. }
1021            | Self::IgnoreFindingsPatternUnmatched { .. }
1022            | Self::EntryPatternRedundant { .. }
1023            | Self::IgnoreDependenciesEntryRedundant { .. }
1024            | Self::IgnorePatternsEntryRedundant { .. }
1025            | Self::CircularDependenciesAllowUnmatched { .. }
1026            | Self::OverrideRuleIneffective { .. }
1027            | Self::RequestedRuleOff { .. }
1028            | Self::BaselineInstallStateMismatch { .. } => false,
1029        }
1030    }
1031
1032    /// Whether this diagnostic is recorded by the ANALYZE stage (the
1033    /// dependency-catalog and override detectors) rather than by workspace or
1034    /// source discovery. Analysis-stage diagnostics reach the registry through
1035    /// `record_workspace_diagnostics` after config load, so
1036    /// `stash_workspace_diagnostics` must preserve them across combined-mode's
1037    /// per-analysis config re-loads, and every analyze pass clears its previous
1038    /// entries before re-recording so a fixed cause drops out on the next run
1039    /// (issue #2366). The match is exhaustive on purpose: a new kind must be
1040    /// classified here before it compiles.
1041    ///
1042    /// Classify a kind `true` ONLY when a detector reachable from the dead-code
1043    /// analyze pass (`find_dead_code_full`) re-records it, because that pass is
1044    /// the single clear site. A kind recorded exclusively by another stage would
1045    /// be cleared by the next dead-code pass and never come back.
1046    #[must_use]
1047    pub const fn is_analysis_stage(&self) -> bool {
1048        match self {
1049            Self::MalformedPnpmWorkspaceYaml { .. }
1050            | Self::BunLockbOverrideResolutionSkipped
1051            | Self::BunLockOverrideResolutionSkipped
1052            | Self::PnpmLockOverrideResolutionSkipped
1053            | Self::NpmLockOverrideResolutionSkipped
1054            | Self::BunResolutionsShadowedByOverrides
1055            | Self::PnpmWorkspaceOverridesIgnored { .. }
1056            | Self::BoundariesNotConfigured
1057            | Self::RulePacksNotConfigured
1058            | Self::ClientServerLeakNoClientRoots
1059            | Self::ProductionExcludedFileImported { .. } => true,
1060            Self::UndeclaredWorkspace
1061            | Self::MalformedPackageJson { .. }
1062            | Self::GlobMatchedNoPackageJson { .. }
1063            | Self::WorkspaceGlobOutsideRoot { .. }
1064            | Self::WorkspacePatternDirMissing { .. }
1065            | Self::NestedProjectRoot
1066            | Self::MalformedTsconfig { .. }
1067            | Self::TsconfigReferenceDirMissing
1068            | Self::SkippedLargeFile { .. }
1069            | Self::SkippedMinifiedFile { .. }
1070            | Self::SkippedSourceDotdir
1071            | Self::SourceReadFailure { .. }
1072            | Self::SourceParseDegraded { .. }
1073            | Self::SourceNestingTooDeep { .. }
1074            | Self::NodeModulesMissing
1075            | Self::ExcludedByDefaultIgnore { .. }
1076            | Self::NoSourceFilesAnalyzed { .. }
1077            | Self::FileScoresUnavailable { .. }
1078            | Self::HotspotsSkipped { .. }
1079            | Self::ChangeCouplingSkipped { .. }
1080            | Self::ShallowClone { .. }
1081            | Self::UnpinnedClock
1082            | Self::OwnershipUnavailable { .. }
1083            | Self::TrendSnapshotUnreadable { .. }
1084            | Self::TrendGroupBaselineUnavailable { .. }
1085            | Self::PluginConfigUnreadable { .. }
1086            | Self::PluginEffectNotModeled { .. }
1087            | Self::CoverageAutoDetected
1088            | Self::FlagAgeShallowClone
1089            | Self::FlagAgeUnavailable { .. }
1090            | Self::IgnoreDependenciesGlobUnmatched { .. }
1091            | Self::IgnoreFindingsPatternUnmatched { .. }
1092            | Self::EntryPatternRedundant { .. }
1093            | Self::IgnoreDependenciesEntryRedundant { .. }
1094            | Self::IgnorePatternsEntryRedundant { .. }
1095            | Self::CircularDependenciesAllowUnmatched { .. }
1096            | Self::OverrideRuleIneffective { .. }
1097            | Self::RequestedRuleOff { .. }
1098            | Self::BaselineInstallStateMismatch { .. } => false,
1099        }
1100    }
1101
1102    /// Whether this diagnostic is recorded by the HEALTH pipeline (scoring,
1103    /// churn, ownership, trend, coverage input resolution) rather than by
1104    /// workspace discovery, source discovery or the analyze stage.
1105    ///
1106    /// Health-stage diagnostics are appended to the registry after config
1107    /// load, so `stash_workspace_diagnostics` must preserve them across
1108    /// combined mode's per-analysis config re-loads, and the health run clears
1109    /// its previous entries before re-recording so a fixed CODEOWNERS drops out
1110    /// on the next run (issue #2689).
1111    ///
1112    /// They are deliberately NOT [`Self::is_analysis_stage`], although they
1113    /// share both of those properties. That predicate additionally means "the
1114    /// dead-code analyze pass re-records this", and the pass clears every kind
1115    /// answering it on entry. Health computes file scores by running that same
1116    /// pass, so a health-stage kind classified there would be wiped mid-run by
1117    /// the analysis it is reporting on.
1118    #[must_use]
1119    pub const fn is_health_stage(&self) -> bool {
1120        match self {
1121            Self::FileScoresUnavailable { .. }
1122            | Self::HotspotsSkipped { .. }
1123            | Self::ChangeCouplingSkipped { .. }
1124            | Self::ShallowClone { .. }
1125            | Self::UnpinnedClock
1126            | Self::OwnershipUnavailable { .. }
1127            | Self::TrendSnapshotUnreadable { .. }
1128            | Self::TrendGroupBaselineUnavailable { .. }
1129            | Self::CoverageAutoDetected => true,
1130            Self::UndeclaredWorkspace
1131            | Self::MalformedPackageJson { .. }
1132            | Self::GlobMatchedNoPackageJson { .. }
1133            | Self::WorkspaceGlobOutsideRoot { .. }
1134            | Self::WorkspacePatternDirMissing { .. }
1135            | Self::NestedProjectRoot
1136            | Self::MalformedTsconfig { .. }
1137            | Self::TsconfigReferenceDirMissing
1138            | Self::MalformedPnpmWorkspaceYaml { .. }
1139            | Self::SkippedLargeFile { .. }
1140            | Self::SkippedMinifiedFile { .. }
1141            | Self::SkippedSourceDotdir
1142            | Self::SourceReadFailure { .. }
1143            | Self::SourceParseDegraded { .. }
1144            | Self::SourceNestingTooDeep { .. }
1145            | Self::BunLockbOverrideResolutionSkipped
1146            | Self::BunLockOverrideResolutionSkipped
1147            | Self::PnpmLockOverrideResolutionSkipped
1148            | Self::NpmLockOverrideResolutionSkipped
1149            | Self::BunResolutionsShadowedByOverrides
1150            | Self::PnpmWorkspaceOverridesIgnored { .. }
1151            | Self::NodeModulesMissing
1152            | Self::BoundariesNotConfigured
1153            | Self::RulePacksNotConfigured
1154            | Self::ClientServerLeakNoClientRoots
1155            | Self::ProductionExcludedFileImported { .. }
1156            | Self::ExcludedByDefaultIgnore { .. }
1157            | Self::PluginConfigUnreadable { .. }
1158            | Self::PluginEffectNotModeled { .. }
1159            | Self::NoSourceFilesAnalyzed { .. }
1160            | Self::FlagAgeShallowClone
1161            | Self::FlagAgeUnavailable { .. }
1162            | Self::IgnoreDependenciesGlobUnmatched { .. }
1163            | Self::IgnoreFindingsPatternUnmatched { .. }
1164            | Self::EntryPatternRedundant { .. }
1165            | Self::IgnoreDependenciesEntryRedundant { .. }
1166            | Self::IgnorePatternsEntryRedundant { .. }
1167            | Self::CircularDependenciesAllowUnmatched { .. }
1168            | Self::OverrideRuleIneffective { .. }
1169            | Self::RequestedRuleOff { .. }
1170            | Self::BaselineInstallStateMismatch { .. } => false,
1171        }
1172    }
1173
1174    /// Whether this diagnostic is recorded by the PLUGIN stage (framework
1175    /// plugins reading their own build configs) rather than by workspace
1176    /// discovery, source discovery, the analyze stage or the health pipeline.
1177    ///
1178    /// Plugin-stage diagnostics are recorded after config load, so
1179    /// `stash_workspace_diagnostics` must preserve them across combined mode's
1180    /// per-analysis config re-loads, and each plugin run replaces the previous
1181    /// run's set so a fixed config drops out on the next run (issue #2736).
1182    ///
1183    /// They are deliberately NOT [`Self::is_analysis_stage`], although they
1184    /// share both of those properties. That predicate additionally means "the
1185    /// dead-code analyze pass re-records this", and the pass clears every kind
1186    /// answering it on entry. Plugins run in the prelude of that same pass, so
1187    /// a plugin-stage kind classified there would be wiped inside the run that
1188    /// produced it.
1189    ///
1190    /// The match is exhaustive on purpose: a new kind must be classified here
1191    /// before it compiles.
1192    #[must_use]
1193    pub const fn is_plugin_stage(&self) -> bool {
1194        match self {
1195            Self::PluginConfigUnreadable { .. } | Self::PluginEffectNotModeled { .. } => true,
1196            Self::UndeclaredWorkspace
1197            | Self::MalformedPackageJson { .. }
1198            | Self::GlobMatchedNoPackageJson { .. }
1199            | Self::WorkspaceGlobOutsideRoot { .. }
1200            | Self::WorkspacePatternDirMissing { .. }
1201            | Self::NestedProjectRoot
1202            | Self::MalformedTsconfig { .. }
1203            | Self::TsconfigReferenceDirMissing
1204            | Self::MalformedPnpmWorkspaceYaml { .. }
1205            | Self::SkippedLargeFile { .. }
1206            | Self::SkippedMinifiedFile { .. }
1207            | Self::SkippedSourceDotdir
1208            | Self::SourceReadFailure { .. }
1209            | Self::SourceParseDegraded { .. }
1210            | Self::SourceNestingTooDeep { .. }
1211            | Self::BunLockbOverrideResolutionSkipped
1212            | Self::BunLockOverrideResolutionSkipped
1213            | Self::PnpmLockOverrideResolutionSkipped
1214            | Self::NpmLockOverrideResolutionSkipped
1215            | Self::BunResolutionsShadowedByOverrides
1216            | Self::PnpmWorkspaceOverridesIgnored { .. }
1217            | Self::NodeModulesMissing
1218            | Self::BoundariesNotConfigured
1219            | Self::RulePacksNotConfigured
1220            | Self::ClientServerLeakNoClientRoots
1221            | Self::ProductionExcludedFileImported { .. }
1222            | Self::ExcludedByDefaultIgnore { .. }
1223            | Self::NoSourceFilesAnalyzed { .. }
1224            | Self::FileScoresUnavailable { .. }
1225            | Self::HotspotsSkipped { .. }
1226            | Self::ChangeCouplingSkipped { .. }
1227            | Self::ShallowClone { .. }
1228            | Self::UnpinnedClock
1229            | Self::OwnershipUnavailable { .. }
1230            | Self::TrendSnapshotUnreadable { .. }
1231            | Self::TrendGroupBaselineUnavailable { .. }
1232            | Self::CoverageAutoDetected
1233            | Self::FlagAgeShallowClone
1234            | Self::FlagAgeUnavailable { .. }
1235            | Self::IgnoreDependenciesGlobUnmatched { .. }
1236            | Self::IgnoreFindingsPatternUnmatched { .. }
1237            | Self::EntryPatternRedundant { .. }
1238            | Self::IgnoreDependenciesEntryRedundant { .. }
1239            | Self::IgnorePatternsEntryRedundant { .. }
1240            | Self::CircularDependenciesAllowUnmatched { .. }
1241            | Self::OverrideRuleIneffective { .. }
1242            | Self::RequestedRuleOff { .. }
1243            | Self::BaselineInstallStateMismatch { .. } => false,
1244        }
1245    }
1246}
1247
1248/// Render a byte count as a megabyte figure with one decimal place for
1249/// human-readable diagnostic messages (e.g. `12.3 MB`).
1250#[must_use]
1251fn format_size_mb(bytes: u64) -> String {
1252    #[expect(
1253        clippy::cast_precision_loss,
1254        reason = "display-only size figure; precision loss past 2^53 bytes is irrelevant"
1255    )]
1256    let mb = bytes as f64 / (1024.0 * 1024.0);
1257    format!("{mb:.1} MB")
1258}
1259
1260/// A diagnostic about a workspace-discovery candidate.
1261///
1262/// The `message` field is a human-readable rendering derived from `kind`. It
1263/// always ends with a concrete next step ("fix the JSON syntax", "remove from
1264/// `workspaces`", "add to `ignorePatterns`") so first-time users have a path
1265/// forward.
1266#[derive(Debug, Clone, Serialize, Deserialize)]
1267#[cfg_attr(feature = "schema", derive(JsonSchema))]
1268pub struct WorkspaceDiagnostic {
1269    /// Path to the directory or file that triggered the diagnostic.
1270    #[serde(serialize_with = "serde_path::serialize")]
1271    pub path: PathBuf,
1272    /// Kind discriminator with the typed payload.
1273    #[serde(flatten)]
1274    pub kind: WorkspaceDiagnosticKind,
1275    /// Human-readable rendering derived from `kind` + `path`. Always ends
1276    /// with a next-step hint.
1277    pub message: String,
1278    /// True when this diagnostic reports a run whose RESULTS are degraded:
1279    /// something the user installed, wrote, or expected did not reach the
1280    /// analysis. Projected from [`WorkspaceDiagnosticKind::warns_on_stderr`],
1281    /// which is the same classification that decides whether the CLI prints a
1282    /// stderr line, so a CI log built from this field and a local non-quiet run
1283    /// say the same thing.
1284    ///
1285    /// Omitted when false, which is what keeps every clean run byte-identical.
1286    /// The two unconfigured-check kinds answer false on purpose: they fire in
1287    /// the product's default state on every project that never opted into
1288    /// boundaries or rule packs, so warning on them would warn forever. So does
1289    /// `excluded-by-default-ignore`, which is designed behavior on generated
1290    /// output; the alarm for that case is `no-source-files-analyzed`.
1291    ///
1292    /// Read this instead of hardcoding a kind allowlist: a degrading kind added
1293    /// in a later release then reaches an unchanged consumer.
1294    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1295    pub degrades_analysis: bool,
1296}
1297
1298impl WorkspaceDiagnostic {
1299    /// Construct a diagnostic with the message rendered from `kind` + `path`.
1300    ///
1301    /// `root` is used to produce project-relative paths in the message text
1302    /// AND inside the variant payload (e.g. the `error` field of
1303    /// `MalformedPackageJson` / `MalformedTsconfig` which embed the absolute
1304    /// file path from `PackageJson::load()`'s error text). Without the
1305    /// payload-side normalisation the embedded path would survive
1306    /// environment-specific differences (CI vs Docker vs local) because the
1307    /// post-serialisation `strip_root_prefix` only catches whole-string
1308    /// matches, not paths embedded mid-sentence.
1309    ///
1310    /// If `path` is not under `root` (e.g. canonicalisation crossed a
1311    /// symlink), the absolute path is emitted instead.
1312    ///
1313    /// `path` also loses any no-op `.` component, for the same reason the
1314    /// payload loses a glob's `./` prefix: one directory reached through two
1315    /// spellings of one glob must be one diagnostic.
1316    #[must_use]
1317    pub fn new(root: &Path, path: PathBuf, kind: WorkspaceDiagnosticKind) -> Self {
1318        let path = normalise_diagnostic_path(path);
1319        let kind = normalise_payload_paths(root, kind);
1320        let message = render_message(root, &path, &kind);
1321        let degrades_analysis = kind.warns_on_stderr();
1322        Self {
1323            path,
1324            kind,
1325            message,
1326            degrades_analysis,
1327        }
1328    }
1329
1330    /// Return this diagnostic with `path` rewritten relative to `root`.
1331    ///
1332    /// `path` is stored absolute so callers can act on it. Every JSON envelope
1333    /// emits it project-relative instead: the analysis envelopes get there
1334    /// through the post-serialisation `strip_root_prefix` pass, which the
1335    /// `fallow workspaces` / `fallow list --workspaces` envelope and the MCP
1336    /// `project_info` tool never run, so those emitted the absolute path while
1337    /// the sibling `workspaces[].path` next to it was relative. They normalise
1338    /// at the typed layer with this method instead.
1339    ///
1340    /// Paths outside `root` (canonicalisation crossed a symlink) are left
1341    /// absolute, matching how [`Self::new`] renders the message.
1342    ///
1343    /// A diagnostic anchored at the root itself becomes `.`, not the empty
1344    /// path: an empty string is not a location, and the analysis envelopes'
1345    /// post-serialisation strip only removes a `root + separator` prefix, so a
1346    /// root-anchored path that stays absolute here leaks a host path.
1347    #[must_use]
1348    pub fn into_root_relative(mut self, root: &Path) -> Self {
1349        if let Ok(relative) = self.path.strip_prefix(root) {
1350            self.path = if relative.as_os_str().is_empty() {
1351                PathBuf::from(".")
1352            } else {
1353                relative.to_path_buf()
1354            };
1355        }
1356        self
1357    }
1358}
1359
1360/// Rebuild `path` from its components so one directory has one spelling.
1361///
1362/// The dedupe key was never the problem: [`Path`] equality already ignores an
1363/// interior `.`, so `<root>/./pkgs/aaa` and `<root>/pkgs/aaa` are one key. The
1364/// stored bytes were. A workspace glob spelled `./pkgs/*` in `package.json`
1365/// expands to the first spelling and the same glob spelled `pkgs/*` in
1366/// `pnpm-workspace.yaml` expands to the second, and the two envelope families
1367/// make a project-relative path differently: the analysis envelopes strip the
1368/// root as a string (leaving `./pkgs/aaa`) while the workspace listing
1369/// envelope uses [`WorkspaceDiagnostic::into_root_relative`] (leaving
1370/// `pkgs/aaa`). Whichever
1371/// manifest happened to be read first then decided which shape every consumer
1372/// saw. Collapsing at construction gives them one answer (issue #2366).
1373///
1374/// A path that is already component-clean rebuilds to itself. Serialization
1375/// normalises separators, so the rebuild is wire-invisible on Windows.
1376fn normalise_diagnostic_path(path: PathBuf) -> PathBuf {
1377    let rebuilt: PathBuf = path.components().collect();
1378    if rebuilt.as_os_str() == path.as_os_str() {
1379        path
1380    } else {
1381        rebuilt
1382    }
1383}
1384
1385/// Strip the project root from absolute paths embedded inside variant
1386/// payloads (the `error` field of malformed-config and source-read failures),
1387/// and drop a glob pattern's no-op `./` prefix.
1388///
1389/// Mirrors the per-platform `display()` byte sequence so the substring match
1390/// works on Windows too.
1391///
1392/// The pattern prefix matters because the payload is part of the dedupe key in
1393/// [`merge_workspace_diagnostics`]. A repository whose `package.json` declares
1394/// `"./apps/**"` and whose `pnpm-workspace.yaml` declares `apps/**` names one
1395/// glob twice, and without this both spellings would report every package-less
1396/// directory under `apps/` a second time (issue #2366).
1397fn normalise_payload_paths(root: &Path, kind: WorkspaceDiagnosticKind) -> WorkspaceDiagnosticKind {
1398    let root_str = root.display().to_string();
1399    let root_alt = root_str.replace('\\', "/");
1400    let normalise = |text: String| -> String {
1401        let stripped = text
1402            .replace(&format!("{root_str}/"), "")
1403            .replace(&format!("{root_alt}/"), "");
1404        stripped
1405            .replace(&format!("{root_str}\\"), "")
1406            .replace(&format!("{root_alt}\\"), "")
1407    };
1408    match kind {
1409        WorkspaceDiagnosticKind::MalformedPackageJson { error } => {
1410            WorkspaceDiagnosticKind::MalformedPackageJson {
1411                error: normalise(error),
1412            }
1413        }
1414        WorkspaceDiagnosticKind::MalformedTsconfig { error } => {
1415            WorkspaceDiagnosticKind::MalformedTsconfig {
1416                error: normalise(error),
1417            }
1418        }
1419        WorkspaceDiagnosticKind::SourceReadFailure { error } => {
1420            WorkspaceDiagnosticKind::SourceReadFailure {
1421                error: normalise(error),
1422            }
1423        }
1424        WorkspaceDiagnosticKind::FileScoresUnavailable { error } => {
1425            WorkspaceDiagnosticKind::FileScoresUnavailable {
1426                error: normalise(error),
1427            }
1428        }
1429        WorkspaceDiagnosticKind::OwnershipUnavailable { cause, error } => {
1430            WorkspaceDiagnosticKind::OwnershipUnavailable {
1431                cause,
1432                error: normalise(error),
1433            }
1434        }
1435        WorkspaceDiagnosticKind::TrendSnapshotUnreadable { error } => {
1436            WorkspaceDiagnosticKind::TrendSnapshotUnreadable {
1437                error: normalise(error),
1438            }
1439        }
1440        WorkspaceDiagnosticKind::GlobMatchedNoPackageJson { pattern } => {
1441            WorkspaceDiagnosticKind::GlobMatchedNoPackageJson {
1442                pattern: canonical_glob_pattern(pattern),
1443            }
1444        }
1445        WorkspaceDiagnosticKind::WorkspaceGlobOutsideRoot { pattern } => {
1446            WorkspaceDiagnosticKind::WorkspaceGlobOutsideRoot {
1447                pattern: canonical_glob_pattern(pattern),
1448            }
1449        }
1450        WorkspaceDiagnosticKind::WorkspacePatternDirMissing { pattern } => {
1451            WorkspaceDiagnosticKind::WorkspacePatternDirMissing {
1452                pattern: canonical_glob_pattern(pattern),
1453            }
1454        }
1455        other => other,
1456    }
1457}
1458
1459/// Drop the leading `./` (or `.\`) a workspace glob may carry, so the same
1460/// pattern declared in two manifests is one payload.
1461///
1462/// A pattern that is nothing BUT the prefix (`"./"`, the root itself) keeps
1463/// its spelling: stripping it would report an empty `pattern` field and an
1464/// empty quoted glob in the warning text, which names no glob at all.
1465fn canonical_glob_pattern(pattern: String) -> String {
1466    for prefix in ["./", ".\\"] {
1467        if let Some(rest) = pattern.strip_prefix(prefix)
1468            && !rest.is_empty()
1469        {
1470            return rest.to_owned();
1471        }
1472    }
1473    pattern
1474}
1475
1476/// The first segment of a glob that contains no glob metacharacter, so it
1477/// names a real directory rather than a wildcard.
1478///
1479/// Source discovery uses it to decide which directory a built-in ignore
1480/// pattern excluded a file "at"; `render_message` uses it to decide which
1481/// remedy is true for that pattern. The two have to agree, so the function
1482/// lives here rather than once per crate: a pattern with such a segment
1483/// (`**/dist/**`) is lifted by re-rooting inside the matched directory,
1484/// because the glob is matched against the path relative to the run root. A
1485/// pattern without one (`**/*.min.js`) matches on the file name and keeps
1486/// matching at every root.
1487#[must_use]
1488pub fn glob_first_literal_segment(pattern: &str) -> Option<&str> {
1489    pattern.split('/').find(|segment| {
1490        !segment.is_empty()
1491            && !segment.contains(['*', '?', '[', ']', '{', '}'])
1492            && *segment != "."
1493            && *segment != ".."
1494    })
1495}
1496
1497/// The catalog entries that a `workspace-pattern-dir-missing` diagnostic
1498/// keeps out of the run, as the subject of a sentence. `source_display` is
1499/// the declaring file, relative to the project root.
1500///
1501/// A missing directory of a root pattern hides consumers of every catalog. A
1502/// missing directory of a `packages` entry of a nested `pnpm-workspace.yaml`
1503/// hides consumers of the catalog of that file only.
1504#[must_use]
1505pub fn missing_pattern_dir_skipped_entries(source_display: &str) -> &'static str {
1506    if source_display.contains('/') && source_display.ends_with("pnpm-workspace.yaml") {
1507        "Unused entries of the catalog in that file"
1508    } else {
1509        "Unused catalog entries"
1510    }
1511}
1512
1513/// The directory part of a workspace pattern: the segments before the first
1514/// segment with a glob character, joined with `/`.
1515///
1516/// `vite/packages/*` gives `vite/packages`, `vite` gives `vite`, and a
1517/// pattern that starts with a glob segment (`**/pkg`, `{a,b}/*`) gives
1518/// `None`. A leading `./` and empty or `.` segments are dropped. Workspace
1519/// discovery uses it to find a pattern whose directory does not exist, and
1520/// the diagnostic message uses it to name that directory, so both read the
1521/// same part of the pattern.
1522#[must_use]
1523pub fn workspace_pattern_literal_dir(pattern: &str) -> Option<String> {
1524    let literal: Vec<&str> = pattern
1525        .split(['/', '\\'])
1526        .filter(|segment| !segment.is_empty() && *segment != ".")
1527        .take_while(|segment| !segment.contains(['*', '?', '[', ']', '{', '}']))
1528        .collect();
1529    if literal.is_empty() {
1530        None
1531    } else {
1532        Some(literal.join("/"))
1533    }
1534}
1535
1536fn render_message(root: &Path, path: &Path, kind: &WorkspaceDiagnosticKind) -> String {
1537    let display = display_relative(root, path);
1538    match kind {
1539        WorkspaceDiagnosticKind::UndeclaredWorkspace => format!(
1540            "Directory '{display}' contains package.json but is not declared as a workspace. \
1541             Add it to package.json workspaces or pnpm-workspace.yaml, or add it to ignorePatterns."
1542        ),
1543        WorkspaceDiagnosticKind::MalformedPackageJson { error } => format!(
1544            "Dropped workspace '{display}': package.json is not valid JSON ({error}). \
1545             Fix the JSON syntax or remove '{display}' from the workspaces pattern."
1546        ),
1547        WorkspaceDiagnosticKind::GlobMatchedNoPackageJson { pattern } => format!(
1548            "Glob '{pattern}' matched '{display}' but no package.json is present. \
1549             Add a package.json, narrow the pattern, or add '{display}' to ignorePatterns."
1550        ),
1551        WorkspaceDiagnosticKind::WorkspaceGlobOutsideRoot { pattern } => {
1552            let source = if display.is_empty() {
1553                "the fallow config `workspaces.patterns`".to_owned()
1554            } else {
1555                format!("'{display}'")
1556            };
1557            format!(
1558                "Skipped workspace entry '{pattern}' in {source}: it is an absolute path \
1559                 or its '..' segments lead above the project root, so it can match directories \
1560                 outside the root. \
1561                 Fallow analyzes no package from it. Move the package inside the project root, \
1562                 or run fallow with --root set to a directory that holds both."
1563            )
1564        }
1565        WorkspaceDiagnosticKind::WorkspacePatternDirMissing { pattern } => {
1566            let source = if display.is_empty() {
1567                "the fallow config `workspaces.patterns`".to_owned()
1568            } else {
1569                format!("'{display}'")
1570            };
1571            let dir = workspace_pattern_literal_dir(pattern).unwrap_or_else(|| pattern.clone());
1572            let skipped = missing_pattern_dir_skipped_entries(&display);
1573            format!(
1574                "Workspace pattern '{pattern}' in {source} names directory '{dir}', which does \
1575                 not exist. Fallow analyzes no package from it. {skipped} are not \
1576                 reported in this run, because packages in that directory can use them. \
1577                 Create the directory before the run, or remove the pattern."
1578            )
1579        }
1580        WorkspaceDiagnosticKind::NestedProjectRoot => format!(
1581            "Directory '{display}' has its own pnpm-workspace.yaml, so it is an independent \
1582             project. Fallow analyzes it as a workspace: its package.json owns its files and \
1583             dependencies, the packages that its pnpm-workspace.yaml declares are workspaces, \
1584             and their catalog references resolve against its own catalog. Add '{display}' to \
1585             ignorePatterns to exclude it."
1586        ),
1587        WorkspaceDiagnosticKind::MalformedTsconfig { error } => format!(
1588            "tsconfig at '{display}' failed to parse ({error}); \
1589             its project references, path aliases and compiler options are ignored. \
1590             Fix the JSON syntax."
1591        ),
1592        WorkspaceDiagnosticKind::TsconfigReferenceDirMissing => format!(
1593            "tsconfig.json references '{display}' but the directory does not exist. \
1594             Update or remove the reference, or restore the missing directory."
1595        ),
1596        WorkspaceDiagnosticKind::MalformedPnpmWorkspaceYaml { error } => format!(
1597            "'{display}' is not valid YAML ({error}). Catalog checks are skipped \
1598             and its override entries are ignored until it parses. pnpm install \
1599             can accept this file, but `pnpm add` and YAML formatters reject it. \
1600             Indent each continuation line of a quoted value or a `[...]` / \
1601             `{{...}}` list deeper than its key."
1602        ),
1603        WorkspaceDiagnosticKind::SkippedLargeFile { size_bytes } => format!(
1604            "Skipped '{display}' ({size}): exceeds the max file size limit. \
1605             Its imports and exports are not analyzed. Raise the limit with \
1606             --max-file-size <MB> (or FALLOW_MAX_FILE_SIZE), or add '{display}' \
1607             to ignorePatterns.",
1608            size = format_size_mb(*size_bytes)
1609        ),
1610        WorkspaceDiagnosticKind::SkippedMinifiedFile { size_bytes } => format!(
1611            "Skipped '{display}' ({size}): appears to be minified generated JavaScript. \
1612             Its imports and exports are not analyzed. Add '{display}' to ignorePatterns, \
1613             rename it with a .min.js suffix, or use --max-file-size 0 if this file \
1614             should be analyzed.",
1615            size = format_size_mb(*size_bytes)
1616        ),
1617        WorkspaceDiagnosticKind::SkippedSourceDotdir => format!(
1618            "Skipped hidden directory '{display}': it contains source files but hidden \
1619             directories are not traversed. Its imports and exports are not analyzed. \
1620             A file, export or dependency that only this directory uses can be reported as \
1621             unused. To analyze it, add '!{display}/**' to ignorePatterns. To stop \
1622             that false positive without that, add the file to entry, the export to \
1623             ignoreExports or the dependency to ignoreDependencies. To silence this message, \
1624             add '{display}/**' to ignorePatterns. fallow --root {display} analyzes only \
1625             that directory on its own and does not fix this run."
1626        ),
1627        WorkspaceDiagnosticKind::SourceReadFailure { error } => format!(
1628            "Could not read source '{display}' ({error}). Restore the file or its read permissions, \
1629             ensure it contains valid UTF-8 text, or add '{display}' to ignorePatterns."
1630        ),
1631        WorkspaceDiagnosticKind::SourceParseDegraded {
1632            error_count,
1633            panicked,
1634        } => {
1635            let outcome = if *panicked {
1636                "the parser stopped there"
1637            } else {
1638                "the parser recovered and continued"
1639            };
1640            format!(
1641                "Parsed '{display}' with {error_count} error(s); {outcome}. Imports, exports, and \
1642                 references it did not reach are missing from this run, so files and symbols it \
1643                 uses can be reported as unused. Fix the syntax, or ignore this if the file uses \
1644                 syntax newer than fallow's parser."
1645            )
1646        }
1647        WorkspaceDiagnosticKind::SourceNestingTooDeep { limit } => format!(
1648            "Did not parse '{display}': it nests brackets deeper than {limit} levels, or it \
1649             needs more stack than fallow reserves, so a parse could overflow the stack. Its \
1650             imports and exports are missing from this run, so files and symbols it uses can be \
1651             reported as unused, and while the file is reachable `fallow fix` holds back its \
1652             actions for the whole project. Add '{display}' to ignoreFindings if it is generated \
1653             code, or reduce its nesting."
1654        ),
1655        WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped => format!(
1656            "Skipped dependency-override resolution for '{display}': bun's legacy binary bun.lockb \
1657             sits next to it, fallow cannot read the binary format, and no parseable text lockfile \
1658             (bun.lock, pnpm-lock.yaml, package-lock.json, or npm-shrinkwrap.json) was found to \
1659             use instead, so unused-dependency-overrides findings are not reported. Run bun install \
1660             --save-text-lockfile (bun 1.2 or newer) to write a text bun.lock, or delete the stale \
1661             bun.lockb if this repository no longer uses bun."
1662        ),
1663        WorkspaceDiagnosticKind::BunLockOverrideResolutionSkipped => format!(
1664            "Skipped dependency-override resolution because '{display}' could not be parsed and \
1665             no readable pnpm or npm lockfile was available, so unused-dependency-overrides \
1666             findings are not reported. Run bun install to regenerate the text lockfile, then \
1667             rerun fallow."
1668        ),
1669        WorkspaceDiagnosticKind::PnpmLockOverrideResolutionSkipped => format!(
1670            "Skipped dependency-override resolution because '{display}' could not be parsed and \
1671             no other parseable lockfile was available, so unused-dependency-overrides findings \
1672             are not reported. Resolve any merge-conflict markers in the lockfile, or run pnpm \
1673             install to regenerate it, then rerun fallow."
1674        ),
1675        WorkspaceDiagnosticKind::NpmLockOverrideResolutionSkipped => format!(
1676            "Skipped dependency-override resolution because '{display}' could not be parsed and \
1677             no other parseable lockfile was available, so unused-dependency-overrides findings \
1678             are not reported. Resolve any merge-conflict markers in the lockfile, or run npm \
1679             install to regenerate it, then rerun fallow."
1680        ),
1681        WorkspaceDiagnosticKind::BunResolutionsShadowedByOverrides => format!(
1682            "'{display}' declares both `overrides` and non-empty `resolutions`; bun applies \
1683             `overrides` and ignores `resolutions`. Move the intended pins into `overrides` or \
1684             remove the shadowed `resolutions` entries."
1685        ),
1686        WorkspaceDiagnosticKind::PnpmWorkspaceOverridesIgnored {
1687            cause: PnpmWorkspaceOverridesIgnoredCause::PackageJsonOverrides,
1688        } => format!(
1689            "pnpm 10 and earlier ignore the `overrides` in '{display}' because the root package.json \
1690             declares `pnpm.overrides` or `resolutions`, so fallow does not check them. Move the \
1691             entries into one source."
1692        ),
1693        WorkspaceDiagnosticKind::PnpmWorkspaceOverridesIgnored {
1694            cause: PnpmWorkspaceOverridesIgnoredCause::PnpmVersion,
1695        } => format!(
1696            "pnpm versions before 10.5.1 do not read the `overrides` in '{display}', so fallow \
1697             does not check them. Update `packageManager` to pnpm 10.5.1 or later, or move the \
1698             entries into `pnpm.overrides` in the root package.json."
1699        ),
1700        WorkspaceDiagnosticKind::NodeModulesMissing => format!(
1701            "'{display}' does not exist. Package exports and conditional exports cannot be read, \
1702             framework plugins that activate on an installed package stay inactive, and \
1703             dependency classification degrades, so imports and dependencies can be \
1704             misreported. Run npm install / pnpm install / yarn / bun install first."
1705        ),
1706        WorkspaceDiagnosticKind::BoundariesNotConfigured => {
1707            "No architecture boundaries are configured, so the boundary detector did not run and \
1708             its violation counts are zero because nothing was measured. Add `boundaries` to the \
1709             config, or set `boundary-violation` to off to state that the check is not wanted."
1710                .to_string()
1711        }
1712        WorkspaceDiagnosticKind::RulePacksNotConfigured => {
1713            "No rule packs are configured, so the policy detector did not run and its violation \
1714             counts are zero because nothing was measured. Add `rulePacks` to the config, or set \
1715             `policy-violation` to off to state that the check is not wanted."
1716                .to_string()
1717        }
1718        WorkspaceDiagnosticKind::ClientServerLeakNoClientRoots => {
1719            "No file has a top-level \"use client\" directive and no framework plugin supplies \
1720             a client root, so the client-server-leak detector had no starting point and its zero \
1721             count measures nothing. The rule does not apply to projects whose client code has \
1722             neither, such as a Vite SPA."
1723                .to_string()
1724        }
1725        WorkspaceDiagnosticKind::ProductionExcludedFileImported {
1726            pattern,
1727            file_count,
1728            files,
1729        } => production_text::excluded_import_message(pattern, *file_count, files),
1730        WorkspaceDiagnosticKind::NoSourceFilesAnalyzed {
1731            excluded_file_count,
1732        } => {
1733            if *excluded_file_count == 0 {
1734                "No source files were analyzed, so every finding count this run reports is zero \
1735                 because nothing was measured. Check the analysis root, ignorePatterns, and any \
1736                 path or workspace filter this run applied."
1737                    .to_owned()
1738            } else {
1739                format!(
1740                    "No source files were analyzed. Fallow's built-in ignore patterns excluded \
1741                     {excluded_file_count} candidate files, so every finding count this run \
1742                     reports is zero because nothing was measured; run with --explain-skipped \
1743                     for the breakdown."
1744                )
1745            }
1746        }
1747        WorkspaceDiagnosticKind::FileScoresUnavailable { .. }
1748        | WorkspaceDiagnosticKind::HotspotsSkipped { .. }
1749        | WorkspaceDiagnosticKind::ChangeCouplingSkipped { .. }
1750        | WorkspaceDiagnosticKind::ShallowClone { .. }
1751        | WorkspaceDiagnosticKind::UnpinnedClock
1752        | WorkspaceDiagnosticKind::OwnershipUnavailable { .. }
1753        | WorkspaceDiagnosticKind::TrendSnapshotUnreadable { .. }
1754        | WorkspaceDiagnosticKind::TrendGroupBaselineUnavailable { .. }
1755        | WorkspaceDiagnosticKind::CoverageAutoDetected => {
1756            health_text::health_stage_message(&display, kind)
1757        }
1758        WorkspaceDiagnosticKind::FlagAgeShallowClone => {
1759            "This is a shallow clone, so the flag retirement report gives no flag age. Run git \
1760             fetch --unshallow for the full history, or pass --flag-age off."
1761                .to_owned()
1762        }
1763        WorkspaceDiagnosticKind::BaselineInstallStateMismatch {
1764            baseline_node_modules,
1765            ..
1766        } => {
1767            let (saved, now, remedy) = match baseline_node_modules {
1768                NodeModulesState::Present => (
1769                    "present",
1770                    "has no node_modules",
1771                    "Install dependencies before you compare",
1772                ),
1773                NodeModulesState::Missing => (
1774                    "missing",
1775                    "has node_modules",
1776                    "Compare without installed dependencies",
1777                ),
1778            };
1779            format!(
1780                "The baseline '{display}' was saved with node_modules {saved}, and this run \
1781                 {now}. Findings that need installed packages (dependency, unlisted, \
1782                 unresolved-import and script-binary findings) can differ, so the run can report \
1783                 baseline findings as new. {remedy}, or save the baseline again in the same \
1784                 install state."
1785            )
1786        }
1787        WorkspaceDiagnosticKind::IgnoreDependenciesGlobUnmatched { .. }
1788        | WorkspaceDiagnosticKind::IgnoreFindingsPatternUnmatched { .. }
1789        | WorkspaceDiagnosticKind::EntryPatternRedundant { .. }
1790        | WorkspaceDiagnosticKind::IgnoreDependenciesEntryRedundant { .. }
1791        | WorkspaceDiagnosticKind::IgnorePatternsEntryRedundant { .. }
1792        | WorkspaceDiagnosticKind::CircularDependenciesAllowUnmatched { .. }
1793        | WorkspaceDiagnosticKind::OverrideRuleIneffective { .. }
1794        | WorkspaceDiagnosticKind::RequestedRuleOff { .. } => {
1795            config_entry::config_entry_message(kind)
1796        }
1797        WorkspaceDiagnosticKind::FlagAgeUnavailable { cause } => {
1798            if cause == "no-commits" {
1799                "The flag retirement report gives no flag age, because the current branch has no \
1800                 commit. Commit the code, or pass --flag-age off."
1801                    .to_owned()
1802            } else {
1803                "The flag retirement report gives no flag age, because no git repository was \
1804                 found at the project root. Run fallow inside the repository, or pass --flag-age \
1805                 off."
1806                    .to_owned()
1807            }
1808        }
1809        WorkspaceDiagnosticKind::PluginConfigUnreadable {
1810            plugin,
1811            key,
1812            reason,
1813        } => {
1814            let (consequence, advice) = plugin_text::unreadable_key_consequence(key, reason);
1815            format!(
1816                "Plugin '{plugin}': `{key}` in '{display}' {situation}, so {consequence}. {advice}",
1817                situation = plugin_text::unreadable_situation(reason)
1818            )
1819        }
1820        WorkspaceDiagnosticKind::PluginEffectNotModeled {
1821            plugin,
1822            key,
1823            reason,
1824        } => {
1825            // Two causes, one effect, one remedy. Each cause gets its own
1826            // sentence: the cause and the effect on the findings are separate
1827            // facts, and one sentence with two `so` clauses states neither fact
1828            // clearly.
1829            let effect = "`autoImports` kept the convention entry patterns for that surface, and \
1830                          fallow reports no unused file there. Write the setting as static \
1831                          literals, or remove the key to use the framework defaults.";
1832            if key.starts_with('#') {
1833                format!(
1834                    "Plugin '{plugin}': fallow cannot read which names '{display}' takes from \
1835                     `{key}`, so every name of `{key}` counts as used, and fallow reports no \
1836                     unused file for these names. Read each name with a member access such as \
1837                     `C.Card`, or import it by name."
1838                )
1839            } else if reason == "config-property-unreadable" {
1840                format!(
1841                    "Plugin '{plugin}': fallow cannot read a top-level property in '{display}', so \
1842                     it cannot classify the `{key}` surface. {effect}"
1843                )
1844            } else {
1845                format!(
1846                    "Plugin '{plugin}': fallow does not model the effect of `{key}` in \
1847                     '{display}'. {effect}"
1848                )
1849            }
1850        }
1851        WorkspaceDiagnosticKind::ExcludedByDefaultIgnore {
1852            pattern,
1853            file_count,
1854            directory_count,
1855        } => {
1856            // `path` is a location, and an empty string is not one: a built-in
1857            // that matched a file sitting directly at the analysis root
1858            // anchors at the root itself.
1859            let display = if display.is_empty() {
1860                ".".to_owned()
1861            } else {
1862                display
1863            };
1864            // The payload carries no directory list, so the message names the
1865            // one directory `path` anchors at. With several excluded
1866            // directories that is the largest group and NOT a majority, so the
1867            // sentence says which claim it is making and how many directories
1868            // it is leaving unnamed.
1869            let location = if *directory_count > 1 {
1870                format!(
1871                    "Skipped {file_count} source files across {directory_count} directories, \
1872                     the largest group under '{display}'"
1873                )
1874            } else if *file_count == 1 {
1875                format!("Skipped 1 source file under '{display}'")
1876            } else {
1877                format!("Skipped {file_count} source files under '{display}'")
1878            };
1879            let singular = *file_count == 1 && *directory_count <= 1;
1880            let (subject, effect) = if singular {
1881                ("it matches", "it imports, exports, or defines")
1882            } else {
1883                ("they match", "they import, export, or define")
1884            };
1885            // Only a directory-shaped built-in is lifted by re-rooting. Telling
1886            // a user with a `vendor/lib.min.js` to run `fallow --root vendor`
1887            // hands them a command that excludes the same file again.
1888            let remedy = if glob_first_literal_segment(pattern).is_some() {
1889                format!(
1890                    "To analyze first-party source there, add '!{display}/**' to \
1891                     ignorePatterns, or analyze that directory on its own with \
1892                     fallow --root {display}."
1893                )
1894            } else {
1895                "This pattern matches a file name rather than a directory, so re-running under \
1896                 a different --root excludes the same files again. Rename first-party source \
1897                 that only looks generated, dropping the '.min' or '.bundle' infix, or add a \
1898                 '!' entry for the file to ignorePatterns."
1899                    .to_owned()
1900            };
1901            format!(
1902                "{location}: {subject} fallow's built-in ignore pattern '{pattern}', so nothing \
1903                 {effect} is visible to this run. {remedy}"
1904            )
1905        }
1906    }
1907}
1908
1909#[cfg(test)]
1910#[path = "workspace_tests.rs"]
1911mod tests;