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