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