Skip to main content

fallow_engine/
module_graph.rs

1//! Module graph contracts owned by the engine boundary.
2
3#![allow(
4    clippy::implicit_hasher,
5    reason = "engine graph helpers use FxHashSet changed-file sets consistently with the rest of fallow"
6)]
7
8use std::path::{Path, PathBuf};
9
10use fallow_output::TestAdjacency;
11use fallow_types::discover::FileId;
12use rustc_hash::{FxHashMap, FxHashSet};
13
14use fallow_graph::graph::{
15    CoordinationGapPaths as GraphCoordinationGapPaths,
16    FocusFileFactsPaths as GraphFocusFileFactsPaths, ImpactClosurePaths as GraphImpactClosurePaths,
17    ModuleGraph, PartitionOrderPaths as GraphPartitionOrderPaths,
18    ReviewUnitPaths as GraphReviewUnitPaths,
19};
20use fallow_graph::graph::{
21    DirectImporterSummary as GraphDirectImporterSummary,
22    ImportedSymbolSummary as GraphImportedSymbolSummary,
23};
24use fallow_graph::graph::{
25    ExportTestReach as GraphExportTestReach, ExportTestReachResult as GraphExportTestReachResult,
26    TestMaskingState as GraphTestMaskingState,
27};
28
29/// Engine-owned retained graph handle.
30///
31/// Downstream crates can request stable graph facts through engine helpers
32/// without depending on `fallow-graph` node internals.
33#[derive(Debug)]
34pub struct RetainedModuleGraph {
35    inner: ModuleGraph,
36}
37
38impl RetainedModuleGraph {
39    /// Wrap a freshly built module graph for engine result contracts.
40    #[must_use]
41    const fn new(inner: ModuleGraph) -> Self {
42        Self { inner }
43    }
44
45    pub(crate) const fn as_graph(&self) -> &ModuleGraph {
46        &self.inner
47    }
48
49    /// Borrow the shared static test-coverage view for health analysis.
50    pub(crate) const fn static_test_coverage(&self) -> StaticTestCoverage<'_> {
51        StaticTestCoverage::new(&self.inner)
52    }
53
54    /// Number of modules in the retained graph.
55    #[must_use]
56    pub fn module_count(&self) -> usize {
57        self.inner.module_count()
58    }
59
60    /// Number of edges in the retained graph.
61    #[must_use]
62    pub fn edge_count(&self) -> usize {
63        self.inner.edge_count()
64    }
65
66    /// Build public export keys for a precomputed public-entry set.
67    #[must_use]
68    pub(crate) fn public_export_keys(
69        &self,
70        public_entries: &FxHashSet<FileId>,
71        root: &Path,
72    ) -> FxHashSet<String> {
73        self.inner.public_export_keys(public_entries, root)
74    }
75
76    /// Count direct importer modules for one file id.
77    #[must_use]
78    pub fn direct_importer_count(&self, file_id: FileId) -> usize {
79        self.inner
80            .reverse_deps
81            .get(file_id.0 as usize)
82            .map_or(0, Vec::len)
83    }
84
85    /// Summaries for modules that directly import one file.
86    #[must_use]
87    pub fn direct_importer_summaries(&self, target: FileId) -> Vec<DirectImporterSummary> {
88        self.inner
89            .direct_importer_summaries(target)
90            .into_iter()
91            .map(DirectImporterSummary::from)
92            .collect()
93    }
94}
95
96/// Engine-owned view of root-correlated static test reachability.
97///
98/// This keeps health consumers on one contract while the graph crate owns the
99/// traversal and replacement-mask representation.
100///
101/// A view can read a second graph that holds the test files. Production mode
102/// keeps test files out of the analysis graph, so health reads test
103/// reachability from a graph of the full project. `file_map` then maps each
104/// analysis file id to the file id of the same path in that graph.
105#[derive(Clone, Copy)]
106pub(crate) struct StaticTestCoverage<'a> {
107    graph: &'a ModuleGraph,
108    file_map: Option<&'a FxHashMap<FileId, FileId>>,
109}
110
111impl<'a> StaticTestCoverage<'a> {
112    pub(crate) const fn new(graph: &'a ModuleGraph) -> Self {
113        Self {
114            graph,
115            file_map: None,
116        }
117    }
118
119    /// Read test reachability from `graph`, a graph built over a different
120    /// file set. `file_map` maps the caller's file ids to the ids in `graph`.
121    pub(crate) const fn mapped(
122        graph: &'a ModuleGraph,
123        file_map: &'a FxHashMap<FileId, FileId>,
124    ) -> Self {
125        Self {
126            graph,
127            file_map: Some(file_map),
128        }
129    }
130
131    fn graph_file_id(self, file_id: FileId) -> Option<FileId> {
132        match self.file_map {
133            Some(file_map) => file_map.get(&file_id).copied(),
134            None => Some(file_id),
135        }
136    }
137
138    /// The export in the coverage graph that has the name of `export`.
139    fn graph_export<'b>(
140        self,
141        file_id: FileId,
142        export: &'b fallow_graph::graph::ExportSymbol,
143    ) -> Option<(FileId, &'b fallow_graph::graph::ExportSymbol)>
144    where
145        'a: 'b,
146    {
147        if self.file_map.is_none() {
148            return Some((file_id, export));
149        }
150        let graph_file_id = self.graph_file_id(file_id)?;
151        let node = self.graph.modules.get(graph_file_id.0 as usize)?;
152        node.exports
153            .iter()
154            .find(|candidate| candidate.name == export.name)
155            .map(|candidate| (graph_file_id, candidate))
156    }
157
158    pub(crate) fn covers_file(self, file_id: FileId) -> bool {
159        self.graph_file_id(file_id)
160            .is_some_and(|graph_file_id| self.graph.is_test_reachable(graph_file_id))
161    }
162
163    pub(crate) fn covers_any_reference(
164        self,
165        file_id: FileId,
166        export: &fallow_graph::graph::ExportSymbol,
167    ) -> bool {
168        self.graph_export(file_id, export)
169            .is_some_and(|(_, export)| self.graph.is_any_test_reference_covered(export))
170    }
171
172    /// Whether only tests that mock a module on the reference path reference
173    /// `export`. Call it for an export without a covered reference.
174    pub(crate) fn is_mocked_only(
175        self,
176        file_id: FileId,
177        export: &fallow_graph::graph::ExportSymbol,
178    ) -> bool {
179        if self.graph.test_masking_state() != GraphTestMaskingState::Active {
180            return false;
181        }
182        self.graph_export(file_id, export)
183            .is_some_and(|(graph_file_id, export)| {
184                self.graph
185                    .export_test_reach(graph_file_id, export, &|_| false)
186                    .reach
187                    == GraphExportTestReach::MockedOnly
188            })
189    }
190}
191
192impl From<ModuleGraph> for RetainedModuleGraph {
193    fn from(inner: ModuleGraph) -> Self {
194        Self::new(inner)
195    }
196}
197
198/// Engine-owned importer details for one file that directly imports a target module.
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct DirectImporterSummary {
201    /// File containing the import statement.
202    pub source: FileId,
203    /// Symbols this importer pulls from the target module.
204    pub symbols: Vec<ImportedSymbolSummary>,
205}
206
207impl From<GraphDirectImporterSummary> for DirectImporterSummary {
208    fn from(summary: GraphDirectImporterSummary) -> Self {
209        Self {
210            source: summary.source,
211            symbols: summary.symbols.into_iter().map(Into::into).collect(),
212        }
213    }
214}
215
216/// Engine-owned symbol details for a direct import edge.
217#[derive(Debug, Clone, PartialEq, Eq)]
218pub struct ImportedSymbolSummary {
219    /// Exported name as declared by the target module.
220    pub imported: String,
221    /// Local binding name at the import site.
222    pub local: String,
223    /// True for type-only imports, which do not count as value usage.
224    pub type_only: bool,
225}
226
227impl From<GraphImportedSymbolSummary> for ImportedSymbolSummary {
228    fn from(symbol: GraphImportedSymbolSummary) -> Self {
229        Self {
230            imported: symbol.imported,
231            local: symbol.local,
232            type_only: symbol.type_only,
233        }
234    }
235}
236
237/// Engine-owned snapshot of one value export in a module graph.
238#[derive(Debug, Clone, PartialEq, Eq)]
239pub struct ModuleValueExport {
240    /// File declaring the export.
241    pub file_id: FileId,
242    /// Exported name.
243    pub name: String,
244    /// Byte offset where the export declaration starts.
245    pub span_start: u32,
246    /// True when a test file references this export.
247    pub test_referenced: bool,
248}
249
250/// Engine-owned impact closure with file ids resolved to paths.
251#[derive(Debug, Clone, Default, PartialEq, Eq)]
252pub struct ImpactClosurePaths {
253    /// Changed files that are part of the diff under review.
254    pub in_diff: Vec<String>,
255    /// Files affected through the import closure but absent from the diff.
256    pub affected_not_shown: Vec<String>,
257    /// Changed contracts whose consumers were not updated in the same diff.
258    pub coordination_gap: Vec<CoordinationGapPaths>,
259}
260
261impl From<GraphImpactClosurePaths> for ImpactClosurePaths {
262    fn from(paths: GraphImpactClosurePaths) -> Self {
263        Self {
264            in_diff: paths.in_diff,
265            affected_not_shown: paths.affected_not_shown,
266            coordination_gap: paths
267                .coordination_gap
268                .into_iter()
269                .map(CoordinationGapPaths::from)
270                .collect(),
271        }
272    }
273}
274
275/// Engine-owned coordination gap between a changed contract and consumer.
276#[derive(Debug, Clone, PartialEq, Eq)]
277pub struct CoordinationGapPaths {
278    /// Path of the changed file whose contract moved.
279    pub changed_file: String,
280    /// Path of the consumer that was not updated alongside it.
281    pub consumer_file: String,
282    /// Symbols the consumer imports from the changed file.
283    pub consumed_symbols: Vec<String>,
284}
285
286impl From<GraphCoordinationGapPaths> for CoordinationGapPaths {
287    fn from(paths: GraphCoordinationGapPaths) -> Self {
288        Self {
289            changed_file: paths.changed_file,
290            consumer_file: paths.consumer_file,
291            consumed_symbols: paths.consumed_symbols,
292        }
293    }
294}
295
296/// Engine-owned review partition and dependency-sensible order.
297#[derive(Debug, Clone, Default, PartialEq, Eq)]
298pub struct PartitionOrderPaths {
299    /// Changed files partitioned into per-module review units.
300    pub units: Vec<ReviewUnitPaths>,
301    /// File paths in dependency-sensible review order (dependencies first).
302    pub order: Vec<String>,
303    /// Connected components of the inter-unit dependency graph: units that
304    /// share no import edge with any unit outside their slice.
305    pub independent_slices: Vec<Vec<String>>,
306}
307
308impl From<GraphPartitionOrderPaths> for PartitionOrderPaths {
309    fn from(paths: GraphPartitionOrderPaths) -> Self {
310        Self {
311            units: paths.units.into_iter().map(ReviewUnitPaths::from).collect(),
312            order: paths.order,
313            independent_slices: paths.independent_slices,
314        }
315    }
316}
317
318/// Engine-owned changed-file review unit.
319#[derive(Debug, Clone, PartialEq, Eq)]
320pub struct ReviewUnitPaths {
321    /// Directory the unit's files share.
322    pub module_dir: String,
323    /// Changed files grouped into this unit.
324    pub files: Vec<String>,
325}
326
327impl From<GraphReviewUnitPaths> for ReviewUnitPaths {
328    fn from(paths: GraphReviewUnitPaths) -> Self {
329        Self {
330            module_dir: paths.module_dir,
331            files: paths.files,
332        }
333    }
334}
335
336/// Engine-owned focus facts for one changed file.
337#[derive(Debug, Clone, PartialEq, Eq)]
338pub struct FocusFileFactsPaths {
339    /// Path of the changed file the facts describe.
340    pub file: String,
341    /// Count of distinct files importing this file (blast radius), excluding
342    /// the file itself.
343    pub fan_in: u32,
344    /// Count of distinct files this file imports, excluding the file itself.
345    pub fan_out: u32,
346    /// True when the file has a dynamic-import edge in either direction, so
347    /// its static reachability signal is not complete. Conservative: a file
348    /// that MAY be dynamically wired carries the flag.
349    pub dynamic_dispatch: bool,
350    /// True when the file's reachability runs through re-export indirection,
351    /// so direct importer counts understate its reach.
352    pub re_export_indirection: bool,
353}
354
355impl From<GraphFocusFileFactsPaths> for FocusFileFactsPaths {
356    fn from(paths: GraphFocusFileFactsPaths) -> Self {
357        Self {
358            file: paths.file,
359            fan_in: paths.fan_in,
360            fan_out: paths.fan_out,
361            dynamic_dispatch: paths.dynamic_dispatch,
362            re_export_indirection: paths.re_export_indirection,
363        }
364    }
365}
366
367/// Return value exports with test-reference state without exposing graph node
368/// internals to downstream crates.
369#[must_use]
370pub fn module_value_exports(graph: &RetainedModuleGraph) -> Vec<ModuleValueExport> {
371    module_value_exports_with_test_reach(graph, None)
372}
373
374/// Return value exports of `graph` with test-reference state.
375///
376/// When `test_reach` is given, test-reference state comes from that
377/// full-project graph. Production mode needs this because its analysis graph
378/// has no test files.
379#[must_use]
380pub fn module_value_exports_with_test_reach(
381    graph: &RetainedModuleGraph,
382    test_reach: Option<&crate::health::TestReachGraph>,
383) -> Vec<ModuleValueExport> {
384    let test_coverage = test_reach.map_or_else(
385        || graph.static_test_coverage(),
386        crate::health::TestReachGraph::static_test_coverage,
387    );
388    let graph = graph.as_graph();
389
390    graph
391        .modules
392        .iter()
393        .flat_map(|node| {
394            node.exports
395                .iter()
396                .filter(|export| !export.is_type_only)
397                .map(|export| ModuleValueExport {
398                    file_id: node.file_id,
399                    name: export.name.to_string(),
400                    span_start: export.span.start,
401                    test_referenced: test_coverage.covers_any_reference(node.file_id, export),
402                })
403        })
404        .collect()
405}
406
407/// Compute a path-resolved impact closure for absolute changed paths.
408#[must_use]
409pub fn impact_closure_for_changed_paths(
410    graph: &RetainedModuleGraph,
411    root: &Path,
412    changed_files: &FxHashSet<PathBuf>,
413) -> Option<ImpactClosurePaths> {
414    let graph = graph.as_graph();
415    let changed_ids = changed_file_ids(graph, changed_files);
416    if changed_ids.is_empty() {
417        return None;
418    }
419
420    let closure = graph.impact_closure(&changed_ids);
421    Some(graph.closure_with_paths(&closure, root).into())
422}
423
424/// Compute path-resolved partition order for absolute changed paths.
425#[must_use]
426pub fn partition_order_for_changed_paths(
427    graph: &RetainedModuleGraph,
428    root: &Path,
429    changed_files: &FxHashSet<PathBuf>,
430) -> Option<PartitionOrderPaths> {
431    let graph = graph.as_graph();
432    let changed_ids = changed_file_ids(graph, changed_files);
433    if changed_ids.is_empty() {
434        return None;
435    }
436
437    let partition = graph.partition_order(&changed_ids);
438    Some(graph.partition_order_with_paths(&partition, root).into())
439}
440
441/// Compute path-resolved focus graph facts for absolute changed paths.
442#[must_use]
443pub fn focus_facts_for_changed_paths(
444    graph: &RetainedModuleGraph,
445    root: &Path,
446    changed_files: &FxHashSet<PathBuf>,
447) -> Option<Vec<FocusFileFactsPaths>> {
448    let graph = graph.as_graph();
449    let changed_ids = changed_file_ids(graph, changed_files);
450    if changed_ids.is_empty() {
451        return None;
452    }
453
454    let facts = graph.focus_file_facts(&changed_ids);
455    Some(
456        graph
457            .focus_facts_with_paths(&facts, root)
458            .into_iter()
459            .map(FocusFileFactsPaths::from)
460            .collect(),
461    )
462}
463
464/// Compute changed-file export line anchors without exposing graph nodes.
465#[must_use]
466pub fn export_lines_for_changed_paths(
467    graph: &RetainedModuleGraph,
468    root: &Path,
469    changed_files: &FxHashSet<PathBuf>,
470) -> Option<FxHashMap<String, Vec<(String, u32)>>> {
471    let graph = graph.as_graph();
472    let changed_norm = normalized_changed_paths(changed_files);
473    let mut map: FxHashMap<String, Vec<(String, u32)>> = FxHashMap::default();
474    for module in &graph.modules {
475        let abs = normalize_path(&module.path);
476        if !changed_norm.contains(&abs) || module.exports.is_empty() {
477            continue;
478        }
479        let Ok(content) = std::fs::read_to_string(&module.path) else {
480            continue;
481        };
482        let offsets = fallow_types::extract::compute_line_offsets(&content);
483        let exports: Vec<(String, u32)> = module
484            .exports
485            .iter()
486            .map(|export| {
487                let (line, _) =
488                    fallow_types::extract::byte_offset_to_line_col(&offsets, export.span.start);
489                (export.name.to_string(), line)
490            })
491            .collect();
492        map.insert(relative_key_path(&module.path, root), exports);
493    }
494    Some(map)
495}
496
497/// One consumer that a whole-word text search for an export name does not
498/// find, or finds only under another local name.
499#[derive(Debug, Clone, PartialEq, Eq)]
500pub struct ConsumerSearchGapPaths {
501    /// Root-relative path of the consumer, forward-slashed.
502    pub consumer_file: String,
503    /// The literal-search check for the consumer.
504    pub check: crate::search_visibility::SearchCheck,
505}
506
507/// Literal-search gaps for one export of a changed file.
508#[derive(Debug, Clone, PartialEq, Eq)]
509pub struct ExportSearchGapPaths {
510    /// Root-relative path of the changed file, forward-slashed.
511    pub file: String,
512    /// The export name, `default` for a default export.
513    pub export_name: String,
514    /// 1-based line of the export.
515    pub line: u32,
516    /// 1-based first and last line of the top-level statement that declares
517    /// the export.
518    pub declaration_lines: (u32, u32),
519    /// The `missed` and `renamed` consumers outside the changed files, sorted
520    /// by path.
521    pub consumers: Vec<ConsumerSearchGapPaths>,
522}
523
524/// The names of the exports that `source` declares, parsed as the file at
525/// `path`. The names use the format of [`ChangedExport::export_name`].
526#[must_use]
527pub fn export_names_in_source(path: &Path, source: &str) -> FxHashSet<String> {
528    let module = fallow_extract::parse_source_to_module(FileId(0), path, source, 0, false);
529    module
530        .exports
531        .iter()
532        .map(|export| export.name.to_string())
533        .collect()
534}
535
536/// One export of a changed file, with the line facts that the review brief
537/// joins on the diff.
538///
539/// [`changed_exports_for_changed_paths`] reads and parses each changed file
540/// once. The literal-search gap pass and the test reach pass share the list.
541#[derive(Debug, Clone, PartialEq, Eq)]
542pub struct ChangedExport {
543    file_id: FileId,
544    export_index: usize,
545    /// Root-relative path of the changed file, forward-slashed.
546    pub file: String,
547    /// The export name, `default` for a default export.
548    pub export_name: String,
549    /// 1-based line of the export.
550    pub line: u32,
551    /// 1-based first and last line of the top-level statement that declares
552    /// the export.
553    pub declaration_lines: (u32, u32),
554    /// True for a type-only export.
555    pub is_type_only: bool,
556    /// True when the export is a variable whose initializer is a literal, or
557    /// an object or array of literals.
558    pub literal_value: bool,
559    /// True when a re-export statement (`export { x } from`) makes the export.
560    pub is_re_export: bool,
561}
562
563/// List the exports of absolute changed paths with their declaration lines.
564///
565/// Each changed file is read and parsed once. The exports keep graph order
566/// within a file, and the files are in `FileId` order. `None` when no module
567/// matches a changed path.
568#[must_use]
569pub fn changed_exports_for_changed_paths(
570    graph: &RetainedModuleGraph,
571    root: &Path,
572    changed_files: &FxHashSet<PathBuf>,
573) -> Option<Vec<ChangedExport>> {
574    let graph = graph.as_graph();
575    let mut changed_ids = changed_file_ids(graph, changed_files);
576    if changed_ids.is_empty() {
577        return None;
578    }
579    changed_ids.sort_unstable_by_key(|id| id.0);
580    let mut changed_exports = Vec::new();
581    for file_id in changed_ids {
582        let Some(module) = graph.modules.get(file_id.0 as usize) else {
583            continue;
584        };
585        if module.exports.is_empty() {
586            continue;
587        }
588        let Ok(source) = std::fs::read_to_string(&module.path) else {
589            continue;
590        };
591        changed_exports.extend(module_exports(graph, root, file_id, &source));
592    }
593    Some(changed_exports)
594}
595
596/// List the exports of one module with their declaration lines. `source` is
597/// the current text of the module. The exports keep graph order.
598pub(crate) fn module_exports(
599    graph: &ModuleGraph,
600    root: &Path,
601    file_id: FileId,
602    source: &str,
603) -> Vec<ChangedExport> {
604    let Some(module) = graph.modules.get(file_id.0 as usize) else {
605        return Vec::new();
606    };
607    if module.exports.is_empty() {
608        return Vec::new();
609    }
610    let offsets = fallow_types::extract::compute_line_offsets(source);
611    let starts: Vec<u32> = module
612        .exports
613        .iter()
614        .map(|export| export.span.start)
615        .collect();
616    let declarations = crate::search_visibility::export_declarations(&module.path, source, &starts);
617    let file = relative_key_path(&module.path, root);
618    module
619        .exports
620        .iter()
621        .enumerate()
622        .map(|(export_index, export)| {
623            let line =
624                fallow_types::extract::byte_offset_to_line_col(&offsets, export.span.start).0;
625            let declaration = declarations.get(&export.span.start);
626            ChangedExport {
627                file_id,
628                export_index,
629                file: file.clone(),
630                export_name: export.name.to_string(),
631                line,
632                declaration_lines: declaration.map_or((line, line), |found| found.lines),
633                is_type_only: export.is_type_only,
634                literal_value: declaration.is_some_and(|found| found.literal_value),
635                is_re_export: declaration.is_some_and(|found| found.is_re_export),
636            }
637        })
638        .collect()
639}
640
641/// Compute the literal-search gaps of the changed exports.
642///
643/// For each export of a changed file, the consumers outside the changed set
644/// are checked against a whole-word text search for the export name. Only
645/// exports with at least one `missed` or `renamed` consumer are returned. The
646/// consumer sources are read on demand.
647#[must_use]
648pub fn search_gaps_for_changed_paths(
649    graph: &RetainedModuleGraph,
650    root: &Path,
651    changed_files: &FxHashSet<PathBuf>,
652    changed_exports: &[ChangedExport],
653) -> Option<Vec<ExportSearchGapPaths>> {
654    use crate::search_visibility::{SearchTarget, SourceCache};
655    use fallow_graph::graph::ExportNamespace;
656    use fallow_types::trace::SearchVisibility;
657
658    let graph = graph.as_graph();
659    let changed_set: FxHashSet<FileId> =
660        changed_file_ids(graph, changed_files).into_iter().collect();
661    if changed_set.is_empty() {
662        return None;
663    }
664    let mut sources = SourceCache::new(graph);
665    let mut gaps = Vec::new();
666    for changed in changed_exports {
667        let Some(export) = graph
668            .modules
669            .get(changed.file_id.0 as usize)
670            .and_then(|module| module.exports.get(changed.export_index))
671        else {
672            continue;
673        };
674        let mut seen = FxHashSet::default();
675        let candidates: Vec<_> = export
676            .references
677            .iter()
678            .filter(|reference| {
679                !changed_set.contains(&reference.from_file)
680                    && graph
681                        .modules
682                        .get(reference.from_file.0 as usize)
683                        .is_some_and(fallow_graph::graph::ModuleNode::is_reachable)
684                    && seen.insert(reference.from_file)
685            })
686            .collect();
687        if candidates.is_empty() {
688            continue;
689        }
690        let namespace = if export.is_type_only {
691            ExportNamespace::Type
692        } else {
693            ExportNamespace::Value
694        };
695        let target = SearchTarget::new(
696            graph,
697            &mut sources,
698            changed.file_id,
699            &changed.export_name,
700            namespace,
701        );
702        let mut consumers: Vec<ConsumerSearchGapPaths> = candidates
703            .into_iter()
704            .filter_map(|reference| {
705                let check = target.check(graph, &mut sources, reference)?;
706                if check.visibility == SearchVisibility::Found {
707                    return None;
708                }
709                let consumer = graph.modules.get(reference.from_file.0 as usize)?;
710                Some(ConsumerSearchGapPaths {
711                    consumer_file: relative_key_path(&consumer.path, root),
712                    check,
713                })
714            })
715            .collect();
716        if consumers.is_empty() {
717            continue;
718        }
719        consumers.sort_by(|a, b| a.consumer_file.cmp(&b.consumer_file));
720        gaps.push(ExportSearchGapPaths {
721            file: changed.file.clone(),
722            export_name: changed.export_name.clone(),
723            line: changed.line,
724            declaration_lines: changed.declaration_lines,
725            consumers,
726        });
727    }
728    Some(gaps)
729}
730
731/// Package names whose presence marks an end-to-end test runner. Such tests
732/// drive a running app and do not import the source files.
733const E2E_RUNNER_PACKAGES: &[&str] = &["@playwright/test", "playwright", "cypress"];
734
735/// How tests reach one export.
736#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
737#[serde(rename_all = "kebab-case")]
738pub enum ExportTestReach {
739    /// A test file references the export, and a test root covers it.
740    Direct,
741    /// A covered reference exists, but no test file names the export.
742    Transitive,
743    /// No reference is covered, and a mock replaces a module on a reference
744    /// path.
745    MockedOnly,
746    /// A test root reaches the declaring file, but no reference is covered.
747    None,
748    /// No test root reaches the declaring file.
749    NoneFile,
750}
751
752impl From<GraphExportTestReach> for ExportTestReach {
753    fn from(reach: GraphExportTestReach) -> Self {
754        match reach {
755            GraphExportTestReach::Direct => Self::Direct,
756            GraphExportTestReach::Transitive => Self::Transitive,
757            GraphExportTestReach::MockedOnly => Self::MockedOnly,
758            GraphExportTestReach::None => Self::None,
759            GraphExportTestReach::NoneFile => Self::NoneFile,
760        }
761    }
762}
763
764/// Why replacement masking is or is not active for test reachability.
765#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
766pub enum TestMaskingState {
767    /// At least one test root replaces a module with a closed factory mock.
768    Active,
769    /// No test root declares a closed factory mock.
770    NoMocks,
771    /// Too many distinct mock sets, so masking is off.
772    Capped,
773}
774
775impl From<GraphTestMaskingState> for TestMaskingState {
776    fn from(state: GraphTestMaskingState) -> Self {
777        match state {
778            GraphTestMaskingState::Active => Self::Active,
779            GraphTestMaskingState::NoMocks => Self::NoMocks,
780            GraphTestMaskingState::Capped => Self::Capped,
781        }
782    }
783}
784
785/// How tests reach one changed value export.
786#[derive(Debug, Clone, PartialEq, Eq)]
787pub struct ExportTestReachPaths {
788    /// Root-relative path of the changed file, forward-slashed.
789    pub file: String,
790    /// The export name, `default` for a default export.
791    pub export_name: String,
792    /// 1-based line of the export.
793    pub line: u32,
794    /// 1-based first and last line of the declaring statement.
795    pub declaration_lines: (u32, u32),
796    /// True when the export is a variable with a literal initializer.
797    pub literal_value: bool,
798    /// The reach class.
799    pub reach: ExportTestReach,
800    /// Test files that name the export, sorted: the covered test references
801    /// for `Direct`, the masked test references for `MockedOnly`.
802    pub tests: Vec<String>,
803    /// For `MockedOnly`: the masked modules on the reference paths, sorted.
804    pub mocked_targets: Vec<String>,
805}
806
807/// Test reach of the changed value exports of a diff.
808#[derive(Debug, Clone, PartialEq, Eq)]
809pub struct TestReachPaths {
810    /// False when the project has no test entry points. Every export is then
811    /// `NoneFile`.
812    pub has_tests: bool,
813    /// Whether test reachability applies replacement masks.
814    pub masking: TestMaskingState,
815    /// True when the project imports an end-to-end test runner package.
816    pub has_e2e_runner: bool,
817    /// One row per changed value export of a changed source file.
818    pub exports: Vec<ExportTestReachPaths>,
819}
820
821/// Classify how tests reach the value exports in `changed_exports`.
822///
823/// Type-only exports, re-exports, exports of test files, of declaration files
824/// and of stylesheets are skipped. `is_test_path` classifies a root-relative,
825/// forward-slashed path; a test entry point always counts as a test file.
826/// The rows keep the order of `changed_exports`. `None` when the list holds no
827/// such export.
828#[must_use]
829pub fn test_reach_for_changed_paths(
830    graph: &RetainedModuleGraph,
831    root: &Path,
832    changed_exports: &[ChangedExport],
833    is_test_path: &dyn Fn(&str) -> bool,
834) -> Option<TestReachPaths> {
835    let graph = graph.as_graph();
836    let mut test_files: FxHashMap<FileId, bool> = FxHashMap::default();
837    let mut is_test_file = |file_id: FileId| -> bool {
838        *test_files.entry(file_id).or_insert_with(|| {
839            graph.test_entry_points.contains(&file_id)
840                || graph
841                    .modules
842                    .get(file_id.0 as usize)
843                    .is_some_and(|module| is_test_path(&relative_key_path(&module.path, root)))
844        })
845    };
846    let has_tests = !graph.test_entry_points.is_empty();
847    let exports: Vec<ExportTestReachPaths> = changed_exports
848        .iter()
849        .filter_map(|changed| classify_export_test_reach(graph, root, changed, &mut is_test_file))
850        .collect();
851    if exports.is_empty() {
852        return None;
853    }
854    let has_e2e_runner = E2E_RUNNER_PACKAGES.iter().any(|name| {
855        graph.package_usage.contains_key(*name) || graph.type_only_package_usage.contains_key(*name)
856    });
857    Some(TestReachPaths {
858        has_tests,
859        masking: graph.test_masking_state().into(),
860        has_e2e_runner,
861        exports,
862    })
863}
864
865/// Classify how tests reach one export. `None` for a type-only export, a
866/// re-export, an export of a test file, of a declaration file or of a
867/// stylesheet. `is_test_file` decides which referencing files are tests. In a
868/// project with no test entry points, the class is `NoneFile`.
869pub(crate) fn classify_export_test_reach(
870    graph: &ModuleGraph,
871    root: &Path,
872    changed: &ChangedExport,
873    is_test_file: &mut dyn FnMut(FileId) -> bool,
874) -> Option<ExportTestReachPaths> {
875    if changed.is_type_only || changed.is_re_export {
876        return None;
877    }
878    let module = graph.modules.get(changed.file_id.0 as usize)?;
879    let export = module.exports.get(changed.export_index)?;
880    if !is_reach_subject(&module.path) || is_test_file(changed.file_id) {
881        return None;
882    }
883    let result = if graph.test_entry_points.is_empty() {
884        GraphExportTestReachResult {
885            reach: GraphExportTestReach::NoneFile,
886            tests: Vec::new(),
887            mocked_targets: Vec::new(),
888        }
889    } else {
890        let test_flags: FxHashMap<FileId, bool> = export
891            .references
892            .iter()
893            .map(|reference| (reference.from_file, is_test_file(reference.from_file)))
894            .collect();
895        graph.export_test_reach(changed.file_id, export, &|file_id| {
896            test_flags.get(&file_id).copied().unwrap_or(false)
897        })
898    };
899    let paths_of = |files: &[FileId]| -> Vec<String> {
900        let mut paths: Vec<String> = files
901            .iter()
902            .filter_map(|file_id| graph.modules.get(file_id.0 as usize))
903            .map(|node| relative_key_path(&node.path, root))
904            .collect();
905        paths.sort_unstable();
906        paths
907    };
908    Some(ExportTestReachPaths {
909        file: changed.file.clone(),
910        export_name: changed.export_name.clone(),
911        line: changed.line,
912        declaration_lines: changed.declaration_lines,
913        literal_value: changed.literal_value,
914        reach: result.reach.into(),
915        tests: paths_of(&result.tests),
916        mocked_targets: paths_of(&result.mocked_targets),
917    })
918}
919
920/// Whether test reach applies to a file: runtime source code, not a
921/// declaration file or a stylesheet.
922fn is_reach_subject(path: &Path) -> bool {
923    if fallow_graph::graph::is_declaration_file_path(path) {
924        return false;
925    }
926    !path
927        .extension()
928        .and_then(|extension| extension.to_str())
929        .is_some_and(|extension| matches!(extension, "css" | "scss" | "less" | "sass"))
930}
931
932/// Compute direct non-diff internal consumer counts for absolute changed paths.
933#[must_use]
934pub fn internal_consumers_for_changed_paths(
935    graph: &RetainedModuleGraph,
936    root: &Path,
937    changed_files: &FxHashSet<PathBuf>,
938) -> Option<FxHashMap<String, u64>> {
939    let graph = graph.as_graph();
940    let changed_norm = normalized_changed_paths(changed_files);
941    let id_to_norm: FxHashMap<FileId, String> = graph
942        .modules
943        .iter()
944        .map(|module| (module.file_id, normalize_path(&module.path)))
945        .collect();
946
947    let mut map: FxHashMap<String, u64> = FxHashMap::default();
948    for module in &graph.modules {
949        let abs = normalize_path(&module.path);
950        if !changed_norm.contains(&abs) {
951            continue;
952        }
953        let count = graph
954            .importers_of(module.file_id)
955            .iter()
956            .filter(|imp| {
957                id_to_norm
958                    .get(imp)
959                    .is_none_or(|p| !changed_norm.contains(p))
960            })
961            .count() as u64;
962        map.insert(relative_key_path(&module.path, root), count);
963    }
964    Some(map)
965}
966
967/// Compute per-changed-file test adjacency for the review direction: whether a
968/// test file imports the changed module directly, and whether one of those tests
969/// is itself in the changed set. `is_test_path` classifies a root-relative,
970/// forward-slashed path; the caller owns that definition so the brief's
971/// weakening and direction surfaces agree on it. Changed test files get no
972/// entry of their own. `None` when no module matches a changed path.
973#[must_use]
974pub fn test_adjacency_for_changed_paths(
975    graph: &RetainedModuleGraph,
976    root: &Path,
977    changed_files: &FxHashSet<PathBuf>,
978    is_test_path: &dyn Fn(&str) -> bool,
979) -> Option<FxHashMap<String, TestAdjacency>> {
980    let graph = graph.as_graph();
981    // A project with no test files at all gets no adjacency claims: "no direct
982    // test" on every unit would say nothing about the change.
983    if !graph
984        .modules
985        .iter()
986        .any(|module| is_test_path(&relative_key_path(&module.path, root)))
987    {
988        return None;
989    }
990    let changed_norm = normalized_changed_paths(changed_files);
991    let mut map: FxHashMap<String, TestAdjacency> = FxHashMap::default();
992    for module in &graph.modules {
993        if !changed_norm.contains(&normalize_path(&module.path)) {
994            continue;
995        }
996        let rel = relative_key_path(&module.path, root);
997        if is_test_path(&rel) {
998            continue;
999        }
1000        let mut adjacency = TestAdjacency::None;
1001        for importer in graph.importers_of(module.file_id) {
1002            let Some(node) = graph.modules.get(importer.0 as usize) else {
1003                continue;
1004            };
1005            if !is_test_path(&relative_key_path(&node.path, root)) {
1006                continue;
1007            }
1008            if changed_norm.contains(&normalize_path(&node.path)) {
1009                adjacency = TestAdjacency::Changed;
1010                break;
1011            }
1012            adjacency = TestAdjacency::Untouched;
1013        }
1014        map.insert(rel, adjacency);
1015    }
1016    if map.is_empty() {
1017        return None;
1018    }
1019    Some(map)
1020}
1021
1022/// In-repo importer counts for one third-party package.
1023#[derive(Debug, Clone, Default, PartialEq, Eq)]
1024pub struct PackageImporters {
1025    /// Modules that import the package (value imports only), id-sorted. Kept
1026    /// as ids rather than a count so a decision that batches several packages
1027    /// can take the union instead of double-counting a module that imports
1028    /// more than one of them.
1029    pub importers: Vec<FileId>,
1030    /// The subset of `importers` outside the changed set, id-sorted.
1031    pub out_of_diff: Vec<FileId>,
1032}
1033
1034/// Compute per-package in-repo importer counts for every third-party package
1035/// the graph saw an import of, value or type-only, split by whether the
1036/// importer is in the changed set. Type-only importers count because a major
1037/// bump of a types package is a compile-wide change even when no value
1038/// crosses the boundary. The dependency decision arm reads these so a new or
1039/// bumped `package.json` entry carries the modules it actually reaches. `None`
1040/// when the graph recorded no package usage.
1041#[must_use]
1042pub fn package_importers_for_changed_paths(
1043    graph: &RetainedModuleGraph,
1044    changed_files: &FxHashSet<PathBuf>,
1045) -> Option<FxHashMap<String, PackageImporters>> {
1046    let graph = graph.as_graph();
1047    if graph.package_usage.is_empty() && graph.type_only_package_usage.is_empty() {
1048        return None;
1049    }
1050    let changed_norm = normalized_changed_paths(changed_files);
1051    let id_to_norm: FxHashMap<FileId, String> = graph
1052        .modules
1053        .iter()
1054        .map(|module| (module.file_id, normalize_path(&module.path)))
1055        .collect();
1056    let mut usage: FxHashMap<&str, Vec<FileId>> = FxHashMap::default();
1057    for (package, files) in graph
1058        .package_usage
1059        .iter()
1060        .chain(graph.type_only_package_usage.iter())
1061    {
1062        usage
1063            .entry(package.as_str())
1064            .or_default()
1065            .extend(files.iter().copied());
1066    }
1067    let map = usage
1068        .into_iter()
1069        .map(|(package, files)| {
1070            let mut importers: Vec<FileId> = files;
1071            importers.sort_unstable_by_key(|id| id.0);
1072            importers.dedup();
1073            let out_of_diff: Vec<FileId> = importers
1074                .iter()
1075                .copied()
1076                .filter(|id| id_to_norm.get(id).is_none_or(|p| !changed_norm.contains(p)))
1077                .collect();
1078            (
1079                package.to_string(),
1080                PackageImporters {
1081                    importers,
1082                    out_of_diff,
1083                },
1084            )
1085        })
1086        .collect();
1087    Some(map)
1088}
1089
1090fn changed_file_ids(graph: &ModuleGraph, changed_files: &FxHashSet<PathBuf>) -> Vec<FileId> {
1091    let path_to_id: FxHashMap<String, FileId> = graph
1092        .modules
1093        .iter()
1094        .map(|module| (normalize_path(&module.path), module.file_id))
1095        .collect();
1096
1097    changed_files
1098        .iter()
1099        .filter_map(|path| path_to_id.get(&normalize_path(path)).copied())
1100        .collect()
1101}
1102
1103fn normalized_changed_paths(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<String> {
1104    changed_files
1105        .iter()
1106        .map(|path| normalize_path(path))
1107        .collect()
1108}
1109
1110fn normalize_path(path: &Path) -> String {
1111    path.to_string_lossy().replace('\\', "/")
1112}
1113
1114/// Canonical path form used inside audit attribution keys: root-relative with
1115/// forward slashes on every platform. Paths outside `root` keep their
1116/// simplified absolute form so keys stay unique.
1117///
1118/// The engine keys its per-module maps with this function, and
1119/// `fallow-api` builds its lookup keys with the same function, so both sides
1120/// of the join always agree.
1121pub fn relative_key_path(path: &Path, root: &Path) -> String {
1122    let simple_path = dunce::simplified(path);
1123    let simple_root = dunce::simplified(root);
1124    simple_path
1125        .strip_prefix(simple_root)
1126        .unwrap_or(simple_path)
1127        .to_string_lossy()
1128        .replace('\\', "/")
1129}
1130
1131#[cfg(test)]
1132mod tests {
1133    use super::{RetainedModuleGraph, module_value_exports};
1134    use fallow_graph::graph::ModuleGraph;
1135    use fallow_graph::resolve::{
1136        ResolveResult, ResolvedImport, ResolvedModule, ResolvedReplacedModuleTarget,
1137    };
1138    use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource, FileId};
1139    use fallow_types::extract::{ExportInfo, ExportName, ImportInfo, ImportedName, VisibilityTag};
1140    use std::path::PathBuf;
1141
1142    fn import(target: FileId, imported_name: ImportedName) -> ResolvedImport {
1143        import_with_mechanism(target, imported_name, false)
1144    }
1145
1146    fn import_with_mechanism(
1147        target: FileId,
1148        imported_name: ImportedName,
1149        commonjs: bool,
1150    ) -> ResolvedImport {
1151        ResolvedImport {
1152            info: ImportInfo {
1153                source: "./target".to_string(),
1154                imported_name,
1155                local_name: "target".to_string(),
1156                is_type_only: false,
1157                is_type_only_star: false,
1158                from_style: false,
1159                span: oxc_span::Span::new(0, 10),
1160                source_span: oxc_span::Span::default(),
1161            },
1162            target: if commonjs {
1163                ResolveResult::CommonJsInternalModule(target)
1164            } else {
1165                ResolveResult::InternalModule(target)
1166            },
1167        }
1168    }
1169
1170    fn value_export(name: &str, span_start: u32) -> ExportInfo {
1171        ExportInfo {
1172            name: ExportName::Named(name.to_string()),
1173            local_name: Some(name.to_string()),
1174            is_type_only: false,
1175            visibility: VisibilityTag::None,
1176            expected_unused_reason: None,
1177            span: oxc_span::Span::new(span_start, span_start + 10),
1178            members: Vec::new(),
1179            is_side_effect_used: false,
1180            super_class: None,
1181            deprecated: false,
1182            deprecated_reason: None,
1183        }
1184    }
1185
1186    fn mixed_root_graph(unmasked_root_imports_export: bool) -> RetainedModuleGraph {
1187        let files: Vec<_> = (0..3)
1188            .map(|id| DiscoveredFile {
1189                id: FileId(id),
1190                path: PathBuf::from(format!("/project/file{id}.ts")),
1191                size_bytes: 1,
1192            })
1193            .collect();
1194        let modules = vec![
1195            ResolvedModule {
1196                file_id: FileId(0),
1197                path: files[0].path.clone(),
1198                resolved_imports: vec![import(
1199                    FileId(2),
1200                    ImportedName::Named("target".to_string()),
1201                )],
1202                ..ResolvedModule::default()
1203            },
1204            ResolvedModule {
1205                file_id: FileId(1),
1206                path: files[1].path.clone(),
1207                resolved_imports: vec![import(
1208                    FileId(2),
1209                    if unmasked_root_imports_export {
1210                        ImportedName::Named("target".to_string())
1211                    } else {
1212                        ImportedName::SideEffect
1213                    },
1214                )],
1215                ..ResolvedModule::default()
1216            },
1217            ResolvedModule {
1218                file_id: FileId(2),
1219                path: files[2].path.clone(),
1220                exports: vec![value_export("target", 0)].into(),
1221                ..ResolvedModule::default()
1222            },
1223        ];
1224        let test_entry_points = vec![
1225            EntryPoint {
1226                path: files[0].path.clone(),
1227                source: EntryPointSource::TestFile,
1228            },
1229            EntryPoint {
1230                path: files[1].path.clone(),
1231                source: EntryPointSource::TestFile,
1232            },
1233        ];
1234        let graph = ModuleGraph::build_with_reachability_roots_and_replacements(
1235            &modules,
1236            &[ResolvedReplacedModuleTarget {
1237                source_file: FileId(0),
1238                target_file: FileId(2),
1239            }],
1240            &test_entry_points,
1241            &[],
1242            &test_entry_points,
1243            &files,
1244        );
1245        RetainedModuleGraph::from(graph)
1246    }
1247
1248    #[test]
1249    fn export_coverage_requires_one_root_to_reach_consumer_and_target() {
1250        let graph = mixed_root_graph(false);
1251
1252        let exports = module_value_exports(&graph);
1253
1254        assert_eq!(exports.len(), 1);
1255        assert!(!exports[0].test_referenced);
1256    }
1257
1258    #[test]
1259    fn export_coverage_accepts_an_unmasked_correlated_reference() {
1260        let graph = mixed_root_graph(true);
1261
1262        let exports = module_value_exports(&graph);
1263
1264        assert_eq!(exports.len(), 1);
1265        assert!(exports[0].test_referenced);
1266    }
1267
1268    #[test]
1269    fn commonjs_reference_does_not_credit_a_mocked_esm_export() {
1270        let files: Vec<_> = (0..2)
1271            .map(|id| DiscoveredFile {
1272                id: FileId(id),
1273                path: PathBuf::from(format!("/project/file{id}.ts")),
1274                size_bytes: 1,
1275            })
1276            .collect();
1277        let modules = vec![
1278            ResolvedModule {
1279                file_id: FileId(0),
1280                path: files[0].path.clone(),
1281                resolved_imports: vec![
1282                    import_with_mechanism(
1283                        FileId(1),
1284                        ImportedName::Named("esmOnly".to_string()),
1285                        false,
1286                    ),
1287                    import_with_mechanism(
1288                        FileId(1),
1289                        ImportedName::Named("required".to_string()),
1290                        true,
1291                    ),
1292                ],
1293                ..ResolvedModule::default()
1294            },
1295            ResolvedModule {
1296                file_id: FileId(1),
1297                path: files[1].path.clone(),
1298                exports: vec![value_export("esmOnly", 0), value_export("required", 20)].into(),
1299                ..ResolvedModule::default()
1300            },
1301        ];
1302        let test_entry_points = vec![EntryPoint {
1303            path: files[0].path.clone(),
1304            source: EntryPointSource::TestFile,
1305        }];
1306        let graph =
1307            RetainedModuleGraph::from(ModuleGraph::build_with_reachability_roots_and_replacements(
1308                &modules,
1309                &[ResolvedReplacedModuleTarget {
1310                    source_file: FileId(0),
1311                    target_file: FileId(1),
1312                }],
1313                &test_entry_points,
1314                &[],
1315                &test_entry_points,
1316                &files,
1317            ));
1318
1319        let exports = module_value_exports(&graph);
1320        let coverage: rustc_hash::FxHashMap<_, _> = exports
1321            .into_iter()
1322            .map(|export| (export.name, export.test_referenced))
1323            .collect();
1324
1325        assert_eq!(coverage.get("esmOnly"), Some(&false));
1326        assert_eq!(coverage.get("required"), Some(&true));
1327    }
1328
1329    #[test]
1330    fn type_only_test_import_does_not_credit_a_value_export() {
1331        let files: Vec<_> = (0..3)
1332            .map(|id| DiscoveredFile {
1333                id: FileId(id),
1334                path: PathBuf::from(format!("/project/file{id}.ts")),
1335                size_bytes: 1,
1336            })
1337            .collect();
1338        let mut type_only = import(FileId(1), ImportedName::Named("typed".to_string()));
1339        type_only.info.is_type_only = true;
1340        let modules = vec![
1341            ResolvedModule {
1342                file_id: FileId(0),
1343                path: files[0].path.clone(),
1344                resolved_imports: vec![
1345                    type_only,
1346                    import(FileId(2), ImportedName::Named("called".to_string())),
1347                ],
1348                ..ResolvedModule::default()
1349            },
1350            ResolvedModule {
1351                file_id: FileId(1),
1352                path: files[1].path.clone(),
1353                exports: vec![value_export("typed", 0)].into(),
1354                ..ResolvedModule::default()
1355            },
1356            ResolvedModule {
1357                file_id: FileId(2),
1358                path: files[2].path.clone(),
1359                exports: vec![value_export("called", 0)].into(),
1360                ..ResolvedModule::default()
1361            },
1362        ];
1363        let test_entry_points = vec![EntryPoint {
1364            path: files[0].path.clone(),
1365            source: EntryPointSource::TestFile,
1366        }];
1367        let graph =
1368            RetainedModuleGraph::from(ModuleGraph::build_with_reachability_roots_and_replacements(
1369                &modules,
1370                &[],
1371                &test_entry_points,
1372                &[],
1373                &test_entry_points,
1374                &files,
1375            ));
1376
1377        let coverage: rustc_hash::FxHashMap<_, _> = module_value_exports(&graph)
1378            .into_iter()
1379            .map(|export| (export.name, export.test_referenced))
1380            .collect();
1381
1382        assert_eq!(coverage.get("typed"), Some(&false));
1383        assert_eq!(coverage.get("called"), Some(&true));
1384    }
1385}