Skip to main content

fallow_api/runtime/
decision_surface.rs

1use std::path::{Path, PathBuf};
2use std::time::Instant;
3
4use fallow_engine::repo_refs::{self, TemporaryBaseWorktree};
5use fallow_output::ReviewDeltas;
6use rustc_hash::{FxHashMap, FxHashSet};
7
8use crate::{
9    AnalysisOptions, AuditOptions, DecisionSurfaceOptions, DecisionSurfaceProgrammaticOutput,
10    ProgrammaticError,
11    analysis_context::{
12        ProgrammaticAnalysisContext, changed_files_for_run, resolve_programmatic_analysis_context,
13        workspace_roots_for_session,
14    },
15    decision_surface::{
16        BoundaryAnchor, CoordinationAnchor, DEFAULT_DECISION_CAP, DecisionInputs,
17        extract_decision_surface,
18    },
19};
20
21use super::ProgrammaticResult;
22
23/// Run changed-code decision-surface analysis through the typed programmatic API.
24///
25/// # Errors
26///
27/// Returns a structured error for invalid options, base-ref discovery failures,
28/// git changed-file failures, or analysis failures.
29pub fn run_decision_surface(
30    options: &DecisionSurfaceOptions,
31) -> ProgrammaticResult<DecisionSurfaceProgrammaticOutput> {
32    let start = Instant::now();
33    let audit_options = audit_options_for_decision_surface(options);
34    let resolved_base = super::audit_base_ref::resolve_audit_base_ref(&audit_options)?;
35    let analysis = AnalysisOptions {
36        changed_since: Some(resolved_base.git_ref.clone()),
37        ..options.analysis.clone()
38    };
39    let resolved = resolve_programmatic_analysis_context(&analysis)?;
40    let changed_files = changed_files_for_run(&resolved)?.unwrap_or_default();
41    if changed_files.is_empty() {
42        return Ok(DecisionSurfaceProgrammaticOutput {
43            surface: fallow_output::DecisionSurface::default(),
44            elapsed: start.elapsed(),
45            telemetry_analysis_run_id: None,
46        });
47    }
48
49    // The caller can be a 2 MiB Tokio blocking thread. Parse on the worker
50    // stack of the analysis pool instead.
51    let head = resolved
52        .install(|| run_decision_analysis(&resolved, &analysis, Some(&changed_files), None))?;
53    let manifests = changed_manifests(&resolved.root, &changed_files);
54    let old_paths = renamed_old_paths(&resolved.root, &resolved_base.git_ref);
55    let base = compute_base_decision_snapshot(
56        options,
57        &resolved.root,
58        &resolved_base.git_ref,
59        &BaseManifests {
60            manifests: &manifests,
61            old_paths: &old_paths,
62        },
63        &head.config,
64    )?;
65    let manifest_pairs = manifest_pairs(&resolved.root, &manifests, &base);
66    let dependency_anchors = crate::dependency_deltas::dependency_anchors_from_manifests(
67        &manifest_pairs,
68        head.package_importers.as_ref(),
69    );
70    let deltas = build_decision_deltas(&head, &base, &dependency_anchors);
71    let surface = build_surface(options, &head, &deltas, &dependency_anchors, &old_paths);
72
73    Ok(DecisionSurfaceProgrammaticOutput {
74        surface,
75        elapsed: start.elapsed(),
76        telemetry_analysis_run_id: None,
77    })
78}
79
80fn audit_options_for_decision_surface(options: &DecisionSurfaceOptions) -> AuditOptions {
81    AuditOptions {
82        analysis: options.analysis.clone(),
83        base: options.base.clone(),
84        ..AuditOptions::default()
85    }
86}
87
88pub(super) struct DecisionAnalysis {
89    root: PathBuf,
90    pub(super) results: fallow_types::results::AnalysisResults,
91    public_api: FxHashSet<String>,
92    impact_closure: Option<fallow_engine::module_graph::ImpactClosurePaths>,
93    export_lines: Option<FxHashMap<String, Vec<(String, u32)>>>,
94    internal_consumers: Option<FxHashMap<String, u64>>,
95    package_importers: Option<FxHashMap<String, fallow_engine::module_graph::PackageImporters>>,
96    routing: fallow_output::RoutingFacts,
97    /// The configuration the analysis session loaded, kept so the base
98    /// snapshot can resolve rule severity against the head configuration.
99    pub(super) config: fallow_config::ResolvedConfig,
100}
101
102struct DecisionGraphSignals {
103    public_api: FxHashSet<String>,
104    impact_closure: Option<fallow_engine::module_graph::ImpactClosurePaths>,
105    export_lines: Option<FxHashMap<String, Vec<(String, u32)>>>,
106    internal_consumers: Option<FxHashMap<String, u64>>,
107    package_importers: Option<FxHashMap<String, fallow_engine::module_graph::PackageImporters>>,
108}
109
110/// Root-relative, forward-slashed paths of the changed `package.json`
111/// manifests, sorted.
112fn changed_manifests(root: &Path, changed_files: &FxHashSet<PathBuf>) -> Vec<String> {
113    let mut manifests: Vec<String> = changed_files
114        .iter()
115        .filter_map(|abs| abs.strip_prefix(root).ok())
116        .map(|rel| rel.to_string_lossy().replace('\\', "/"))
117        .filter(|rel| crate::dependency_deltas::is_manifest_path(rel))
118        .collect();
119    manifests.sort();
120    manifests
121}
122
123/// The base-relative path of each file that the change renamed, keyed by its
124/// root-relative head path.
125///
126/// Best effort: when git fails, a renamed file reads as new.
127fn renamed_old_paths(root: &Path, base_ref: &str) -> FxHashMap<String, String> {
128    fallow_engine::changed_files::try_get_renamed_files(root, base_ref)
129        .unwrap_or_default()
130        .iter()
131        .map(|rename| {
132            (
133                crate::audit_keys::relative_key_path(&rename.to, root),
134                crate::audit_keys::relative_key_path(&rename.from, root),
135            )
136        })
137        .filter(|(to, from)| to != from)
138        .collect()
139}
140
141/// The changed manifests, by head path, and the base path of each renamed one.
142struct BaseManifests<'a> {
143    manifests: &'a [String],
144    old_paths: &'a FxHashMap<String, String>,
145}
146
147/// Pair each changed manifest's head text with the base text captured from the
148/// base worktree. A manifest unreadable at head is skipped; one absent at base
149/// reads as new.
150fn manifest_pairs(
151    root: &Path,
152    manifests: &[String],
153    base: &DecisionSnapshot,
154) -> Vec<crate::dependency_deltas::ManifestPair> {
155    manifests
156        .iter()
157        .filter_map(|manifest| {
158            let head = std::fs::read_to_string(root.join(manifest)).ok()?;
159            Some(crate::dependency_deltas::ManifestPair {
160                manifest: manifest.clone(),
161                base: base.manifests.get(manifest).cloned(),
162                head,
163            })
164        })
165        .collect()
166}
167
168/// Analyze one revision for the decision surface. `severity_config` resolves
169/// rule severity in place of the session's own configuration; the base
170/// snapshot passes the head configuration so both revisions are judged by the
171/// rules under review, as the CLI's base worktree pass already does.
172pub(super) fn run_decision_analysis(
173    resolved: &ProgrammaticAnalysisContext,
174    analysis: &AnalysisOptions,
175    changed_files: Option<&FxHashSet<PathBuf>>,
176    severity_config: Option<&fallow_config::ResolvedConfig>,
177) -> ProgrammaticResult<DecisionAnalysis> {
178    let options = super::dead_code::default_dead_code_options(analysis);
179    let run = super::dead_code::resolve_dead_code_run(
180        &options,
181        &crate::run::ProgrammaticEntry::DecisionSurface,
182    )?;
183    let session = super::dead_code::load_dead_code_session(&options, resolved, &run)?;
184    let root = session.root().to_path_buf();
185    let artifacts = session
186        .analyze_dead_code_with_session_artifacts(false, true, changed_files.cloned())
187        .map_err(|err| {
188            ProgrammaticError::new(format!("decision-surface analysis failed: {err}"), 2)
189                .with_code("FALLOW_DECISION_SURFACE_FAILED")
190                .with_context("decision-surface")
191        })?;
192    let fallow_engine::session::AnalysisSessionArtifacts {
193        analysis: mut output,
194        changed_files,
195        ..
196    } = artifacts;
197    let changed_files = changed_files.as_ref();
198
199    // Rule severity is resolved before anything is framed as a decision, so a
200    // rule or a per-path override that turns a finding off also removes the
201    // decision built from it. The CLI reaches the same state through `check`.
202    let severity = severity_config.unwrap_or_else(|| session.config());
203    fallow_engine::dead_code::apply_rule_severities(&mut output.results, severity);
204
205    let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
206    filter_decision_results(&mut output.results, workspace_roots.as_ref(), changed_files);
207
208    let graph_signals =
209        decision_graph_signals(output.graph.as_ref(), &session, &root, changed_files);
210    let routing = changed_files.map_or_else(fallow_output::RoutingFacts::default, |files| {
211        crate::routing::compute_routing(&root, session.config(), files)
212    });
213
214    Ok(DecisionAnalysis {
215        root,
216        results: output.results,
217        public_api: graph_signals.public_api,
218        impact_closure: graph_signals.impact_closure,
219        export_lines: graph_signals.export_lines,
220        internal_consumers: graph_signals.internal_consumers,
221        package_importers: graph_signals.package_importers,
222        routing,
223        config: session.config().clone(),
224    })
225}
226
227fn decision_graph_signals(
228    graph: Option<&fallow_engine::module_graph::RetainedModuleGraph>,
229    session: &fallow_engine::session::AnalysisSession,
230    root: &Path,
231    changed_files: Option<&FxHashSet<PathBuf>>,
232) -> DecisionGraphSignals {
233    let public_api = graph.map_or_else(FxHashSet::default, |graph| {
234        crate::review_deltas::public_export_keys_for(
235            graph,
236            session.config(),
237            session.workspaces(),
238            root,
239        )
240    });
241    let impact_closure = graph.and_then(|graph| {
242        changed_files.and_then(|files| {
243            fallow_engine::module_graph::impact_closure_for_changed_paths(graph, root, files)
244        })
245    });
246    let export_lines = graph.and_then(|graph| {
247        changed_files.and_then(|files| {
248            fallow_engine::module_graph::export_lines_for_changed_paths(graph, root, files)
249        })
250    });
251    let internal_consumers = graph.and_then(|graph| {
252        changed_files.and_then(|files| {
253            fallow_engine::module_graph::internal_consumers_for_changed_paths(graph, root, files)
254        })
255    });
256    let package_importers = graph.and_then(|graph| {
257        changed_files.and_then(|files| {
258            fallow_engine::module_graph::package_importers_for_changed_paths(graph, files)
259        })
260    });
261
262    DecisionGraphSignals {
263        public_api,
264        impact_closure,
265        export_lines,
266        internal_consumers,
267        package_importers,
268    }
269}
270
271fn filter_decision_results(
272    results: &mut fallow_types::results::AnalysisResults,
273    workspace_roots: Option<&fallow_engine::workspace_scope::WorkspaceScope>,
274    changed_files: Option<&FxHashSet<PathBuf>>,
275) {
276    if let Some(workspace_roots) = workspace_roots {
277        fallow_engine::dead_code::filter_to_workspaces(results, workspace_roots);
278    }
279    if let Some(changed_files) = changed_files {
280        fallow_engine::dead_code::filter_by_changed_files(results, changed_files);
281    }
282}
283
284fn compute_base_decision_snapshot(
285    options: &DecisionSurfaceOptions,
286    current_root: &Path,
287    base_ref: &str,
288    manifests: &BaseManifests<'_>,
289    head_config: &fallow_config::ResolvedConfig,
290) -> ProgrammaticResult<DecisionSnapshot> {
291    let worktree =
292        TemporaryBaseWorktree::create(current_root, base_ref, &head_config.workspace_patterns)
293            .map_err(|err| {
294                ProgrammaticError::new(err.to_string(), 2)
295                    .with_code("FALLOW_DECISION_SURFACE_FAILED")
296                    .with_context("decisionSurface.base")
297            })?;
298    let base_root = match repo_refs::resolve_base_analysis_root(current_root, worktree.path()) {
299        repo_refs::BaseAnalysisRoot::Present(root) => root,
300        // A root the base commit does not contain has an empty base snapshot:
301        // no boundary edges, no cycles, no public API and no manifests, so the
302        // whole surface reads as new in this change.
303        repo_refs::BaseAnalysisRoot::NewInHead(_) => return Ok(DecisionSnapshot::default()),
304    };
305    // The base manifests are read while the worktree still exists; a manifest
306    // absent at base stays absent (it is new in this change). A renamed
307    // manifest is read under its base path and keyed by its head path, so a
308    // move compares the same dependencies.
309    let base_manifests: FxHashMap<String, String> = manifests
310        .manifests
311        .iter()
312        .filter_map(|manifest| {
313            let base_path = manifests.old_paths.get(manifest).unwrap_or(manifest);
314            std::fs::read_to_string(base_root.join(base_path))
315                .ok()
316                .map(|text| (manifest.clone(), text))
317        })
318        .collect();
319    let base_analysis = AnalysisOptions {
320        root: Some(base_root),
321        config_path: options.analysis.config_path.clone(),
322        changed_since: None,
323        explain: false,
324        ..options.analysis.clone()
325    };
326    let resolved = resolve_programmatic_analysis_context(&base_analysis)?;
327    let base = resolved
328        .install(|| run_decision_analysis(&resolved, &base_analysis, None, Some(head_config)))?;
329    let mut snapshot = snapshot_from_decision_analysis(&base);
330    snapshot.manifests = base_manifests;
331    Ok(snapshot)
332}
333
334#[derive(Default)]
335struct DecisionSnapshot {
336    boundary_edges: FxHashSet<String>,
337    cycles: FxHashSet<String>,
338    public_api: FxHashSet<String>,
339    /// Base text of each changed manifest, keyed by root-relative path.
340    manifests: FxHashMap<String, String>,
341}
342
343fn snapshot_from_decision_analysis(analysis: &DecisionAnalysis) -> DecisionSnapshot {
344    DecisionSnapshot {
345        boundary_edges: crate::review_deltas::boundary_edge_keys(
346            &analysis.results.boundary_violations,
347        ),
348        cycles: crate::review_deltas::cycle_keys(
349            &analysis.results.circular_dependencies,
350            &analysis.root,
351        ),
352        public_api: analysis.public_api.clone(),
353        manifests: FxHashMap::default(),
354    }
355}
356
357fn build_decision_deltas(
358    head: &DecisionAnalysis,
359    base: &DecisionSnapshot,
360    dependency_anchors: &[crate::decision_surface::DependencyAnchor],
361) -> ReviewDeltas {
362    let head_snapshot = snapshot_from_decision_analysis(head);
363    let mut deltas = fallow_output::ReviewDeltas {
364        boundary_introduced: crate::review_deltas::introduced_keys(
365            &head_snapshot.boundary_edges,
366            &base.boundary_edges,
367        ),
368        cycle_introduced: crate::review_deltas::introduced_keys(
369            &head_snapshot.cycles,
370            &base.cycles,
371        ),
372        public_api_added: crate::review_deltas::introduced_keys(
373            &head_snapshot.public_api,
374            &base.public_api,
375        ),
376        dependency_added: Vec::new(),
377        dependency_major_bumped: Vec::new(),
378    };
379    crate::dependency_deltas::fill_dependency_delta_keys(&mut deltas, dependency_anchors);
380    deltas
381}
382
383fn build_surface(
384    options: &DecisionSurfaceOptions,
385    head: &DecisionAnalysis,
386    deltas: &ReviewDeltas,
387    dependency_anchors: &[crate::decision_surface::DependencyAnchor],
388    old_paths: &FxHashMap<String, String>,
389) -> fallow_output::DecisionSurface {
390    let boundary_anchors = boundary_anchors(head, deltas);
391    let mut coordination = coordination_anchors(head.impact_closure.as_ref());
392    let resolve_line = export_line_resolver(head.export_lines.as_ref());
393    for anchor in &mut coordination {
394        anchor.line = resolve_line(&anchor.changed_file, &anchor.consumed_symbols);
395    }
396    let public_api_anchor_line = deltas.public_api_added.first().map_or(0, |key| {
397        let mut parts = key.splitn(2, "::");
398        let path = parts.next().unwrap_or_default();
399        let name = parts.next().unwrap_or_default();
400        resolve_line(path, &[name.to_string()])
401    });
402    let affected_not_shown = head
403        .impact_closure
404        .as_ref()
405        .map_or(0, |closure| closure.affected_not_shown.len() as u64);
406    let root = head.root.clone();
407    let head_source = move |rel: &str| std::fs::read_to_string(root.join(rel)).ok();
408    let rename_old_path = |rel: &str| old_paths.get(rel).cloned();
409    let internal_consumers_map = head.internal_consumers.as_ref();
410    let internal_consumers = |rel: &str| -> u64 {
411        internal_consumers_map
412            .and_then(|map| map.get(rel))
413            .copied()
414            .unwrap_or(0)
415    };
416    extract_decision_surface(&DecisionInputs {
417        deltas,
418        boundary_anchors: &boundary_anchors,
419        coordination: &coordination,
420        dependency_anchors,
421        public_api_anchor_line,
422        affected_not_shown,
423        routing: &head.routing,
424        head_source: &head_source,
425        rename_old_path: &rename_old_path,
426        internal_consumers: &internal_consumers,
427        cap: options.max_decisions.unwrap_or(DEFAULT_DECISION_CAP),
428    })
429}
430
431fn boundary_anchors(head: &DecisionAnalysis, deltas: &ReviewDeltas) -> Vec<BoundaryAnchor> {
432    let mut boundary_anchors = Vec::new();
433    let mut seen_pairs = FxHashSet::default();
434    for finding in &head.results.boundary_violations {
435        let key = crate::review_deltas::boundary_edge_key(finding);
436        if !deltas.boundary_introduced.contains(&key) || !seen_pairs.insert(key.clone()) {
437            continue;
438        }
439        boundary_anchors.push(BoundaryAnchor {
440            zone_pair_key: key,
441            from_file: crate::audit_keys::relative_key_path(
442                &finding.violation.from_path,
443                &head.root,
444            ),
445            from_zone: finding.violation.from_zone.clone(),
446            to_zone: finding.violation.to_zone.clone(),
447            line: finding.violation.line,
448        });
449    }
450    boundary_anchors
451}
452
453fn coordination_anchors(
454    closure: Option<&fallow_engine::module_graph::ImpactClosurePaths>,
455) -> Vec<CoordinationAnchor> {
456    let Some(closure) = closure else {
457        return Vec::new();
458    };
459    let mut by_file: FxHashMap<String, (u64, FxHashSet<String>)> = FxHashMap::default();
460    for gap in &closure.coordination_gap {
461        let entry = by_file
462            .entry(gap.changed_file.clone())
463            .or_insert_with(|| (0, FxHashSet::default()));
464        entry.0 += 1;
465        for symbol in &gap.consumed_symbols {
466            entry.1.insert(symbol.clone());
467        }
468    }
469    let mut anchors = by_file
470        .into_iter()
471        .map(|(changed_file, (consumer_count, symbols))| {
472            let mut consumed_symbols: Vec<String> = symbols.into_iter().collect();
473            consumed_symbols.sort_unstable();
474            CoordinationAnchor {
475                changed_file,
476                consumed_symbols,
477                consumer_count,
478                line: 0,
479            }
480        })
481        .collect::<Vec<_>>();
482    anchors.sort_by(|a, b| a.changed_file.cmp(&b.changed_file));
483    anchors
484}
485
486fn export_line_resolver(
487    export_lines: Option<&FxHashMap<String, Vec<(String, u32)>>>,
488) -> impl Fn(&str, &[String]) -> u32 + '_ {
489    move |rel: &str, symbols: &[String]| -> u32 {
490        let Some(exports) = export_lines.and_then(|map| map.get(rel)) else {
491            return 0;
492        };
493        exports
494            .iter()
495            .find(|(name, _)| symbols.iter().any(|symbol| name == symbol))
496            .or_else(|| exports.first())
497            .map_or(0, |(_, line)| *line)
498    }
499}
500
501#[cfg(test)]
502mod tests {
503    use std::path::Path;
504    use std::process::Command;
505
506    use crate::{AnalysisOptions, DecisionSurfaceOptions};
507
508    const STACK_PROBE_ENV: &str = "FALLOW_DECISION_SURFACE_STACK_PROBE_CHILD";
509    const STACK_PROBE_TEST: &str =
510        "runtime::decision_surface::tests::decision_surface_parses_on_the_worker_stack";
511    /// Deep enough to overflow a 2 MiB thread in a release build and to fit
512    /// the 16 MiB worker stack in a debug build. An assignment chain has no
513    /// brackets, so the pre-parse bracket guard does not stop it.
514    const ASSIGNMENT_CHAIN_DEPTH: usize = 4_000;
515
516    // A stack overflow aborts the process, so the probe re-runs this test
517    // binary as a child without RUST_MIN_STACK (pinned to 16 MiB in
518    // .cargo/config.toml). The child test thread then has the 2 MiB default
519    // stack of an MCP blocking thread.
520    #[test]
521    fn decision_surface_parses_on_the_worker_stack() {
522        if std::env::var_os(STACK_PROBE_ENV).is_some() {
523            run_stack_probe_child();
524            return;
525        }
526
527        let current_exe = std::env::current_exe().expect("current test binary should be known");
528        let output = Command::new(current_exe)
529            .arg("--exact")
530            .arg(STACK_PROBE_TEST)
531            .arg("--nocapture")
532            .env(STACK_PROBE_ENV, "1")
533            .env_remove("RUST_MIN_STACK")
534            .output()
535            .expect("stack probe child should start");
536
537        assert!(
538            output.status.success(),
539            "stack probe child failed with status {:?}\nstdout:\n{}\nstderr:\n{}",
540            output.status.code(),
541            String::from_utf8_lossy(&output.stdout),
542            String::from_utf8_lossy(&output.stderr)
543        );
544    }
545
546    fn run_stack_probe_child() {
547        let project = tempfile::tempdir().expect("temp dir");
548        let root = project.path();
549        std::fs::write(root.join("index.ts"), "export const used = 1;\n").expect("write entry");
550        git(root, &["init", "-b", "main"]);
551        git(root, &["add", "."]);
552        commit(root, "initial");
553        git(root, &["checkout", "-b", "feature"]);
554        let deep = format!(
555            "export let a = 0;\n{}1;\n",
556            "a=".repeat(ASSIGNMENT_CHAIN_DEPTH)
557        );
558        std::fs::write(root.join("deep.ts"), deep).expect("write deep file");
559        git(root, &["add", "."]);
560        commit(root, "deep");
561
562        let options = DecisionSurfaceOptions {
563            analysis: AnalysisOptions {
564                root: Some(root.to_path_buf()),
565                threads: Some(1),
566                no_cache: true,
567                ..AnalysisOptions::default()
568            },
569            base: Some("main".to_owned()),
570            max_decisions: None,
571        };
572        super::super::run_decision_surface(&options).expect("decision surface should run");
573    }
574
575    fn commit(root: &Path, message: &str) {
576        git(
577            root,
578            &[
579                "-c",
580                "user.email=test@example.com",
581                "-c",
582                "user.name=Test",
583                "-c",
584                "commit.gpgsign=false",
585                "commit",
586                "-m",
587                message,
588            ],
589        );
590    }
591
592    use fallow_engine::git_fixture::fixture_git as git;
593}