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