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