Skip to main content

fallow_engine/baseline/
mod.rs

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