Skip to main content

fallow_engine/baseline/
mod.rs

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