Skip to main content

fallow_engine/baseline/
mod.rs

1use rustc_hash::{FxHashMap, FxHashSet};
2use std::collections::BTreeMap;
3use std::path::Path;
4
5use fallow_types::extract::is_anonymous_function_name;
6use fallow_types::identity::{IdentifiedFinding, IdentityPaths};
7
8use crate::duplicates::DuplicationReport;
9
10/// Strip the project root from a path to produce a portable relative key.
11///
12/// Both `path` and `root` must be in the same form (both canonicalized or both
13/// not) for `strip_prefix` to succeed. The analysis pipeline keeps all paths
14/// non-canonicalized, so this invariant holds in practice.
15fn relative_path(path: &Path, root: &Path) -> String {
16    match path.strip_prefix(root) {
17        Ok(relative) => relative.to_string_lossy().replace('\\', "/"),
18        Err(_) => {
19            tracing::debug!(
20                path = %path.display(),
21                root = %root.display(),
22                "baseline key: path is not under project root, using absolute path as key"
23            );
24            path.to_string_lossy().replace('\\', "/")
25        }
26    }
27}
28
29fn package_json_dependency_key(package_name: &str, path: &Path, root: &Path) -> String {
30    format!("{}:{package_name}", relative_path(path, root))
31}
32
33fn baseline_contains_dependency(
34    baseline_keys: &FxHashSet<&str>,
35    package_name: &str,
36    path_key: &str,
37) -> bool {
38    baseline_keys.contains(path_key) || baseline_keys.contains(package_name)
39}
40
41fn retain_new_by_keys<T>(
42    items: &mut Vec<T>,
43    baseline_keys: &[String],
44    root: &Path,
45    key_builder: fn(&[T], &Path) -> Vec<String>,
46) {
47    let baseline_keys: FxHashSet<&str> = baseline_keys.iter().map(String::as_str).collect();
48    let item_keys = key_builder(items, root);
49    let mut key_iter = item_keys.into_iter();
50    items.retain(|_| match key_iter.next() {
51        Some(key) => !baseline_keys.contains(key.as_str()),
52        None => true,
53    });
54}
55
56/// Call `$callback!` with every finding field of a dead-code baseline. The
57/// save path and the canonical filter read this one list, so a field cannot
58/// be saved without being matched.
59macro_rules! with_baseline_fields {
60    ($callback:ident) => {
61        $callback!(
62            unused_files,
63            unused_exports,
64            unused_types,
65            private_type_leaks,
66            deprecated_exports_in_use,
67            unused_dependencies,
68            unused_dev_dependencies,
69            circular_dependencies,
70            re_export_cycles,
71            package_cycles,
72            unused_optional_dependencies,
73            unused_enum_members,
74            unused_class_members,
75            unused_store_members,
76            unused_namespace_members,
77            unused_protected_class_members,
78            namespace_escapes,
79            unprovided_injects,
80            unrendered_components,
81            unused_component_props,
82            absent_component_props,
83            constant_parameters,
84            unused_component_emits,
85            unused_component_inputs,
86            unused_component_outputs,
87            unused_svelte_events,
88            unused_effect_layers,
89            unused_tagged_errors,
90            unproduced_catch_tags,
91            unused_server_actions,
92            unused_load_data_keys,
93            unresolved_imports,
94            unlisted_dependencies,
95            unlisted_binaries,
96            duplicate_exports,
97            duplicate_export_aliases,
98            type_only_dependencies,
99            test_only_dependencies,
100            dev_dependencies_in_production,
101            boundary_violations,
102            boundary_coverage_violations,
103            boundary_call_violations,
104            policy_violations,
105            stale_suppressions,
106            unused_catalog_entries,
107            empty_catalog_groups,
108            unresolved_catalog_references,
109            unused_dependency_overrides,
110            misconfigured_dependency_overrides,
111            invalid_client_exports,
112            mixed_client_server_barrels,
113            misplaced_directives,
114            route_collisions,
115            dynamic_segment_name_conflicts,
116            prop_drilling_chains,
117            thin_wrappers,
118            duplicate_prop_shapes,
119        )
120    };
121}
122
123mod finding_counts;
124mod install_state;
125
126use finding_counts::{baseline_finding_count, cascade_hidden_matches};
127mod caller_review_keys;
128mod health_categories;
129use health_categories::{
130    FileLengthCounting, HEALTH_FINDING_DIMENSIONS, HealthFindingCategory, health_finding_counts,
131    severity_counts_for_dimension, severity_index,
132};
133mod health_match;
134#[cfg(test)]
135pub(crate) use health_match::filter_new_health_findings;
136use health_match::{HealthMatch, match_health_baseline, match_severity_slots};
137mod identity_counts;
138
139#[cfg(test)]
140mod legacy_key_builders;
141use caller_review_keys::{absent_component_prop_baseline_keys, constant_parameter_baseline_keys};
142mod prune;
143mod saved_scope;
144mod stale_advice;
145#[cfg(test)]
146use legacy_key_builders::{
147    baseline_catalog_keys, baseline_dependency_keys, baseline_file_export_keys,
148    baseline_graph_keys, baseline_member_import_keys,
149};
150
151pub use install_state::install_state_diagnostic;
152#[cfg(test)]
153pub(crate) use install_state::saved_node_modules_state;
154pub use prune::{
155    BaselinePrune, BaselinePruneRefusal, PrunedEntry, prune_dead_code_baseline,
156    prune_dupes_baseline, prune_health_baseline,
157};
158pub use saved_scope::{saved_finding_categories, saved_scope_reasons};
159
160#[path = "legacy_key_filter.rs"]
161mod legacy_key_filter;
162use legacy_key_filter::filter_new_issues_by_legacy_keys;
163
164/// The sorted canonical keys of `items`, one for each occurrence.
165fn canonical_keys<T: IdentifiedFinding>(items: &[T], paths: &IdentityPaths<'_>) -> Vec<String> {
166    let mut keys: Vec<String> = items.iter().map(|item| item.canonical_key(paths)).collect();
167    keys.sort_unstable();
168    keys
169}
170
171/// Remove the findings that a saved occurrence covers. Each saved key hides
172/// one current finding with the same canonical key, in input order.
173fn retain_unsaved<T: IdentifiedFinding>(
174    items: &mut Vec<T>,
175    saved: &[String],
176    paths: &IdentityPaths<'_>,
177) {
178    if saved.is_empty() {
179        return;
180    }
181    let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
182    for key in saved {
183        *remaining.entry(key.as_str()).or_default() += 1;
184    }
185    items.retain(|item| !consume_baseline_key(&mut remaining, &item.canonical_key(paths)));
186}
187
188/// Stale fraction (in percent) at which a partial-staleness warning fires.
189///
190/// A little drift is the normal state of a living baseline, so warning on any
191/// stale entry would train people to ignore the note. A quarter of the
192/// baseline matching nothing means the gate protects meaningfully less than
193/// what was saved. Shared by the dead-code and health baselines so the two
194/// warnings cannot drift apart.
195const STALE_WARN_PERCENT: usize = 25;
196
197/// True when `stale_entries` out of `baseline_entries` is a large enough share
198/// to be worth warning about.
199///
200/// The threshold alone; [`BaselineStaleness::warning`] owns the surrounding
201/// guards and is what commands call.
202#[must_use]
203const fn stale_share_warrants_warning(baseline_entries: usize, stale_entries: usize) -> bool {
204    stale_entries > 0 && stale_entries * 100 >= baseline_entries * STALE_WARN_PERCENT
205}
206
207/// One run's view of a loaded baseline: everything needed to decide whether the
208/// baseline still describes the project.
209///
210/// Every command that accepts `--baseline` builds one of these and asks it the
211/// same two questions, so `dead-code`, `dupes` and `health` cannot answer
212/// "is this baseline stale enough to say something" three different ways.
213#[derive(Clone, Copy, Debug, PartialEq, Eq)]
214pub struct BaselineStaleness {
215    /// Entries saved in the baseline file.
216    pub entries: usize,
217    /// Baseline entries that matched something in this run.
218    pub matched: usize,
219    /// Findings this run produced before the baseline filtered them. Zero means
220    /// there was nothing to compare, either because the project is clean or the
221    /// scope was empty, so staleness cannot be judged.
222    pub current_findings: usize,
223    /// True when this run cannot judge the loaded baseline, because its scope
224    /// differs from the scope of the file. The baseline then matches less for
225    /// reasons that are not rot.
226    pub change_scoped: bool,
227}
228
229/// Which advisory warning a loaded baseline earns, if any.
230#[derive(Clone, Copy, Debug, PartialEq, Eq)]
231pub enum BaselineStalenessWarning {
232    /// Say nothing: the baseline is fresh enough, or this run cannot judge it.
233    None,
234    /// Nothing in the baseline matched, and there were findings to match.
235    ZeroOverlap,
236    /// A large enough share of the baseline matched nothing.
237    Partial,
238}
239
240impl BaselineStaleness {
241    /// Entries that matched no current finding on this run.
242    #[must_use]
243    pub const fn stale_entries(&self) -> usize {
244        self.entries.saturating_sub(self.matched)
245    }
246
247    /// The advisory warning this run prints on stderr by default.
248    ///
249    /// Silent for a run narrowed to part of the project, because such a run
250    /// legitimately sees only a slice of a whole-project baseline and re-saving
251    /// from it would drop every entry the run never looked at. Silent as well
252    /// when the run produced no findings: a cleaned project and a rotted
253    /// baseline look identical from here, and the re-save advice is wrong when
254    /// the right move is deleting the file.
255    #[must_use]
256    pub const fn warning(&self) -> BaselineStalenessWarning {
257        if self.change_scoped || self.entries == 0 || self.current_findings == 0 {
258            return BaselineStalenessWarning::None;
259        }
260        if self.matched == 0 {
261            return BaselineStalenessWarning::ZeroOverlap;
262        }
263        if stale_share_warrants_warning(self.entries, self.stale_entries()) {
264            return BaselineStalenessWarning::Partial;
265        }
266        BaselineStalenessWarning::None
267    }
268
269    /// Whether the opt-in `--fail-on-stale-baseline` gate fires.
270    ///
271    /// Deliberately stricter than [`Self::warning`]: any stale entry counts.
272    /// The quarter threshold exists to keep an unasked-for line from training
273    /// people to ignore it, and the empty-run silence exists because an
274    /// advisory cannot tell rot from success; a repository that passes the flag
275    /// has asked for both. Change-scope stays the one shared suppression,
276    /// because a narrowed run still cannot judge a whole-project baseline.
277    #[must_use]
278    pub const fn trips_gate(&self) -> bool {
279        stale_baseline_gate_trips(self.entries, self.matched, self.change_scoped)
280    }
281    /// This run's machine-readable view of the baseline, for the JSON envelope.
282    ///
283    /// Every member is derived here rather than in a consumer, so the advisory
284    /// threshold and the gate rule have exactly one implementation. Only
285    /// `health` can follow a file move; the commands that match entries by
286    /// fingerprint pass `0`.
287    ///
288    /// `scope_reasons` and `unrecognised_format` come from the caller because
289    /// only the command knows which channels it read and which format it read
290    /// the file as; this struct carries the counts the analysis needs and
291    /// nothing more. `change_scoped` and `scope_reasons` must agree, which is
292    /// why every caller derives the boolean from the same reason set it passes
293    /// here.
294    ///
295    /// `unrecognised_format` widens `gate_trips` here, at the single site that
296    /// builds it, so the opt-in gate, the exit code, every CI surface that reads
297    /// the boolean and the MCP sentences move together: a file this command
298    /// cannot read as its own suppresses nothing, which no count can express.
299    /// Unlike the count rule it is not suppressed by `change_scoped`, because
300    /// telling a foreign file from this command's own needs no project-wide run.
301    #[must_use]
302    pub fn to_envelope(
303        &self,
304        moved_entries: usize,
305        scope_reasons: fallow_output::BaselineScopeReasons,
306        unrecognised_format: bool,
307    ) -> fallow_output::BaselineStaleness {
308        debug_assert_eq!(
309            self.change_scoped,
310            !scope_reasons.is_empty(),
311            "change_scoped and scope_reasons must be derived from the same predicate"
312        );
313        let warning = self.warning();
314        fallow_output::BaselineStaleness {
315            baseline_entries: self.entries,
316            matched_entries: self.matched,
317            stale_entries: self.stale_entries(),
318            current_findings: self.current_findings,
319            remaining_findings: None,
320            change_scoped: self.change_scoped,
321            stale: warning != BaselineStalenessWarning::None,
322            warning: match warning {
323                BaselineStalenessWarning::None => fallow_output::BaselineStalenessAdvisory::None,
324                BaselineStalenessWarning::ZeroOverlap => {
325                    fallow_output::BaselineStalenessAdvisory::ZeroOverlap
326                }
327                BaselineStalenessWarning::Partial => {
328                    fallow_output::BaselineStalenessAdvisory::Partial
329                }
330            },
331            gate_trips: self.trips_gate() || unrecognised_format,
332            moved_entries,
333            unrecognised_format,
334            saved_by: None,
335            format: None,
336            scope_reasons,
337        }
338    }
339}
340
341/// [`BaselineStaleness::trips_gate`] over the three counts it reads, for
342/// callers that carry the numbers in their own output type.
343#[must_use]
344pub const fn stale_baseline_gate_trips(
345    entries: usize,
346    matched: usize,
347    change_scoped: bool,
348) -> bool {
349    !change_scoped && entries > 0 && matched < entries
350}
351
352/// Whether a baseline file is written in the format it was loaded as.
353///
354/// The duplication and health formats give every field a serde default, so a
355/// baseline another command saved, and an object with nothing in it, both
356/// deserialize into zero entries and are indistinguishable from this command's
357/// own baseline saved from a project that had nothing to record. Asking which
358/// keys the file actually carries separates them: a file that declares at
359/// least one key of the format it was read as is that command's baseline,
360/// however empty it is.
361///
362/// False for anything that is not a JSON object, including a file this crate
363/// would refuse to deserialize; those paths report their own error before a
364/// caller gets here.
365#[must_use]
366pub fn declares_baseline_format(json: &str, declared_keys: &[&str]) -> bool {
367    let Ok(value) = serde_json::from_str::<serde_json::Value>(json) else {
368        return false;
369    };
370    value_declares_baseline_format(&value, declared_keys)
371}
372
373/// [`declares_baseline_format`] for a caller that has already parsed the file.
374fn value_declares_baseline_format(value: &serde_json::Value, declared_keys: &[&str]) -> bool {
375    let Some(object) = value.as_object() else {
376        return false;
377    };
378    declared_keys.iter().any(|key| object.contains_key(*key))
379}
380
381/// Which command saved a baseline file.
382///
383/// Written as the top-level `kind` of every baseline this version saves, spelled
384/// exactly as the envelope root kinds, so a file states which command can read
385/// it instead of leaving three formats to be told apart by the keys they happen
386/// to carry. A file saved before the member exists carries no `kind`, which
387/// [`classify_baseline_file`] falls back from.
388#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
389#[serde(rename_all = "kebab-case")]
390pub enum BaselineKind {
391    /// Saved by `fallow dead-code` (or `fallow check`), and by
392    /// `fallow architecture`.
393    ///
394    /// The kind names the baseline format, not the command: `fallow
395    /// architecture` runs the dead-code analysis, so it writes and reads this
396    /// format although its JSON envelope has `kind: "architecture"`.
397    DeadCode,
398    /// Saved by `fallow dupes`.
399    Dupes,
400    /// Saved by `fallow health`.
401    Health,
402}
403
404impl BaselineKind {
405    /// The token this kind is written as, which is also the command to run.
406    #[must_use]
407    pub const fn as_str(self) -> &'static str {
408        match self {
409            Self::DeadCode => "dead-code",
410            Self::Dupes => "dupes",
411            Self::Health => "health",
412        }
413    }
414
415    /// The kind a `kind` token names, or `None` for a token this version does
416    /// not know (for example one that only a newer fallow writes).
417    #[must_use]
418    fn from_token(token: &str) -> Option<Self> {
419        [Self::DeadCode, Self::Dupes, Self::Health]
420            .into_iter()
421            .find(|kind| kind.as_str() == token)
422    }
423
424    /// The keys that identify this format in a file carrying no `kind`.
425    #[must_use]
426    const fn declared_keys(self) -> &'static [&'static str] {
427        match self {
428            Self::DeadCode => BaselineData::REQUIRED_KEYS,
429            Self::Dupes => DuplicationBaselineData::DECLARED_KEYS,
430            Self::Health => HealthBaselineData::DECLARED_KEYS,
431        }
432    }
433}
434
435/// What a saved baseline file is, read as one command's format.
436#[derive(Debug, Clone, PartialEq, Eq)]
437pub enum BaselineFileKind {
438    /// This command's own baseline: it names this command in `kind`, or it
439    /// carries no `kind` and at least one key of this command's format.
440    Own,
441    /// A baseline another command saved, carrying the `kind` as written so a
442    /// message can quote it, including a token only a newer fallow writes.
443    Foreign(String),
444    /// No `kind` and no key of this command's format: a baseline another
445    /// command saved before `kind` existed, or an object with nothing of this
446    /// command's in it.
447    Unrecognised,
448    /// Not a JSON object, so it says nothing about which command wrote it and
449    /// the caller's own parse error is the honest report.
450    NotAnObject,
451}
452
453impl BaselineFileKind {
454    /// The known command that saved a file another command wrote.
455    ///
456    /// `None` for this command's own file, for a file that names no writer, and
457    /// for a `kind` token this version does not know. The CLI computes this one
458    /// time per loaded baseline and uses it for the stderr note and for
459    /// `baseline_staleness.saved_by`, so the two cannot disagree.
460    #[must_use]
461    pub fn saved_by(&self) -> Option<BaselineKind> {
462        match self {
463            Self::Foreign(token) => BaselineKind::from_token(token),
464            Self::Own | Self::Unrecognised | Self::NotAnObject => None,
465        }
466    }
467}
468
469/// Why a `--save-baseline` must not overwrite the file at `save_path`, or `None`
470/// when the save may proceed.
471///
472/// A save serializes a fresh struct over the whole file, so one command's save
473/// aimed at another command's baseline destroys it with nothing left to recover
474/// from. Read from the destination's own `kind`: a file saved before that member
475/// existed carries nothing to identify it and is still overwritten silently, and
476/// an unreadable or absent destination is not a guard condition, exactly as the
477/// health identity-overwrite guard treats one.
478#[must_use]
479pub fn refuse_baseline_kind_overwrite(save_path: &Path, saving: BaselineKind) -> Option<String> {
480    let existing = std::fs::read_to_string(save_path).ok()?;
481    let BaselineFileKind::Foreign(found) = classify_baseline_file(&existing, saving) else {
482        return None;
483    };
484    Some(format!(
485        "refusing to overwrite the baseline at {}: it was saved by `fallow {found}` and this is a \
486         `fallow {}` save, which would destroy it. Save each command's baseline to its own path.",
487        save_path.display(),
488        saving.as_str(),
489    ))
490}
491
492/// Which command a saved baseline file belongs to, read as `expected`'s format.
493///
494/// `kind` decides whenever the file carries one, which is every baseline saved
495/// from this version onward. A file without one predates the member, so the keys
496/// it carries decide instead, exactly as [`declares_baseline_format`] documents.
497///
498/// Reads the raw file rather than a deserialized struct, because the one format
499/// with required fields (`dead-code`) has to answer this before its own parse
500/// error hides the answer.
501#[must_use]
502pub fn classify_baseline_file(json: &str, expected: BaselineKind) -> BaselineFileKind {
503    let Ok(value) = serde_json::from_str::<serde_json::Value>(json) else {
504        return BaselineFileKind::NotAnObject;
505    };
506    classify_baseline_value(&value, expected)
507}
508
509/// [`classify_baseline_file`] for a caller that parses the file itself.
510///
511/// The `dead-code` read needs both this answer and the deserialized struct, and
512/// its format is the one with required fields, so it parses once into a value and
513/// asks here rather than paying for a second parse of the same bytes.
514#[must_use]
515fn classify_baseline_value(value: &serde_json::Value, expected: BaselineKind) -> BaselineFileKind {
516    let Some(object) = value.as_object() else {
517        return BaselineFileKind::NotAnObject;
518    };
519    match object.get("kind").and_then(serde_json::Value::as_str) {
520        Some(token) if token == expected.as_str() => BaselineFileKind::Own,
521        Some(token) => BaselineFileKind::Foreign(token.to_owned()),
522        // A `kind` that is not a string is no statement about the writer, so the
523        // keys answer as they do for a file that carries no `kind` at all.
524        None => {
525            if value_declares_baseline_format(value, expected.declared_keys()) {
526                BaselineFileKind::Own
527            } else {
528                BaselineFileKind::Unrecognised
529            }
530        }
531    }
532}
533
534/// The key scheme of a dead-code baseline that stores canonical keys.
535///
536/// A baseline with `"identity": "dc1"` stores, for each finding, the canonical
537/// key from [`fallow_types::identity`] (`<rule>:<path>:<name>...`, never a
538/// line), once for each occurrence. N saved occurrences of a key hide at most
539/// N current findings with that key. A baseline without `identity` is a legacy
540/// baseline: each entry keeps its old form (some old forms hold a line) and
541/// hides every current finding with that exact key.
542pub const BASELINE_KEY_SCHEME: &str = fallow_types::identity::DEAD_CODE_ID_SCHEME;
543
544/// Baseline data for comparison.
545///
546/// The per-field notes below give the legacy key forms. A baseline with an
547/// `identity` stores canonical keys in every field; see
548/// [`BASELINE_KEY_SCHEME`].
549#[derive(serde::Serialize, serde::Deserialize)]
550pub struct BaselineData {
551    /// The command that saved this file, written on every save and never read
552    /// back through this struct: [`classify_baseline_file`] reads it off the raw
553    /// file, before the required fields below can reject another command's
554    /// baseline. `skip_deserializing` keeps a `kind` only a newer fallow writes
555    /// from turning a loadable file into a parse error.
556    #[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")]
557    kind: Option<BaselineKind>,
558    /// Analysis identity plus install state; legacy files read as syntactic,
559    /// never silently compared with type-aware output.
560    #[serde(default)]
561    analysis_identity: install_state::BaselineAnalysisIdentity,
562    /// The key scheme of the entries: [`BASELINE_KEY_SCHEME`] for canonical,
563    /// count-matched keys, absent for a legacy baseline.
564    #[serde(default, skip_serializing_if = "Option::is_none")]
565    identity: Option<String>,
566    /// The `scope_reasons` of the run that saved this file, absent for a
567    /// whole-project save. A listed reason means the file holds only the
568    /// findings in that scope, so a wider run that loads it can report old
569    /// findings as new. Read back with [`saved_scope_reasons`].
570    #[serde(default, skip_serializing_if = "Vec::is_empty")]
571    scope_reasons: Vec<String>,
572    unused_files: Vec<String>,
573    unused_exports: Vec<String>,
574    unused_types: Vec<String>,
575    #[serde(default)]
576    private_type_leaks: Vec<String>,
577    /// Deprecated exports still in use, keyed by `path:export_name`.
578    #[serde(default)]
579    deprecated_exports_in_use: Vec<String>,
580    /// Unused dependencies, keyed by `package.json:package_name`. Legacy
581    /// bare `package_name` keys are still matched for back-compat with
582    /// baselines saved by older fallow versions.
583    unused_dependencies: Vec<String>,
584    /// Unused dev dependencies, keyed by `package.json:package_name`. Legacy
585    /// bare `package_name` keys are still matched for back-compat with
586    /// baselines saved by older fallow versions.
587    unused_dev_dependencies: Vec<String>,
588    /// Circular dependency chains, keyed by sorted file paths joined with `->`.
589    #[serde(default)]
590    circular_dependencies: Vec<String>,
591    /// Re-export cycles, keyed by `kind:sorted_file_paths_joined_with_<->`
592    /// (where `kind` is `multi-node` or `self-loop`). The kind prefix keeps
593    /// self-loops from keyspace-colliding with future single-file multi-node
594    /// shapes.
595    #[serde(default)]
596    re_export_cycles: Vec<String>,
597    /// Package cycles, keyed by package names in canonical cycle order joined
598    /// with `->`.
599    #[serde(default)]
600    package_cycles: Vec<String>,
601    /// Unused optional dependencies, keyed by `package.json:package_name`.
602    /// Legacy bare `package_name` keys are still matched for back-compat
603    /// with baselines saved by older fallow versions.
604    #[serde(default)]
605    unused_optional_dependencies: Vec<String>,
606    /// Unused enum members, keyed by `file:parent.member`.
607    #[serde(default)]
608    unused_enum_members: Vec<String>,
609    /// Unused class members, keyed by `file:parent.member`.
610    #[serde(default)]
611    unused_class_members: Vec<String>,
612    /// Unused store members, keyed by `file:parent.member`.
613    #[serde(default)]
614    unused_store_members: Vec<String>,
615    /// Unused namespace members, keyed by `file:parent.member`.
616    #[serde(default)]
617    unused_namespace_members: Vec<String>,
618    /// Unused protected class members, keyed by `file:parent.member`.
619    #[serde(default, skip_serializing_if = "Vec::is_empty")]
620    unused_protected_class_members: Vec<String>,
621    /// Namespace escapes, keyed by the canonical finding identity.
622    #[serde(default, skip_serializing_if = "Vec::is_empty")]
623    namespace_escapes: Vec<String>,
624    /// Unprovided injects, keyed by `file:key_name`.
625    #[serde(default)]
626    unprovided_injects: Vec<String>,
627    /// Unrendered components, keyed by `file:component_name`.
628    #[serde(default)]
629    unrendered_components: Vec<String>,
630    /// Unused component props, keyed by `file:prop_name`.
631    #[serde(default)]
632    unused_component_props: Vec<String>,
633    #[serde(default)]
634    absent_component_props: Vec<String>,
635    /// Constant parameters, keyed by `file:function:parameter`.
636    #[serde(default)]
637    constant_parameters: Vec<String>,
638    /// Unused component emits, keyed by `file:emit_name`.
639    #[serde(default)]
640    unused_component_emits: Vec<String>,
641    /// Unused component inputs, keyed by `file:input_name`.
642    #[serde(default)]
643    unused_component_inputs: Vec<String>,
644    /// Unused component outputs, keyed by `file:output_name`.
645    #[serde(default)]
646    unused_component_outputs: Vec<String>,
647    /// Unused Svelte dispatched events, keyed by `file:event_name`.
648    #[serde(default)]
649    unused_svelte_events: Vec<String>,
650    /// Unused Effect layers, keyed by `file:layer_name`.
651    #[serde(default)]
652    unused_effect_layers: Vec<String>,
653    /// Unused tagged errors, keyed by `file:class_name`.
654    #[serde(default)]
655    unused_tagged_errors: Vec<String>,
656    /// Unproduced catch tags, keyed by `file:tag`.
657    #[serde(default)]
658    unproduced_catch_tags: Vec<String>,
659    /// Unused server actions, keyed by `file:action_name`.
660    #[serde(default)]
661    unused_server_actions: Vec<String>,
662    /// Unused SvelteKit load() data keys, keyed by `file:key_name`.
663    #[serde(default)]
664    unused_load_data_keys: Vec<String>,
665    /// Unresolved imports, keyed by `file:specifier`.
666    #[serde(default)]
667    unresolved_imports: Vec<String>,
668    /// Unlisted dependencies, keyed by package name.
669    #[serde(default)]
670    unlisted_dependencies: Vec<String>,
671    /// Unlisted binaries, keyed by binary name.
672    #[serde(default)]
673    unlisted_binaries: Vec<String>,
674    /// Duplicate exports, keyed by export name.
675    #[serde(default)]
676    duplicate_exports: Vec<String>,
677    /// Bindings exported under two or more names in one file, keyed by the
678    /// canonical finding key. No legacy key form exists.
679    #[serde(default)]
680    duplicate_export_aliases: Vec<String>,
681    /// Type-only dependencies, keyed by `package.json:package_name`. Legacy
682    /// bare `package_name` keys are still matched for back-compat with
683    /// baselines saved by older fallow versions.
684    #[serde(default)]
685    type_only_dependencies: Vec<String>,
686    /// Test-only dependencies, keyed by `package.json:package_name`. Legacy
687    /// bare `package_name` keys are still matched for back-compat with
688    /// baselines saved by older fallow versions.
689    #[serde(default)]
690    test_only_dependencies: Vec<String>,
691    /// Dev dependencies used in production, keyed by `package.json:package_name`.
692    #[serde(default)]
693    dev_dependencies_in_production: Vec<String>,
694    /// Boundary violations, keyed by `from_path->to_path`.
695    #[serde(default)]
696    boundary_violations: Vec<String>,
697    /// Boundary coverage violations, keyed by `path`.
698    #[serde(default)]
699    boundary_coverage_violations: Vec<String>,
700    /// Boundary call violations, keyed by `path:callee`.
701    #[serde(default)]
702    boundary_call_violations: Vec<String>,
703    /// Rule-pack policy violations, keyed by `path:pack/rule_id:matched`.
704    #[serde(default)]
705    policy_violations: Vec<String>,
706    /// Stale suppressions, keyed by `file:line`.
707    #[serde(default)]
708    stale_suppressions: Vec<String>,
709    /// Unused pnpm catalog entries, keyed by `catalog_name:entry_name`.
710    #[serde(default)]
711    unused_catalog_entries: Vec<String>,
712    /// Empty pnpm catalog groups, keyed by `catalog_name`.
713    #[serde(default)]
714    empty_catalog_groups: Vec<String>,
715    /// Unresolved catalog references, keyed by `path:line:catalog_name:entry_name`.
716    #[serde(default)]
717    unresolved_catalog_references: Vec<String>,
718    /// Unused package-manager dependency overrides, keyed by `source:raw_key`.
719    #[serde(default)]
720    unused_dependency_overrides: Vec<String>,
721    /// Misconfigured package-manager dependency overrides, keyed by `source:raw_key`.
722    #[serde(default)]
723    misconfigured_dependency_overrides: Vec<String>,
724    /// Invalid `"use client"` exports, keyed by `path:export_name`.
725    #[serde(default)]
726    invalid_client_exports: Vec<String>,
727    /// Mixed client/server barrels, keyed by `path:client_origin:server_origin`.
728    #[serde(default)]
729    mixed_client_server_barrels: Vec<String>,
730    /// Misplaced `"use client"` / `"use server"` directives, keyed by
731    /// `path:line:directive`.
732    #[serde(default)]
733    misplaced_directives: Vec<String>,
734    /// Next.js route collisions, keyed by `path:url`.
735    #[serde(default)]
736    route_collisions: Vec<String>,
737    /// Next.js dynamic-segment name conflicts, keyed by `path:position`.
738    #[serde(default)]
739    dynamic_segment_name_conflicts: Vec<String>,
740    /// Reviewed prop chains, keyed by source component and prop with occurrence matching.
741    #[serde(default)]
742    prop_drilling_chains: Vec<String>,
743    /// Reviewed thin wrappers, keyed by source component with occurrence matching.
744    #[serde(default)]
745    thin_wrappers: Vec<String>,
746    /// Reviewed duplicate prop shapes, keyed by component and significant shape.
747    #[serde(default)]
748    duplicate_prop_shapes: Vec<String>,
749}
750
751impl BaselineData {
752    /// The keys a dead-code baseline cannot load without. They carry no serde
753    /// default, so a file that deserializes into this struct carries all of
754    /// them, and a file carrying none of them is not a dead-code baseline
755    /// however it is spelled. Deliberately a subset of what the format writes:
756    /// the rest are optional and say nothing about which command wrote the file.
757    const REQUIRED_KEYS: &'static [&'static str] = &[
758        "unused_files",
759        "unused_exports",
760        "unused_types",
761        "unused_dependencies",
762        "unused_dev_dependencies",
763    ];
764
765    /// Build baseline keys from analysis results under the syntactic identity.
766    #[cfg(test)]
767    fn from_results(results: &crate::results::AnalysisResults, root: &Path) -> Self {
768        Self::from_results_with_identity(
769            results,
770            root,
771            fallow_types::semantic::SemanticAnalysisIdentity::syntactic(),
772        )
773    }
774
775    /// Build baseline keys from analysis results, stamping the given analysis
776    /// identity so later loads can reject baselines produced under an
777    /// incompatible analysis mode.
778    ///
779    /// Every entry is a canonical key, written once for each occurrence and
780    /// sorted, so the file does not change when findings move.
781    pub fn from_results_with_identity(
782        results: &crate::results::AnalysisResults,
783        root: &Path,
784        analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
785    ) -> Self {
786        let paths = IdentityPaths::new(root);
787        macro_rules! build {
788            ($($field:ident),* $(,)?) => {
789                Self {
790                    kind: Some(BaselineKind::DeadCode),
791                    analysis_identity: analysis_identity.into(),
792                    identity: Some(BASELINE_KEY_SCHEME.to_owned()),
793                    scope_reasons: Vec::new(),
794                    $($field: canonical_keys(&results.$field, &paths),)*
795                }
796            };
797        }
798        with_baseline_fields!(build)
799    }
800
801    /// Build a baseline in the legacy key forms that fallow wrote before
802    /// canonical keys. Tests use it to prove that legacy files still load.
803    #[cfg(test)]
804    fn legacy_from_results(results: &crate::results::AnalysisResults, root: &Path) -> Self {
805        let analysis_identity = fallow_types::semantic::SemanticAnalysisIdentity::syntactic();
806        let file_exports = baseline_file_export_keys(results, root);
807        let member_imports = baseline_member_import_keys(results, root);
808        let dependencies = baseline_dependency_keys(results, root);
809        let graph = baseline_graph_keys(results, root);
810        let catalog = baseline_catalog_keys(results, root);
811
812        Self {
813            kind: Some(BaselineKind::DeadCode),
814            analysis_identity: analysis_identity.into(),
815            identity: None,
816            scope_reasons: Vec::new(),
817            unused_files: file_exports.unused_files,
818            unused_exports: file_exports.unused_exports,
819            unused_types: file_exports.unused_types,
820            private_type_leaks: file_exports.private_type_leaks,
821            deprecated_exports_in_use: file_exports.deprecated_exports_in_use,
822            unused_dependencies: dependencies.unused,
823            unused_dev_dependencies: dependencies.unused_dev,
824            circular_dependencies: graph.circular_dependencies,
825            re_export_cycles: graph.re_export_cycles,
826            package_cycles: graph.package_cycles,
827            unused_optional_dependencies: dependencies.unused_optional,
828            unused_enum_members: member_imports.unused_enum_members,
829            unused_class_members: member_imports.unused_class_members,
830            unused_store_members: member_imports.unused_store_members,
831            unused_namespace_members: member_imports.unused_namespace_members,
832            unused_protected_class_members: member_imports.unused_protected_class_members,
833            namespace_escapes: Vec::new(),
834            unprovided_injects: member_imports.unprovided_injects,
835            unrendered_components: member_imports.unrendered_components,
836            unused_component_props: member_imports.unused_component_props,
837            absent_component_props: member_imports.absent_component_props,
838            constant_parameters: member_imports.constant_parameters,
839            unused_component_emits: member_imports.unused_component_emits,
840            unused_component_inputs: member_imports.unused_component_inputs,
841            unused_component_outputs: member_imports.unused_component_outputs,
842            unused_svelte_events: member_imports.unused_svelte_events,
843            unused_effect_layers: member_imports.unused_effect_layers,
844            unused_tagged_errors: member_imports.unused_tagged_errors,
845            unproduced_catch_tags: member_imports.unproduced_catch_tags,
846            unused_server_actions: member_imports.unused_server_actions,
847            unused_load_data_keys: member_imports.unused_load_data_keys,
848            unresolved_imports: member_imports.unresolved_imports,
849            unlisted_dependencies: dependencies.unlisted,
850            unlisted_binaries: Vec::new(),
851            duplicate_exports: member_imports.duplicate_exports,
852            duplicate_export_aliases: Vec::new(),
853            type_only_dependencies: dependencies.type_only,
854            test_only_dependencies: dependencies.test_only,
855            dev_dependencies_in_production: dependencies.dev_in_prod,
856            boundary_violations: graph.boundary_violations,
857            boundary_coverage_violations: graph.boundary_coverage_violations,
858            boundary_call_violations: graph.boundary_call_violations,
859            policy_violations: graph.policy_violations,
860            stale_suppressions: member_imports.stale_suppressions,
861            unused_catalog_entries: catalog.unused_catalog_entries,
862            empty_catalog_groups: catalog.empty_catalog_groups,
863            unresolved_catalog_references: catalog.unresolved_catalog_references,
864            unused_dependency_overrides: catalog.unused_dependency_overrides,
865            misconfigured_dependency_overrides: catalog.misconfigured_dependency_overrides,
866            invalid_client_exports: file_exports.invalid_client_exports,
867            mixed_client_server_barrels: file_exports.mixed_client_server_barrels,
868            misplaced_directives: file_exports.misplaced_directives,
869            route_collisions: file_exports.route_collisions,
870            dynamic_segment_name_conflicts: file_exports.dynamic_segment_name_conflicts,
871            prop_drilling_chains: Vec::new(),
872            thin_wrappers: Vec::new(),
873            duplicate_prop_shapes: Vec::new(),
874        }
875    }
876
877    /// The analysis identity this baseline was captured under.
878    #[must_use]
879    pub const fn analysis_identity(&self) -> &fallow_types::semantic::SemanticAnalysisIdentity {
880        &self.analysis_identity.semantic
881    }
882
883    /// Total number of entries across all categories.
884    fn total_entries(&self) -> usize {
885        self.unused_files.len()
886            + self.unused_exports.len()
887            + self.unused_types.len()
888            + self.private_type_leaks.len()
889            + self.deprecated_exports_in_use.len()
890            + self.unused_dependencies.len()
891            + self.unused_dev_dependencies.len()
892            + self.circular_dependencies.len()
893            + self.re_export_cycles.len()
894            + self.package_cycles.len()
895            + self.unused_optional_dependencies.len()
896            + self.unused_enum_members.len()
897            + self.unused_class_members.len()
898            + self.unused_store_members.len()
899            + self.unused_namespace_members.len()
900            + self.unused_protected_class_members.len()
901            + self.namespace_escapes.len()
902            + self.unprovided_injects.len()
903            + self.unrendered_components.len()
904            + self.unused_component_props.len()
905            + self.absent_component_props.len()
906            + self.constant_parameters.len()
907            + self.unused_component_emits.len()
908            + self.unused_component_inputs.len()
909            + self.unused_component_outputs.len()
910            + self.unused_svelte_events.len()
911            + self.unused_effect_layers.len()
912            + self.unused_tagged_errors.len()
913            + self.unproduced_catch_tags.len()
914            + self.unused_server_actions.len()
915            + self.unused_load_data_keys.len()
916            + self.unresolved_imports.len()
917            + self.unlisted_dependencies.len()
918            + self.unlisted_binaries.len()
919            + self.duplicate_exports.len()
920            + self.duplicate_export_aliases.len()
921            + self.type_only_dependencies.len()
922            + self.test_only_dependencies.len()
923            + self.dev_dependencies_in_production.len()
924            + self.boundary_violations.len()
925            + self.boundary_coverage_violations.len()
926            + self.boundary_call_violations.len()
927            + self.policy_violations.len()
928            + self.stale_suppressions.len()
929            + self.unused_catalog_entries.len()
930            + self.empty_catalog_groups.len()
931            + self.unresolved_catalog_references.len()
932            + self.unused_dependency_overrides.len()
933            + self.misconfigured_dependency_overrides.len()
934            + self.invalid_client_exports.len()
935            + self.mixed_client_server_barrels.len()
936            + self.misplaced_directives.len()
937            + self.route_collisions.len()
938            + self.dynamic_segment_name_conflicts.len()
939            + self.prop_drilling_chains.len()
940            + self.thin_wrappers.len()
941            + self.duplicate_prop_shapes.len()
942    }
943}
944
945#[cfg(test)]
946struct BaselineFileExportKeys {
947    unused_files: Vec<String>,
948    unused_exports: Vec<String>,
949    unused_types: Vec<String>,
950    private_type_leaks: Vec<String>,
951    deprecated_exports_in_use: Vec<String>,
952    invalid_client_exports: Vec<String>,
953    mixed_client_server_barrels: Vec<String>,
954    misplaced_directives: Vec<String>,
955    route_collisions: Vec<String>,
956    dynamic_segment_name_conflicts: Vec<String>,
957}
958
959#[cfg(test)]
960struct BaselineMemberImportKeys {
961    unused_enum_members: Vec<String>,
962    unused_class_members: Vec<String>,
963    unused_store_members: Vec<String>,
964    unused_namespace_members: Vec<String>,
965    unused_protected_class_members: Vec<String>,
966    unprovided_injects: Vec<String>,
967    unrendered_components: Vec<String>,
968    unused_component_props: Vec<String>,
969    absent_component_props: Vec<String>,
970    constant_parameters: Vec<String>,
971    unused_component_emits: Vec<String>,
972    unused_component_inputs: Vec<String>,
973    unused_component_outputs: Vec<String>,
974    unused_svelte_events: Vec<String>,
975    unused_effect_layers: Vec<String>,
976    unused_tagged_errors: Vec<String>,
977    unproduced_catch_tags: Vec<String>,
978    unused_server_actions: Vec<String>,
979    unused_load_data_keys: Vec<String>,
980    unresolved_imports: Vec<String>,
981    duplicate_exports: Vec<String>,
982    stale_suppressions: Vec<String>,
983}
984
985fn stale_suppression_baseline_key(
986    suppression: &crate::results::StaleSuppression,
987    root: &Path,
988) -> String {
989    let rule_id = if suppression.missing_reason {
990        "missing-suppression-reason"
991    } else {
992        "stale-suppression"
993    };
994    format!(
995        "{rule_id}:{}:{}",
996        relative_path(&suppression.path, root),
997        suppression.line
998    )
999}
1000
1001fn inject_baseline_keys(
1002    items: &[crate::results::UnprovidedInjectFinding],
1003    root: &Path,
1004) -> Vec<String> {
1005    items
1006        .iter()
1007        .map(|f| {
1008            format!(
1009                "{}:{}",
1010                relative_path(&f.inject.path, root),
1011                f.inject.key_name
1012            )
1013        })
1014        .collect()
1015}
1016
1017fn component_baseline_keys(
1018    items: &[crate::results::UnrenderedComponentFinding],
1019    root: &Path,
1020) -> Vec<String> {
1021    items
1022        .iter()
1023        .map(|c| {
1024            format!(
1025                "{}:{}",
1026                relative_path(&c.component.path, root),
1027                c.component.component_name
1028            )
1029        })
1030        .collect()
1031}
1032
1033fn component_prop_baseline_keys(
1034    items: &[crate::results::UnusedComponentPropFinding],
1035    root: &Path,
1036) -> Vec<String> {
1037    items
1038        .iter()
1039        .map(|p| format!("{}:{}", relative_path(&p.prop.path, root), p.prop.prop_name))
1040        .collect()
1041}
1042
1043fn component_emit_baseline_keys(
1044    items: &[crate::results::UnusedComponentEmitFinding],
1045    root: &Path,
1046) -> Vec<String> {
1047    items
1048        .iter()
1049        .map(|e| format!("{}:{}", relative_path(&e.emit.path, root), e.emit.emit_name))
1050        .collect()
1051}
1052
1053fn component_input_baseline_keys(
1054    items: &[crate::results::UnusedComponentInputFinding],
1055    root: &Path,
1056) -> Vec<String> {
1057    items
1058        .iter()
1059        .map(|i| {
1060            format!(
1061                "{}:{}",
1062                relative_path(&i.input.path, root),
1063                i.input.input_name
1064            )
1065        })
1066        .collect()
1067}
1068
1069fn component_output_baseline_keys(
1070    items: &[crate::results::UnusedComponentOutputFinding],
1071    root: &Path,
1072) -> Vec<String> {
1073    items
1074        .iter()
1075        .map(|o| {
1076            format!(
1077                "{}:{}",
1078                relative_path(&o.output.path, root),
1079                o.output.output_name
1080            )
1081        })
1082        .collect()
1083}
1084
1085fn effect_layer_baseline_keys(
1086    items: &[crate::results::UnusedEffectLayerFinding],
1087    root: &Path,
1088) -> Vec<String> {
1089    items
1090        .iter()
1091        .map(|f| format!("{}:{}", relative_path(&f.layer.path, root), f.layer.name))
1092        .collect()
1093}
1094
1095fn tagged_error_baseline_keys(
1096    items: &[crate::results::UnusedTaggedErrorFinding],
1097    root: &Path,
1098) -> Vec<String> {
1099    items
1100        .iter()
1101        .map(|f| format!("{}:{}", relative_path(&f.error.path, root), f.error.name))
1102        .collect()
1103}
1104
1105fn catch_tag_baseline_keys(
1106    items: &[crate::results::UnproducedCatchTagFinding],
1107    root: &Path,
1108) -> Vec<String> {
1109    items
1110        .iter()
1111        .map(|f| {
1112            format!(
1113                "{}:{}",
1114                relative_path(&f.catch_tag.path, root),
1115                f.catch_tag.tag
1116            )
1117        })
1118        .collect()
1119}
1120
1121fn svelte_event_baseline_keys(
1122    items: &[crate::results::UnusedSvelteEventFinding],
1123    root: &Path,
1124) -> Vec<String> {
1125    items
1126        .iter()
1127        .map(|e| {
1128            format!(
1129                "{}:{}",
1130                relative_path(&e.event.path, root),
1131                e.event.event_name
1132            )
1133        })
1134        .collect()
1135}
1136
1137#[cfg(test)]
1138struct BaselineDependencyKeys {
1139    unused: Vec<String>,
1140    unused_dev: Vec<String>,
1141    unused_optional: Vec<String>,
1142    unlisted: Vec<String>,
1143    type_only: Vec<String>,
1144    test_only: Vec<String>,
1145    dev_in_prod: Vec<String>,
1146}
1147
1148/// Generate a stable key for a boundary violation: `from_path->to_path`.
1149fn boundary_violation_key(v: &crate::results::BoundaryViolation, root: &Path) -> String {
1150    format!(
1151        "{}->{}",
1152        relative_path(&v.from_path, root),
1153        relative_path(&v.to_path, root),
1154    )
1155}
1156
1157/// Generate a stable key for a boundary call violation: `path:callee`.
1158fn boundary_call_violation_key(v: &crate::results::BoundaryCallViolation, root: &Path) -> String {
1159    format!("{}:{}", relative_path(&v.path, root), v.callee)
1160}
1161
1162/// Generate a stable key for a duplicate export: `name|sorted_paths`.
1163fn duplicate_export_key(dup: &crate::results::DuplicateExport, root: &Path) -> String {
1164    let mut locs: Vec<String> = dup
1165        .locations
1166        .iter()
1167        .map(|l| relative_path(&l.path, root))
1168        .collect();
1169    locs.sort();
1170    format!("{}|{}", dup.export_name, locs.join("|"))
1171}
1172
1173/// Generate a stable key for a circular dependency based on sorted file paths.
1174fn circular_dep_key(dep: &crate::results::CircularDependency, root: &Path) -> String {
1175    let mut paths: Vec<String> = dep.files.iter().map(|f| relative_path(f, root)).collect();
1176    paths.sort();
1177    paths.join("->")
1178}
1179
1180/// Generate a stable key for a re-export cycle based on its discriminator
1181/// kind plus sorted member paths. The `kind` prefix is mandatory: without
1182/// it a self-loop on `src/foo.ts` would keyspace-collide with any future
1183/// single-file multi-node shape, and the `--baseline new` filter would
1184/// silently drop the new one as already-seen (panel catch #7).
1185fn re_export_cycle_key(cycle: &crate::results::ReExportCycle, root: &Path) -> String {
1186    let kind = match cycle.kind {
1187        crate::results::ReExportCycleKind::MultiNode => "multi-node",
1188        crate::results::ReExportCycleKind::SelfLoop => "self-loop",
1189    };
1190    let mut paths: Vec<String> = cycle.files.iter().map(|f| relative_path(f, root)).collect();
1191    paths.sort();
1192    format!("{kind}:{}", paths.join("<->"))
1193}
1194
1195/// Generate a stable key for a package cycle. The package names are already
1196/// in canonical cycle order, and they do not depend on the example import, so
1197/// the key survives a change of example import.
1198fn package_cycle_key(cycle: &crate::results::PackageCycle) -> String {
1199    cycle.packages.join("->")
1200}
1201
1202fn private_type_leak_key(leak: &crate::results::PrivateTypeLeak, root: &Path) -> String {
1203    format!(
1204        "{}:{}->{}",
1205        relative_path(&leak.path, root),
1206        leak.export_name,
1207        leak.type_name
1208    )
1209}
1210
1211fn deprecated_export_key(
1212    export: &fallow_types::results::DeprecatedExportInUse,
1213    root: &Path,
1214) -> String {
1215    format!(
1216        "{}:{}",
1217        relative_path(&export.path, root),
1218        export.export_name
1219    )
1220}
1221
1222fn filter_private_type_leaks(
1223    leaks: &mut Vec<fallow_types::output_dead_code::PrivateTypeLeakFinding>,
1224    baseline_keys: &[String],
1225    root: &Path,
1226) {
1227    let baseline_private_type_leaks: FxHashSet<&str> =
1228        baseline_keys.iter().map(String::as_str).collect();
1229    leaks.retain(|entry| {
1230        let key = private_type_leak_key(&entry.leak, root);
1231        !baseline_private_type_leaks.contains(key.as_str())
1232    });
1233}
1234
1235struct BaselineFilterContext<'a> {
1236    baseline: &'a BaselineData,
1237    root: &'a Path,
1238}
1239
1240impl BaselineFilterContext<'_> {
1241    fn filter_cycles_and_members(&self, results: &mut crate::results::AnalysisResults) {
1242        let baseline_circular: FxHashSet<&str> = self
1243            .baseline
1244            .circular_dependencies
1245            .iter()
1246            .map(String::as_str)
1247            .collect();
1248        results.circular_dependencies.retain(|cycle| {
1249            let key = circular_dep_key(&cycle.cycle, self.root);
1250            !baseline_circular.contains(key.as_str())
1251        });
1252
1253        let baseline_re_export_cycles: FxHashSet<&str> = self
1254            .baseline
1255            .re_export_cycles
1256            .iter()
1257            .map(String::as_str)
1258            .collect();
1259        results.re_export_cycles.retain(|cycle| {
1260            let key = re_export_cycle_key(&cycle.cycle, self.root);
1261            !baseline_re_export_cycles.contains(key.as_str())
1262        });
1263
1264        let baseline_package_cycles: FxHashSet<&str> = self
1265            .baseline
1266            .package_cycles
1267            .iter()
1268            .map(String::as_str)
1269            .collect();
1270        results.package_cycles.retain(|cycle| {
1271            !baseline_package_cycles.contains(package_cycle_key(&cycle.cycle).as_str())
1272        });
1273
1274        self.filter_unused_members(results);
1275        self.filter_unresolved_and_exports(results);
1276    }
1277
1278    fn filter_unused_members(&self, results: &mut crate::results::AnalysisResults) {
1279        self.filter_enum_class_store_members(results);
1280        self.filter_component_surface_members(results);
1281        self.filter_route_action_members(results);
1282    }
1283
1284    fn filter_enum_class_store_members(&self, results: &mut crate::results::AnalysisResults) {
1285        let baseline_enum_members: FxHashSet<&str> = self
1286            .baseline
1287            .unused_enum_members
1288            .iter()
1289            .map(String::as_str)
1290            .collect();
1291        results.unused_enum_members.retain(|member| {
1292            let key = format!(
1293                "{}:{}.{}",
1294                relative_path(&member.member.path, self.root),
1295                member.member.parent_name,
1296                member.member.member_name
1297            );
1298            !baseline_enum_members.contains(key.as_str())
1299        });
1300
1301        let baseline_class_members: FxHashSet<&str> = self
1302            .baseline
1303            .unused_class_members
1304            .iter()
1305            .map(String::as_str)
1306            .collect();
1307        results.unused_class_members.retain(|member| {
1308            let key = format!(
1309                "{}:{}.{}",
1310                relative_path(&member.member.path, self.root),
1311                member.member.parent_name,
1312                member.member.member_name
1313            );
1314            !baseline_class_members.contains(key.as_str())
1315        });
1316
1317        let baseline_store_members: FxHashSet<&str> = self
1318            .baseline
1319            .unused_store_members
1320            .iter()
1321            .map(String::as_str)
1322            .collect();
1323        results.unused_store_members.retain(|member| {
1324            let key = format!(
1325                "{}:{}.{}",
1326                relative_path(&member.member.path, self.root),
1327                member.member.parent_name,
1328                member.member.member_name
1329            );
1330            !baseline_store_members.contains(key.as_str())
1331        });
1332        let baseline_namespace_members: FxHashSet<&str> = self
1333            .baseline
1334            .unused_namespace_members
1335            .iter()
1336            .map(String::as_str)
1337            .collect();
1338        results.unused_namespace_members.retain(|member| {
1339            let key = format!(
1340                "{}:{}.{}",
1341                relative_path(&member.member.path, self.root),
1342                member.member.parent_name,
1343                member.member.member_name
1344            );
1345            !baseline_namespace_members.contains(key.as_str())
1346        });
1347        let baseline_protected_class_members: FxHashSet<&str> = self
1348            .baseline
1349            .unused_protected_class_members
1350            .iter()
1351            .map(String::as_str)
1352            .collect();
1353        results.unused_protected_class_members.retain(|member| {
1354            let key = format!(
1355                "{}:{}.{}",
1356                relative_path(&member.member.path, self.root),
1357                member.member.parent_name,
1358                member.member.member_name
1359            );
1360            !baseline_protected_class_members.contains(key.as_str())
1361        });
1362    }
1363
1364    fn filter_component_surface_members(&self, results: &mut crate::results::AnalysisResults) {
1365        retain_new_by_keys(
1366            &mut results.unprovided_injects,
1367            &self.baseline.unprovided_injects,
1368            self.root,
1369            inject_baseline_keys,
1370        );
1371        retain_new_by_keys(
1372            &mut results.unrendered_components,
1373            &self.baseline.unrendered_components,
1374            self.root,
1375            component_baseline_keys,
1376        );
1377        retain_new_by_keys(
1378            &mut results.unused_component_props,
1379            &self.baseline.unused_component_props,
1380            self.root,
1381            component_prop_baseline_keys,
1382        );
1383        retain_new_by_keys(
1384            &mut results.absent_component_props,
1385            &self.baseline.absent_component_props,
1386            self.root,
1387            absent_component_prop_baseline_keys,
1388        );
1389        retain_new_by_keys(
1390            &mut results.constant_parameters,
1391            &self.baseline.constant_parameters,
1392            self.root,
1393            constant_parameter_baseline_keys,
1394        );
1395        retain_new_by_keys(
1396            &mut results.unused_component_emits,
1397            &self.baseline.unused_component_emits,
1398            self.root,
1399            component_emit_baseline_keys,
1400        );
1401        retain_new_by_keys(
1402            &mut results.unused_component_inputs,
1403            &self.baseline.unused_component_inputs,
1404            self.root,
1405            component_input_baseline_keys,
1406        );
1407        retain_new_by_keys(
1408            &mut results.unused_component_outputs,
1409            &self.baseline.unused_component_outputs,
1410            self.root,
1411            component_output_baseline_keys,
1412        );
1413        retain_new_by_keys(
1414            &mut results.unused_svelte_events,
1415            &self.baseline.unused_svelte_events,
1416            self.root,
1417            svelte_event_baseline_keys,
1418        );
1419        retain_new_by_keys(
1420            &mut results.unused_effect_layers,
1421            &self.baseline.unused_effect_layers,
1422            self.root,
1423            effect_layer_baseline_keys,
1424        );
1425        retain_new_by_keys(
1426            &mut results.unused_tagged_errors,
1427            &self.baseline.unused_tagged_errors,
1428            self.root,
1429            tagged_error_baseline_keys,
1430        );
1431        retain_new_by_keys(
1432            &mut results.unproduced_catch_tags,
1433            &self.baseline.unproduced_catch_tags,
1434            self.root,
1435            catch_tag_baseline_keys,
1436        );
1437    }
1438
1439    fn filter_route_action_members(&self, results: &mut crate::results::AnalysisResults) {
1440        let baseline_unused_server_actions: FxHashSet<&str> = self
1441            .baseline
1442            .unused_server_actions
1443            .iter()
1444            .map(String::as_str)
1445            .collect();
1446        results.unused_server_actions.retain(|finding| {
1447            let key = format!(
1448                "{}:{}",
1449                relative_path(&finding.action.path, self.root),
1450                finding.action.action_name
1451            );
1452            !baseline_unused_server_actions.contains(key.as_str())
1453        });
1454
1455        let baseline_unused_load_data_keys: FxHashSet<&str> = self
1456            .baseline
1457            .unused_load_data_keys
1458            .iter()
1459            .map(String::as_str)
1460            .collect();
1461        results.unused_load_data_keys.retain(|finding| {
1462            let key = format!(
1463                "{}:{}",
1464                relative_path(&finding.key.path, self.root),
1465                finding.key.key_name
1466            );
1467            !baseline_unused_load_data_keys.contains(key.as_str())
1468        });
1469    }
1470
1471    fn filter_unresolved_and_exports(&self, results: &mut crate::results::AnalysisResults) {
1472        let baseline_unresolved: FxHashSet<&str> = self
1473            .baseline
1474            .unresolved_imports
1475            .iter()
1476            .map(String::as_str)
1477            .collect();
1478        results.unresolved_imports.retain(|import| {
1479            let key = format!(
1480                "{}:{}",
1481                relative_path(&import.import.path, self.root),
1482                import.import.specifier
1483            );
1484            !baseline_unresolved.contains(key.as_str())
1485        });
1486
1487        let baseline_unlisted: FxHashSet<&str> = self
1488            .baseline
1489            .unlisted_dependencies
1490            .iter()
1491            .map(String::as_str)
1492            .collect();
1493        results
1494            .unlisted_dependencies
1495            .retain(|dep| !baseline_unlisted.contains(dep.dep.package_name.as_str()));
1496
1497        let baseline_dup_exports: FxHashSet<&str> = self
1498            .baseline
1499            .duplicate_exports
1500            .iter()
1501            .map(String::as_str)
1502            .collect();
1503        results.duplicate_exports.retain(|duplicate| {
1504            let key = duplicate_export_key(&duplicate.export, self.root);
1505            !baseline_dup_exports.contains(key.as_str())
1506        });
1507    }
1508
1509    fn filter_dependency_variants(&self, results: &mut crate::results::AnalysisResults) {
1510        let baseline_optional_deps: FxHashSet<&str> = self
1511            .baseline
1512            .unused_optional_dependencies
1513            .iter()
1514            .map(String::as_str)
1515            .collect();
1516        results.unused_optional_dependencies.retain(|dep| {
1517            let key = package_json_dependency_key(&dep.dep.package_name, &dep.dep.path, self.root);
1518            !baseline_contains_dependency(
1519                &baseline_optional_deps,
1520                &dep.dep.package_name,
1521                key.as_str(),
1522            )
1523        });
1524
1525        self.filter_type_and_test_only_dependencies(results);
1526    }
1527
1528    fn filter_type_and_test_only_dependencies(
1529        &self,
1530        results: &mut crate::results::AnalysisResults,
1531    ) {
1532        let baseline_type_only: FxHashSet<&str> = self
1533            .baseline
1534            .type_only_dependencies
1535            .iter()
1536            .map(String::as_str)
1537            .collect();
1538        results.type_only_dependencies.retain(|dep| {
1539            let key = package_json_dependency_key(&dep.dep.package_name, &dep.dep.path, self.root);
1540            !baseline_contains_dependency(&baseline_type_only, &dep.dep.package_name, key.as_str())
1541        });
1542
1543        let baseline_test_only: FxHashSet<&str> = self
1544            .baseline
1545            .test_only_dependencies
1546            .iter()
1547            .map(String::as_str)
1548            .collect();
1549        results.test_only_dependencies.retain(|dep| {
1550            let key = package_json_dependency_key(&dep.dep.package_name, &dep.dep.path, self.root);
1551            !baseline_contains_dependency(&baseline_test_only, &dep.dep.package_name, key.as_str())
1552        });
1553
1554        let baseline_dev_in_prod: FxHashSet<&str> = self
1555            .baseline
1556            .dev_dependencies_in_production
1557            .iter()
1558            .map(String::as_str)
1559            .collect();
1560        results.dev_dependencies_in_production.retain(|dep| {
1561            let key = package_json_dependency_key(&dep.dep.package_name, &dep.dep.path, self.root);
1562            !baseline_contains_dependency(
1563                &baseline_dev_in_prod,
1564                &dep.dep.package_name,
1565                key.as_str(),
1566            )
1567        });
1568    }
1569
1570    fn filter_boundaries_and_suppressions(&self, results: &mut crate::results::AnalysisResults) {
1571        let baseline_boundary: FxHashSet<&str> = self
1572            .baseline
1573            .boundary_violations
1574            .iter()
1575            .map(String::as_str)
1576            .collect();
1577        results.boundary_violations.retain(|violation| {
1578            let key = boundary_violation_key(&violation.violation, self.root);
1579            !baseline_boundary.contains(key.as_str())
1580        });
1581
1582        self.filter_boundary_details(results);
1583        self.filter_stale_suppressions(results);
1584        self.filter_invalid_client_exports(results);
1585        self.filter_mixed_client_server_barrels(results);
1586        self.filter_misplaced_directives(results);
1587        self.filter_route_collisions(results);
1588        self.filter_dynamic_segment_name_conflicts(results);
1589    }
1590
1591    fn filter_invalid_client_exports(&self, results: &mut crate::results::AnalysisResults) {
1592        let baseline_invalid: FxHashSet<&str> = self
1593            .baseline
1594            .invalid_client_exports
1595            .iter()
1596            .map(String::as_str)
1597            .collect();
1598        results.invalid_client_exports.retain(|finding| {
1599            let key = format!(
1600                "{}:{}",
1601                relative_path(&finding.export.path, self.root),
1602                finding.export.export_name
1603            );
1604            !baseline_invalid.contains(key.as_str())
1605        });
1606    }
1607
1608    fn filter_mixed_client_server_barrels(&self, results: &mut crate::results::AnalysisResults) {
1609        let baseline_barrels: FxHashSet<&str> = self
1610            .baseline
1611            .mixed_client_server_barrels
1612            .iter()
1613            .map(String::as_str)
1614            .collect();
1615        results.mixed_client_server_barrels.retain(|finding| {
1616            let key = format!(
1617                "{}:{}:{}",
1618                relative_path(&finding.barrel.path, self.root),
1619                finding.barrel.client_origin,
1620                finding.barrel.server_origin
1621            );
1622            !baseline_barrels.contains(key.as_str())
1623        });
1624    }
1625
1626    fn filter_misplaced_directives(&self, results: &mut crate::results::AnalysisResults) {
1627        let baseline_directives: FxHashSet<&str> = self
1628            .baseline
1629            .misplaced_directives
1630            .iter()
1631            .map(String::as_str)
1632            .collect();
1633        results.misplaced_directives.retain(|finding| {
1634            let key = format!(
1635                "{}:{}:{}",
1636                relative_path(&finding.directive_site.path, self.root),
1637                finding.directive_site.line,
1638                finding.directive_site.directive
1639            );
1640            !baseline_directives.contains(key.as_str())
1641        });
1642    }
1643
1644    fn filter_route_collisions(&self, results: &mut crate::results::AnalysisResults) {
1645        let baseline_collisions: FxHashSet<&str> = self
1646            .baseline
1647            .route_collisions
1648            .iter()
1649            .map(String::as_str)
1650            .collect();
1651        results.route_collisions.retain(|finding| {
1652            let key = format!(
1653                "{}:{}",
1654                relative_path(&finding.collision.path, self.root),
1655                finding.collision.url
1656            );
1657            !baseline_collisions.contains(key.as_str())
1658        });
1659    }
1660
1661    fn filter_dynamic_segment_name_conflicts(&self, results: &mut crate::results::AnalysisResults) {
1662        let baseline_conflicts: FxHashSet<&str> = self
1663            .baseline
1664            .dynamic_segment_name_conflicts
1665            .iter()
1666            .map(String::as_str)
1667            .collect();
1668        results.dynamic_segment_name_conflicts.retain(|finding| {
1669            let key = format!(
1670                "{}:{}",
1671                relative_path(&finding.conflict.path, self.root),
1672                finding.conflict.position
1673            );
1674            !baseline_conflicts.contains(key.as_str())
1675        });
1676    }
1677
1678    fn filter_boundary_details(&self, results: &mut crate::results::AnalysisResults) {
1679        let baseline_boundary_coverage: FxHashSet<&str> = self
1680            .baseline
1681            .boundary_coverage_violations
1682            .iter()
1683            .map(String::as_str)
1684            .collect();
1685        results.boundary_coverage_violations.retain(|violation| {
1686            let key = relative_path(&violation.violation.path, self.root);
1687            !baseline_boundary_coverage.contains(key.as_str())
1688        });
1689
1690        let baseline_boundary_calls: FxHashSet<&str> = self
1691            .baseline
1692            .boundary_call_violations
1693            .iter()
1694            .map(String::as_str)
1695            .collect();
1696        results.boundary_call_violations.retain(|violation| {
1697            let key = boundary_call_violation_key(&violation.violation, self.root);
1698            !baseline_boundary_calls.contains(key.as_str())
1699        });
1700    }
1701
1702    fn filter_stale_suppressions(&self, results: &mut crate::results::AnalysisResults) {
1703        let baseline_stale: FxHashSet<&str> = self
1704            .baseline
1705            .stale_suppressions
1706            .iter()
1707            .map(String::as_str)
1708            .collect();
1709        results.stale_suppressions.retain(|suppression| {
1710            let key = stale_suppression_baseline_key(suppression, self.root);
1711            let legacy_key = format!(
1712                "{}:{}",
1713                relative_path(&suppression.path, self.root),
1714                suppression.line
1715            );
1716            !baseline_stale.contains(key.as_str()) && !baseline_stale.contains(legacy_key.as_str())
1717        });
1718    }
1719
1720    fn filter_pnpm_entries(&self, results: &mut crate::results::AnalysisResults) {
1721        let baseline_catalog: FxHashSet<&str> = self
1722            .baseline
1723            .unused_catalog_entries
1724            .iter()
1725            .map(String::as_str)
1726            .collect();
1727        results.unused_catalog_entries.retain(|entry| {
1728            let key = format!("{}:{}", entry.entry.catalog_name, entry.entry.entry_name);
1729            !baseline_catalog.contains(key.as_str())
1730        });
1731
1732        let baseline_empty_catalog_groups: FxHashSet<&str> = self
1733            .baseline
1734            .empty_catalog_groups
1735            .iter()
1736            .map(String::as_str)
1737            .collect();
1738        results.empty_catalog_groups.retain(|group| {
1739            !baseline_empty_catalog_groups.contains(group.group.catalog_name.as_str())
1740        });
1741
1742        self.filter_pnpm_references_and_overrides(results);
1743    }
1744
1745    fn filter_pnpm_references_and_overrides(&self, results: &mut crate::results::AnalysisResults) {
1746        let baseline_unresolved: FxHashSet<&str> = self
1747            .baseline
1748            .unresolved_catalog_references
1749            .iter()
1750            .map(String::as_str)
1751            .collect();
1752        results.unresolved_catalog_references.retain(|reference| {
1753            let key = format!(
1754                "{}:{}:{}:{}",
1755                relative_path(&reference.reference.path, self.root),
1756                reference.reference.line,
1757                reference.reference.catalog_name,
1758                reference.reference.entry_name,
1759            );
1760            !baseline_unresolved.contains(key.as_str())
1761        });
1762
1763        self.filter_pnpm_overrides(results);
1764    }
1765
1766    fn filter_pnpm_overrides(&self, results: &mut crate::results::AnalysisResults) {
1767        let baseline_unused_overrides: FxHashSet<&str> = self
1768            .baseline
1769            .unused_dependency_overrides
1770            .iter()
1771            .map(String::as_str)
1772            .collect();
1773        results
1774            .unused_dependency_overrides
1775            .retain(|override_entry| {
1776                let key = format!(
1777                    "{}:{}",
1778                    override_entry.entry.source, override_entry.entry.raw_key
1779                );
1780                !baseline_unused_overrides.contains(key.as_str())
1781            });
1782
1783        let baseline_misconfigured_overrides: FxHashSet<&str> = self
1784            .baseline
1785            .misconfigured_dependency_overrides
1786            .iter()
1787            .map(String::as_str)
1788            .collect();
1789        results
1790            .misconfigured_dependency_overrides
1791            .retain(|override_entry| {
1792                let key = format!(
1793                    "{}:{}",
1794                    override_entry.entry.source, override_entry.entry.raw_key
1795                );
1796                !baseline_misconfigured_overrides.contains(key.as_str())
1797            });
1798    }
1799}
1800
1801/// Filter results to only include issues not present in the baseline.
1802///
1803/// A baseline with an `identity` matches canonical keys by count. A legacy
1804/// baseline matches each entry in its old form, as older fallow versions did.
1805fn filter_new_issues(
1806    results: crate::results::AnalysisResults,
1807    baseline: &BaselineData,
1808    root: &Path,
1809) -> crate::results::AnalysisResults {
1810    if baseline.identity.is_some() {
1811        filter_new_issues_by_canonical_keys(results, baseline, root)
1812    } else {
1813        filter_new_issues_by_legacy_keys(results, baseline, root)
1814    }
1815}
1816
1817fn filter_new_issues_by_canonical_keys(
1818    mut results: crate::results::AnalysisResults,
1819    baseline: &BaselineData,
1820    root: &Path,
1821) -> crate::results::AnalysisResults {
1822    let paths = IdentityPaths::new(root);
1823    macro_rules! retain {
1824        ($($field:ident),* $(,)?) => {
1825            $(retain_unsaved(&mut results.$field, &baseline.$field, &paths);)*
1826        };
1827    }
1828    with_baseline_fields!(retain);
1829    results
1830}
1831
1832/// What a loaded dead-code baseline did to a result.
1833#[derive(Debug, Clone, PartialEq, Eq)]
1834pub enum DeadCodeBaselineOutcome {
1835    /// The file is a dead-code baseline. The findings it holds are removed.
1836    Applied {
1837        /// This run's view of the baseline.
1838        staleness: BaselineStaleness,
1839        /// True when the file has no `identity`, so its entries use the legacy
1840        /// key forms. `--save-baseline` rewrites it with canonical keys.
1841        legacy_keys: bool,
1842    },
1843    /// The file is not a dead-code baseline: another command saved it
1844    /// (`saved_by` names that command), or nothing in it names a writer. It
1845    /// suppresses nothing, so every finding stays.
1846    NotDeadCode {
1847        /// This run's view of the file: zero entries, zero matches.
1848        staleness: BaselineStaleness,
1849        /// The known command that saved the file, when the file names one.
1850        saved_by: Option<BaselineKind>,
1851    },
1852}
1853
1854/// Why a dead-code baseline could not be applied.
1855#[derive(Debug, Clone, PartialEq, Eq)]
1856pub enum DeadCodeBaselineError {
1857    /// The file is not valid JSON, or a dead-code baseline with a missing or
1858    /// wrong field.
1859    Parse(String),
1860    /// The baseline was saved with another analysis identity, for example a
1861    /// type-aware run. The fields that differ are listed.
1862    IncompatibleIdentity(Vec<&'static str>),
1863}
1864
1865/// Apply a dead-code baseline to a result.
1866///
1867/// The CLI (`--baseline`) and the programmatic API read a baseline through this
1868/// one function, so a baseline hides the same findings on every surface.
1869/// `content` is the text of the baseline file. `change_scoped` is true when the
1870/// run analyzed only part of the project; see [`BaselineStaleness`].
1871///
1872/// The file kind is read before the strict parse. Several fields of the
1873/// dead-code format have no default, so another command's baseline would fail
1874/// the parse before anything could name its writer.
1875///
1876/// # Errors
1877///
1878/// Returns [`DeadCodeBaselineError`] when the file is not valid JSON, is a
1879/// broken dead-code baseline, or was saved with an incompatible analysis
1880/// identity.
1881pub fn apply_dead_code_baseline(
1882    results: &mut crate::results::AnalysisResults,
1883    content: &str,
1884    root: &Path,
1885    identity: &fallow_types::semantic::SemanticAnalysisIdentity,
1886    change_scoped: bool,
1887) -> Result<DeadCodeBaselineOutcome, DeadCodeBaselineError> {
1888    let parsed = serde_json::from_str::<serde_json::Value>(content)
1889        .map_err(|err| DeadCodeBaselineError::Parse(err.to_string()))?;
1890    let saved_by = match classify_baseline_value(&parsed, BaselineKind::DeadCode) {
1891        BaselineFileKind::Own | BaselineFileKind::NotAnObject => None,
1892        foreign @ BaselineFileKind::Foreign(_) => Some(foreign.saved_by()),
1893        BaselineFileKind::Unrecognised => Some(None),
1894    };
1895    if let Some(saved_by) = saved_by {
1896        return Ok(DeadCodeBaselineOutcome::NotDeadCode {
1897            staleness: BaselineStaleness {
1898                entries: 0,
1899                matched: 0,
1900                current_findings: results.total_issues(),
1901                change_scoped,
1902            },
1903            saved_by,
1904        });
1905    }
1906    let baseline = serde_json::from_value::<BaselineData>(parsed)
1907        .map_err(|err| DeadCodeBaselineError::Parse(err.to_string()))?;
1908    if let Some(scheme) = baseline.identity.as_deref()
1909        && scheme != BASELINE_KEY_SCHEME
1910    {
1911        return Err(DeadCodeBaselineError::Parse(format!(
1912            "unknown baseline identity `{scheme}`: this fallow version reads `{BASELINE_KEY_SCHEME}` and legacy baselines. Regenerate the file with --save-baseline"
1913        )));
1914    }
1915    let incompatible = baseline.analysis_identity().incompatible_fields(identity);
1916    if !incompatible.is_empty() {
1917        return Err(DeadCodeBaselineError::IncompatibleIdentity(incompatible));
1918    }
1919    let before = baseline_finding_count(results);
1920    let hidden_matched = cascade_hidden_matches(results, &baseline, root);
1921    *results = filter_new_issues(std::mem::take(results), &baseline, root);
1922    Ok(DeadCodeBaselineOutcome::Applied {
1923        staleness: BaselineStaleness {
1924            entries: baseline.total_entries(),
1925            matched: before.saturating_sub(baseline_finding_count(results)) + hidden_matched,
1926            current_findings: before,
1927            change_scoped,
1928        },
1929        legacy_keys: baseline.identity.is_none(),
1930    })
1931}
1932
1933/// Baseline data for duplication comparison.
1934///
1935/// New baselines key every clone group by `<fingerprint>:<instance count>` in
1936/// `normalized_clone_fingerprints`. The fingerprint hashes normalized clone
1937/// content, so an unrelated line shift or formatting-only edit keeps it matched,
1938/// while a token edit or extra copy reports a new finding.
1939///
1940/// `clone_groups` keeps the oldest location keys, while `clone_fingerprints`
1941/// keeps the raw-fragment keys expected by older binaries. New readers prefer
1942/// the normalized field. This makes baselines readable in both directions.
1943#[derive(Default, serde::Serialize, serde::Deserialize)]
1944pub struct DuplicationBaselineData {
1945    /// The command that saved this file. See [`BaselineData::kind`] for why it
1946    /// is written but never read back through this struct.
1947    #[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")]
1948    kind: Option<BaselineKind>,
1949    /// `production` when the saving run used production mode, absent otherwise.
1950    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1951    scope_reasons: Vec<String>,
1952    /// Legacy clone group keys: sorted list of `file:start-end` per group.
1953    #[serde(default)]
1954    pub clone_groups: Vec<String>,
1955    /// Legacy raw-fragment keys expected by older binaries.
1956    #[serde(default)]
1957    pub clone_fingerprints: Vec<String>,
1958    /// Normalized content keys used by current binaries.
1959    #[serde(default)]
1960    pub(crate) normalized_clone_fingerprints: Vec<String>,
1961}
1962
1963impl DuplicationBaselineData {
1964    /// The keys this format writes, for [`declares_baseline_format`].
1965    const DECLARED_KEYS: &'static [&'static str] = &[
1966        "clone_groups",
1967        "clone_fingerprints",
1968        "normalized_clone_fingerprints",
1969    ];
1970
1971    /// Build a duplication baseline from the current report.
1972    pub fn from_report(report: &DuplicationReport, root: &Path) -> Self {
1973        let fingerprints =
1974            crate::duplicates::CloneFingerprintSet::from_groups(&report.clone_groups);
1975        Self {
1976            kind: Some(BaselineKind::Dupes),
1977            scope_reasons: Vec::new(),
1978            clone_groups: report
1979                .clone_groups
1980                .iter()
1981                .map(|g| clone_group_key(g, root))
1982                .collect(),
1983            clone_fingerprints: report
1984                .clone_groups
1985                .iter()
1986                .map(legacy_clone_group_fingerprint_key)
1987                .collect(),
1988            normalized_clone_fingerprints: report
1989                .clone_groups
1990                .iter()
1991                .map(|group| clone_group_fingerprint_key(group, &fingerprints))
1992                .collect(),
1993        }
1994    }
1995
1996    /// True when the baseline holds a key that older versions gave to every
1997    /// clone group whose code did not parse on its own. A re-save replaces it.
1998    #[must_use]
1999    pub fn has_unparsed_collision_keys(&self) -> bool {
2000        self.normalized_clone_fingerprints
2001            .iter()
2002            .any(|key| crate::duplicates::is_unparsed_collision_key(key))
2003    }
2004
2005    /// Number of baseline entries actually used for comparison.
2006    #[must_use]
2007    pub fn entry_count(&self) -> usize {
2008        if !self.normalized_clone_fingerprints.is_empty() {
2009            self.normalized_clone_fingerprints.len()
2010        } else if !self.clone_fingerprints.is_empty() {
2011            self.clone_fingerprints.len()
2012        } else {
2013            self.clone_groups.len()
2014        }
2015    }
2016}
2017
2018/// Generate a stable key for a clone group based on its instance locations.
2019fn clone_group_key(group: &crate::duplicates::CloneGroup, root: &Path) -> String {
2020    let mut parts: Vec<String> = group
2021        .instances
2022        .iter()
2023        .map(|i| {
2024            format!(
2025                "{}:{}-{}",
2026                relative_path(&i.file, root),
2027                i.start_line,
2028                i.end_line
2029            )
2030        })
2031        .collect();
2032    parts.sort();
2033    parts.join("|")
2034}
2035
2036/// Generate the normalized, location-independent key written by new baselines.
2037fn clone_group_fingerprint_key(
2038    group: &crate::duplicates::CloneGroup,
2039    fingerprints: &crate::duplicates::CloneFingerprintSet,
2040) -> String {
2041    fingerprints.ignored_clone_key_for_group(group)
2042}
2043
2044/// Recreate the raw-fragment key written by baseline versions before normalized
2045/// clone identity. Kept only as a read fallback during migration.
2046fn legacy_clone_group_fingerprint_key(group: &crate::duplicates::CloneGroup) -> String {
2047    let representative = group
2048        .instances
2049        .iter()
2050        .min_by(|a, b| (a.file.as_path(), a.start_line).cmp(&(b.file.as_path(), b.start_line)))
2051        .map_or("", |i| i.fragment.as_str());
2052    let hash = if representative.as_bytes().contains(&b'\r') {
2053        xxhash_rust::xxh3::xxh3_64(representative.replace('\r', "").as_bytes())
2054    } else {
2055        xxhash_rust::xxh3::xxh3_64(representative.as_bytes())
2056    };
2057    format!(
2058        "{}{:08x}:{}",
2059        crate::duplicates::FINGERPRINT_PREFIX,
2060        hash as u32,
2061        group.instances.len()
2062    )
2063}
2064
2065fn consume_baseline_key(remaining: &mut FxHashMap<&str, usize>, key: &str) -> bool {
2066    match remaining.get_mut(key) {
2067        Some(count) if *count > 0 => {
2068            *count -= 1;
2069            true
2070        }
2071        _ => false,
2072    }
2073}
2074
2075/// Filter a duplication report to only include clone groups not present in the baseline.
2076///
2077/// Baselines carrying `normalized_clone_fingerprints` compare on normalized
2078/// content plus instance count. Older raw fingerprints and location keys remain
2079/// supported as fallbacks.
2080pub fn filter_new_clone_groups(
2081    mut report: DuplicationReport,
2082    baseline: &DuplicationBaselineData,
2083    root: &Path,
2084) -> DuplicationReport {
2085    if !baseline.normalized_clone_fingerprints.is_empty() {
2086        let fingerprints =
2087            crate::duplicates::CloneFingerprintSet::from_groups(&report.clone_groups);
2088        let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
2089        for key in &baseline.normalized_clone_fingerprints {
2090            *remaining.entry(key.as_str()).or_insert(0) += 1;
2091        }
2092        report.clone_groups.retain(|group| {
2093            let key = clone_group_fingerprint_key(group, &fingerprints);
2094            !consume_baseline_key(&mut remaining, &key)
2095        });
2096    } else if baseline.clone_fingerprints.is_empty() {
2097        let baseline_keys: FxHashSet<&str> =
2098            baseline.clone_groups.iter().map(String::as_str).collect();
2099        report.clone_groups.retain(|g| {
2100            let key = clone_group_key(g, root);
2101            !baseline_keys.contains(key.as_str())
2102        });
2103    } else {
2104        let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
2105        for key in &baseline.clone_fingerprints {
2106            *remaining.entry(key.as_str()).or_insert(0) += 1;
2107        }
2108        report.clone_groups.retain(|group| {
2109            let key = legacy_clone_group_fingerprint_key(group);
2110            !consume_baseline_key(&mut remaining, &key)
2111        });
2112    }
2113
2114    crate::duplicates::refresh_scoped_report(&mut report, root);
2115
2116    report
2117}
2118
2119/// Recompute duplication statistics after filtering (baseline or `--changed-since`).
2120///
2121/// Covered lines are the union of the line ranges of each file, so
2122/// overlapping clone instances do not count a line two times.
2123pub fn recompute_stats(report: &DuplicationReport) -> crate::duplicates::DuplicationStats {
2124    crate::duplicates::recompute_stats(report)
2125}
2126
2127/// Baseline data for health (complexity) comparison.
2128///
2129/// New baselines store count-per-category-per-file data in `finding_counts` so
2130/// line shifts do not leak pre-existing findings. Legacy baselines with
2131/// `findings: ["path:name:line"]` still load so users can refresh them in
2132/// place with `--save-baseline`.
2133///
2134/// `identity_finding_counts` carries the same counts bucketed per function
2135/// identity instead of per file, for the stricter [`HealthBaselineMode::Identity`]
2136/// comparison. It is written only when the baseline is saved in identity mode,
2137/// so default baselines keep their count-only shape. Identity baselines still
2138/// carry `finding_counts`, so they also work in count mode and with older
2139/// binaries.
2140#[derive(Default, serde::Serialize, serde::Deserialize)]
2141pub struct HealthBaselineData {
2142    /// The command that saved this file. See [`BaselineData::kind`] for why it
2143    /// is written but never read back through this struct.
2144    #[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")]
2145    pub(crate) kind: Option<BaselineKind>,
2146    /// `production` when the saving run used production mode, absent otherwise.
2147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2148    pub(crate) scope_reasons: Vec<String>,
2149    /// Legacy health baseline keys: `relative_path:function_name:line`.
2150    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2151    pub(crate) findings: Vec<String>,
2152    /// Count-per-category-per-file baseline buckets.
2153    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2154    pub(crate) finding_counts: HealthFindingCountMap,
2155    /// Count-per-category buckets keyed by `relative_path\0function_name`.
2156    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2157    pub(crate) identity_finding_counts: HealthFindingCountMap,
2158    /// Stable runtime-coverage finding IDs from the sidecar.
2159    #[serde(default)]
2160    pub(crate) runtime_coverage_findings: Vec<String>,
2161    /// Line-move-tolerant runtime-coverage suppression keys of the form
2162    /// `path\0name\0source_hash`. Unlike `runtime_coverage_findings` (whose
2163    /// keys hash the start line and so churn when a function moves), the
2164    /// `source_hash` component is the content digest of the function body, so a
2165    /// moved-but-unedited function keeps the same key and stays suppressed.
2166    /// Only findings whose `source_hash` is present contribute an entry.
2167    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2168    pub(crate) runtime_coverage_source_hashes: Vec<String>,
2169    /// Refactoring target keys: `relative_path:category`.
2170    #[serde(default)]
2171    pub(crate) target_keys: Vec<String>,
2172    /// `true` when the counts hold file-length findings as `file_lines_*`. A
2173    /// file without the marker holds them as `complexity_*`, and a run reads
2174    /// it that way. See `FileLengthCounting`.
2175    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2176    pub(crate) file_lines_categories: bool,
2177}
2178
2179/// Serialized per-bucket finding tally inside a health baseline file.
2180#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
2181pub struct HealthBaselineCount {
2182    count: usize,
2183}
2184
2185type HealthFindingCountMap = BTreeMap<String, BTreeMap<String, HealthBaselineCount>>;
2186
2187/// How a saved health baseline is matched against current findings.
2188#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2189pub enum HealthBaselineMode {
2190    /// Match per file and finding category. Resilient to renames and line
2191    /// shifts, but a replacement hotspot consumes the allowance of the hotspot
2192    /// it replaced.
2193    ///
2194    /// Count buckets do not survive file moves: the bucket key is the path and
2195    /// the payload is category tallies alone, so a bucket whose file moved has
2196    /// no surviving identity component to re-match on. Guessing a new path
2197    /// from count shapes could silently transfer allowance between unrelated
2198    /// files, so no move tolerance is attempted in this mode.
2199    #[default]
2200    Count,
2201    /// Match per function identity (path plus function name) and finding
2202    /// category. A hotspot that replaces another hotspot in the same file is
2203    /// reported, while line shifts and in-place edits stay suppressed.
2204    ///
2205    /// Identity buckets tolerate file moves conservatively: a bucket whose
2206    /// path no longer exists on disk follows its function name to a new path
2207    /// when exactly one unclaimed current bucket carries that name, resolved
2208    /// by `moved_identity_bucket_remaps`.
2209    Identity,
2210}
2211
2212impl HealthBaselineData {
2213    /// The keys this format writes, for [`declares_baseline_format`]. A health
2214    /// baseline omits the buckets it has nothing for, so a file carrying any
2215    /// one of these is health's own.
2216    const DECLARED_KEYS: &'static [&'static str] = &[
2217        "findings",
2218        "finding_counts",
2219        "identity_finding_counts",
2220        "runtime_coverage_findings",
2221        "runtime_coverage_source_hashes",
2222        "target_keys",
2223    ];
2224
2225    /// Build a health baseline from findings and targets.
2226    pub(crate) fn from_findings(
2227        findings: &[fallow_output::ComplexityViolation],
2228        runtime_coverage_findings: &[fallow_output::RuntimeCoverageFinding],
2229        targets: &[fallow_output::RefactoringTarget],
2230        root: &Path,
2231    ) -> Self {
2232        Self {
2233            kind: Some(BaselineKind::Health),
2234            scope_reasons: Vec::new(),
2235            findings: Vec::new(),
2236            finding_counts: health_finding_counts(
2237                findings,
2238                root,
2239                HealthBaselineMode::Count,
2240                FileLengthCounting::Separate,
2241            ),
2242            identity_finding_counts: HealthFindingCountMap::new(),
2243            runtime_coverage_findings: runtime_coverage_findings
2244                .iter()
2245                .map(|f| runtime_coverage_finding_key(f, root))
2246                .collect(),
2247            runtime_coverage_source_hashes: runtime_coverage_findings
2248                .iter()
2249                .filter_map(|f| runtime_coverage_source_hash_key(f, root))
2250                .collect(),
2251            target_keys: targets
2252                .iter()
2253                .map(|t| target_baseline_key(t, root))
2254                .collect(),
2255            file_lines_categories: true,
2256        }
2257    }
2258
2259    pub(crate) fn finding_entry_count(&self) -> usize {
2260        if self.finding_counts.is_empty() {
2261            self.findings.len()
2262        } else {
2263            self.finding_counts
2264                .values()
2265                .flat_map(BTreeMap::values)
2266                .map(|entry| entry.count)
2267                .sum()
2268        }
2269    }
2270
2271    /// Add per-function identity buckets to a saved baseline.
2272    ///
2273    /// Only [`HealthBaselineMode::Identity`] saves record these, so a default
2274    /// baseline keeps carrying counts alone and stays free of function names.
2275    #[must_use]
2276    pub(crate) fn with_identity(
2277        mut self,
2278        findings: &[fallow_output::ComplexityViolation],
2279        root: &Path,
2280    ) -> Self {
2281        self.identity_finding_counts = health_finding_counts(
2282            findings,
2283            root,
2284            HealthBaselineMode::Identity,
2285            self.file_length_counting(),
2286        );
2287        self
2288    }
2289
2290    /// `true` when identity matching would silently degrade because the saved
2291    /// baseline predates `identity_finding_counts` yet does carry findings.
2292    pub(crate) fn lacks_identity_data(&self) -> bool {
2293        self.identity_finding_counts.is_empty()
2294            && (!self.finding_counts.is_empty() || !self.findings.is_empty())
2295    }
2296
2297    fn counts_for(&self, mode: HealthBaselineMode) -> &HealthFindingCountMap {
2298        match mode {
2299            HealthBaselineMode::Count => &self.finding_counts,
2300            HealthBaselineMode::Identity => &self.identity_finding_counts,
2301        }
2302    }
2303}
2304
2305/// Baseline entry overlap for one run, split so followed file moves stay
2306/// observable in output rather than silently absorbed into the match count.
2307pub(crate) struct HealthBaselineOverlap {
2308    /// Entries that matched a current finding, including via followed moves.
2309    pub(crate) matched_entries: usize,
2310    /// Entries that matched only because a retired identity bucket was
2311    /// re-keyed to a moved file.
2312    pub(crate) moved_entries: usize,
2313}
2314
2315/// Generate a stable key for a refactoring target: `relative_path:category`.
2316fn target_baseline_key(target: &fallow_output::RefactoringTarget, root: &Path) -> String {
2317    format!(
2318        "{}:{}",
2319        relative_path(&target.path, root),
2320        target.category.label()
2321    )
2322}
2323
2324/// Generate a stable key for a health finding.
2325fn health_finding_key(finding: &fallow_output::ComplexityViolation, root: &Path) -> String {
2326    format!(
2327        "{}:{}:{}",
2328        relative_path(&finding.path, root),
2329        finding.name,
2330        finding.line
2331    )
2332}
2333
2334/// Bucket a finding belongs to for the given comparison mode.
2335///
2336/// The NUL separator keeps the identity bucket unambiguous for paths and
2337/// function names that contain `:`.
2338fn health_bucket_key(
2339    finding: &fallow_output::ComplexityViolation,
2340    root: &Path,
2341    mode: HealthBaselineMode,
2342) -> String {
2343    let path = relative_path(&finding.path, root);
2344    match mode {
2345        HealthBaselineMode::Count => path,
2346        HealthBaselineMode::Identity => format!("{path}\0{}", finding.name),
2347    }
2348}
2349
2350fn identity_bucket_parts(key: &str) -> Option<(&str, &str)> {
2351    key.split_once('\0')
2352}
2353
2354/// Conservative file-move tolerance for identity baseline buckets.
2355///
2356/// A baseline bucket follows its function to a new path only when every one of
2357/// these holds:
2358///
2359/// - the bucket matched no current bucket at its saved path,
2360/// - the saved path no longer exists on disk under the project root, so the
2361///   file was moved or deleted rather than merely fixed,
2362/// - exactly one current bucket carries the same function name at a path the
2363///   baseline does not already cover,
2364/// - no other retired baseline bucket claims that same candidate.
2365///
2366/// The function name is the only identity component that survives a move, so
2367/// anything more permissive would risk transferring allowance between
2368/// unrelated functions. Anonymous placeholders never match. The result is
2369/// deterministic: both maps iterate in `BTreeMap` order and the
2370/// exactly-one rules make the outcome independent of iteration order.
2371fn moved_identity_bucket_remaps(
2372    baseline_counts: &HealthFindingCountMap,
2373    current_counts: &HealthFindingCountMap,
2374    root: &Path,
2375) -> Vec<(String, String)> {
2376    let mut candidates_by_name: FxHashMap<&str, Vec<&str>> = FxHashMap::default();
2377    for key in current_counts.keys() {
2378        if baseline_counts.contains_key(key) {
2379            continue;
2380        }
2381        if let Some((_, name)) = identity_bucket_parts(key)
2382            && !is_anonymous_function_name(name)
2383        {
2384            candidates_by_name.entry(name).or_default().push(key);
2385        }
2386    }
2387
2388    let mut proposals: Vec<(&str, &str)> = Vec::new();
2389    let mut claims: FxHashMap<&str, usize> = FxHashMap::default();
2390    for key in baseline_counts.keys() {
2391        if current_counts.contains_key(key.as_str()) {
2392            continue;
2393        }
2394        let Some((path, name)) = identity_bucket_parts(key) else {
2395            continue;
2396        };
2397        if is_anonymous_function_name(name) || root.join(path).exists() {
2398            continue;
2399        }
2400        if let Some(candidates) = candidates_by_name.get(name)
2401            && let [only_candidate] = candidates.as_slice()
2402        {
2403            proposals.push((key.as_str(), only_candidate));
2404            *claims.entry(only_candidate).or_default() += 1;
2405        }
2406    }
2407
2408    proposals
2409        .into_iter()
2410        .filter(|(_, candidate)| claims.get(candidate) == Some(&1))
2411        .map(|(old, new)| (old.to_string(), new.to_string()))
2412        .collect()
2413}
2414
2415fn runtime_coverage_finding_key(
2416    finding: &fallow_output::RuntimeCoverageFinding,
2417    _root: &Path,
2418) -> String {
2419    finding
2420        .stable_id
2421        .clone()
2422        .unwrap_or_else(|| finding.id.clone())
2423}
2424
2425/// Line-move-tolerant writer key: `path\0name\0source_hash`.
2426///
2427/// Returns `None` when the finding carries no `source_hash` (e.g. a 0.5-shape
2428/// sidecar or an un-migrated producer); such findings fall back to the
2429/// line-sensitive `runtime_coverage_finding_key` for suppression. The NUL
2430/// separator avoids collisions with paths/names that contain `:`.
2431fn runtime_coverage_source_hash_key(
2432    finding: &fallow_output::RuntimeCoverageFinding,
2433    root: &Path,
2434) -> Option<String> {
2435    finding.source_hash.as_deref().map(|hash| {
2436        format!(
2437            "{}\0{}\0{}",
2438            relative_path(&finding.path, root),
2439            finding.function,
2440            hash
2441        )
2442    })
2443}
2444
2445pub(crate) fn filter_new_runtime_coverage_findings(
2446    mut findings: Vec<fallow_output::RuntimeCoverageFinding>,
2447    baseline: &HealthBaselineData,
2448    root: &Path,
2449) -> Vec<fallow_output::RuntimeCoverageFinding> {
2450    let baseline_keys: FxHashSet<&str> = baseline
2451        .runtime_coverage_findings
2452        .iter()
2453        .map(String::as_str)
2454        .collect();
2455    let baseline_source_hash_keys: FxHashSet<&str> = baseline
2456        .runtime_coverage_source_hashes
2457        .iter()
2458        .map(String::as_str)
2459        .collect();
2460    findings.retain(|finding| {
2461        let suppressed_by_stable_id = finding
2462            .stable_id
2463            .as_deref()
2464            .is_some_and(|id| baseline_keys.contains(id));
2465        let suppressed_by_legacy_id = baseline_keys.contains(finding.id.as_str());
2466        let suppressed_by_source_hash = runtime_coverage_source_hash_key(finding, root)
2467            .is_some_and(|key| baseline_source_hash_keys.contains(key.as_str()));
2468        !(suppressed_by_stable_id || suppressed_by_legacy_id || suppressed_by_source_hash)
2469    });
2470    findings
2471}
2472
2473/// Filter refactoring targets to only include those not present in the baseline.
2474pub(crate) fn filter_new_health_targets(
2475    mut targets: Vec<fallow_output::RefactoringTarget>,
2476    baseline: &HealthBaselineData,
2477    root: &Path,
2478) -> Vec<fallow_output::RefactoringTarget> {
2479    let baseline_keys: FxHashSet<&str> = baseline.target_keys.iter().map(String::as_str).collect();
2480    targets.retain(|t| {
2481        let key = target_baseline_key(t, root);
2482        !baseline_keys.contains(key.as_str())
2483    });
2484    targets
2485}
2486
2487/// Per-category delta between current results and a baseline.
2488#[derive(Debug, Clone, serde::Serialize)]
2489pub struct CategoryDelta {
2490    /// Finding count in the current run.
2491    pub current: usize,
2492    /// Finding count recorded in the baseline.
2493    pub baseline: usize,
2494    /// `current - baseline`; positive means new findings appeared.
2495    pub delta: i64,
2496}
2497
2498/// Deltas between current analysis results and a saved baseline.
2499///
2500/// Used in combined mode to show +/- counts in the failure summary and
2501/// to emit `baseline_deltas` in JSON output.
2502#[derive(Debug, Clone)]
2503pub struct BaselineDeltas {
2504    /// Net change in total issue count (positive = more issues).
2505    pub total_delta: i64,
2506    /// Per-category deltas keyed by category name.
2507    pub per_category: Vec<(String, CategoryDelta)>,
2508}
2509
2510#[cfg(test)]
2511#[path = "baseline_tests.rs"]
2512mod tests;