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(
179        &mut output.results,
180        workspace_roots.as_deref(),
181        changed_files,
182    );
183
184    let graph_signals =
185        decision_graph_signals(output.graph.as_ref(), &session, &root, changed_files);
186    let routing = changed_files.map_or_else(fallow_output::RoutingFacts::default, |files| {
187        crate::routing::compute_routing(&root, session.config(), files)
188    });
189
190    Ok(DecisionAnalysis {
191        root,
192        results: output.results,
193        public_api: graph_signals.public_api,
194        impact_closure: graph_signals.impact_closure,
195        export_lines: graph_signals.export_lines,
196        internal_consumers: graph_signals.internal_consumers,
197        package_importers: graph_signals.package_importers,
198        routing,
199        config: session.config().clone(),
200    })
201}
202
203fn decision_graph_signals(
204    graph: Option<&fallow_engine::module_graph::RetainedModuleGraph>,
205    session: &fallow_engine::session::AnalysisSession,
206    root: &Path,
207    changed_files: Option<&FxHashSet<PathBuf>>,
208) -> DecisionGraphSignals {
209    let public_api = graph.map_or_else(FxHashSet::default, |graph| {
210        crate::review_deltas::public_export_keys_for(
211            graph,
212            session.config(),
213            session.workspaces(),
214            root,
215        )
216    });
217    let impact_closure = graph.and_then(|graph| {
218        changed_files.and_then(|files| {
219            fallow_engine::module_graph::impact_closure_for_changed_paths(graph, root, files)
220        })
221    });
222    let export_lines = graph.and_then(|graph| {
223        changed_files.and_then(|files| {
224            fallow_engine::module_graph::export_lines_for_changed_paths(graph, root, files)
225        })
226    });
227    let internal_consumers = graph.and_then(|graph| {
228        changed_files.and_then(|files| {
229            fallow_engine::module_graph::internal_consumers_for_changed_paths(graph, root, files)
230        })
231    });
232    let package_importers = graph.and_then(|graph| {
233        changed_files.and_then(|files| {
234            fallow_engine::module_graph::package_importers_for_changed_paths(graph, files)
235        })
236    });
237
238    DecisionGraphSignals {
239        public_api,
240        impact_closure,
241        export_lines,
242        internal_consumers,
243        package_importers,
244    }
245}
246
247fn filter_decision_results(
248    results: &mut fallow_types::results::AnalysisResults,
249    workspace_roots: Option<&[PathBuf]>,
250    changed_files: Option<&FxHashSet<PathBuf>>,
251) {
252    if let Some(workspace_roots) = workspace_roots {
253        fallow_engine::dead_code::filter_to_workspaces(results, workspace_roots);
254    }
255    if let Some(changed_files) = changed_files {
256        fallow_engine::dead_code::filter_by_changed_files(results, changed_files);
257    }
258}
259
260fn compute_base_decision_snapshot(
261    options: &DecisionSurfaceOptions,
262    current_root: &Path,
263    base_ref: &str,
264    manifests: &[String],
265    head_config: &fallow_config::ResolvedConfig,
266) -> ProgrammaticResult<DecisionSnapshot> {
267    let worktree =
268        TemporaryBaseWorktree::create(current_root, base_ref, &head_config.workspace_patterns)
269            .map_err(|err| {
270                ProgrammaticError::new(err.to_string(), 2)
271                    .with_code("FALLOW_DECISION_SURFACE_FAILED")
272                    .with_context("decisionSurface.base")
273            })?;
274    let base_root = match repo_refs::resolve_base_analysis_root(current_root, worktree.path()) {
275        repo_refs::BaseAnalysisRoot::Present(root) => root,
276        // A root the base commit does not contain has an empty base snapshot:
277        // no boundary edges, no cycles, no public API and no manifests, so the
278        // whole surface reads as new in this change.
279        repo_refs::BaseAnalysisRoot::NewInHead(_) => return Ok(DecisionSnapshot::default()),
280    };
281    // The base manifests are read while the worktree still exists; a manifest
282    // absent at base stays absent (it is new in this change).
283    let base_manifests: FxHashMap<String, String> = manifests
284        .iter()
285        .filter_map(|manifest| {
286            std::fs::read_to_string(base_root.join(manifest))
287                .ok()
288                .map(|text| (manifest.clone(), text))
289        })
290        .collect();
291    let base_analysis = AnalysisOptions {
292        root: Some(base_root),
293        config_path: options.analysis.config_path.clone(),
294        changed_since: None,
295        explain: false,
296        ..options.analysis.clone()
297    };
298    let resolved = resolve_programmatic_analysis_context(&base_analysis)?;
299    let base = resolved
300        .install(|| run_decision_analysis(&resolved, &base_analysis, None, Some(head_config)))?;
301    let mut snapshot = snapshot_from_decision_analysis(&base);
302    snapshot.manifests = base_manifests;
303    Ok(snapshot)
304}
305
306#[derive(Default)]
307struct DecisionSnapshot {
308    boundary_edges: FxHashSet<String>,
309    cycles: FxHashSet<String>,
310    public_api: FxHashSet<String>,
311    /// Base text of each changed manifest, keyed by root-relative path.
312    manifests: FxHashMap<String, String>,
313}
314
315fn snapshot_from_decision_analysis(analysis: &DecisionAnalysis) -> DecisionSnapshot {
316    DecisionSnapshot {
317        boundary_edges: crate::review_deltas::boundary_edge_keys(
318            &analysis.results.boundary_violations,
319        ),
320        cycles: crate::review_deltas::cycle_keys(
321            &analysis.results.circular_dependencies,
322            &analysis.root,
323        ),
324        public_api: analysis.public_api.clone(),
325        manifests: FxHashMap::default(),
326    }
327}
328
329fn build_decision_deltas(
330    head: &DecisionAnalysis,
331    base: &DecisionSnapshot,
332    dependency_anchors: &[crate::decision_surface::DependencyAnchor],
333) -> ReviewDeltas {
334    let head_snapshot = snapshot_from_decision_analysis(head);
335    let mut deltas = fallow_output::ReviewDeltas {
336        boundary_introduced: crate::review_deltas::introduced_keys(
337            &head_snapshot.boundary_edges,
338            &base.boundary_edges,
339        ),
340        cycle_introduced: crate::review_deltas::introduced_keys(
341            &head_snapshot.cycles,
342            &base.cycles,
343        ),
344        public_api_added: crate::review_deltas::introduced_keys(
345            &head_snapshot.public_api,
346            &base.public_api,
347        ),
348        dependency_added: Vec::new(),
349        dependency_major_bumped: Vec::new(),
350    };
351    crate::dependency_deltas::fill_dependency_delta_keys(&mut deltas, dependency_anchors);
352    deltas
353}
354
355fn build_surface(
356    options: &DecisionSurfaceOptions,
357    head: &DecisionAnalysis,
358    deltas: &ReviewDeltas,
359    dependency_anchors: &[crate::decision_surface::DependencyAnchor],
360) -> fallow_output::DecisionSurface {
361    let boundary_anchors = boundary_anchors(head, deltas);
362    let mut coordination = coordination_anchors(head.impact_closure.as_ref());
363    let resolve_line = export_line_resolver(head.export_lines.as_ref());
364    for anchor in &mut coordination {
365        anchor.line = resolve_line(&anchor.changed_file, &anchor.consumed_symbols);
366    }
367    let public_api_anchor_line = deltas.public_api_added.first().map_or(0, |key| {
368        let mut parts = key.splitn(2, "::");
369        let path = parts.next().unwrap_or_default();
370        let name = parts.next().unwrap_or_default();
371        resolve_line(path, &[name.to_string()])
372    });
373    let affected_not_shown = head
374        .impact_closure
375        .as_ref()
376        .map_or(0, |closure| closure.affected_not_shown.len() as u64);
377    let root = head.root.clone();
378    let head_source = move |rel: &str| std::fs::read_to_string(root.join(rel)).ok();
379    let rename_old_path = |_rel: &str| -> Option<String> { None };
380    let internal_consumers_map = head.internal_consumers.as_ref();
381    let internal_consumers = |rel: &str| -> u64 {
382        internal_consumers_map
383            .and_then(|map| map.get(rel))
384            .copied()
385            .unwrap_or(0)
386    };
387    extract_decision_surface(&DecisionInputs {
388        deltas,
389        boundary_anchors: &boundary_anchors,
390        coordination: &coordination,
391        dependency_anchors,
392        public_api_anchor_line,
393        affected_not_shown,
394        routing: &head.routing,
395        head_source: &head_source,
396        rename_old_path: &rename_old_path,
397        internal_consumers: &internal_consumers,
398        cap: options.max_decisions.unwrap_or(DEFAULT_DECISION_CAP),
399    })
400}
401
402fn boundary_anchors(head: &DecisionAnalysis, deltas: &ReviewDeltas) -> Vec<BoundaryAnchor> {
403    let mut boundary_anchors = Vec::new();
404    let mut seen_pairs = FxHashSet::default();
405    for finding in &head.results.boundary_violations {
406        let key = crate::review_deltas::boundary_edge_key(finding);
407        if !deltas.boundary_introduced.contains(&key) || !seen_pairs.insert(key.clone()) {
408            continue;
409        }
410        boundary_anchors.push(BoundaryAnchor {
411            zone_pair_key: key,
412            from_file: crate::audit_keys::relative_key_path(
413                &finding.violation.from_path,
414                &head.root,
415            ),
416            from_zone: finding.violation.from_zone.clone(),
417            to_zone: finding.violation.to_zone.clone(),
418            line: finding.violation.line,
419        });
420    }
421    boundary_anchors
422}
423
424fn coordination_anchors(
425    closure: Option<&fallow_engine::module_graph::ImpactClosurePaths>,
426) -> Vec<CoordinationAnchor> {
427    let Some(closure) = closure else {
428        return Vec::new();
429    };
430    let mut by_file: FxHashMap<String, (u64, FxHashSet<String>)> = FxHashMap::default();
431    for gap in &closure.coordination_gap {
432        let entry = by_file
433            .entry(gap.changed_file.clone())
434            .or_insert_with(|| (0, FxHashSet::default()));
435        entry.0 += 1;
436        for symbol in &gap.consumed_symbols {
437            entry.1.insert(symbol.clone());
438        }
439    }
440    let mut anchors = by_file
441        .into_iter()
442        .map(|(changed_file, (consumer_count, symbols))| {
443            let mut consumed_symbols: Vec<String> = symbols.into_iter().collect();
444            consumed_symbols.sort_unstable();
445            CoordinationAnchor {
446                changed_file,
447                consumed_symbols,
448                consumer_count,
449                line: 0,
450            }
451        })
452        .collect::<Vec<_>>();
453    anchors.sort_by(|a, b| a.changed_file.cmp(&b.changed_file));
454    anchors
455}
456
457fn export_line_resolver(
458    export_lines: Option<&FxHashMap<String, Vec<(String, u32)>>>,
459) -> impl Fn(&str, &[String]) -> u32 + '_ {
460    move |rel: &str, symbols: &[String]| -> u32 {
461        let Some(exports) = export_lines.and_then(|map| map.get(rel)) else {
462            return 0;
463        };
464        exports
465            .iter()
466            .find(|(name, _)| symbols.iter().any(|symbol| name == symbol))
467            .or_else(|| exports.first())
468            .map_or(0, |(_, line)| *line)
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use std::path::Path;
475    use std::process::Command;
476
477    use crate::{AnalysisOptions, DecisionSurfaceOptions};
478
479    const STACK_PROBE_ENV: &str = "FALLOW_DECISION_SURFACE_STACK_PROBE_CHILD";
480    const STACK_PROBE_TEST: &str =
481        "runtime::decision_surface::tests::decision_surface_parses_on_the_worker_stack";
482    /// Deep enough to overflow a 2 MiB thread in a release build and to fit
483    /// the 16 MiB worker stack in a debug build. An assignment chain has no
484    /// brackets, so the pre-parse bracket guard does not stop it.
485    const ASSIGNMENT_CHAIN_DEPTH: usize = 4_000;
486
487    // A stack overflow aborts the process, so the probe re-runs this test
488    // binary as a child without RUST_MIN_STACK (pinned to 16 MiB in
489    // .cargo/config.toml). The child test thread then has the 2 MiB default
490    // stack of an MCP blocking thread.
491    #[test]
492    fn decision_surface_parses_on_the_worker_stack() {
493        if std::env::var_os(STACK_PROBE_ENV).is_some() {
494            run_stack_probe_child();
495            return;
496        }
497
498        let current_exe = std::env::current_exe().expect("current test binary should be known");
499        let output = Command::new(current_exe)
500            .arg("--exact")
501            .arg(STACK_PROBE_TEST)
502            .arg("--nocapture")
503            .env(STACK_PROBE_ENV, "1")
504            .env_remove("RUST_MIN_STACK")
505            .output()
506            .expect("stack probe child should start");
507
508        assert!(
509            output.status.success(),
510            "stack probe child failed with status {:?}\nstdout:\n{}\nstderr:\n{}",
511            output.status.code(),
512            String::from_utf8_lossy(&output.stdout),
513            String::from_utf8_lossy(&output.stderr)
514        );
515    }
516
517    fn run_stack_probe_child() {
518        let project = tempfile::tempdir().expect("temp dir");
519        let root = project.path();
520        std::fs::write(root.join("index.ts"), "export const used = 1;\n").expect("write entry");
521        git(root, &["init", "-b", "main"]);
522        git(root, &["add", "."]);
523        commit(root, "initial");
524        git(root, &["checkout", "-b", "feature"]);
525        let deep = format!(
526            "export let a = 0;\n{}1;\n",
527            "a=".repeat(ASSIGNMENT_CHAIN_DEPTH)
528        );
529        std::fs::write(root.join("deep.ts"), deep).expect("write deep file");
530        git(root, &["add", "."]);
531        commit(root, "deep");
532
533        let options = DecisionSurfaceOptions {
534            analysis: AnalysisOptions {
535                root: Some(root.to_path_buf()),
536                threads: Some(1),
537                no_cache: true,
538                ..AnalysisOptions::default()
539            },
540            base: Some("main".to_owned()),
541            max_decisions: None,
542        };
543        super::super::run_decision_surface(&options).expect("decision surface should run");
544    }
545
546    fn commit(root: &Path, message: &str) {
547        git(
548            root,
549            &[
550                "-c",
551                "user.email=test@example.com",
552                "-c",
553                "user.name=Test",
554                "-c",
555                "commit.gpgsign=false",
556                "commit",
557                "-m",
558                message,
559            ],
560        );
561    }
562
563    fn git(root: &Path, args: &[&str]) {
564        let status = fallow_engine::changed_files::clear_ambient_git_env(&mut Command::new("git"))
565            .args(args)
566            .current_dir(root)
567            .status()
568            .expect("git command");
569        assert!(status.success(), "git {args:?} failed");
570    }
571}