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