Skip to main content

fallow_api/
audit_keys.rs

1use std::collections::hash_map::DefaultHasher;
2use std::hash::{Hash, Hasher};
3use std::path::Path;
4
5use rustc_hash::{FxHashMap, FxHashSet};
6
7#[path = "audit_keys_collection.rs"]
8mod collection;
9#[macro_use]
10#[path = "audit_keys_ledger_collections.rs"]
11mod ledger_collections;
12#[path = "audit_keys_styling.rs"]
13mod styling;
14
15pub use styling::{
16    styling_finding_key, styling_keys, styling_ledger_keys, styling_ledger_keys_with_diff,
17};
18
19use collection::AuditCollection;
20
21use fallow_config::{ResolvedConfig, Severity};
22use fallow_types::envelope::AuditIntroduced;
23use fallow_types::identity::{IdentifiedFinding, IdentityPaths, dead_code_occurrence_keys};
24
25pub use crate::audit_complexity::{
26    ChangedPaths, ComplexityBaseline, ComplexityClass, ComplexityMetrics,
27    classify_complexity_attribution, classify_complexity_attribution_against_all,
28    classify_complexity_attribution_against_all_with_moves,
29    classify_complexity_attribution_with_moves, classify_complexity_findings,
30    classify_complexity_findings_against_all, complexity_baseline, complexity_baseline_keys,
31    complexity_ledger_keys, remap_complexity_baseline_for_renames,
32};
33
34/// One dead-code finding classified for audit comparison.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct AuditFindingRecord {
37    /// JSON collection containing the finding.
38    pub collection: &'static str,
39    /// Stable position inside the collection for typed annotation routing.
40    pub ordinal: usize,
41    /// Stable cross-run identity used for base comparison.
42    pub stable_key: String,
43    /// Whether the finding is absent from the base snapshot.
44    pub introduced: bool,
45    /// Effective rule severity after per-file overrides.
46    pub effective_severity: Severity,
47}
48
49fn is_counted_dead_code_finding(collection: &str, severity: Severity) -> bool {
50    severity != Severity::Off
51        && (!fallow_types::results::ERROR_ONLY_RESULT_KEYS.contains(&collection)
52            || severity == Severity::Error)
53}
54
55/// Exhaustive dead-code comparison ledger shared by audit verdict and output.
56#[derive(Debug, Clone, Default)]
57pub struct DeadCodeAuditLedger {
58    records: Vec<AuditFindingRecord>,
59    keys: FxHashSet<String>,
60    introduced_keys: FxHashSet<String>,
61    inherited_keys: FxHashSet<String>,
62    #[cfg(test)]
63    classifications: usize,
64}
65
66impl DeadCodeAuditLedger {
67    /// Classified findings in deterministic output order.
68    #[must_use]
69    pub fn records(&self) -> &[AuditFindingRecord] {
70        &self.records
71    }
72
73    /// Stable current-run key set for cache snapshots and graph hashes.
74    #[must_use]
75    pub const fn keys(&self) -> &FxHashSet<String> {
76        &self.keys
77    }
78
79    #[cfg(test)]
80    const fn classification_count(&self) -> usize {
81        self.classifications
82    }
83
84    /// Number of visible findings introduced since the base snapshot.
85    #[must_use]
86    pub fn introduced_count(&self) -> usize {
87        self.introduced_keys.len()
88    }
89
90    /// Number of counted findings whose effective severity is not off.
91    /// Advisory component findings remain available in the records.
92    #[must_use]
93    pub fn visible_count(&self) -> usize {
94        self.records
95            .iter()
96            .filter(|record| {
97                is_counted_dead_code_finding(record.collection, record.effective_severity)
98            })
99            .count()
100    }
101
102    /// Number of counted findings that are introduced, with the filter of
103    /// [`Self::visible_count`]. This is the dead-code count of a report that
104    /// keeps only introduced findings.
105    #[must_use]
106    pub fn visible_introduced_count(&self) -> usize {
107        self.records
108            .iter()
109            .filter(|record| {
110                record.introduced
111                    && is_counted_dead_code_finding(record.collection, record.effective_severity)
112            })
113            .count()
114    }
115
116    /// Number of visible findings inherited from the base snapshot.
117    #[must_use]
118    pub fn inherited_count(&self) -> usize {
119        self.inherited_keys.len()
120    }
121
122    /// Whether an introduced finding has effective error severity.
123    #[must_use]
124    pub fn has_introduced_errors(&self) -> bool {
125        self.records
126            .iter()
127            .any(|record| record.introduced && record.effective_severity == Severity::Error)
128    }
129    /// Whether an introduced finding has effective warning severity.
130    #[must_use]
131    pub fn has_introduced_warnings(&self) -> bool {
132        self.records
133            .iter()
134            .any(|record| record.introduced && record.effective_severity == Severity::Warn)
135    }
136    /// Demote introduced findings that have no syntactic counterpart in the
137    /// current head run to inherited (advisory) status.
138    ///
139    /// Used by the audit's degraded type-aware path: when base and head
140    /// semantic identities cannot be compared, attribution diffs the
141    /// pre-refinement syntactic key sets. A head finding absent from its own
142    /// syntactic set exists only because of semantic evidence and cannot be
143    /// attributed against a syntactic base, so it must not fail the new-only
144    /// gate. Findings present syntactically keep their classification, so a
145    /// genuinely new syntactic finding still gates.
146    pub fn demote_unattributable_introductions(&mut self, head_syntactic: &FxHashSet<String>) {
147        for record in &mut self.records {
148            if record.introduced && !head_syntactic.contains(&record.stable_key) {
149                record.introduced = false;
150                self.introduced_keys.remove(&record.stable_key);
151                if is_counted_dead_code_finding(record.collection, record.effective_severity) {
152                    self.inherited_keys.insert(record.stable_key.clone());
153                }
154            }
155        }
156    }
157    /// Mark the introduced findings whose keys are in `inherit` as inherited:
158    /// each one matches a base finding under another key.
159    pub fn inherit_introductions(&mut self, inherit: &FxHashSet<String>) {
160        for record in &mut self.records {
161            if record.introduced && inherit.contains(&record.stable_key) {
162                record.introduced = false;
163                self.introduced_keys.remove(&record.stable_key);
164                if is_counted_dead_code_finding(record.collection, record.effective_severity) {
165                    self.inherited_keys.insert(record.stable_key.clone());
166                }
167            }
168        }
169    }
170    /// Persist comparison membership into existing typed output fields.
171    ///
172    /// `StaleSuppression` is the sole legacy finding without a typed
173    /// `introduced` slot. Its serializer keeps a narrow stable-key fallback.
174    pub fn annotate_results(&self, results: &mut fallow_types::results::AnalysisResults) {
175        macro_rules! annotate {
176            (@no_slot $field:ident, $collection:literal) => {
177                let _ = $field;
178            };
179            ($field:ident, $collection:literal) => {
180                for (item, introduced) in $field.iter_mut().zip(self.flags($collection)) {
181                    item.introduced = Some(AuditIntroduced(introduced));
182                }
183            };
184        }
185        for_each_ledger_collection!(results, annotate);
186    }
187
188    /// Remove every finding that the base snapshot already holds. A finding
189    /// without a ledger record stays, so the filter never hides a finding
190    /// that the comparison did not classify.
191    pub fn retain_introduced_results(&self, results: &mut fallow_types::results::AnalysisResults) {
192        macro_rules! retain {
193            ($(@no_slot)? $field:ident, $collection:literal) => {
194                let mut flags = self.flags($collection);
195                $field.retain(|_| flags.next().unwrap_or(true));
196            };
197        }
198        for_each_ledger_collection!(results, retain);
199    }
200
201    /// The introduced flag of each record of `collection`, in output order.
202    fn flags<'a>(&'a self, collection: &'a str) -> impl Iterator<Item = bool> + 'a {
203        self.records
204            .iter()
205            .filter(move |record| record.collection == collection)
206            .map(|record| record.introduced)
207    }
208}
209
210/// Stable-key membership for one non-dead-code audit domain.
211#[derive(Debug, Clone, Default)]
212pub struct AuditDomainLedger {
213    records: Vec<(String, bool)>,
214    keys: FxHashSet<String>,
215    introduced_keys: FxHashSet<String>,
216    inherited_keys: FxHashSet<String>,
217    demoted_keys: FxHashSet<String>,
218}
219
220impl AuditDomainLedger {
221    /// Compare ordered stable keys against an optional base snapshot.
222    #[must_use]
223    pub fn compare(
224        keys: impl IntoIterator<Item = String>,
225        base: Option<&FxHashSet<String>>,
226    ) -> Self {
227        let mut records = Vec::new();
228        let mut unique_keys = FxHashSet::default();
229        let mut introduced_keys = FxHashSet::default();
230        let mut inherited_keys = FxHashSet::default();
231        for key in keys {
232            let introduced = base.is_some_and(|base| !base.contains(&key));
233            if base.is_some() {
234                if introduced {
235                    introduced_keys.insert(key.clone());
236                } else {
237                    inherited_keys.insert(key.clone());
238                }
239            }
240            unique_keys.insert(key.clone());
241            records.push((key, introduced));
242        }
243        Self {
244            records,
245            keys: unique_keys,
246            introduced_keys,
247            inherited_keys,
248            demoted_keys: FxHashSet::default(),
249        }
250    }
251
252    /// Build a ledger from keys that the caller already classified, in
253    /// typed output order. `has_base` is false when the run has no base
254    /// snapshot, so no finding counts as introduced or inherited.
255    #[must_use]
256    pub fn from_classified(
257        records: impl IntoIterator<Item = (String, bool)>,
258        has_base: bool,
259    ) -> Self {
260        let mut ledger = Self::default();
261        for (key, introduced) in records {
262            let introduced = has_base && introduced;
263            if has_base {
264                if introduced {
265                    ledger.introduced_keys.insert(key.clone());
266                } else {
267                    ledger.inherited_keys.insert(key.clone());
268                }
269            }
270            ledger.keys.insert(key.clone());
271            ledger.records.push((key, introduced));
272        }
273        ledger
274    }
275
276    /// Stable current-run key set.
277    #[must_use]
278    pub const fn keys(&self) -> &FxHashSet<String> {
279        &self.keys
280    }
281
282    /// Number of introduced findings.
283    #[must_use]
284    pub fn introduced_count(&self) -> usize {
285        self.introduced_keys.len()
286    }
287
288    /// Number of inherited findings.
289    #[must_use]
290    pub fn inherited_count(&self) -> usize {
291        self.inherited_keys.len()
292    }
293
294    /// Introduced membership in typed output order.
295    pub fn introduced(&self) -> impl ExactSizeIterator<Item = bool> + '_ {
296        self.records.iter().map(|(_, introduced)| *introduced)
297    }
298
299    /// Number of findings demoted from introduced to inherited. Demoted
300    /// findings stay counted as inherited, so
301    /// `demoted_count() <= inherited_count()` holds by construction.
302    #[must_use]
303    pub fn demoted_count(&self) -> usize {
304        self.demoted_keys.len()
305    }
306
307    /// Keys demoted from introduced to inherited by
308    /// [`Self::demote_introductions`].
309    #[must_use]
310    pub const fn demoted_keys(&self) -> &FxHashSet<String> {
311        &self.demoted_keys
312    }
313
314    /// Demoted membership in typed output order, parallel to
315    /// [`Self::introduced`].
316    pub fn demoted(&self) -> impl ExactSizeIterator<Item = bool> + '_ {
317        self.records
318            .iter()
319            .map(|(key, _)| self.demoted_keys.contains(key))
320    }
321
322    /// Demote introduced findings whose keys are in `demote` to inherited
323    /// (advisory) status so they no longer fail the new-only gate. Each key
324    /// actually flipped is recorded so output surfaces can report the
325    /// demotion (issue #2220).
326    pub fn demote_introductions(&mut self, demote: &FxHashSet<String>) {
327        for (key, introduced) in &mut self.records {
328            if *introduced && demote.contains(key) {
329                *introduced = false;
330                self.introduced_keys.remove(key);
331                self.inherited_keys.insert(key.clone());
332                self.demoted_keys.insert(key.clone());
333            }
334        }
335    }
336
337    /// Whether the finding with `key` is introduced.
338    #[must_use]
339    pub fn is_introduced(&self, key: &str) -> bool {
340        self.introduced_keys.contains(key)
341    }
342
343    /// Mark introduced findings whose keys are in `inherit` as inherited.
344    /// Unlike [`Self::demote_introductions`], this records no demotion: the
345    /// finding matches a base finding, only its key changed.
346    pub fn inherit_introductions(&mut self, inherit: &FxHashSet<String>) {
347        for (key, introduced) in &mut self.records {
348            if *introduced && inherit.contains(key) {
349                *introduced = false;
350                self.introduced_keys.remove(key);
351                self.inherited_keys.insert(key.clone());
352            }
353        }
354    }
355}
356
357/// One-pass audit comparison shared by attribution, verdict, and annotations.
358#[derive(Debug, Clone, Default)]
359pub struct AuditComparison {
360    /// Dead-code finding ledger with effective severity routing.
361    pub dead_code: DeadCodeAuditLedger,
362    /// Complexity finding membership.
363    pub health: AuditDomainLedger,
364    /// Attribution class of each complexity finding, in report order. Empty
365    /// without a base snapshot.
366    pub health_classes: Vec<crate::audit_complexity::ComplexityClass>,
367    /// Duplication group membership. The introduced flag of a group is the
368    /// gate result of its region.
369    pub dupes: AuditDomainLedger,
370    /// The clone regions: the head groups whose instances overlap, with a
371    /// grade each. Empty until the audit grades them, or without a base.
372    pub dupe_regions: crate::audit_run::CloneRegions,
373    /// Styling finding membership.
374    pub styling: AuditDomainLedger,
375}
376
377impl AuditComparison {
378    /// Number of clone regions that fail the gate. Without graded regions,
379    /// the number of introduced clone groups.
380    #[must_use]
381    pub fn duplication_introduced_count(&self) -> usize {
382        if self.dupe_regions.regions().is_empty() {
383            self.dupes.introduced_count()
384        } else {
385            self.dupe_regions.introduced_count()
386        }
387    }
388
389    /// Number of clone regions that do not fail the gate. Without graded
390    /// regions, the number of inherited clone groups.
391    #[must_use]
392    pub fn duplication_inherited_count(&self) -> usize {
393        if self.dupe_regions.regions().is_empty() {
394            self.dupes.inherited_count()
395        } else {
396            self.dupe_regions.inherited_count()
397        }
398    }
399
400    /// Number of complexity findings whose attribution is `worsened`.
401    #[must_use]
402    pub fn complexity_worsened_count(&self) -> usize {
403        self.health_classes
404            .iter()
405            .filter(|class| class.is_worsened())
406            .count()
407    }
408
409    /// Reclassify worsened complexity findings as inherited when `worsened`
410    /// is `audit.worsened: off`. Growth of an exceeded metric stays worsened,
411    /// see [`ComplexityClass::clear_worsened_for_off`].
412    pub fn clear_worsened_when_off(&mut self, worsened: fallow_config::AuditWorsened) {
413        if worsened != fallow_config::AuditWorsened::Off {
414            return;
415        }
416        for class in &mut self.health_classes {
417            class.clear_worsened_for_off();
418        }
419    }
420}
421
422/// Remap root-relative path tokens inside base-snapshot attribution keys so a
423/// finding on a renamed file matches its base counterpart under the old path.
424///
425/// `renames` maps base-relative old paths to head-relative new paths, both in
426/// [`relative_key_path`] form. Keys embed paths as whole `:`-separated
427/// segments, with sorted `|`-separated path lists inside one segment for
428/// multi-file findings (duplication groups, circular dependencies, duplicate
429/// exports). Segments are remapped only on an exact path match, and
430/// multi-path list segments are re-sorted after remapping so they stay
431/// canonical. Non-path segments (names, lines, hashes) never collide with a
432/// relative path and pass through unchanged.
433#[must_use]
434#[expect(
435    clippy::implicit_hasher,
436    reason = "fallow standardizes on FxHashMap/FxHashSet across audit attribution keys"
437)]
438pub fn remap_keys_for_renames(
439    keys: &FxHashSet<String>,
440    renames: &FxHashMap<String, String>,
441) -> FxHashSet<String> {
442    keys.iter()
443        .map(|key| remap_key_for_renames(key, renames))
444        .collect()
445}
446
447pub(crate) fn remap_key_for_renames(key: &str, renames: &FxHashMap<String, String>) -> String {
448    let renamed = |segment: &str| {
449        if segment.contains('|') {
450            segment
451                .split('|')
452                .any(|piece| renamed_set_member(piece, renames).is_some())
453        } else {
454            renamed_part(segment, renames).is_some()
455        }
456    };
457    if !key.split(':').any(renamed) {
458        return key.to_string();
459    }
460    let segments: Vec<String> = key
461        .split(':')
462        .map(|segment| {
463            if segment.contains('|') {
464                let mut pieces: Vec<String> = segment
465                    .split('|')
466                    .map(|piece| {
467                        renamed_set_member(piece, renames).unwrap_or_else(|| piece.to_string())
468                    })
469                    .collect();
470                // The key sorts the set members before it escapes the part.
471                pieces.sort_unstable_by_key(|piece| unescape_key_part(piece));
472                pieces.dedup();
473                pieces.join("|")
474            } else {
475                renamed_part(segment, renames).unwrap_or_else(|| segment.to_string())
476            }
477        })
478        .collect();
479    segments.join(":")
480}
481
482/// The head path of a renamed key part, in the form of the part.
483///
484/// A dead-code key escapes `%` and `:` in each part, and the rename map holds
485/// plain paths, so an escaped part is compared and returned in the escaped
486/// form. Other keys hold the plain path.
487fn renamed_part(part: &str, renames: &FxHashMap<String, String>) -> Option<String> {
488    if let Some(renamed) = renames.get(part) {
489        return Some(renamed.clone());
490    }
491    if !part.contains('%') {
492        return None;
493    }
494    renames
495        .get(&unescape_key_part(part))
496        .map(|renamed| escape_key_part(renamed))
497}
498
499/// The head path of a renamed member of a `|`-separated path set, in the form
500/// of the member.
501///
502/// A dead-code key escapes each set member (`%` as `%25`, `|` as `%7C`) and
503/// then the whole part, so an escaped member is decoded twice and encoded
504/// twice. Other keys hold the plain path.
505fn renamed_set_member(member: &str, renames: &FxHashMap<String, String>) -> Option<String> {
506    if let Some(renamed) = renames.get(member) {
507        return Some(renamed.clone());
508    }
509    if !member.contains('%') {
510        return None;
511    }
512    let path = unescape_key_part(member)
513        .replace("%7C", "|")
514        .replace("%25", "%");
515    renames
516        .get(&path)
517        .map(|renamed| escape_key_part(&renamed.replace('%', "%25").replace('|', "%7C")))
518}
519
520/// A key part as the finding holds it: `%3A` is `:` and `%25` is `%`.
521pub(crate) fn unescape_key_part(part: &str) -> String {
522    part.replace("%3A", ":").replace("%25", "%")
523}
524
525/// A path as a dead-code key part holds it: `%` is `%25` and `:` is `%3A`.
526fn escape_key_part(path: &str) -> String {
527    path.replace('%', "%25").replace(':', "%3A")
528}
529
530/// Canonical path form used inside attribution keys. The engine owns the one
531/// implementation, because its module-graph maps use the same keys.
532pub use fallow_engine::module_graph::relative_key_path;
533
534/// The audit keys of one finding collection, in collection order.
535///
536/// Each key is the canonical key of the finding (see
537/// [`fallow_types::identity`]), so a line shift does not change it. A repeated
538/// key gets an occurrence suffix, so the base and the head compare by count:
539/// a new second finding with an inherited key is introduced.
540pub fn collection_keys<T: IdentifiedFinding>(items: &[T], root: &Path) -> Vec<String> {
541    dead_code_occurrence_keys(items, &IdentityPaths::new(root))
542}
543
544/// The six dependency-related finding slices, bundled so the dependency
545/// dispatcher takes one parameter instead of six.
546#[derive(Clone, Copy)]
547struct DependencyFindingSlices<'a> {
548    unused_dependencies: &'a [fallow_types::output_dead_code::UnusedDependencyFinding],
549    unused_dev_dependencies: &'a [fallow_types::output_dead_code::UnusedDevDependencyFinding],
550    unused_optional_dependencies:
551        &'a [fallow_types::output_dead_code::UnusedOptionalDependencyFinding],
552    unlisted_dependencies: &'a [fallow_types::output_dead_code::UnlistedDependencyFinding],
553    type_only_dependencies: &'a [fallow_types::output_dead_code::TypeOnlyDependencyFinding],
554    test_only_dependencies: &'a [fallow_types::output_dead_code::TestOnlyDependencyFinding],
555    dev_dependencies_in_production:
556        &'a [fallow_types::output_dead_code::DevDependencyInProductionFinding],
557}
558
559/// The six framework-specific finding slices, bundled so the framework
560/// dispatcher takes one parameter instead of six.
561#[derive(Clone, Copy)]
562struct FrameworkFindingSlices<'a> {
563    unprovided_injects: &'a [fallow_types::output_dead_code::UnprovidedInjectFinding],
564    unrendered_components: &'a [fallow_types::output_dead_code::UnrenderedComponentFinding],
565    unused_server_actions: &'a [fallow_types::output_dead_code::UnusedServerActionFinding],
566    unused_load_data_keys: &'a [fallow_types::output_dead_code::UnusedLoadDataKeyFinding],
567    route_collisions: &'a [fallow_types::output_dead_code::RouteCollisionFinding],
568    dynamic_segment_name_conflicts:
569        &'a [fallow_types::output_dead_code::DynamicSegmentNameConflictFinding],
570}
571
572#[derive(Clone, Copy)]
573struct ComponentContractFindingSlices<'a> {
574    unused_component_props: &'a [fallow_types::output_dead_code::UnusedComponentPropFinding],
575    absent_component_props: &'a [fallow_types::output_dead_code::AbsentComponentPropFinding],
576    constant_parameters: &'a [fallow_types::results::ConstantParameterFinding],
577    unused_component_emits: &'a [fallow_types::output_dead_code::UnusedComponentEmitFinding],
578    unused_component_inputs: &'a [fallow_types::output_dead_code::UnusedComponentInputFinding],
579    unused_component_outputs: &'a [fallow_types::output_dead_code::UnusedComponentOutputFinding],
580    unused_svelte_events: &'a [fallow_types::output_dead_code::UnusedSvelteEventFinding],
581    unused_effect_layers: &'a [fallow_types::output_dead_code::UnusedEffectLayerFinding],
582    unused_tagged_errors: &'a [fallow_types::output_dead_code::UnusedTaggedErrorFinding],
583    unproduced_catch_tags: &'a [fallow_types::output_dead_code::UnproducedCatchTagFinding],
584}
585
586/// Build the set of audit attribution keys for all dead-code findings in
587/// `results`.
588///
589/// Each key is a stable string that uniquely identifies one finding across
590/// runs (e.g. `unused-file:src/dead.ts`, `unused-export:src/a.ts:Foo`).
591/// `retain_introduced_dead_code` and `annotate_dead_code_json` use the same
592/// key format to diff the current run against a base snapshot.
593///
594/// This destructure is deliberately exhaustive: adding a field to
595/// `AnalysisResults` must fail compilation here so the author decides
596/// explicitly whether the new finding type needs an audit key (add a loop)
597/// or has no key representation today (bind with underscore and document why).
598///
599/// Sibling exhaustive sites: `retain_in_scope` in `crates/engine/src/result_scope.rs`,
600/// `retain_introduced_dead_code`.
601/// Non-exhaustive siblings the compiler will NOT flag (wire manually when a
602/// finding type is added): `annotate_dead_code_json` (same key formats, this
603/// file) and the per-collection `off` filter branches in
604/// `crates/engine/src/dead_code.rs` (`apply_rule_severities`). The severity of
605/// each record comes from the `RuleSeverity` table in
606/// `crates/engine/src/effective_severity.rs`, whose visitors are exhaustive.
607/// TypeScript mirror: `editors/vscode/scripts/codegen-contracts.mjs` derives
608/// backwards-compatible aliases from `fallow schema` `ts_alias` rows.
609pub fn dead_code_keys(
610    results: &fallow_types::results::AnalysisResults,
611    root: &Path,
612) -> FxHashSet<String> {
613    let mut collector = DeadCodeKeyCollector::new(root);
614    collector.add_all_findings(results);
615    collector.into_keys()
616}
617
618/// Build the exhaustive dead-code comparison ledger once for an audit run.
619#[must_use]
620#[expect(
621    clippy::implicit_hasher,
622    reason = "fallow standardizes on FxHashSet across audit attribution keys"
623)]
624pub fn dead_code_audit_ledger(
625    results: &fallow_types::results::AnalysisResults,
626    root: &Path,
627    config: &ResolvedConfig,
628    base: Option<&FxHashSet<String>>,
629) -> DeadCodeAuditLedger {
630    let mut collector = DeadCodeKeyCollector::for_comparison(root, config, base);
631    collector.add_all_findings(results);
632    collector.into_ledger()
633}
634
635impl DeadCodeKeyCollector<'_> {
636    #[expect(
637        clippy::too_many_lines,
638        reason = "flat field-by-field destructure of the large AnalysisResults struct (with per-field provenance comments) plus straight-line dispatch; length tracks the field count, not branching"
639    )]
640    fn add_all_findings(&mut self, results: &fallow_types::results::AnalysisResults) {
641        let fallow_types::results::AnalysisResults {
642            shared_state: _,
643            unused_files,
644            unused_exports,
645            unused_types,
646            private_type_leaks,
647            deprecated_exports_in_use,
648            unused_dependencies,
649            unused_dev_dependencies,
650            unused_optional_dependencies,
651            unused_enum_members,
652            unused_class_members,
653            unused_namespace_members,
654            unused_protected_class_members,
655            namespace_escapes,
656            test_only_exports,
657            unused_store_members,
658            unresolved_imports,
659            unlisted_dependencies,
660            unlisted_binaries,
661            duplicate_exports,
662            duplicate_export_aliases,
663            type_only_dependencies,
664            test_only_dependencies,
665            dev_dependencies_in_production,
666            circular_dependencies,
667            re_export_cycles,
668            package_cycles,
669            boundary_violations,
670            boundary_coverage_violations,
671            boundary_call_violations,
672            policy_violations,
673            stale_suppressions,
674            unused_catalog_entries,
675            empty_catalog_groups,
676            unresolved_catalog_references,
677            unused_dependency_overrides,
678            misconfigured_dependency_overrides,
679            invalid_client_exports,
680            mixed_client_server_barrels,
681            misplaced_directives,
682            unprovided_injects,
683            unrendered_components,
684            unused_component_props,
685            absent_component_props,
686            constant_parameters,
687            unused_component_emits,
688            unused_component_inputs,
689            unused_component_outputs,
690            unused_svelte_events,
691            unused_effect_layers,
692            unused_tagged_errors,
693            unproduced_catch_tags,
694            unused_server_actions,
695            unused_load_data_keys,
696            unused_load_data_keys_global_abstain: _unused_load_data_keys_global_abstain,
697            route_collisions,
698            dynamic_segment_name_conflicts,
699            // Non-finding fields: counts and metadata, not attributable to a key.
700            cascade_hidden: _cascade_hidden,
701            cascade: _cascade,
702            suppression_count: _suppression_count,
703            unused_component_props_exempted: _unused_component_props_exempted,
704            active_suppressions: _active_suppressions,
705            feature_flags: _feature_flags,
706            // Security findings are emitted via `fallow security`, not the audit
707            // dead-code gate; they have no dead-code key representation today.
708            security_findings: _security_findings,
709            suppressed_security_findings: _suppressed_security_findings,
710            security_unresolved_edge_files: _security_unresolved_edge_files,
711            security_unresolved_callee_sites: _security_unresolved_callee_sites,
712            security_unresolved_callee_diagnostics: _security_unresolved_callee_diagnostics,
713            prop_drilling_chains,
714            thin_wrappers,
715            duplicate_prop_shapes,
716            // Export usages and entry-point summary are metadata, not issue
717            // collections; no key needed.
718            export_usages: _export_usages,
719            signature_backed_types: _signature_backed_types,
720            entry_point_summary: _entry_point_summary,
721            // Render fan-in is a whole-project descriptive metric, not an issue
722            // collection; no attribution key needed.
723            render_fan_in: _render_fan_in,
724            // Per-component React intel is a descriptive ambient-editor carrier,
725            // not an issue collection; no attribution key needed.
726            react_component_intel: _react_component_intel,
727            semantic_reachable_files: _,
728            semantic_framework_contracts: _semantic_framework_contracts,
729            constant_parameter_candidates: _constant_parameter_candidates,
730        } = results;
731
732        self.add_items(AuditCollection::PropDrillingChains, prop_drilling_chains);
733        self.add_items(AuditCollection::ThinWrappers, thin_wrappers);
734        self.add_items(AuditCollection::DuplicatePropShapes, duplicate_prop_shapes);
735        self.add_core_findings(
736            unused_files,
737            unused_exports,
738            unused_types,
739            private_type_leaks,
740        );
741        self.add_deprecated_exports_in_use(deprecated_exports_in_use);
742        self.add_client_directive_findings(
743            invalid_client_exports,
744            mixed_client_server_barrels,
745            misplaced_directives,
746        );
747        self.add_unlisted_binaries(unlisted_binaries);
748        self.add_dependency_findings(&DependencyFindingSlices {
749            unused_dependencies,
750            unused_dev_dependencies,
751            unused_optional_dependencies,
752            unlisted_dependencies,
753            type_only_dependencies,
754            test_only_dependencies,
755            dev_dependencies_in_production,
756        });
757        self.add_dependency_override_findings(
758            unused_dependency_overrides,
759            misconfigured_dependency_overrides,
760        );
761        self.add_member_findings(
762            unused_enum_members,
763            unused_class_members,
764            unused_namespace_members,
765            unused_protected_class_members,
766            unused_store_members,
767        );
768        self.add_items(AuditCollection::NamespaceEscapes, namespace_escapes);
769        self.add_items(AuditCollection::TestOnlyExports, test_only_exports);
770        self.add_component_contract_findings(&ComponentContractFindingSlices {
771            unused_component_props,
772            absent_component_props,
773            constant_parameters,
774            unused_component_emits,
775            unused_component_inputs,
776            unused_component_outputs,
777            unused_svelte_events,
778            unused_effect_layers,
779            unused_tagged_errors,
780            unproduced_catch_tags,
781        });
782        self.add_items(
783            AuditCollection::DuplicateExportAliases,
784            duplicate_export_aliases,
785        );
786        self.add_graph_findings(
787            unresolved_imports,
788            duplicate_exports,
789            circular_dependencies,
790            re_export_cycles,
791            package_cycles,
792        );
793        self.add_boundary_findings(
794            boundary_violations,
795            boundary_coverage_violations,
796            boundary_call_violations,
797            policy_violations,
798            stale_suppressions,
799        );
800        self.add_catalog_findings(
801            unresolved_catalog_references,
802            unused_catalog_entries,
803            empty_catalog_groups,
804        );
805        self.add_framework_findings(&FrameworkFindingSlices {
806            unprovided_injects,
807            unrendered_components,
808            unused_server_actions,
809            unused_load_data_keys,
810            route_collisions,
811            dynamic_segment_name_conflicts,
812        });
813    }
814}
815
816struct DeadCodeKeyCollector<'a> {
817    root: &'a Path,
818    keys: FxHashSet<String>,
819    introduced_keys: FxHashSet<String>,
820    inherited_keys: FxHashSet<String>,
821    records: Vec<AuditFindingRecord>,
822    collection_counts: FxHashMap<&'static str, usize>,
823    config: Option<&'a ResolvedConfig>,
824    base: Option<&'a FxHashSet<String>>,
825    #[cfg(test)]
826    classifications: usize,
827}
828
829impl<'a> DeadCodeKeyCollector<'a> {
830    fn new(root: &'a Path) -> Self {
831        Self {
832            root,
833            keys: FxHashSet::default(),
834            introduced_keys: FxHashSet::default(),
835            inherited_keys: FxHashSet::default(),
836            records: Vec::new(),
837            collection_counts: FxHashMap::default(),
838            config: None,
839            base: None,
840            #[cfg(test)]
841            classifications: 0,
842        }
843    }
844
845    fn for_comparison(
846        root: &'a Path,
847        config: &'a ResolvedConfig,
848        base: Option<&'a FxHashSet<String>>,
849    ) -> Self {
850        Self {
851            root,
852            keys: FxHashSet::default(),
853            introduced_keys: FxHashSet::default(),
854            inherited_keys: FxHashSet::default(),
855            records: Vec::new(),
856            collection_counts: FxHashMap::default(),
857            config: Some(config),
858            base,
859            #[cfg(test)]
860            classifications: 0,
861        }
862    }
863
864    fn into_keys(self) -> FxHashSet<String> {
865        self.keys
866    }
867
868    fn into_ledger(self) -> DeadCodeAuditLedger {
869        DeadCodeAuditLedger {
870            records: self.records,
871            keys: self.keys,
872            introduced_keys: self.introduced_keys,
873            inherited_keys: self.inherited_keys,
874            #[cfg(test)]
875            classifications: self.classifications,
876        }
877    }
878
879    fn insert(&mut self, collection: AuditCollection, key: String, effective_severity: Severity) {
880        let collection = collection.json_key();
881        let ordinal = self.collection_counts.entry(collection).or_default();
882        if self.config.is_some() {
883            #[cfg(test)]
884            {
885                self.classifications += 1;
886            }
887            let introduced = self.base.is_some_and(|base| !base.contains(&key));
888            if self.base.is_some() && is_counted_dead_code_finding(collection, effective_severity) {
889                if introduced {
890                    self.introduced_keys.insert(key.clone());
891                } else {
892                    self.inherited_keys.insert(key.clone());
893                }
894            }
895            self.records.push(AuditFindingRecord {
896                collection,
897                ordinal: *ordinal,
898                introduced,
899                effective_severity,
900                stable_key: key.clone(),
901            });
902        }
903        *ordinal += 1;
904        self.keys.insert(key);
905    }
906
907    /// Insert every finding of one collection under its audit key.
908    fn add_items<T>(&mut self, collection: AuditCollection, items: &[T])
909    where
910        T: IdentifiedFinding + fallow_engine::dead_code::RuleSeverity,
911    {
912        let keys = collection_keys(items, self.root);
913        for (item, key) in items.iter().zip(keys) {
914            self.insert_rule(collection, key, item);
915        }
916    }
917
918    /// Insert a finding with the severity that the shared rule table gives
919    /// it. The exit code and the CI formats read the same table.
920    fn insert_rule(
921        &mut self,
922        collection: AuditCollection,
923        key: String,
924        item: &impl fallow_engine::dead_code::RuleSeverity,
925    ) {
926        let effective = self.config.map_or(Severity::Off, |config| {
927            item.rule_severity(&fallow_engine::dead_code::SeveritySource::from_config(
928                config,
929            ))
930        });
931        self.insert(collection, key, effective);
932    }
933
934    fn add_core_findings(
935        &mut self,
936        unused_files: &[fallow_types::output_dead_code::UnusedFileFinding],
937        unused_exports: &[fallow_types::output_dead_code::UnusedExportFinding],
938        unused_types: &[fallow_types::output_dead_code::UnusedTypeFinding],
939        private_type_leaks: &[fallow_types::output_dead_code::PrivateTypeLeakFinding],
940    ) {
941        self.add_unused_files(unused_files);
942        self.add_unused_exports(unused_exports);
943        self.add_unused_types(unused_types);
944        self.add_private_type_leaks(private_type_leaks);
945    }
946
947    fn add_client_directive_findings(
948        &mut self,
949        invalid_client_exports: &[fallow_types::output_dead_code::InvalidClientExportFinding],
950        mixed_client_server_barrels: &[fallow_types::output_dead_code::MixedClientServerBarrelFinding],
951        misplaced_directives: &[fallow_types::output_dead_code::MisplacedDirectiveFinding],
952    ) {
953        self.add_invalid_client_exports(invalid_client_exports);
954        self.add_mixed_client_server_barrels(mixed_client_server_barrels);
955        self.add_misplaced_directives(misplaced_directives);
956    }
957
958    fn add_dependency_findings(&mut self, deps: &DependencyFindingSlices<'_>) {
959        let DependencyFindingSlices {
960            unused_dependencies,
961            unused_dev_dependencies,
962            unused_optional_dependencies,
963            unlisted_dependencies,
964            type_only_dependencies,
965            test_only_dependencies,
966            dev_dependencies_in_production,
967        } = *deps;
968        self.add_unused_dependencies(unused_dependencies);
969        self.add_unused_dev_dependencies(unused_dev_dependencies);
970        self.add_unused_optional_dependencies(unused_optional_dependencies);
971        self.add_unlisted_dependencies(unlisted_dependencies);
972        self.add_type_only_dependencies(type_only_dependencies);
973        self.add_test_only_dependencies(test_only_dependencies);
974        self.add_dev_dependencies_in_production(dev_dependencies_in_production);
975    }
976
977    fn add_dependency_override_findings(
978        &mut self,
979        unused_dependency_overrides: &[fallow_types::output_dead_code::UnusedDependencyOverrideFinding],
980        misconfigured_dependency_overrides: &[fallow_types::output_dead_code::MisconfiguredDependencyOverrideFinding],
981    ) {
982        self.add_unused_dependency_overrides(unused_dependency_overrides);
983        self.add_misconfigured_dependency_overrides(misconfigured_dependency_overrides);
984    }
985
986    fn add_member_findings(
987        &mut self,
988        unused_enum_members: &[fallow_types::output_dead_code::UnusedEnumMemberFinding],
989        unused_class_members: &[fallow_types::output_dead_code::UnusedClassMemberFinding],
990        unused_namespace_members: &[fallow_types::output_dead_code::UnusedNamespaceMemberFinding],
991        unused_protected_class_members: &[fallow_types::output_dead_code::UnusedProtectedClassMemberFinding],
992        unused_store_members: &[fallow_types::output_dead_code::UnusedStoreMemberFinding],
993    ) {
994        self.add_unused_enum_members(unused_enum_members);
995        self.add_unused_class_members(unused_class_members);
996        self.add_unused_namespace_members(unused_namespace_members);
997        self.add_unused_protected_class_members(unused_protected_class_members);
998        self.add_unused_store_members(unused_store_members);
999    }
1000
1001    fn add_component_contract_findings(&mut self, components: &ComponentContractFindingSlices<'_>) {
1002        let ComponentContractFindingSlices {
1003            unused_component_props,
1004            absent_component_props,
1005            constant_parameters,
1006            unused_component_emits,
1007            unused_component_inputs,
1008            unused_component_outputs,
1009            unused_svelte_events,
1010            unused_effect_layers,
1011            unused_tagged_errors,
1012            unproduced_catch_tags,
1013        } = *components;
1014        self.add_unused_component_props(unused_component_props);
1015        self.add_items(
1016            AuditCollection::AbsentComponentProps,
1017            absent_component_props,
1018        );
1019        self.add_items(AuditCollection::ConstantParameters, constant_parameters);
1020        self.add_unused_component_emits(unused_component_emits);
1021        self.add_unused_component_inputs(unused_component_inputs);
1022        self.add_unused_component_outputs(unused_component_outputs);
1023        self.add_unused_svelte_events(unused_svelte_events);
1024        self.add_unused_effect_layers(unused_effect_layers);
1025        self.add_unused_tagged_errors(unused_tagged_errors);
1026        self.add_unproduced_catch_tags(unproduced_catch_tags);
1027    }
1028
1029    fn add_graph_findings(
1030        &mut self,
1031        unresolved_imports: &[fallow_types::output_dead_code::UnresolvedImportFinding],
1032        duplicate_exports: &[fallow_types::output_dead_code::DuplicateExportFinding],
1033        circular_dependencies: &[fallow_types::output_dead_code::CircularDependencyFinding],
1034        re_export_cycles: &[fallow_types::output_dead_code::ReExportCycleFinding],
1035        package_cycles: &[fallow_types::output_dead_code::PackageCycleFinding],
1036    ) {
1037        self.add_unresolved_imports(unresolved_imports);
1038        self.add_duplicate_exports(duplicate_exports);
1039        self.add_circular_dependencies(circular_dependencies);
1040        self.add_re_export_cycles(re_export_cycles);
1041        self.add_package_cycles(package_cycles);
1042    }
1043
1044    fn add_boundary_findings(
1045        &mut self,
1046        boundary_violations: &[fallow_types::output_dead_code::BoundaryViolationFinding],
1047        boundary_coverage_violations: &[fallow_types::output_dead_code::BoundaryCoverageViolationFinding],
1048        boundary_call_violations: &[fallow_types::output_dead_code::BoundaryCallViolationFinding],
1049        policy_violations: &[fallow_types::output_dead_code::PolicyViolationFinding],
1050        stale_suppressions: &[fallow_types::results::StaleSuppression],
1051    ) {
1052        self.add_boundary_violations(boundary_violations);
1053        self.add_boundary_coverage_violations(boundary_coverage_violations);
1054        self.add_boundary_call_violations(boundary_call_violations);
1055        self.add_policy_violations(policy_violations);
1056        self.add_stale_suppressions(stale_suppressions);
1057    }
1058
1059    fn add_catalog_findings(
1060        &mut self,
1061        unresolved_catalog_references: &[fallow_types::output_dead_code::UnresolvedCatalogReferenceFinding],
1062        unused_catalog_entries: &[fallow_types::output_dead_code::UnusedCatalogEntryFinding],
1063        empty_catalog_groups: &[fallow_types::output_dead_code::EmptyCatalogGroupFinding],
1064    ) {
1065        self.add_unresolved_catalog_references(unresolved_catalog_references);
1066        self.add_unused_catalog_entries(unused_catalog_entries);
1067        self.add_empty_catalog_groups(empty_catalog_groups);
1068    }
1069
1070    fn add_framework_findings(&mut self, framework: &FrameworkFindingSlices<'_>) {
1071        let FrameworkFindingSlices {
1072            unprovided_injects,
1073            unrendered_components,
1074            unused_server_actions,
1075            unused_load_data_keys,
1076            route_collisions,
1077            dynamic_segment_name_conflicts,
1078        } = *framework;
1079        self.add_unprovided_injects(unprovided_injects);
1080        self.add_unrendered_components(unrendered_components);
1081        self.add_unused_server_actions(unused_server_actions);
1082        self.add_unused_load_data_keys(unused_load_data_keys);
1083        self.add_route_collisions(route_collisions);
1084        self.add_dynamic_segment_name_conflicts(dynamic_segment_name_conflicts);
1085    }
1086
1087    fn add_unused_files(&mut self, items: &[fallow_types::output_dead_code::UnusedFileFinding]) {
1088        self.add_items(AuditCollection::UnusedFiles, items);
1089    }
1090
1091    fn add_unused_exports(
1092        &mut self,
1093        items: &[fallow_types::output_dead_code::UnusedExportFinding],
1094    ) {
1095        self.add_items(AuditCollection::UnusedExports, items);
1096    }
1097
1098    fn add_unused_types(&mut self, items: &[fallow_types::output_dead_code::UnusedTypeFinding]) {
1099        self.add_items(AuditCollection::UnusedTypes, items);
1100    }
1101
1102    fn add_private_type_leaks(
1103        &mut self,
1104        items: &[fallow_types::output_dead_code::PrivateTypeLeakFinding],
1105    ) {
1106        self.add_items(AuditCollection::PrivateTypeLeaks, items);
1107    }
1108
1109    fn add_deprecated_exports_in_use(
1110        &mut self,
1111        items: &[fallow_types::output_dead_code::DeprecatedExportInUseFinding],
1112    ) {
1113        self.add_items(AuditCollection::DeprecatedExportsInUse, items);
1114    }
1115
1116    fn add_invalid_client_exports(
1117        &mut self,
1118        items: &[fallow_types::output_dead_code::InvalidClientExportFinding],
1119    ) {
1120        self.add_items(AuditCollection::InvalidClientExports, items);
1121    }
1122
1123    fn add_mixed_client_server_barrels(
1124        &mut self,
1125        items: &[fallow_types::output_dead_code::MixedClientServerBarrelFinding],
1126    ) {
1127        self.add_items(AuditCollection::MixedClientServerBarrels, items);
1128    }
1129
1130    fn add_misplaced_directives(
1131        &mut self,
1132        items: &[fallow_types::output_dead_code::MisplacedDirectiveFinding],
1133    ) {
1134        self.add_items(AuditCollection::MisplacedDirectives, items);
1135    }
1136
1137    fn add_unprovided_injects(
1138        &mut self,
1139        items: &[fallow_types::output_dead_code::UnprovidedInjectFinding],
1140    ) {
1141        self.add_items(AuditCollection::UnprovidedInjects, items);
1142    }
1143
1144    fn add_unrendered_components(
1145        &mut self,
1146        items: &[fallow_types::output_dead_code::UnrenderedComponentFinding],
1147    ) {
1148        self.add_items(AuditCollection::UnrenderedComponents, items);
1149    }
1150
1151    fn add_unused_component_props(
1152        &mut self,
1153        items: &[fallow_types::output_dead_code::UnusedComponentPropFinding],
1154    ) {
1155        self.add_items(AuditCollection::UnusedComponentProps, items);
1156    }
1157
1158    fn add_unused_component_emits(
1159        &mut self,
1160        items: &[fallow_types::output_dead_code::UnusedComponentEmitFinding],
1161    ) {
1162        self.add_items(AuditCollection::UnusedComponentEmits, items);
1163    }
1164
1165    fn add_unused_component_inputs(
1166        &mut self,
1167        items: &[fallow_types::output_dead_code::UnusedComponentInputFinding],
1168    ) {
1169        self.add_items(AuditCollection::UnusedComponentInputs, items);
1170    }
1171
1172    fn add_unused_component_outputs(
1173        &mut self,
1174        items: &[fallow_types::output_dead_code::UnusedComponentOutputFinding],
1175    ) {
1176        self.add_items(AuditCollection::UnusedComponentOutputs, items);
1177    }
1178
1179    fn add_unused_svelte_events(
1180        &mut self,
1181        items: &[fallow_types::output_dead_code::UnusedSvelteEventFinding],
1182    ) {
1183        self.add_items(AuditCollection::UnusedSvelteEvents, items);
1184    }
1185    fn add_unused_effect_layers(
1186        &mut self,
1187        items: &[fallow_types::output_dead_code::UnusedEffectLayerFinding],
1188    ) {
1189        self.add_items(AuditCollection::UnusedEffectLayers, items);
1190    }
1191    fn add_unused_tagged_errors(
1192        &mut self,
1193        items: &[fallow_types::output_dead_code::UnusedTaggedErrorFinding],
1194    ) {
1195        self.add_items(AuditCollection::UnusedTaggedErrors, items);
1196    }
1197    fn add_unproduced_catch_tags(
1198        &mut self,
1199        items: &[fallow_types::output_dead_code::UnproducedCatchTagFinding],
1200    ) {
1201        self.add_items(AuditCollection::UnproducedCatchTags, items);
1202    }
1203
1204    fn add_unused_server_actions(
1205        &mut self,
1206        items: &[fallow_types::output_dead_code::UnusedServerActionFinding],
1207    ) {
1208        self.add_items(AuditCollection::UnusedServerActions, items);
1209    }
1210
1211    fn add_unused_load_data_keys(
1212        &mut self,
1213        items: &[fallow_types::output_dead_code::UnusedLoadDataKeyFinding],
1214    ) {
1215        self.add_items(AuditCollection::UnusedLoadDataKeys, items);
1216    }
1217
1218    fn add_route_collisions(
1219        &mut self,
1220        items: &[fallow_types::output_dead_code::RouteCollisionFinding],
1221    ) {
1222        self.add_items(AuditCollection::RouteCollisions, items);
1223    }
1224
1225    fn add_dynamic_segment_name_conflicts(
1226        &mut self,
1227        items: &[fallow_types::output_dead_code::DynamicSegmentNameConflictFinding],
1228    ) {
1229        self.add_items(AuditCollection::DynamicSegmentNameConflicts, items);
1230    }
1231
1232    fn add_unused_dependencies(
1233        &mut self,
1234        items: &[fallow_types::output_dead_code::UnusedDependencyFinding],
1235    ) {
1236        self.add_items(AuditCollection::UnusedDependencies, items);
1237    }
1238
1239    fn add_unused_dev_dependencies(
1240        &mut self,
1241        items: &[fallow_types::output_dead_code::UnusedDevDependencyFinding],
1242    ) {
1243        self.add_items(AuditCollection::UnusedDevDependencies, items);
1244    }
1245
1246    fn add_unused_optional_dependencies(
1247        &mut self,
1248        items: &[fallow_types::output_dead_code::UnusedOptionalDependencyFinding],
1249    ) {
1250        self.add_items(AuditCollection::UnusedOptionalDependencies, items);
1251    }
1252
1253    fn add_unused_enum_members(
1254        &mut self,
1255        items: &[fallow_types::output_dead_code::UnusedEnumMemberFinding],
1256    ) {
1257        self.add_items(AuditCollection::UnusedEnumMembers, items);
1258    }
1259
1260    fn add_unused_class_members(
1261        &mut self,
1262        items: &[fallow_types::output_dead_code::UnusedClassMemberFinding],
1263    ) {
1264        self.add_items(AuditCollection::UnusedClassMembers, items);
1265    }
1266
1267    fn add_unused_namespace_members(
1268        &mut self,
1269        items: &[fallow_types::output_dead_code::UnusedNamespaceMemberFinding],
1270    ) {
1271        self.add_items(AuditCollection::UnusedNamespaceMembers, items);
1272    }
1273
1274    fn add_unused_protected_class_members(
1275        &mut self,
1276        items: &[fallow_types::output_dead_code::UnusedProtectedClassMemberFinding],
1277    ) {
1278        self.add_items(AuditCollection::UnusedProtectedClassMembers, items);
1279    }
1280
1281    fn add_unused_store_members(
1282        &mut self,
1283        items: &[fallow_types::output_dead_code::UnusedStoreMemberFinding],
1284    ) {
1285        self.add_items(AuditCollection::UnusedStoreMembers, items);
1286    }
1287
1288    fn add_unresolved_imports(
1289        &mut self,
1290        items: &[fallow_types::output_dead_code::UnresolvedImportFinding],
1291    ) {
1292        self.add_items(AuditCollection::UnresolvedImports, items);
1293    }
1294
1295    fn add_unlisted_dependencies(
1296        &mut self,
1297        items: &[fallow_types::output_dead_code::UnlistedDependencyFinding],
1298    ) {
1299        self.add_items(AuditCollection::UnlistedDependencies, items);
1300    }
1301
1302    fn add_unlisted_binaries(
1303        &mut self,
1304        items: &[fallow_types::output_dead_code::UnlistedBinaryFinding],
1305    ) {
1306        self.add_items(AuditCollection::UnlistedBinaries, items);
1307    }
1308
1309    fn add_duplicate_exports(
1310        &mut self,
1311        items: &[fallow_types::output_dead_code::DuplicateExportFinding],
1312    ) {
1313        self.add_items(AuditCollection::DuplicateExports, items);
1314    }
1315
1316    fn add_type_only_dependencies(
1317        &mut self,
1318        items: &[fallow_types::output_dead_code::TypeOnlyDependencyFinding],
1319    ) {
1320        self.add_items(AuditCollection::TypeOnlyDependencies, items);
1321    }
1322
1323    fn add_test_only_dependencies(
1324        &mut self,
1325        items: &[fallow_types::output_dead_code::TestOnlyDependencyFinding],
1326    ) {
1327        self.add_items(AuditCollection::TestOnlyDependencies, items);
1328    }
1329
1330    fn add_dev_dependencies_in_production(
1331        &mut self,
1332        items: &[fallow_types::output_dead_code::DevDependencyInProductionFinding],
1333    ) {
1334        self.add_items(AuditCollection::DevDependenciesInProduction, items);
1335    }
1336
1337    fn add_circular_dependencies(
1338        &mut self,
1339        items: &[fallow_types::output_dead_code::CircularDependencyFinding],
1340    ) {
1341        self.add_items(AuditCollection::CircularDependencies, items);
1342    }
1343
1344    fn add_re_export_cycles(
1345        &mut self,
1346        items: &[fallow_types::output_dead_code::ReExportCycleFinding],
1347    ) {
1348        self.add_items(AuditCollection::ReExportCycles, items);
1349    }
1350
1351    fn add_package_cycles(
1352        &mut self,
1353        items: &[fallow_types::output_dead_code::PackageCycleFinding],
1354    ) {
1355        self.add_items(AuditCollection::PackageCycles, items);
1356    }
1357
1358    fn add_boundary_violations(
1359        &mut self,
1360        items: &[fallow_types::output_dead_code::BoundaryViolationFinding],
1361    ) {
1362        self.add_items(AuditCollection::BoundaryViolations, items);
1363    }
1364
1365    fn add_boundary_coverage_violations(
1366        &mut self,
1367        items: &[fallow_types::output_dead_code::BoundaryCoverageViolationFinding],
1368    ) {
1369        self.add_items(AuditCollection::BoundaryCoverageViolations, items);
1370    }
1371
1372    fn add_boundary_call_violations(
1373        &mut self,
1374        items: &[fallow_types::output_dead_code::BoundaryCallViolationFinding],
1375    ) {
1376        self.add_items(AuditCollection::BoundaryCallViolations, items);
1377    }
1378
1379    fn add_policy_violations(
1380        &mut self,
1381        items: &[fallow_types::output_dead_code::PolicyViolationFinding],
1382    ) {
1383        self.add_items(AuditCollection::PolicyViolations, items);
1384    }
1385
1386    fn add_stale_suppressions(&mut self, items: &[fallow_types::results::StaleSuppression]) {
1387        self.add_items(AuditCollection::StaleSuppressions, items);
1388    }
1389
1390    fn add_unresolved_catalog_references(
1391        &mut self,
1392        items: &[fallow_types::output_dead_code::UnresolvedCatalogReferenceFinding],
1393    ) {
1394        self.add_items(AuditCollection::UnresolvedCatalogReferences, items);
1395    }
1396
1397    fn add_unused_catalog_entries(
1398        &mut self,
1399        items: &[fallow_types::output_dead_code::UnusedCatalogEntryFinding],
1400    ) {
1401        self.add_items(AuditCollection::UnusedCatalogEntries, items);
1402    }
1403
1404    fn add_empty_catalog_groups(
1405        &mut self,
1406        items: &[fallow_types::output_dead_code::EmptyCatalogGroupFinding],
1407    ) {
1408        self.add_items(AuditCollection::EmptyCatalogGroups, items);
1409    }
1410
1411    fn add_unused_dependency_overrides(
1412        &mut self,
1413        items: &[fallow_types::output_dead_code::UnusedDependencyOverrideFinding],
1414    ) {
1415        self.add_items(AuditCollection::UnusedDependencyOverrides, items);
1416    }
1417
1418    fn add_misconfigured_dependency_overrides(
1419        &mut self,
1420        items: &[fallow_types::output_dead_code::MisconfiguredDependencyOverrideFinding],
1421    ) {
1422        self.add_items(AuditCollection::MisconfiguredDependencyOverrides, items);
1423    }
1424}
1425
1426/// Retain only findings whose audit key was NOT present in `base` (i.e. was
1427/// introduced on the current branch).
1428///
1429/// When `base` is `None` (no baseline), all findings are kept.
1430///
1431/// This destructure is deliberately exhaustive: adding a field to
1432/// `AnalysisResults` must fail compilation here so the author decides
1433/// explicitly whether the new finding type needs an introduced-retain (add a
1434/// retain block) or has no key representation today (bind with underscore and
1435/// document why).
1436///
1437/// Sibling exhaustive sites: `retain_in_scope` in `crates/engine/src/result_scope.rs`,
1438/// `dead_code_keys`, `retain_introduced_dead_code`.
1439/// Non-exhaustive siblings the compiler will NOT flag (wire manually when a
1440/// finding type is added): `annotate_dead_code_json` (same key formats, this
1441/// file) and the per-collection `off` filter branches in
1442/// `crates/engine/src/dead_code.rs` (`apply_rule_severities`). The severity of
1443/// each record comes from the `RuleSeverity` table in
1444/// `crates/engine/src/effective_severity.rs`, whose visitors are exhaustive.
1445/// TypeScript mirror: `editors/vscode/scripts/codegen-contracts.mjs` derives
1446/// backwards-compatible aliases from `fallow schema` `ts_alias` rows.
1447#[expect(
1448    clippy::implicit_hasher,
1449    reason = "fallow standardizes on FxHashSet across audit attribution keys"
1450)]
1451pub fn retain_introduced_dead_code(
1452    results: &mut fallow_types::results::AnalysisResults,
1453    root: &Path,
1454    base: Option<&FxHashSet<String>>,
1455) {
1456    let Some(base) = base else {
1457        return;
1458    };
1459
1460    // Compute the introduced set before taking any mutable borrows. Note the
1461    // order differs from the pre-destructure code, which narrowed
1462    // unused_files/exports/types first and computed keys from the narrowed
1463    // results. Computing from the un-narrowed results is equivalent: those
1464    // retains keep exactly the items whose key is NOT in `base`, and the
1465    // `!base.contains(key)` filter below removes the same base-member keys
1466    // from the full key set, so `introduced` is identical either way.
1467    classify_introduced_dead_code_fields(results);
1468    macro_rules! retain {
1469        ($($field:ident),* $(,)?) => {
1470            $(retain_introduced(&mut results.$field, root, base);)*
1471        };
1472    }
1473    retain!(
1474        prop_drilling_chains,
1475        thin_wrappers,
1476        duplicate_prop_shapes,
1477        unused_files,
1478        unused_exports,
1479        unused_types,
1480        private_type_leaks,
1481        deprecated_exports_in_use,
1482        unused_enum_members,
1483        unused_class_members,
1484        unused_namespace_members,
1485        unused_protected_class_members,
1486        namespace_escapes,
1487        test_only_exports,
1488        unused_store_members,
1489        unresolved_imports,
1490        unused_dependencies,
1491        unused_dev_dependencies,
1492        unused_optional_dependencies,
1493        unlisted_dependencies,
1494        unlisted_binaries,
1495        duplicate_exports,
1496        duplicate_export_aliases,
1497        type_only_dependencies,
1498        test_only_dependencies,
1499        circular_dependencies,
1500        re_export_cycles,
1501        package_cycles,
1502        boundary_violations,
1503        boundary_coverage_violations,
1504        boundary_call_violations,
1505        policy_violations,
1506        stale_suppressions,
1507        unresolved_catalog_references,
1508        unused_catalog_entries,
1509        empty_catalog_groups,
1510        unused_dependency_overrides,
1511        misconfigured_dependency_overrides,
1512        invalid_client_exports,
1513        mixed_client_server_barrels,
1514        misplaced_directives,
1515        unprovided_injects,
1516        unrendered_components,
1517        unused_component_props,
1518        absent_component_props,
1519        constant_parameters,
1520        unused_component_emits,
1521        unused_component_inputs,
1522        unused_component_outputs,
1523        unused_svelte_events,
1524        unused_effect_layers,
1525        unused_tagged_errors,
1526        unproduced_catch_tags,
1527        unused_server_actions,
1528        unused_load_data_keys,
1529        route_collisions,
1530        dynamic_segment_name_conflicts,
1531    );
1532}
1533
1534/// Keep the findings of one collection whose audit key is absent from `base`.
1535fn retain_introduced<T: IdentifiedFinding>(
1536    items: &mut Vec<T>,
1537    root: &Path,
1538    base: &FxHashSet<String>,
1539) {
1540    let mut keys = collection_keys(items, root).into_iter();
1541    items.retain(|_| keys.next().is_some_and(|key| !base.contains(&key)));
1542}
1543
1544/// The `introduced` flag of each finding in one collection, in order.
1545fn introduced_flags<T: IdentifiedFinding>(
1546    items: &[T],
1547    root: &Path,
1548    base: &FxHashSet<String>,
1549) -> Vec<bool> {
1550    collection_keys(items, root)
1551        .iter()
1552        .map(|key| !base.contains(key))
1553        .collect()
1554}
1555
1556fn issue_was_introduced(key: &str, base: &FxHashSet<String>) -> bool {
1557    !base.contains(key)
1558}
1559
1560fn annotate_issue_array<I>(json: &mut serde_json::Value, key: &str, introduced: I)
1561where
1562    I: IntoIterator<Item = bool>,
1563{
1564    let Some(items) = json.get_mut(key).and_then(serde_json::Value::as_array_mut) else {
1565        return;
1566    };
1567    for (item, introduced) in items.iter_mut().zip(introduced) {
1568        if let serde_json::Value::Object(map) = item {
1569            map.insert("introduced".to_string(), serde_json::json!(introduced));
1570        }
1571    }
1572}
1573
1574/// Insert `"introduced": bool` into every dead-code finding object in the
1575/// serialized JSON by re-deriving each key and testing membership against
1576/// the base snapshot. JSON arrays must be in the same order as the typed
1577/// `results` collections they were serialized from.
1578#[expect(
1579    clippy::implicit_hasher,
1580    reason = "fallow standardizes on FxHashSet across audit attribution keys"
1581)]
1582pub fn annotate_dead_code_json(
1583    json: &mut serde_json::Value,
1584    results: &fallow_types::results::AnalysisResults,
1585    root: &Path,
1586    base: &FxHashSet<String>,
1587) {
1588    macro_rules! annotate {
1589        ($($field:ident),* $(,)?) => {
1590            $(annotate_issue_array(
1591                json,
1592                stringify!($field),
1593                introduced_flags(&results.$field, root, base),
1594            );)*
1595        };
1596    }
1597    annotate!(
1598        prop_drilling_chains,
1599        thin_wrappers,
1600        duplicate_prop_shapes,
1601        unused_files,
1602        unused_exports,
1603        unused_types,
1604        private_type_leaks,
1605        deprecated_exports_in_use,
1606        unused_dependencies,
1607        unused_dev_dependencies,
1608        unused_optional_dependencies,
1609        type_only_dependencies,
1610        test_only_dependencies,
1611        unlisted_dependencies,
1612        unlisted_binaries,
1613        unused_enum_members,
1614        unused_class_members,
1615        unused_namespace_members,
1616        unused_protected_class_members,
1617        namespace_escapes,
1618        test_only_exports,
1619        unused_store_members,
1620        unresolved_imports,
1621        duplicate_exports,
1622        duplicate_export_aliases,
1623        circular_dependencies,
1624        re_export_cycles,
1625        package_cycles,
1626        boundary_violations,
1627        boundary_coverage_violations,
1628        boundary_call_violations,
1629        policy_violations,
1630        stale_suppressions,
1631        unresolved_catalog_references,
1632        unused_catalog_entries,
1633        empty_catalog_groups,
1634        unused_dependency_overrides,
1635        misconfigured_dependency_overrides,
1636        invalid_client_exports,
1637        mixed_client_server_barrels,
1638        misplaced_directives,
1639        unprovided_injects,
1640        unrendered_components,
1641        unused_component_props,
1642        absent_component_props,
1643        constant_parameters,
1644        unused_component_emits,
1645        unused_component_inputs,
1646        unused_component_outputs,
1647        unused_svelte_events,
1648        unused_effect_layers,
1649        unused_tagged_errors,
1650        unproduced_catch_tags,
1651        unused_server_actions,
1652        route_collisions,
1653        dynamic_segment_name_conflicts,
1654    );
1655}
1656
1657/// Annotate the sole legacy dead-code collection without a typed
1658/// `introduced` field. Every wrapper-backed collection is annotated from the
1659/// persisted [`AuditComparison`] instead.
1660#[expect(
1661    clippy::implicit_hasher,
1662    reason = "fallow standardizes on FxHashSet across audit attribution keys"
1663)]
1664pub fn annotate_stale_suppressions_json(
1665    json: &mut serde_json::Value,
1666    results: &fallow_types::results::AnalysisResults,
1667    root: &Path,
1668    base: &FxHashSet<String>,
1669) {
1670    annotate_issue_array(
1671        json,
1672        "stale_suppressions",
1673        stale_suppression_introduced_flags(results, root, base),
1674    );
1675}
1676
1677/// The audit flag of each stale suppression, in report order. A flag is
1678/// `true` when the base snapshot does not hold the key of the suppression.
1679#[expect(
1680    clippy::implicit_hasher,
1681    reason = "fallow standardizes on FxHashSet across audit attribution keys"
1682)]
1683#[must_use]
1684pub fn stale_suppression_introduced_flags(
1685    results: &fallow_types::results::AnalysisResults,
1686    root: &Path,
1687    base: &FxHashSet<String>,
1688) -> Vec<bool> {
1689    introduced_flags(&results.stale_suppressions, root, base)
1690}
1691
1692const STALE_SUPPRESSION_CHECK_NAMES: [&str; 2] = [
1693    "fallow/stale-suppression",
1694    "fallow/missing-suppression-reason",
1695];
1696
1697/// Set the audit attribution on the stale-suppression issues of the
1698/// dead-code CodeClimate issues.
1699///
1700/// `introduced` holds one audit flag per stale suppression, in the order of
1701/// `AnalysisResults::stale_suppressions`. The builder emits one issue per
1702/// stale suppression in that order, so the flags match the issues by
1703/// position. The inline review comment then states if the change introduced
1704/// the stale suppression.
1705pub fn set_stale_suppression_audit_attribution(
1706    issues: &mut [fallow_output::CodeClimateIssue],
1707    introduced: impl IntoIterator<Item = bool>,
1708) {
1709    let stale_issues = issues
1710        .iter_mut()
1711        .filter(|issue| STALE_SUPPRESSION_CHECK_NAMES.contains(&issue.check_name.as_str()));
1712    for (issue, introduced) in stale_issues.zip(introduced) {
1713        issue.audit = Some(crate::dead_code_codeclimate::audit_review_context(
1714            introduced,
1715        ));
1716    }
1717}
1718
1719/// Insert `"introduced": bool` into each `findings` and `styling_findings`
1720/// object in serialized health JSON, matching entries to the typed report by
1721/// array position.
1722///
1723/// A complexity finding keeps the typed `introduced` flag that the audit
1724/// comparison set, because that flag compares metric values. Only a finding
1725/// without the typed flag falls back to identity-key membership in `base`.
1726/// A styling finding also keeps its typed flag, because the audit can use the
1727/// run's diff to tell equal findings apart.
1728#[expect(
1729    clippy::implicit_hasher,
1730    reason = "fallow standardizes on FxHashSet across audit attribution keys"
1731)]
1732pub fn annotate_health_json(
1733    json: &mut serde_json::Value,
1734    report: &fallow_output::HealthReport,
1735    root: &Path,
1736    base: &FxHashSet<String>,
1737) {
1738    if let Some(items) = json
1739        .get_mut("findings")
1740        .and_then(serde_json::Value::as_array_mut)
1741    {
1742        for (item, finding) in items.iter_mut().zip(&report.findings) {
1743            if let serde_json::Value::Object(map) = item {
1744                map.insert(
1745                    "introduced".to_string(),
1746                    serde_json::json!(finding.introduced.unwrap_or_else(|| {
1747                        issue_was_introduced(&health_finding_key(finding, root), base)
1748                    })),
1749                );
1750            }
1751        }
1752    }
1753    styling::annotate_styling_json(json, &report.styling_findings, root, base);
1754}
1755
1756/// Insert `"introduced": bool` into each `clone_groups` object in serialized
1757/// duplication JSON, matching groups to the typed report by array position.
1758#[expect(
1759    clippy::implicit_hasher,
1760    reason = "fallow standardizes on FxHashSet across audit attribution keys"
1761)]
1762pub fn annotate_dupes_json(
1763    json: &mut serde_json::Value,
1764    report: &fallow_types::duplicates::DuplicationReport,
1765    root: &Path,
1766    base: &FxHashSet<String>,
1767) {
1768    let Some(items) = json
1769        .get_mut("clone_groups")
1770        .and_then(serde_json::Value::as_array_mut)
1771    else {
1772        return;
1773    };
1774    for (item, group) in items.iter_mut().zip(&report.clone_groups) {
1775        if let serde_json::Value::Object(map) = item {
1776            map.insert(
1777                "introduced".to_string(),
1778                serde_json::json!(issue_was_introduced(&dupe_group_key(group, root), base)),
1779            );
1780        }
1781    }
1782}
1783
1784/// Attach precomputed introduced membership to an audit JSON array.
1785pub fn annotate_domain_json(
1786    json: &mut serde_json::Value,
1787    collection: &str,
1788    introduced: impl IntoIterator<Item = bool>,
1789) {
1790    annotate_issue_array(json, collection, introduced);
1791}
1792
1793/// Attach a `demotion_reason` to demoted entries of an audit JSON array,
1794/// matching entries to demoted membership by array position. Non-demoted
1795/// entries are left untouched so output without demotions stays byte-identical
1796/// (issue #2220).
1797pub fn annotate_domain_demotions_json(
1798    json: &mut serde_json::Value,
1799    collection: &str,
1800    demoted: impl IntoIterator<Item = bool>,
1801    reason: crate::CloneDemotionReason,
1802) {
1803    let Some(items) = json
1804        .get_mut(collection)
1805        .and_then(serde_json::Value::as_array_mut)
1806    else {
1807        return;
1808    };
1809    for (item, demoted) in items.iter_mut().zip(demoted) {
1810        if demoted && let serde_json::Value::Object(map) = item {
1811            map.insert("demotion_reason".to_string(), serde_json::json!(reason));
1812        }
1813    }
1814}
1815
1816/// Attribution key set for every complexity finding in a health report.
1817pub fn health_keys(report: &fallow_output::HealthReport, root: &Path) -> FxHashSet<String> {
1818    report
1819        .findings
1820        .iter()
1821        .map(|finding| health_finding_key(finding, root))
1822        .collect()
1823}
1824
1825/// Identity key for one complexity finding: `complexity:<path>:<function>`.
1826///
1827/// Line numbers are excluded, so a finding survives unrelated edits above it.
1828/// The exceeded category is excluded, so a category change keeps the match.
1829/// The new-only gate compares the metric values of matched findings, see
1830/// [`classify_complexity_findings`].
1831pub fn health_finding_key(finding: &fallow_output::ComplexityViolation, root: &Path) -> String {
1832    format!(
1833        "complexity:{}:{}",
1834        relative_key_path(Path::new(&finding.path), root),
1835        finding.name,
1836    )
1837}
1838
1839/// Attribution key set for every clone group in a duplication report.
1840pub fn dupes_keys(
1841    report: &fallow_types::duplicates::DuplicationReport,
1842    root: &Path,
1843) -> FxHashSet<String> {
1844    report
1845        .clone_groups
1846        .iter()
1847        .map(|group| dupe_group_key(group, root))
1848        .collect()
1849}
1850
1851/// Attribution key for one clone group:
1852/// `dupe:<sorted files joined by |>:<tokens>:<lines>:<fragment hash>`.
1853/// The fragment hash keeps distinct groups spanning the same files apart;
1854/// line positions are excluded so a group survives shifts within its files.
1855/// The fragment hash leaves out `\r`, so the line endings do not change the key.
1856/// It does not depend on the order of the instances, so a group keeps its
1857/// hash when the change moves its instances to other files.
1858pub fn dupe_group_key(group: &fallow_types::duplicates::CloneGroup, root: &Path) -> String {
1859    let mut files: Vec<String> = group
1860        .instances
1861        .iter()
1862        .map(|instance| relative_key_path(&instance.file, root))
1863        .collect();
1864    files.sort();
1865    files.dedup();
1866    let mut fragment_hashes: Vec<u64> = group
1867        .instances
1868        .iter()
1869        .map(|instance| {
1870            let mut hasher = DefaultHasher::new();
1871            if instance.fragment.contains('\r') {
1872                instance.fragment.replace('\r', "").hash(&mut hasher);
1873            } else {
1874                instance.fragment.hash(&mut hasher);
1875            }
1876            hasher.finish()
1877        })
1878        .collect();
1879    fragment_hashes.sort_unstable();
1880    let mut hasher = DefaultHasher::new();
1881    for fragment_hash in fragment_hashes {
1882        fragment_hash.hash(&mut hasher);
1883    }
1884    format!(
1885        "dupe:{}:{}:{}:{:x}",
1886        files.join("|"),
1887        group.token_count,
1888        group.line_count,
1889        hasher.finish()
1890    )
1891}
1892
1893#[path = "audit_keys_introduced.rs"]
1894mod audit_keys_introduced;
1895use audit_keys_introduced::classify_introduced_dead_code_fields;
1896
1897#[cfg(test)]
1898#[path = "audit_keys_tests.rs"]
1899mod tests;