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