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            unused_store_members,
657            unresolved_imports,
658            unlisted_dependencies,
659            unlisted_binaries,
660            duplicate_exports,
661            duplicate_export_aliases,
662            type_only_dependencies,
663            test_only_dependencies,
664            dev_dependencies_in_production,
665            circular_dependencies,
666            re_export_cycles,
667            package_cycles,
668            boundary_violations,
669            boundary_coverage_violations,
670            boundary_call_violations,
671            policy_violations,
672            stale_suppressions,
673            unused_catalog_entries,
674            empty_catalog_groups,
675            unresolved_catalog_references,
676            unused_dependency_overrides,
677            misconfigured_dependency_overrides,
678            invalid_client_exports,
679            mixed_client_server_barrels,
680            misplaced_directives,
681            unprovided_injects,
682            unrendered_components,
683            unused_component_props,
684            absent_component_props,
685            constant_parameters,
686            unused_component_emits,
687            unused_component_inputs,
688            unused_component_outputs,
689            unused_svelte_events,
690            unused_effect_layers,
691            unused_tagged_errors,
692            unproduced_catch_tags,
693            unused_server_actions,
694            unused_load_data_keys,
695            unused_load_data_keys_global_abstain: _unused_load_data_keys_global_abstain,
696            route_collisions,
697            dynamic_segment_name_conflicts,
698            // Non-finding fields: counts and metadata, not attributable to a key.
699            cascade_hidden: _cascade_hidden,
700            cascade: _cascade,
701            suppression_count: _suppression_count,
702            unused_component_props_exempted: _unused_component_props_exempted,
703            active_suppressions: _active_suppressions,
704            feature_flags: _feature_flags,
705            // Security findings are emitted via `fallow security`, not the audit
706            // dead-code gate; they have no dead-code key representation today.
707            security_findings: _security_findings,
708            suppressed_security_findings: _suppressed_security_findings,
709            security_unresolved_edge_files: _security_unresolved_edge_files,
710            security_unresolved_callee_sites: _security_unresolved_callee_sites,
711            security_unresolved_callee_diagnostics: _security_unresolved_callee_diagnostics,
712            prop_drilling_chains,
713            thin_wrappers,
714            duplicate_prop_shapes,
715            // Export usages and entry-point summary are metadata, not issue
716            // collections; no key needed.
717            export_usages: _export_usages,
718            entry_point_summary: _entry_point_summary,
719            // Render fan-in is a whole-project descriptive metric, not an issue
720            // collection; no attribution key needed.
721            render_fan_in: _render_fan_in,
722            // Per-component React intel is a descriptive ambient-editor carrier,
723            // not an issue collection; no attribution key needed.
724            react_component_intel: _react_component_intel,
725            semantic_reachable_files: _,
726            semantic_framework_contracts: _semantic_framework_contracts,
727            constant_parameter_candidates: _constant_parameter_candidates,
728        } = results;
729
730        self.add_items(AuditCollection::PropDrillingChains, prop_drilling_chains);
731        self.add_items(AuditCollection::ThinWrappers, thin_wrappers);
732        self.add_items(AuditCollection::DuplicatePropShapes, duplicate_prop_shapes);
733        self.add_core_findings(
734            unused_files,
735            unused_exports,
736            unused_types,
737            private_type_leaks,
738        );
739        self.add_deprecated_exports_in_use(deprecated_exports_in_use);
740        self.add_client_directive_findings(
741            invalid_client_exports,
742            mixed_client_server_barrels,
743            misplaced_directives,
744        );
745        self.add_unlisted_binaries(unlisted_binaries);
746        self.add_dependency_findings(&DependencyFindingSlices {
747            unused_dependencies,
748            unused_dev_dependencies,
749            unused_optional_dependencies,
750            unlisted_dependencies,
751            type_only_dependencies,
752            test_only_dependencies,
753            dev_dependencies_in_production,
754        });
755        self.add_dependency_override_findings(
756            unused_dependency_overrides,
757            misconfigured_dependency_overrides,
758        );
759        self.add_member_findings(
760            unused_enum_members,
761            unused_class_members,
762            unused_namespace_members,
763            unused_protected_class_members,
764            unused_store_members,
765        );
766        self.add_items(AuditCollection::NamespaceEscapes, namespace_escapes);
767        self.add_component_contract_findings(&ComponentContractFindingSlices {
768            unused_component_props,
769            absent_component_props,
770            constant_parameters,
771            unused_component_emits,
772            unused_component_inputs,
773            unused_component_outputs,
774            unused_svelte_events,
775            unused_effect_layers,
776            unused_tagged_errors,
777            unproduced_catch_tags,
778        });
779        self.add_items(
780            AuditCollection::DuplicateExportAliases,
781            duplicate_export_aliases,
782        );
783        self.add_graph_findings(
784            unresolved_imports,
785            duplicate_exports,
786            circular_dependencies,
787            re_export_cycles,
788            package_cycles,
789        );
790        self.add_boundary_findings(
791            boundary_violations,
792            boundary_coverage_violations,
793            boundary_call_violations,
794            policy_violations,
795            stale_suppressions,
796        );
797        self.add_catalog_findings(
798            unresolved_catalog_references,
799            unused_catalog_entries,
800            empty_catalog_groups,
801        );
802        self.add_framework_findings(&FrameworkFindingSlices {
803            unprovided_injects,
804            unrendered_components,
805            unused_server_actions,
806            unused_load_data_keys,
807            route_collisions,
808            dynamic_segment_name_conflicts,
809        });
810    }
811}
812
813struct DeadCodeKeyCollector<'a> {
814    root: &'a Path,
815    keys: FxHashSet<String>,
816    introduced_keys: FxHashSet<String>,
817    inherited_keys: FxHashSet<String>,
818    records: Vec<AuditFindingRecord>,
819    collection_counts: FxHashMap<&'static str, usize>,
820    config: Option<&'a ResolvedConfig>,
821    base: Option<&'a FxHashSet<String>>,
822    #[cfg(test)]
823    classifications: usize,
824}
825
826impl<'a> DeadCodeKeyCollector<'a> {
827    fn new(root: &'a Path) -> Self {
828        Self {
829            root,
830            keys: FxHashSet::default(),
831            introduced_keys: FxHashSet::default(),
832            inherited_keys: FxHashSet::default(),
833            records: Vec::new(),
834            collection_counts: FxHashMap::default(),
835            config: None,
836            base: None,
837            #[cfg(test)]
838            classifications: 0,
839        }
840    }
841
842    fn for_comparison(
843        root: &'a Path,
844        config: &'a ResolvedConfig,
845        base: Option<&'a FxHashSet<String>>,
846    ) -> Self {
847        Self {
848            root,
849            keys: FxHashSet::default(),
850            introduced_keys: FxHashSet::default(),
851            inherited_keys: FxHashSet::default(),
852            records: Vec::new(),
853            collection_counts: FxHashMap::default(),
854            config: Some(config),
855            base,
856            #[cfg(test)]
857            classifications: 0,
858        }
859    }
860
861    fn into_keys(self) -> FxHashSet<String> {
862        self.keys
863    }
864
865    fn into_ledger(self) -> DeadCodeAuditLedger {
866        DeadCodeAuditLedger {
867            records: self.records,
868            keys: self.keys,
869            introduced_keys: self.introduced_keys,
870            inherited_keys: self.inherited_keys,
871            #[cfg(test)]
872            classifications: self.classifications,
873        }
874    }
875
876    fn insert(&mut self, collection: AuditCollection, key: String, effective_severity: Severity) {
877        let collection = collection.json_key();
878        let ordinal = self.collection_counts.entry(collection).or_default();
879        if self.config.is_some() {
880            #[cfg(test)]
881            {
882                self.classifications += 1;
883            }
884            let introduced = self.base.is_some_and(|base| !base.contains(&key));
885            if self.base.is_some() && is_counted_dead_code_finding(collection, effective_severity) {
886                if introduced {
887                    self.introduced_keys.insert(key.clone());
888                } else {
889                    self.inherited_keys.insert(key.clone());
890                }
891            }
892            self.records.push(AuditFindingRecord {
893                collection,
894                ordinal: *ordinal,
895                introduced,
896                effective_severity,
897                stable_key: key.clone(),
898            });
899        }
900        *ordinal += 1;
901        self.keys.insert(key);
902    }
903
904    /// Insert every finding of one collection under its audit key.
905    fn add_items<T>(&mut self, collection: AuditCollection, items: &[T])
906    where
907        T: IdentifiedFinding + fallow_engine::dead_code::RuleSeverity,
908    {
909        let keys = collection_keys(items, self.root);
910        for (item, key) in items.iter().zip(keys) {
911            self.insert_rule(collection, key, item);
912        }
913    }
914
915    /// Insert a finding with the severity that the shared rule table gives
916    /// it. The exit code and the CI formats read the same table.
917    fn insert_rule(
918        &mut self,
919        collection: AuditCollection,
920        key: String,
921        item: &impl fallow_engine::dead_code::RuleSeverity,
922    ) {
923        let effective = self.config.map_or(Severity::Off, |config| {
924            item.rule_severity(&fallow_engine::dead_code::SeveritySource::from_config(
925                config,
926            ))
927        });
928        self.insert(collection, key, effective);
929    }
930
931    fn add_core_findings(
932        &mut self,
933        unused_files: &[fallow_types::output_dead_code::UnusedFileFinding],
934        unused_exports: &[fallow_types::output_dead_code::UnusedExportFinding],
935        unused_types: &[fallow_types::output_dead_code::UnusedTypeFinding],
936        private_type_leaks: &[fallow_types::output_dead_code::PrivateTypeLeakFinding],
937    ) {
938        self.add_unused_files(unused_files);
939        self.add_unused_exports(unused_exports);
940        self.add_unused_types(unused_types);
941        self.add_private_type_leaks(private_type_leaks);
942    }
943
944    fn add_client_directive_findings(
945        &mut self,
946        invalid_client_exports: &[fallow_types::output_dead_code::InvalidClientExportFinding],
947        mixed_client_server_barrels: &[fallow_types::output_dead_code::MixedClientServerBarrelFinding],
948        misplaced_directives: &[fallow_types::output_dead_code::MisplacedDirectiveFinding],
949    ) {
950        self.add_invalid_client_exports(invalid_client_exports);
951        self.add_mixed_client_server_barrels(mixed_client_server_barrels);
952        self.add_misplaced_directives(misplaced_directives);
953    }
954
955    fn add_dependency_findings(&mut self, deps: &DependencyFindingSlices<'_>) {
956        let DependencyFindingSlices {
957            unused_dependencies,
958            unused_dev_dependencies,
959            unused_optional_dependencies,
960            unlisted_dependencies,
961            type_only_dependencies,
962            test_only_dependencies,
963            dev_dependencies_in_production,
964        } = *deps;
965        self.add_unused_dependencies(unused_dependencies);
966        self.add_unused_dev_dependencies(unused_dev_dependencies);
967        self.add_unused_optional_dependencies(unused_optional_dependencies);
968        self.add_unlisted_dependencies(unlisted_dependencies);
969        self.add_type_only_dependencies(type_only_dependencies);
970        self.add_test_only_dependencies(test_only_dependencies);
971        self.add_dev_dependencies_in_production(dev_dependencies_in_production);
972    }
973
974    fn add_dependency_override_findings(
975        &mut self,
976        unused_dependency_overrides: &[fallow_types::output_dead_code::UnusedDependencyOverrideFinding],
977        misconfigured_dependency_overrides: &[fallow_types::output_dead_code::MisconfiguredDependencyOverrideFinding],
978    ) {
979        self.add_unused_dependency_overrides(unused_dependency_overrides);
980        self.add_misconfigured_dependency_overrides(misconfigured_dependency_overrides);
981    }
982
983    fn add_member_findings(
984        &mut self,
985        unused_enum_members: &[fallow_types::output_dead_code::UnusedEnumMemberFinding],
986        unused_class_members: &[fallow_types::output_dead_code::UnusedClassMemberFinding],
987        unused_namespace_members: &[fallow_types::output_dead_code::UnusedNamespaceMemberFinding],
988        unused_protected_class_members: &[fallow_types::output_dead_code::UnusedProtectedClassMemberFinding],
989        unused_store_members: &[fallow_types::output_dead_code::UnusedStoreMemberFinding],
990    ) {
991        self.add_unused_enum_members(unused_enum_members);
992        self.add_unused_class_members(unused_class_members);
993        self.add_unused_namespace_members(unused_namespace_members);
994        self.add_unused_protected_class_members(unused_protected_class_members);
995        self.add_unused_store_members(unused_store_members);
996    }
997
998    fn add_component_contract_findings(&mut self, components: &ComponentContractFindingSlices<'_>) {
999        let ComponentContractFindingSlices {
1000            unused_component_props,
1001            absent_component_props,
1002            constant_parameters,
1003            unused_component_emits,
1004            unused_component_inputs,
1005            unused_component_outputs,
1006            unused_svelte_events,
1007            unused_effect_layers,
1008            unused_tagged_errors,
1009            unproduced_catch_tags,
1010        } = *components;
1011        self.add_unused_component_props(unused_component_props);
1012        self.add_items(
1013            AuditCollection::AbsentComponentProps,
1014            absent_component_props,
1015        );
1016        self.add_items(AuditCollection::ConstantParameters, constant_parameters);
1017        self.add_unused_component_emits(unused_component_emits);
1018        self.add_unused_component_inputs(unused_component_inputs);
1019        self.add_unused_component_outputs(unused_component_outputs);
1020        self.add_unused_svelte_events(unused_svelte_events);
1021        self.add_unused_effect_layers(unused_effect_layers);
1022        self.add_unused_tagged_errors(unused_tagged_errors);
1023        self.add_unproduced_catch_tags(unproduced_catch_tags);
1024    }
1025
1026    fn add_graph_findings(
1027        &mut self,
1028        unresolved_imports: &[fallow_types::output_dead_code::UnresolvedImportFinding],
1029        duplicate_exports: &[fallow_types::output_dead_code::DuplicateExportFinding],
1030        circular_dependencies: &[fallow_types::output_dead_code::CircularDependencyFinding],
1031        re_export_cycles: &[fallow_types::output_dead_code::ReExportCycleFinding],
1032        package_cycles: &[fallow_types::output_dead_code::PackageCycleFinding],
1033    ) {
1034        self.add_unresolved_imports(unresolved_imports);
1035        self.add_duplicate_exports(duplicate_exports);
1036        self.add_circular_dependencies(circular_dependencies);
1037        self.add_re_export_cycles(re_export_cycles);
1038        self.add_package_cycles(package_cycles);
1039    }
1040
1041    fn add_boundary_findings(
1042        &mut self,
1043        boundary_violations: &[fallow_types::output_dead_code::BoundaryViolationFinding],
1044        boundary_coverage_violations: &[fallow_types::output_dead_code::BoundaryCoverageViolationFinding],
1045        boundary_call_violations: &[fallow_types::output_dead_code::BoundaryCallViolationFinding],
1046        policy_violations: &[fallow_types::output_dead_code::PolicyViolationFinding],
1047        stale_suppressions: &[fallow_types::results::StaleSuppression],
1048    ) {
1049        self.add_boundary_violations(boundary_violations);
1050        self.add_boundary_coverage_violations(boundary_coverage_violations);
1051        self.add_boundary_call_violations(boundary_call_violations);
1052        self.add_policy_violations(policy_violations);
1053        self.add_stale_suppressions(stale_suppressions);
1054    }
1055
1056    fn add_catalog_findings(
1057        &mut self,
1058        unresolved_catalog_references: &[fallow_types::output_dead_code::UnresolvedCatalogReferenceFinding],
1059        unused_catalog_entries: &[fallow_types::output_dead_code::UnusedCatalogEntryFinding],
1060        empty_catalog_groups: &[fallow_types::output_dead_code::EmptyCatalogGroupFinding],
1061    ) {
1062        self.add_unresolved_catalog_references(unresolved_catalog_references);
1063        self.add_unused_catalog_entries(unused_catalog_entries);
1064        self.add_empty_catalog_groups(empty_catalog_groups);
1065    }
1066
1067    fn add_framework_findings(&mut self, framework: &FrameworkFindingSlices<'_>) {
1068        let FrameworkFindingSlices {
1069            unprovided_injects,
1070            unrendered_components,
1071            unused_server_actions,
1072            unused_load_data_keys,
1073            route_collisions,
1074            dynamic_segment_name_conflicts,
1075        } = *framework;
1076        self.add_unprovided_injects(unprovided_injects);
1077        self.add_unrendered_components(unrendered_components);
1078        self.add_unused_server_actions(unused_server_actions);
1079        self.add_unused_load_data_keys(unused_load_data_keys);
1080        self.add_route_collisions(route_collisions);
1081        self.add_dynamic_segment_name_conflicts(dynamic_segment_name_conflicts);
1082    }
1083
1084    fn add_unused_files(&mut self, items: &[fallow_types::output_dead_code::UnusedFileFinding]) {
1085        self.add_items(AuditCollection::UnusedFiles, items);
1086    }
1087
1088    fn add_unused_exports(
1089        &mut self,
1090        items: &[fallow_types::output_dead_code::UnusedExportFinding],
1091    ) {
1092        self.add_items(AuditCollection::UnusedExports, items);
1093    }
1094
1095    fn add_unused_types(&mut self, items: &[fallow_types::output_dead_code::UnusedTypeFinding]) {
1096        self.add_items(AuditCollection::UnusedTypes, items);
1097    }
1098
1099    fn add_private_type_leaks(
1100        &mut self,
1101        items: &[fallow_types::output_dead_code::PrivateTypeLeakFinding],
1102    ) {
1103        self.add_items(AuditCollection::PrivateTypeLeaks, items);
1104    }
1105
1106    fn add_deprecated_exports_in_use(
1107        &mut self,
1108        items: &[fallow_types::output_dead_code::DeprecatedExportInUseFinding],
1109    ) {
1110        self.add_items(AuditCollection::DeprecatedExportsInUse, items);
1111    }
1112
1113    fn add_invalid_client_exports(
1114        &mut self,
1115        items: &[fallow_types::output_dead_code::InvalidClientExportFinding],
1116    ) {
1117        self.add_items(AuditCollection::InvalidClientExports, items);
1118    }
1119
1120    fn add_mixed_client_server_barrels(
1121        &mut self,
1122        items: &[fallow_types::output_dead_code::MixedClientServerBarrelFinding],
1123    ) {
1124        self.add_items(AuditCollection::MixedClientServerBarrels, items);
1125    }
1126
1127    fn add_misplaced_directives(
1128        &mut self,
1129        items: &[fallow_types::output_dead_code::MisplacedDirectiveFinding],
1130    ) {
1131        self.add_items(AuditCollection::MisplacedDirectives, items);
1132    }
1133
1134    fn add_unprovided_injects(
1135        &mut self,
1136        items: &[fallow_types::output_dead_code::UnprovidedInjectFinding],
1137    ) {
1138        self.add_items(AuditCollection::UnprovidedInjects, items);
1139    }
1140
1141    fn add_unrendered_components(
1142        &mut self,
1143        items: &[fallow_types::output_dead_code::UnrenderedComponentFinding],
1144    ) {
1145        self.add_items(AuditCollection::UnrenderedComponents, items);
1146    }
1147
1148    fn add_unused_component_props(
1149        &mut self,
1150        items: &[fallow_types::output_dead_code::UnusedComponentPropFinding],
1151    ) {
1152        self.add_items(AuditCollection::UnusedComponentProps, items);
1153    }
1154
1155    fn add_unused_component_emits(
1156        &mut self,
1157        items: &[fallow_types::output_dead_code::UnusedComponentEmitFinding],
1158    ) {
1159        self.add_items(AuditCollection::UnusedComponentEmits, items);
1160    }
1161
1162    fn add_unused_component_inputs(
1163        &mut self,
1164        items: &[fallow_types::output_dead_code::UnusedComponentInputFinding],
1165    ) {
1166        self.add_items(AuditCollection::UnusedComponentInputs, items);
1167    }
1168
1169    fn add_unused_component_outputs(
1170        &mut self,
1171        items: &[fallow_types::output_dead_code::UnusedComponentOutputFinding],
1172    ) {
1173        self.add_items(AuditCollection::UnusedComponentOutputs, items);
1174    }
1175
1176    fn add_unused_svelte_events(
1177        &mut self,
1178        items: &[fallow_types::output_dead_code::UnusedSvelteEventFinding],
1179    ) {
1180        self.add_items(AuditCollection::UnusedSvelteEvents, items);
1181    }
1182    fn add_unused_effect_layers(
1183        &mut self,
1184        items: &[fallow_types::output_dead_code::UnusedEffectLayerFinding],
1185    ) {
1186        self.add_items(AuditCollection::UnusedEffectLayers, items);
1187    }
1188    fn add_unused_tagged_errors(
1189        &mut self,
1190        items: &[fallow_types::output_dead_code::UnusedTaggedErrorFinding],
1191    ) {
1192        self.add_items(AuditCollection::UnusedTaggedErrors, items);
1193    }
1194    fn add_unproduced_catch_tags(
1195        &mut self,
1196        items: &[fallow_types::output_dead_code::UnproducedCatchTagFinding],
1197    ) {
1198        self.add_items(AuditCollection::UnproducedCatchTags, items);
1199    }
1200
1201    fn add_unused_server_actions(
1202        &mut self,
1203        items: &[fallow_types::output_dead_code::UnusedServerActionFinding],
1204    ) {
1205        self.add_items(AuditCollection::UnusedServerActions, items);
1206    }
1207
1208    fn add_unused_load_data_keys(
1209        &mut self,
1210        items: &[fallow_types::output_dead_code::UnusedLoadDataKeyFinding],
1211    ) {
1212        self.add_items(AuditCollection::UnusedLoadDataKeys, items);
1213    }
1214
1215    fn add_route_collisions(
1216        &mut self,
1217        items: &[fallow_types::output_dead_code::RouteCollisionFinding],
1218    ) {
1219        self.add_items(AuditCollection::RouteCollisions, items);
1220    }
1221
1222    fn add_dynamic_segment_name_conflicts(
1223        &mut self,
1224        items: &[fallow_types::output_dead_code::DynamicSegmentNameConflictFinding],
1225    ) {
1226        self.add_items(AuditCollection::DynamicSegmentNameConflicts, items);
1227    }
1228
1229    fn add_unused_dependencies(
1230        &mut self,
1231        items: &[fallow_types::output_dead_code::UnusedDependencyFinding],
1232    ) {
1233        self.add_items(AuditCollection::UnusedDependencies, items);
1234    }
1235
1236    fn add_unused_dev_dependencies(
1237        &mut self,
1238        items: &[fallow_types::output_dead_code::UnusedDevDependencyFinding],
1239    ) {
1240        self.add_items(AuditCollection::UnusedDevDependencies, items);
1241    }
1242
1243    fn add_unused_optional_dependencies(
1244        &mut self,
1245        items: &[fallow_types::output_dead_code::UnusedOptionalDependencyFinding],
1246    ) {
1247        self.add_items(AuditCollection::UnusedOptionalDependencies, items);
1248    }
1249
1250    fn add_unused_enum_members(
1251        &mut self,
1252        items: &[fallow_types::output_dead_code::UnusedEnumMemberFinding],
1253    ) {
1254        self.add_items(AuditCollection::UnusedEnumMembers, items);
1255    }
1256
1257    fn add_unused_class_members(
1258        &mut self,
1259        items: &[fallow_types::output_dead_code::UnusedClassMemberFinding],
1260    ) {
1261        self.add_items(AuditCollection::UnusedClassMembers, items);
1262    }
1263
1264    fn add_unused_namespace_members(
1265        &mut self,
1266        items: &[fallow_types::output_dead_code::UnusedNamespaceMemberFinding],
1267    ) {
1268        self.add_items(AuditCollection::UnusedNamespaceMembers, items);
1269    }
1270
1271    fn add_unused_protected_class_members(
1272        &mut self,
1273        items: &[fallow_types::output_dead_code::UnusedProtectedClassMemberFinding],
1274    ) {
1275        self.add_items(AuditCollection::UnusedProtectedClassMembers, items);
1276    }
1277
1278    fn add_unused_store_members(
1279        &mut self,
1280        items: &[fallow_types::output_dead_code::UnusedStoreMemberFinding],
1281    ) {
1282        self.add_items(AuditCollection::UnusedStoreMembers, items);
1283    }
1284
1285    fn add_unresolved_imports(
1286        &mut self,
1287        items: &[fallow_types::output_dead_code::UnresolvedImportFinding],
1288    ) {
1289        self.add_items(AuditCollection::UnresolvedImports, items);
1290    }
1291
1292    fn add_unlisted_dependencies(
1293        &mut self,
1294        items: &[fallow_types::output_dead_code::UnlistedDependencyFinding],
1295    ) {
1296        self.add_items(AuditCollection::UnlistedDependencies, items);
1297    }
1298
1299    fn add_unlisted_binaries(
1300        &mut self,
1301        items: &[fallow_types::output_dead_code::UnlistedBinaryFinding],
1302    ) {
1303        self.add_items(AuditCollection::UnlistedBinaries, items);
1304    }
1305
1306    fn add_duplicate_exports(
1307        &mut self,
1308        items: &[fallow_types::output_dead_code::DuplicateExportFinding],
1309    ) {
1310        self.add_items(AuditCollection::DuplicateExports, items);
1311    }
1312
1313    fn add_type_only_dependencies(
1314        &mut self,
1315        items: &[fallow_types::output_dead_code::TypeOnlyDependencyFinding],
1316    ) {
1317        self.add_items(AuditCollection::TypeOnlyDependencies, items);
1318    }
1319
1320    fn add_test_only_dependencies(
1321        &mut self,
1322        items: &[fallow_types::output_dead_code::TestOnlyDependencyFinding],
1323    ) {
1324        self.add_items(AuditCollection::TestOnlyDependencies, items);
1325    }
1326
1327    fn add_dev_dependencies_in_production(
1328        &mut self,
1329        items: &[fallow_types::output_dead_code::DevDependencyInProductionFinding],
1330    ) {
1331        self.add_items(AuditCollection::DevDependenciesInProduction, items);
1332    }
1333
1334    fn add_circular_dependencies(
1335        &mut self,
1336        items: &[fallow_types::output_dead_code::CircularDependencyFinding],
1337    ) {
1338        self.add_items(AuditCollection::CircularDependencies, items);
1339    }
1340
1341    fn add_re_export_cycles(
1342        &mut self,
1343        items: &[fallow_types::output_dead_code::ReExportCycleFinding],
1344    ) {
1345        self.add_items(AuditCollection::ReExportCycles, items);
1346    }
1347
1348    fn add_package_cycles(
1349        &mut self,
1350        items: &[fallow_types::output_dead_code::PackageCycleFinding],
1351    ) {
1352        self.add_items(AuditCollection::PackageCycles, items);
1353    }
1354
1355    fn add_boundary_violations(
1356        &mut self,
1357        items: &[fallow_types::output_dead_code::BoundaryViolationFinding],
1358    ) {
1359        self.add_items(AuditCollection::BoundaryViolations, items);
1360    }
1361
1362    fn add_boundary_coverage_violations(
1363        &mut self,
1364        items: &[fallow_types::output_dead_code::BoundaryCoverageViolationFinding],
1365    ) {
1366        self.add_items(AuditCollection::BoundaryCoverageViolations, items);
1367    }
1368
1369    fn add_boundary_call_violations(
1370        &mut self,
1371        items: &[fallow_types::output_dead_code::BoundaryCallViolationFinding],
1372    ) {
1373        self.add_items(AuditCollection::BoundaryCallViolations, items);
1374    }
1375
1376    fn add_policy_violations(
1377        &mut self,
1378        items: &[fallow_types::output_dead_code::PolicyViolationFinding],
1379    ) {
1380        self.add_items(AuditCollection::PolicyViolations, items);
1381    }
1382
1383    fn add_stale_suppressions(&mut self, items: &[fallow_types::results::StaleSuppression]) {
1384        self.add_items(AuditCollection::StaleSuppressions, items);
1385    }
1386
1387    fn add_unresolved_catalog_references(
1388        &mut self,
1389        items: &[fallow_types::output_dead_code::UnresolvedCatalogReferenceFinding],
1390    ) {
1391        self.add_items(AuditCollection::UnresolvedCatalogReferences, items);
1392    }
1393
1394    fn add_unused_catalog_entries(
1395        &mut self,
1396        items: &[fallow_types::output_dead_code::UnusedCatalogEntryFinding],
1397    ) {
1398        self.add_items(AuditCollection::UnusedCatalogEntries, items);
1399    }
1400
1401    fn add_empty_catalog_groups(
1402        &mut self,
1403        items: &[fallow_types::output_dead_code::EmptyCatalogGroupFinding],
1404    ) {
1405        self.add_items(AuditCollection::EmptyCatalogGroups, items);
1406    }
1407
1408    fn add_unused_dependency_overrides(
1409        &mut self,
1410        items: &[fallow_types::output_dead_code::UnusedDependencyOverrideFinding],
1411    ) {
1412        self.add_items(AuditCollection::UnusedDependencyOverrides, items);
1413    }
1414
1415    fn add_misconfigured_dependency_overrides(
1416        &mut self,
1417        items: &[fallow_types::output_dead_code::MisconfiguredDependencyOverrideFinding],
1418    ) {
1419        self.add_items(AuditCollection::MisconfiguredDependencyOverrides, items);
1420    }
1421}
1422
1423/// Retain only findings whose audit key was NOT present in `base` (i.e. was
1424/// introduced on the current branch).
1425///
1426/// When `base` is `None` (no baseline), all findings are kept.
1427///
1428/// This destructure is deliberately exhaustive: adding a field to
1429/// `AnalysisResults` must fail compilation here so the author decides
1430/// explicitly whether the new finding type needs an introduced-retain (add a
1431/// retain block) or has no key representation today (bind with underscore and
1432/// document why).
1433///
1434/// Sibling exhaustive sites: `retain_in_scope` in `crates/engine/src/result_scope.rs`,
1435/// `dead_code_keys`, `retain_introduced_dead_code`.
1436/// Non-exhaustive siblings the compiler will NOT flag (wire manually when a
1437/// finding type is added): `annotate_dead_code_json` (same key formats, this
1438/// file) and the per-collection `off` filter branches in
1439/// `crates/engine/src/dead_code.rs` (`apply_rule_severities`). The severity of
1440/// each record comes from the `RuleSeverity` table in
1441/// `crates/engine/src/effective_severity.rs`, whose visitors are exhaustive.
1442/// TypeScript mirror: `editors/vscode/scripts/codegen-contracts.mjs` derives
1443/// backwards-compatible aliases from `fallow schema` `ts_alias` rows.
1444#[expect(
1445    clippy::implicit_hasher,
1446    reason = "fallow standardizes on FxHashSet across audit attribution keys"
1447)]
1448pub fn retain_introduced_dead_code(
1449    results: &mut fallow_types::results::AnalysisResults,
1450    root: &Path,
1451    base: Option<&FxHashSet<String>>,
1452) {
1453    let Some(base) = base else {
1454        return;
1455    };
1456
1457    // Compute the introduced set before taking any mutable borrows. Note the
1458    // order differs from the pre-destructure code, which narrowed
1459    // unused_files/exports/types first and computed keys from the narrowed
1460    // results. Computing from the un-narrowed results is equivalent: those
1461    // retains keep exactly the items whose key is NOT in `base`, and the
1462    // `!base.contains(key)` filter below removes the same base-member keys
1463    // from the full key set, so `introduced` is identical either way.
1464    classify_introduced_dead_code_fields(results);
1465    macro_rules! retain {
1466        ($($field:ident),* $(,)?) => {
1467            $(retain_introduced(&mut results.$field, root, base);)*
1468        };
1469    }
1470    retain!(
1471        prop_drilling_chains,
1472        thin_wrappers,
1473        duplicate_prop_shapes,
1474        unused_files,
1475        unused_exports,
1476        unused_types,
1477        private_type_leaks,
1478        deprecated_exports_in_use,
1479        unused_enum_members,
1480        unused_class_members,
1481        unused_namespace_members,
1482        unused_protected_class_members,
1483        namespace_escapes,
1484        unused_store_members,
1485        unresolved_imports,
1486        unused_dependencies,
1487        unused_dev_dependencies,
1488        unused_optional_dependencies,
1489        unlisted_dependencies,
1490        unlisted_binaries,
1491        duplicate_exports,
1492        duplicate_export_aliases,
1493        type_only_dependencies,
1494        test_only_dependencies,
1495        circular_dependencies,
1496        re_export_cycles,
1497        package_cycles,
1498        boundary_violations,
1499        boundary_coverage_violations,
1500        boundary_call_violations,
1501        policy_violations,
1502        stale_suppressions,
1503        unresolved_catalog_references,
1504        unused_catalog_entries,
1505        empty_catalog_groups,
1506        unused_dependency_overrides,
1507        misconfigured_dependency_overrides,
1508        invalid_client_exports,
1509        mixed_client_server_barrels,
1510        misplaced_directives,
1511        unprovided_injects,
1512        unrendered_components,
1513        unused_component_props,
1514        absent_component_props,
1515        constant_parameters,
1516        unused_component_emits,
1517        unused_component_inputs,
1518        unused_component_outputs,
1519        unused_svelte_events,
1520        unused_effect_layers,
1521        unused_tagged_errors,
1522        unproduced_catch_tags,
1523        unused_server_actions,
1524        unused_load_data_keys,
1525        route_collisions,
1526        dynamic_segment_name_conflicts,
1527    );
1528}
1529
1530/// Keep the findings of one collection whose audit key is absent from `base`.
1531fn retain_introduced<T: IdentifiedFinding>(
1532    items: &mut Vec<T>,
1533    root: &Path,
1534    base: &FxHashSet<String>,
1535) {
1536    let mut keys = collection_keys(items, root).into_iter();
1537    items.retain(|_| keys.next().is_some_and(|key| !base.contains(&key)));
1538}
1539
1540/// The `introduced` flag of each finding in one collection, in order.
1541fn introduced_flags<T: IdentifiedFinding>(
1542    items: &[T],
1543    root: &Path,
1544    base: &FxHashSet<String>,
1545) -> Vec<bool> {
1546    collection_keys(items, root)
1547        .iter()
1548        .map(|key| !base.contains(key))
1549        .collect()
1550}
1551
1552fn issue_was_introduced(key: &str, base: &FxHashSet<String>) -> bool {
1553    !base.contains(key)
1554}
1555
1556fn annotate_issue_array<I>(json: &mut serde_json::Value, key: &str, introduced: I)
1557where
1558    I: IntoIterator<Item = bool>,
1559{
1560    let Some(items) = json.get_mut(key).and_then(serde_json::Value::as_array_mut) else {
1561        return;
1562    };
1563    for (item, introduced) in items.iter_mut().zip(introduced) {
1564        if let serde_json::Value::Object(map) = item {
1565            map.insert("introduced".to_string(), serde_json::json!(introduced));
1566        }
1567    }
1568}
1569
1570/// Insert `"introduced": bool` into every dead-code finding object in the
1571/// serialized JSON by re-deriving each key and testing membership against
1572/// the base snapshot. JSON arrays must be in the same order as the typed
1573/// `results` collections they were serialized from.
1574#[expect(
1575    clippy::implicit_hasher,
1576    reason = "fallow standardizes on FxHashSet across audit attribution keys"
1577)]
1578pub fn annotate_dead_code_json(
1579    json: &mut serde_json::Value,
1580    results: &fallow_types::results::AnalysisResults,
1581    root: &Path,
1582    base: &FxHashSet<String>,
1583) {
1584    macro_rules! annotate {
1585        ($($field:ident),* $(,)?) => {
1586            $(annotate_issue_array(
1587                json,
1588                stringify!($field),
1589                introduced_flags(&results.$field, root, base),
1590            );)*
1591        };
1592    }
1593    annotate!(
1594        prop_drilling_chains,
1595        thin_wrappers,
1596        duplicate_prop_shapes,
1597        unused_files,
1598        unused_exports,
1599        unused_types,
1600        private_type_leaks,
1601        deprecated_exports_in_use,
1602        unused_dependencies,
1603        unused_dev_dependencies,
1604        unused_optional_dependencies,
1605        type_only_dependencies,
1606        test_only_dependencies,
1607        unlisted_dependencies,
1608        unlisted_binaries,
1609        unused_enum_members,
1610        unused_class_members,
1611        unused_namespace_members,
1612        unused_protected_class_members,
1613        namespace_escapes,
1614        unused_store_members,
1615        unresolved_imports,
1616        duplicate_exports,
1617        duplicate_export_aliases,
1618        circular_dependencies,
1619        re_export_cycles,
1620        package_cycles,
1621        boundary_violations,
1622        boundary_coverage_violations,
1623        boundary_call_violations,
1624        policy_violations,
1625        stale_suppressions,
1626        unresolved_catalog_references,
1627        unused_catalog_entries,
1628        empty_catalog_groups,
1629        unused_dependency_overrides,
1630        misconfigured_dependency_overrides,
1631        invalid_client_exports,
1632        mixed_client_server_barrels,
1633        misplaced_directives,
1634        unprovided_injects,
1635        unrendered_components,
1636        unused_component_props,
1637        absent_component_props,
1638        constant_parameters,
1639        unused_component_emits,
1640        unused_component_inputs,
1641        unused_component_outputs,
1642        unused_svelte_events,
1643        unused_effect_layers,
1644        unused_tagged_errors,
1645        unproduced_catch_tags,
1646        unused_server_actions,
1647        route_collisions,
1648        dynamic_segment_name_conflicts,
1649    );
1650}
1651
1652/// Annotate the sole legacy dead-code collection without a typed
1653/// `introduced` field. Every wrapper-backed collection is annotated from the
1654/// persisted [`AuditComparison`] instead.
1655#[expect(
1656    clippy::implicit_hasher,
1657    reason = "fallow standardizes on FxHashSet across audit attribution keys"
1658)]
1659pub fn annotate_stale_suppressions_json(
1660    json: &mut serde_json::Value,
1661    results: &fallow_types::results::AnalysisResults,
1662    root: &Path,
1663    base: &FxHashSet<String>,
1664) {
1665    annotate_issue_array(
1666        json,
1667        "stale_suppressions",
1668        stale_suppression_introduced_flags(results, root, base),
1669    );
1670}
1671
1672/// The audit flag of each stale suppression, in report order. A flag is
1673/// `true` when the base snapshot does not hold the key of the suppression.
1674#[expect(
1675    clippy::implicit_hasher,
1676    reason = "fallow standardizes on FxHashSet across audit attribution keys"
1677)]
1678#[must_use]
1679pub fn stale_suppression_introduced_flags(
1680    results: &fallow_types::results::AnalysisResults,
1681    root: &Path,
1682    base: &FxHashSet<String>,
1683) -> Vec<bool> {
1684    introduced_flags(&results.stale_suppressions, root, base)
1685}
1686
1687const STALE_SUPPRESSION_CHECK_NAMES: [&str; 2] = [
1688    "fallow/stale-suppression",
1689    "fallow/missing-suppression-reason",
1690];
1691
1692/// Set the audit attribution on the stale-suppression issues of the
1693/// dead-code CodeClimate issues.
1694///
1695/// `introduced` holds one audit flag per stale suppression, in the order of
1696/// `AnalysisResults::stale_suppressions`. The builder emits one issue per
1697/// stale suppression in that order, so the flags match the issues by
1698/// position. The inline review comment then states if the change introduced
1699/// the stale suppression.
1700pub fn set_stale_suppression_audit_attribution(
1701    issues: &mut [fallow_output::CodeClimateIssue],
1702    introduced: impl IntoIterator<Item = bool>,
1703) {
1704    let stale_issues = issues
1705        .iter_mut()
1706        .filter(|issue| STALE_SUPPRESSION_CHECK_NAMES.contains(&issue.check_name.as_str()));
1707    for (issue, introduced) in stale_issues.zip(introduced) {
1708        issue.audit = Some(crate::dead_code_codeclimate::audit_review_context(
1709            introduced,
1710        ));
1711    }
1712}
1713
1714/// Insert `"introduced": bool` into each `findings` and `styling_findings`
1715/// object in serialized health JSON, matching entries to the typed report by
1716/// array position.
1717///
1718/// A complexity finding keeps the typed `introduced` flag that the audit
1719/// comparison set, because that flag compares metric values. Only a finding
1720/// without the typed flag falls back to identity-key membership in `base`.
1721/// A styling finding also keeps its typed flag, because the audit can use the
1722/// run's diff to tell equal findings apart.
1723#[expect(
1724    clippy::implicit_hasher,
1725    reason = "fallow standardizes on FxHashSet across audit attribution keys"
1726)]
1727pub fn annotate_health_json(
1728    json: &mut serde_json::Value,
1729    report: &fallow_output::HealthReport,
1730    root: &Path,
1731    base: &FxHashSet<String>,
1732) {
1733    if let Some(items) = json
1734        .get_mut("findings")
1735        .and_then(serde_json::Value::as_array_mut)
1736    {
1737        for (item, finding) in items.iter_mut().zip(&report.findings) {
1738            if let serde_json::Value::Object(map) = item {
1739                map.insert(
1740                    "introduced".to_string(),
1741                    serde_json::json!(finding.introduced.unwrap_or_else(|| {
1742                        issue_was_introduced(&health_finding_key(finding, root), base)
1743                    })),
1744                );
1745            }
1746        }
1747    }
1748    styling::annotate_styling_json(json, &report.styling_findings, root, base);
1749}
1750
1751/// Insert `"introduced": bool` into each `clone_groups` object in serialized
1752/// duplication JSON, matching groups to the typed report by array position.
1753#[expect(
1754    clippy::implicit_hasher,
1755    reason = "fallow standardizes on FxHashSet across audit attribution keys"
1756)]
1757pub fn annotate_dupes_json(
1758    json: &mut serde_json::Value,
1759    report: &fallow_types::duplicates::DuplicationReport,
1760    root: &Path,
1761    base: &FxHashSet<String>,
1762) {
1763    let Some(items) = json
1764        .get_mut("clone_groups")
1765        .and_then(serde_json::Value::as_array_mut)
1766    else {
1767        return;
1768    };
1769    for (item, group) in items.iter_mut().zip(&report.clone_groups) {
1770        if let serde_json::Value::Object(map) = item {
1771            map.insert(
1772                "introduced".to_string(),
1773                serde_json::json!(issue_was_introduced(&dupe_group_key(group, root), base)),
1774            );
1775        }
1776    }
1777}
1778
1779/// Attach precomputed introduced membership to an audit JSON array.
1780pub fn annotate_domain_json(
1781    json: &mut serde_json::Value,
1782    collection: &str,
1783    introduced: impl IntoIterator<Item = bool>,
1784) {
1785    annotate_issue_array(json, collection, introduced);
1786}
1787
1788/// Attach a `demotion_reason` to demoted entries of an audit JSON array,
1789/// matching entries to demoted membership by array position. Non-demoted
1790/// entries are left untouched so output without demotions stays byte-identical
1791/// (issue #2220).
1792pub fn annotate_domain_demotions_json(
1793    json: &mut serde_json::Value,
1794    collection: &str,
1795    demoted: impl IntoIterator<Item = bool>,
1796    reason: crate::CloneDemotionReason,
1797) {
1798    let Some(items) = json
1799        .get_mut(collection)
1800        .and_then(serde_json::Value::as_array_mut)
1801    else {
1802        return;
1803    };
1804    for (item, demoted) in items.iter_mut().zip(demoted) {
1805        if demoted && let serde_json::Value::Object(map) = item {
1806            map.insert("demotion_reason".to_string(), serde_json::json!(reason));
1807        }
1808    }
1809}
1810
1811/// Attribution key set for every complexity finding in a health report.
1812pub fn health_keys(report: &fallow_output::HealthReport, root: &Path) -> FxHashSet<String> {
1813    report
1814        .findings
1815        .iter()
1816        .map(|finding| health_finding_key(finding, root))
1817        .collect()
1818}
1819
1820/// Identity key for one complexity finding: `complexity:<path>:<function>`.
1821///
1822/// Line numbers are excluded, so a finding survives unrelated edits above it.
1823/// The exceeded category is excluded, so a category change keeps the match.
1824/// The new-only gate compares the metric values of matched findings, see
1825/// [`classify_complexity_findings`].
1826pub fn health_finding_key(finding: &fallow_output::ComplexityViolation, root: &Path) -> String {
1827    format!(
1828        "complexity:{}:{}",
1829        relative_key_path(Path::new(&finding.path), root),
1830        finding.name,
1831    )
1832}
1833
1834/// Attribution key set for every clone group in a duplication report.
1835pub fn dupes_keys(
1836    report: &fallow_types::duplicates::DuplicationReport,
1837    root: &Path,
1838) -> FxHashSet<String> {
1839    report
1840        .clone_groups
1841        .iter()
1842        .map(|group| dupe_group_key(group, root))
1843        .collect()
1844}
1845
1846/// Attribution key for one clone group:
1847/// `dupe:<sorted files joined by |>:<tokens>:<lines>:<fragment hash>`.
1848/// The fragment hash keeps distinct groups spanning the same files apart;
1849/// line positions are excluded so a group survives shifts within its files.
1850/// The fragment hash leaves out `\r`, so the line endings do not change the key.
1851/// It does not depend on the order of the instances, so a group keeps its
1852/// hash when the change moves its instances to other files.
1853pub fn dupe_group_key(group: &fallow_types::duplicates::CloneGroup, root: &Path) -> String {
1854    let mut files: Vec<String> = group
1855        .instances
1856        .iter()
1857        .map(|instance| relative_key_path(&instance.file, root))
1858        .collect();
1859    files.sort();
1860    files.dedup();
1861    let mut fragment_hashes: Vec<u64> = group
1862        .instances
1863        .iter()
1864        .map(|instance| {
1865            let mut hasher = DefaultHasher::new();
1866            if instance.fragment.contains('\r') {
1867                instance.fragment.replace('\r', "").hash(&mut hasher);
1868            } else {
1869                instance.fragment.hash(&mut hasher);
1870            }
1871            hasher.finish()
1872        })
1873        .collect();
1874    fragment_hashes.sort_unstable();
1875    let mut hasher = DefaultHasher::new();
1876    for fragment_hash in fragment_hashes {
1877        fragment_hash.hash(&mut hasher);
1878    }
1879    format!(
1880        "dupe:{}:{}:{}:{:x}",
1881        files.join("|"),
1882        group.token_count,
1883        group.line_count,
1884        hasher.finish()
1885    )
1886}
1887
1888#[path = "audit_keys_introduced.rs"]
1889mod audit_keys_introduced;
1890use audit_keys_introduced::classify_introduced_dead_code_fields;
1891
1892#[cfg(test)]
1893#[path = "audit_keys_tests.rs"]
1894mod tests;