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