Skip to main content

fallow_engine/baseline/
mod.rs

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