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