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