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