1use std::path::Path;
5
6use fallow_engine::changed_files::RenamedFile;
7use rustc_hash::{FxHashMap, FxHashSet};
8
9use super::{AuditAnalysesView, DeadCodeView};
10use crate::AuditProgrammaticKeySnapshot;
11use crate::audit_keys::{
12 ComplexityBaseline, collection_keys, complexity_baseline, complexity_baseline_keys,
13 dead_code_audit_ledger, dead_code_keys, relative_key_path,
14 remap_complexity_baseline_for_renames, remap_keys_for_renames, styling_keys,
15};
16use crate::review_deltas::{boundary_edge_keys, cycle_keys};
17
18#[derive(Debug, Clone, Default)]
24pub struct AuditKeySnapshot {
25 pub type_aware_identity: Option<fallow_types::semantic::SemanticAnalysisIdentity>,
28 pub type_aware_gap_signature: Vec<String>,
31 pub syntactic_dead_code: Option<FxHashSet<String>>,
35 pub dead_code: FxHashSet<String>,
37 pub unprovable_dead_code: FxHashSet<String>,
42 pub health: ComplexityBaseline,
45 pub styling: FxHashSet<String>,
47 pub dupes: FxHashSet<String>,
49 pub dupe_groups: Vec<crate::diff_risk::clones::BaseCloneGroup>,
52 pub accepted_dupe_groups: Vec<crate::diff_risk::clones::AcceptedCloneGroup>,
56 pub boundary_edges: FxHashSet<String>,
59 pub cycles: FxHashSet<String>,
61 pub public_api: FxHashSet<String>,
64 pub branching: FxHashMap<String, fallow_types::extract::FileBranching>,
68 pub inherited_health: Vec<ComplexityBaseline>,
72 pub own_config_unused_code: Option<FxHashSet<String>>,
81}
82
83impl AuditKeySnapshot {
84 #[must_use]
86 pub fn from_view(view: &AuditAnalysesView<'_>) -> Self {
87 let mut snapshot = Self::default();
88 if let Some(dead_code) = view.dead_code.as_ref() {
89 snapshot.type_aware_identity =
90 dead_code.type_aware.and_then(|meta| meta.identity.clone());
91 snapshot.type_aware_gap_signature = dead_code
92 .type_aware
93 .map_or_else(Vec::new, type_aware_gap_signature);
94 snapshot.syntactic_dead_code = dead_code.syntactic_keys.cloned();
95 snapshot.dead_code = dead_code_keys(dead_code.results, dead_code.root);
96 snapshot.unprovable_dead_code =
97 fallow_engine::unprovable::unprovable_dead_code_collections(dead_code.config)
98 .into_iter()
99 .map(str::to_owned)
100 .collect();
101 snapshot.boundary_edges = boundary_edge_keys(&dead_code.results.boundary_violations);
102 snapshot.cycles = cycle_keys(&dead_code.results.circular_dependencies, dead_code.root);
103 snapshot.public_api = dead_code.public_api.cloned().unwrap_or_default();
104 snapshot.own_config_unused_code = dead_code.own_config_unused_code.cloned();
105 }
106 if let Some(health) = view.health.as_ref() {
107 snapshot.health = complexity_baseline(health.report, health.root);
108 snapshot.styling = styling_keys(health.report, health.root);
109 snapshot.branching = health.branching.map_or_else(FxHashMap::default, |by_file| {
110 branching_keys(by_file, health.root)
111 });
112 }
113 if let Some(duplication) = view.duplication.as_ref() {
114 snapshot.dupes = duplication
115 .clone_groups
116 .iter()
117 .map(|group| crate::audit_keys::dupe_group_key(group, duplication.root))
118 .collect();
119 snapshot.dupe_groups = duplication
120 .clone_groups
121 .iter()
122 .map(|group| crate::diff_risk::clones::BaseCloneGroup {
123 instances: crate::diff_risk::clone_spans(group, duplication.root),
124 })
125 .collect();
126 snapshot.accepted_dupe_groups = duplication
127 .ignored_groups
128 .iter()
129 .map(|ignored| crate::diff_risk::clones::AcceptedCloneGroup {
130 key: ignored.key.clone(),
131 instances: crate::diff_risk::clone_spans(&ignored.group, duplication.root),
132 })
133 .collect();
134 }
135 snapshot
136 }
137
138 #[must_use]
141 pub fn reports_dead_code(&self, key: &str) -> bool {
142 self.dead_code.contains(key)
143 || self
144 .syntactic_dead_code
145 .as_ref()
146 .is_some_and(|syntactic| syntactic.contains(key))
147 }
148
149 pub fn forget_unused_code_used_under_own_config(&mut self, head: &DeadCodeView<'_>) {
155 let Some(own) = self.own_config_unused_code.as_ref() else {
156 return;
157 };
158 let head_keys = collection_keys(&head.results.unused_files, head.root)
159 .into_iter()
160 .chain(collection_keys(&head.results.unused_exports, head.root));
161 for key in head_keys.filter(|key| !own.contains(key)) {
162 self.dead_code.remove(&key);
163 if let Some(syntactic) = self.syntactic_dead_code.as_mut() {
164 syntactic.remove(&key);
165 }
166 }
167 }
168
169 pub fn absorb_inherited(&mut self, inherited: Self) {
180 let inherited_syntactic = inherited
181 .syntactic_dead_code
182 .unwrap_or_else(|| inherited.dead_code.clone());
183 if let Some(syntactic) = self.syntactic_dead_code.as_mut() {
184 syntactic.extend(inherited_syntactic);
185 }
186 if let Some(own) = self.own_config_unused_code.as_mut() {
189 own.extend(
190 inherited
191 .own_config_unused_code
192 .unwrap_or_else(|| inherited.dead_code.clone()),
193 );
194 }
195 if self.type_aware_identity == inherited.type_aware_identity
198 && self.type_aware_gap_signature == inherited.type_aware_gap_signature
199 {
200 self.dead_code.extend(inherited.dead_code);
201 }
202 self.unprovable_dead_code
203 .extend(inherited.unprovable_dead_code);
204 self.styling.extend(inherited.styling);
205 self.dupes.extend(inherited.dupes);
206 self.boundary_edges.extend(inherited.boundary_edges);
207 self.cycles.extend(inherited.cycles);
208 self.public_api.extend(inherited.public_api);
209 self.inherited_health.push(inherited.health);
210 self.inherited_health.extend(inherited.inherited_health);
211 }
212
213 pub fn inherit_unprovable_dead_code(&mut self, head: &DeadCodeView<'_>) {
223 if self.unprovable_dead_code.is_empty() {
224 return;
225 }
226 let ledger = dead_code_audit_ledger(head.results, head.root, head.config, None);
227 let keys: Vec<String> = ledger
228 .records()
229 .iter()
230 .filter(|record| self.unprovable_dead_code.contains(record.collection))
231 .map(|record| record.stable_key.clone())
232 .collect();
233 if let Some(syntactic) = self.syntactic_dead_code.as_mut() {
234 syntactic.extend(keys.iter().cloned());
235 }
236 self.dead_code.extend(keys);
237 }
238
239 pub fn remap_for_renames(&mut self, renames: &[RenamedFile], root: &Path) {
247 let rename_map: FxHashMap<String, String> = renames
248 .iter()
249 .filter_map(|rename| {
250 let from = relative_key_path(&rename.from, root);
251 let to = relative_key_path(&rename.to, root);
252 (from != to).then_some((from, to))
253 })
254 .collect();
255 if rename_map.is_empty() {
256 return;
257 }
258 self.dead_code = remap_keys_for_renames(&self.dead_code, &rename_map);
259 if let Some(own) = self.own_config_unused_code.as_mut() {
260 *own = remap_keys_for_renames(own, &rename_map);
261 }
262 self.health =
263 remap_complexity_baseline_for_renames(std::mem::take(&mut self.health), &rename_map);
264 self.styling = remap_keys_for_renames(&self.styling, &rename_map);
265 self.dupes = remap_keys_for_renames(&self.dupes, &rename_map);
266 self.cycles = remap_keys_for_renames(&self.cycles, &rename_map);
267 self.public_api = remap_keys_for_renames(&self.public_api, &rename_map);
268 self.branching = self
271 .branching
272 .drain()
273 .map(|(path, totals)| match rename_map.get(&path) {
274 Some(renamed) => (renamed.clone(), totals),
275 None => (path, totals),
276 })
277 .collect();
278 }
279
280 #[must_use]
283 pub fn to_programmatic(&self) -> AuditProgrammaticKeySnapshot {
284 let mut health = complexity_baseline_keys(&self.health);
285 health.extend(self.styling.iter().cloned());
286 AuditProgrammaticKeySnapshot {
287 dead_code: self.dead_code.clone(),
288 health,
289 dupes: self.dupes.clone(),
290 }
291 }
292}
293
294#[must_use]
297pub fn branching_keys(
298 by_file: &fallow_engine::health::BranchingByFile,
299 root: &Path,
300) -> FxHashMap<String, fallow_types::extract::FileBranching> {
301 by_file
302 .iter()
303 .map(|(path, totals)| (relative_key_path(path, root), *totals))
304 .collect()
305}
306
307#[must_use]
318pub fn type_aware_attribution_degrade_reason(
319 base: Option<&AuditKeySnapshot>,
320 head: Option<&fallow_types::envelope::TypeAwareMeta>,
321) -> Option<&'static str> {
322 let base = base?;
323 let base_identity = base.type_aware_identity.as_ref();
324 let head_identity = head.and_then(|meta| meta.identity.as_ref());
325 if let (Some(base_identity), Some(head_identity)) = (base_identity, head_identity)
326 && !base_identity.incompatible_fields(head_identity).is_empty()
327 {
328 return Some("their semantic analysis identities are incompatible");
329 }
330 if let Some(head) = head
331 && base.type_aware_gap_signature != type_aware_gap_signature(head)
332 {
333 return Some("their incomplete semantic query reasons or omissions differ");
334 }
335 None
336}
337
338#[must_use]
341pub fn type_aware_degrade_warning(reason: &str) -> String {
342 format!(
343 "audit compared base and head with syntactic attribution because {reason} \
344(usually a tsconfig or compiler-options change between base and head); \
345type-aware refinement still applies to head findings, and \
346semantic-only findings stay out of the new-only gate for this run; set \
347audit.typeAware: false or pass --no-type-aware to keep the gate syntactic"
348 )
349}
350
351#[must_use]
353pub fn type_aware_gap_signature(meta: &fallow_types::envelope::TypeAwareMeta) -> Vec<String> {
354 let mut signature = meta
355 .queries
356 .iter()
357 .filter(|query| query.status != fallow_types::semantic::SemanticCompleteness::Complete)
358 .map(|query| {
359 let mut omissions = query
360 .omissions
361 .iter()
362 .map(|omission| format!("{:?}:{}", omission.reason_code, omission.count))
363 .collect::<Vec<_>>();
364 omissions.sort();
365 format!(
366 "{:?}:{:?}:{}",
367 query.capability,
368 query.reason_code,
369 omissions.join(",")
370 )
371 })
372 .collect::<Vec<_>>();
373 signature.sort();
374 signature
375}