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