Skip to main content

fallow_api/
analysis_context.rs

1//! Shared programmatic analysis context resolution.
2
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex, OnceLock};
6
7use fallow_config::{ResolvedConfig, WorkspaceInfo};
8use fallow_engine::change_scope::{
9    ChangeScope, ChangeScopeOwner, ChangeScopeRequest, PackageBaselineCache,
10};
11use fallow_engine::workspace_scope::{WorkspaceScope, WorkspaceScopeError, WorkspaceScopeMode};
12use fallow_output::{DiffIndex, MAX_DIFF_BYTES, RequestName, RequestOutcome, RequestOutcomes};
13use fallow_types::path_util::is_absolute_path_any_platform;
14use rustc_hash::FxHashSet;
15
16use crate::{AnalysisOptions, ProgrammaticError};
17
18type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
19
20/// Resolved common programmatic analysis context.
21///
22/// This owns validation, root/config/diff resolution, production overrides,
23/// the workspace selection, and the per-call thread pool shared by programmatic
24/// analysis families. API runtimes and engine-backed runners use it directly.
25///
26/// The workspace selection resolves against the workspaces of the analysis
27/// session (see `workspace_roots_for_session`). These workspaces include the
28/// `workspaces.patterns` of the loaded config, so the context does not resolve
29/// the selection before the config loads.
30pub struct ProgrammaticAnalysisContext {
31    pub(crate) root: PathBuf,
32    pub(crate) config_path: Option<PathBuf>,
33    pub(crate) allow_remote_extends: bool,
34    pub(crate) no_cache: bool,
35    pub(crate) threads: usize,
36    pub(crate) pool: rayon::ThreadPool,
37    pub(crate) diff: Option<DiffIndex>,
38    /// What became of the diff request, for the envelope's `request_outcomes`.
39    pub(crate) diff_request: Option<RequestOutcome>,
40    pub(crate) production_override: Option<bool>,
41    /// The changed-since ref the call narrows by: the caller's own, or the
42    /// ambient one when it resolved. `None` when an ambient ref stood down.
43    pub(crate) changed_since: Option<String>,
44    /// What became of the changed-since request, set once it resolved or
45    /// stood down.
46    pub(crate) changed_since_request: OnceLock<RequestOutcome>,
47    /// The changed files of the resolved ref, normalized like the CLI's.
48    pub(crate) changed_since_files: OnceLock<FxHashSet<PathBuf>>,
49    /// Who owns the change scope of the call's analyses. Audit owns it, so
50    /// its sections never read `workspaces.changedSince`.
51    pub(crate) change_scope_owner: ChangeScopeOwner,
52    /// The caller turned `workspaces.changedSince` off for this call.
53    pub(crate) no_package_baselines: bool,
54    /// The package map as the call's first analysis resolved it. Later
55    /// analyses of the call reuse it, and its outcome is the call's
56    /// `package-baselines` request outcome.
57    pub(crate) package_baselines: PackageBaselineCache,
58    /// The changed files the call's analyses kept, over every analysis that
59    /// measured: the `scope_size` of the `changed-since` entry.
60    pub(crate) changed_since_analyzed: Mutex<Option<FxHashSet<PathBuf>>>,
61    pub(crate) workspace: Option<Vec<String>>,
62    pub(crate) changed_workspaces: Option<String>,
63    pub(crate) explain: bool,
64    pub(crate) cancellation: Option<Arc<AtomicBool>>,
65}
66
67/// Resolve common programmatic analysis options once for a concrete runtime.
68///
69/// # Errors
70///
71/// Returns a structured programmatic error for invalid roots, configs, thread
72/// counts, workspace scopes, or explicit diff files.
73pub fn resolve_programmatic_analysis_context(
74    options: &AnalysisOptions,
75) -> ProgrammaticResult<ProgrammaticAnalysisContext> {
76    validate_analysis_option_shape(options)?;
77    let root = resolve_analysis_root(options.root.as_deref())?;
78    validate_analysis_config_path(options.config_path.as_deref())?;
79    let threads = options.threads.unwrap_or_else(default_threads);
80    let pool = fallow_engine::thread_pool::worker_pool_builder(threads)
81        .build()
82        .map_err(|err| {
83            ProgrammaticError::new(format!("failed to build analysis thread pool: {err}"), 2)
84                .with_code("FALLOW_THREAD_POOL_INIT_FAILED")
85                .with_context("analysis.threads")
86        })?;
87    let (diff, diff_request) = resolve_diff(options, &root)?;
88    let changed_since_request = OnceLock::new();
89    let changed_since_files = OnceLock::new();
90    let changed_since =
91        resolve_changed_since(options, &root, &changed_since_request, &changed_since_files);
92    Ok(ProgrammaticAnalysisContext {
93        root,
94        config_path: options.config_path.clone(),
95        allow_remote_extends: options.allow_remote_extends,
96        no_cache: options.no_cache,
97        threads,
98        pool,
99        diff,
100        diff_request,
101        production_override: options
102            .production_override
103            .or_else(|| options.production.then_some(true)),
104        changed_since,
105        changed_since_request,
106        changed_since_files,
107        change_scope_owner: ChangeScopeOwner::Run,
108        no_package_baselines: options.no_package_baselines,
109        package_baselines: PackageBaselineCache::new(),
110        changed_since_analyzed: Mutex::new(None),
111        workspace: options.workspace.clone(),
112        changed_workspaces: options.changed_workspaces.clone(),
113        explain: options.explain,
114        cancellation: options.cancellation.clone(),
115    })
116}
117
118fn validate_analysis_option_shape(options: &AnalysisOptions) -> ProgrammaticResult<()> {
119    if options.threads == Some(0) {
120        return Err(
121            ProgrammaticError::new("`threads` must be greater than 0", 2)
122                .with_code("FALLOW_INVALID_THREADS")
123                .with_context("analysis.threads"),
124        );
125    }
126    if options.workspace.is_some() && options.changed_workspaces.is_some() {
127        return Err(ProgrammaticError::new(
128            "`workspace` and `changed_workspaces` are mutually exclusive",
129            2,
130        )
131        .with_code("FALLOW_MUTUALLY_EXCLUSIVE_SCOPE")
132        .with_context("analysis.workspace"));
133    }
134    Ok(())
135}
136
137pub fn resolve_analysis_root(root: Option<&Path>) -> ProgrammaticResult<PathBuf> {
138    let given = root.is_some();
139    let root = match root {
140        Some(root) => root.to_path_buf(),
141        None => std::env::current_dir().map_err(|err| {
142            ProgrammaticError::new(
143                format!("failed to resolve current working directory: {err}"),
144                2,
145            )
146            .with_code("FALLOW_CWD_UNAVAILABLE")
147            .with_context("analysis.root")
148        })?,
149    };
150    let validated = if given {
151        fallow_engine::validate::validate_root(&root)
152    } else {
153        fallow_engine::validate::validate_current_dir_root(&root)
154    };
155    validated.map_err(|err| {
156        ProgrammaticError::new(err, 2)
157            .with_code("FALLOW_INVALID_ROOT")
158            .with_context("analysis.root")
159    })
160}
161
162pub fn validate_analysis_config_path(config_path: Option<&Path>) -> ProgrammaticResult<()> {
163    if let Some(config_path) = config_path
164        && !config_path.exists()
165    {
166        return Err(ProgrammaticError::new(
167            format!("config file does not exist: {}", config_path.display()),
168            2,
169        )
170        .with_code("FALLOW_INVALID_CONFIG_PATH")
171        .with_context("analysis.configPath"));
172    }
173    Ok(())
174}
175
176impl ProgrammaticAnalysisContext {
177    /// Run work inside the per-call Rayon pool.
178    pub fn install<R: Send>(&self, f: impl FnOnce() -> R + Send) -> R {
179        self.pool.install(f)
180    }
181
182    /// Resolved analysis root.
183    #[must_use]
184    pub fn root(&self) -> &Path {
185        &self.root
186    }
187
188    /// Config path supplied by the caller, if any.
189    #[must_use]
190    pub fn config_path(&self) -> &Option<PathBuf> {
191        &self.config_path
192    }
193
194    /// Whether this call permits remote config inheritance.
195    #[must_use]
196    pub const fn allow_remote_extends(&self) -> bool {
197        self.allow_remote_extends
198    }
199
200    /// Whether parser cache use is disabled for this call.
201    #[must_use]
202    pub const fn no_cache(&self) -> bool {
203        self.no_cache
204    }
205
206    /// Effective parser thread count for this call.
207    #[must_use]
208    pub const fn threads(&self) -> usize {
209        self.threads
210    }
211
212    /// Parsed diff for this call, explicit or ambient, if one applied.
213    #[must_use]
214    pub const fn diff_index(&self) -> Option<&DiffIndex> {
215        self.diff.as_ref()
216    }
217
218    /// The call's `request_outcomes`, or `None` when it was asked for nothing.
219    ///
220    /// Carries the `diff-filter` entry, which is the one request this context
221    /// resolves and can stand down. Same object as the CLI publishes for the
222    /// same diff.
223    #[must_use]
224    pub fn request_outcomes(&self) -> Option<RequestOutcomes> {
225        let mut requests = RequestOutcomes::new();
226        requests.insert_if(RequestName::ChangedSince, self.changed_since_outcome());
227        requests.insert_if(RequestName::DiffFilter, self.diff_request.clone());
228        requests.insert_if(
229            RequestName::PackageBaselines,
230            self.package_baselines.request_outcome(),
231        );
232        requests.into_option()
233    }
234
235    /// The `changed-since` entry, with the measured scope when the ref applied
236    /// and an analysis measured it, as the CLI publishes it.
237    fn changed_since_outcome(&self) -> Option<RequestOutcome> {
238        let outcome = self.changed_since_request.get()?.clone();
239        let size = self
240            .changed_since_analyzed
241            .lock()
242            .ok()
243            .and_then(|analyzed| analyzed.as_ref().map(|files| files.len() as u64));
244        Some(match size {
245            Some(size) if outcome.status == fallow_output::RequestStatus::Applied => {
246                RequestOutcome {
247                    scope_size: Some(size),
248                    ..outcome
249                }
250            }
251            _ => outcome,
252        })
253    }
254
255    /// Add the changed files an analysis kept to the call's analyzed changed
256    /// files. Does nothing when no ref resolved.
257    pub(crate) fn measure_changed_since_scope<'a>(
258        &self,
259        analyzed: impl IntoIterator<Item = &'a Path>,
260    ) {
261        let Some(changed) = self.changed_since_files.get() else {
262            return;
263        };
264        let Ok(mut union) = self.changed_since_analyzed.lock() else {
265            return;
266        };
267        union.get_or_insert_with(FxHashSet::default).extend(
268            analyzed
269                .into_iter()
270                .map(dunce::simplified)
271                .filter(|path| changed.contains(*path))
272                .map(Path::to_path_buf),
273        );
274    }
275
276    /// Record the resolved changed files of the call's ref, and the `applied`
277    /// entry, once.
278    fn record_changed_since_applied(&self, git_ref: &str, files: &FxHashSet<PathBuf>) {
279        let _ = self.changed_since_files.set(
280            files
281                .iter()
282                .map(|path| dunce::simplified(path).to_path_buf())
283                .collect(),
284        );
285        let _ = self
286            .changed_since_request
287            .set(RequestOutcome::applied(RequestName::ChangedSince, git_ref));
288    }
289
290    /// Record that an engine runner narrowed by the call's ref, with the
291    /// changed files it kept. For a runner that resolves the ref itself.
292    pub(crate) fn record_changed_since_from_runner(&self, kept: Option<&[PathBuf]>) {
293        let (Some(git_ref), Some(kept)) = (self.changed_since.as_deref(), kept) else {
294            return;
295        };
296        if self.changed_since_files.get().is_none() {
297            let files: FxHashSet<PathBuf> = kept.iter().cloned().collect();
298            self.record_changed_since_applied(git_ref, &files);
299        }
300        self.measure_changed_since_scope(kept.iter().map(PathBuf::as_path));
301    }
302
303    /// Explicit production override supplied by the caller.
304    #[must_use]
305    pub const fn production_override(&self) -> Option<bool> {
306        self.production_override
307    }
308
309    /// Git ref used to scope changed files.
310    #[must_use]
311    pub fn changed_since(&self) -> Option<&str> {
312        self.changed_since.as_deref()
313    }
314
315    /// Hand the change scope of this call's analyses to the caller.
316    #[must_use]
317    pub(crate) const fn with_change_scope_owner(mut self, owner: ChangeScopeOwner) -> Self {
318        self.change_scope_owner = owner;
319        self
320    }
321
322    /// Resolve the change scope of one analysis in this call.
323    ///
324    /// `files` is the changed-file set of the analysis: the call's resolved
325    /// ref, or a set that the caller supplied. A requested ref that stood
326    /// down still suppresses the package map, as on the CLI.
327    pub(crate) fn change_scope(
328        &self,
329        files: Option<&FxHashSet<PathBuf>>,
330        config: &ResolvedConfig,
331        workspaces: &[WorkspaceInfo],
332    ) -> ProgrammaticResult<ChangeScope> {
333        let request = ChangeScopeRequest {
334            owner: self.change_scope_owner,
335            global_ref: self.changed_since.is_some() || self.changed_since_request.get().is_some(),
336            files,
337            cache: Some(&self.package_baselines),
338            no_package_baselines: self.no_package_baselines,
339        };
340        ChangeScope::resolve(request, config, workspaces).map_err(|err| {
341            ProgrammaticError::new(format!("workspace baseline error: {err}"), 2)
342                .with_code("FALLOW_PACKAGE_BASELINE_FAILED")
343                .with_context("analysis.workspaces.changedSince")
344        })
345    }
346
347    /// Workspace filter patterns supplied by the caller.
348    #[must_use]
349    pub fn workspace(&self) -> Option<&[String]> {
350        self.workspace.as_deref()
351    }
352
353    /// Git ref used to scope changed workspaces.
354    #[must_use]
355    pub fn changed_workspaces(&self) -> Option<&str> {
356        self.changed_workspaces.as_deref()
357    }
358
359    /// Whether API JSON should include explanatory metadata.
360    #[must_use]
361    pub const fn explain_enabled(&self) -> bool {
362        self.explain
363    }
364
365    /// The caller's cancellation token for this analysis, if it supplied one.
366    #[must_use]
367    pub fn cancellation(&self) -> Option<&Arc<AtomicBool>> {
368        self.cancellation.as_ref()
369    }
370
371    /// Whether the caller has asked this analysis to stop.
372    #[must_use]
373    pub fn is_cancelled(&self) -> bool {
374        self.cancellation
375            .as_ref()
376            .is_some_and(|cancelled| cancelled.load(Ordering::SeqCst))
377    }
378
379    /// Stop the analysis at a stage boundary once the caller has cancelled it.
380    ///
381    /// `stage` names the work that has not been started, so the error says how
382    /// far the run got rather than only that it was stopped.
383    ///
384    /// # Errors
385    ///
386    /// Returns a `FALLOW_CANCELLED` programmatic error when the caller's token
387    /// is set. Cancellation is always an error, never an empty success: an
388    /// empty report reads downstream as a clean project.
389    pub fn ensure_not_cancelled(&self, stage: &str) -> ProgrammaticResult<()> {
390        if self.is_cancelled() {
391            return Err(cancelled_error(stage));
392        }
393        Ok(())
394    }
395}
396
397/// Stop before any work starts when the caller's token is already set.
398///
399/// Runtimes that never build a [`ProgrammaticAnalysisContext`] read the token
400/// straight off the options with this.
401///
402/// # Errors
403///
404/// Returns a `FALLOW_CANCELLED` programmatic error when the token is set.
405pub fn ensure_options_not_cancelled(
406    options: &AnalysisOptions,
407    stage: &str,
408) -> ProgrammaticResult<()> {
409    if options
410        .cancellation
411        .as_ref()
412        .is_some_and(|cancelled| cancelled.load(Ordering::SeqCst))
413    {
414        return Err(cancelled_error(stage));
415    }
416    Ok(())
417}
418
419/// The single `FALLOW_CANCELLED` error shape for the programmatic API.
420///
421/// `stage` names the work the run never started, so the error says how far it
422/// got and not only that it stopped.
423#[must_use]
424pub fn cancelled_error(stage: &str) -> ProgrammaticError {
425    cancelled_error_message(&format!("analysis was cancelled before {stage}"))
426}
427
428/// A `FALLOW_CANCELLED` error carrying a message a lower layer already built.
429#[must_use]
430pub fn cancelled_error_message(message: &str) -> ProgrammaticError {
431    ProgrammaticError::new(message, 2)
432        .with_code("FALLOW_CANCELLED")
433        .with_context("analysis.cancellation")
434}
435
436fn default_threads() -> usize {
437    std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get)
438}
439
440/// Resolve the call's diff from its two sources, which fail differently.
441///
442/// An explicit `diff_file` is the caller's own argument, so a bad file is a
443/// `FALLOW_INVALID_DIFF_FILE` error. An ambient `FALLOW_DIFF_FILE` comes from
444/// the environment the caller inherited, so a bad file stands down: no diff,
445/// full scope, and a `not-applied` outcome with the CLI's reason token and
446/// sentence. A readable patch from either source stands down when its paths
447/// cannot be placed. An explicit source remains authoritative in that case.
448fn resolve_diff(
449    options: &AnalysisOptions,
450    root: &Path,
451) -> ProgrammaticResult<(Option<DiffIndex>, Option<RequestOutcome>)> {
452    if let Some(path) = options.diff_file.as_deref() {
453        let index = load_explicit_diff_file(path, root)?;
454        let label = format!("diffFile {}", path.display());
455        return Ok(
456            match fallow_engine::diff_source::place_diff(
457                index,
458                root,
459                &fallow_engine::diff_source::diff_base_candidates(root),
460                &label,
461            ) {
462                Ok(index) => {
463                    let request = diff_applied(label, &index);
464                    (Some(index), Some(request))
465                }
466                Err(stand_down) => {
467                    let (reason, message) = stand_down.into_parts();
468                    let request = RequestOutcome::not_applied(
469                        RequestName::DiffFilter,
470                        label,
471                        reason,
472                        message,
473                    );
474                    (None, Some(request))
475                }
476            },
477        );
478    }
479    let Some(path) = options.ambient_diff_file.as_deref() else {
480        return Ok((None, None));
481    };
482    Ok(load_ambient_diff_file(path, root))
483}
484
485/// Load and place an ambient diff the way the CLI loads `$FALLOW_DIFF_FILE`,
486/// with the same label, so both routes publish the same outcome object.
487fn load_ambient_diff_file(path: &Path, root: &Path) -> (Option<DiffIndex>, Option<RequestOutcome>) {
488    let abs = if path.is_absolute() {
489        path.to_path_buf()
490    } else {
491        root.join(path)
492    };
493    let label = format!("$FALLOW_DIFF_FILE {}", abs.display());
494    let placed = fallow_engine::diff_source::read_diff_file(&abs, &label).and_then(|text| {
495        fallow_engine::diff_source::place_diff(
496            DiffIndex::from_unified_diff(&text),
497            root,
498            &fallow_engine::diff_source::diff_base_candidates(root),
499            &label,
500        )
501    });
502    match placed {
503        Ok(index) => {
504            let request = diff_applied(label, &index);
505            (Some(index), Some(request))
506        }
507        Err(stand_down) => {
508            let (reason, message) = stand_down.into_parts();
509            let request =
510                RequestOutcome::not_applied(RequestName::DiffFilter, label, reason, message);
511            (None, Some(request))
512        }
513    }
514}
515
516/// An applied diff filter, sized like the CLI's (see
517/// [`DiffIndex::filter_scope_size`]).
518fn diff_applied(label: String, index: &DiffIndex) -> RequestOutcome {
519    RequestOutcome::applied_with_scope_size(
520        RequestName::DiffFilter,
521        label,
522        index.filter_scope_size() as u64,
523    )
524}
525
526fn load_explicit_diff_file(path: &Path, root: &Path) -> ProgrammaticResult<DiffIndex> {
527    if path == Path::new("-") {
528        return Err(ProgrammaticError::new(
529            "`diff_file` does not support stdin; pass a file path",
530            2,
531        )
532        .with_code("FALLOW_INVALID_DIFF_FILE")
533        .with_context("analysis.diffFile"));
534    }
535    let abs = if is_absolute_path_any_platform(path) {
536        path.to_path_buf()
537    } else {
538        root.join(path)
539    };
540    let meta = std::fs::metadata(&abs).map_err(|err| {
541        ProgrammaticError::new(
542            format!(
543                "diff file does not exist or cannot be read: {} ({err})",
544                abs.display()
545            ),
546            2,
547        )
548        .with_code("FALLOW_INVALID_DIFF_FILE")
549        .with_context("analysis.diffFile")
550    })?;
551    if !meta.is_file() {
552        return Err(ProgrammaticError::new(
553            format!("diff path is not a file: {}", abs.display()),
554            2,
555        )
556        .with_code("FALLOW_INVALID_DIFF_FILE")
557        .with_context("analysis.diffFile"));
558    }
559    if meta.len() > MAX_DIFF_BYTES {
560        return Err(ProgrammaticError::new(
561            format!(
562                "diff file is {} bytes, above the {MAX_DIFF_BYTES} byte limit: {}",
563                meta.len(),
564                abs.display()
565            ),
566            2,
567        )
568        .with_code("FALLOW_INVALID_DIFF_FILE")
569        .with_context("analysis.diffFile"));
570    }
571    let text = std::fs::read_to_string(&abs).map_err(|err| {
572        ProgrammaticError::new(
573            format!("failed to read diff file {}: {err}", abs.display()),
574            2,
575        )
576        .with_code("FALLOW_INVALID_DIFF_FILE")
577        .with_context("analysis.diffFile")
578    })?;
579    Ok(DiffIndex::from_unified_diff(&text))
580}
581
582/// Resolve the call's changed-since ref once, when it comes from the
583/// environment.
584///
585/// The two sources fail differently, like the two diff sources. An explicit
586/// `changed_since` is the caller's own argument, so a ref that does not
587/// resolve fails the call later, in [`changed_files_for_run`]. An ambient
588/// `FALLOW_CHANGED_SINCE` comes from the environment the caller inherited, so
589/// a ref that does not resolve stands down here: the call runs at full scope
590/// and publishes `not-applied` with the CLI's reason token and sentence.
591fn resolve_changed_since(
592    options: &AnalysisOptions,
593    root: &Path,
594    request: &OnceLock<RequestOutcome>,
595    files: &OnceLock<FxHashSet<PathBuf>>,
596) -> Option<String> {
597    if let Some(git_ref) = options.changed_since.as_deref() {
598        return Some(git_ref.to_owned());
599    }
600    let git_ref = options.ambient_changed_since.as_deref()?;
601    match fallow_engine::changed_files::changed_files(root, git_ref) {
602        Ok(changed) => {
603            let _ = files.set(
604                changed
605                    .iter()
606                    .map(|path| dunce::simplified(path).to_path_buf())
607                    .collect(),
608            );
609            let _ = request.set(RequestOutcome::applied(RequestName::ChangedSince, git_ref));
610            Some(git_ref.to_owned())
611        }
612        Err(err) => {
613            let _ = request.set(RequestOutcome::not_applied(
614                RequestName::ChangedSince,
615                git_ref,
616                err.reason(),
617                err.changed_since_message(git_ref),
618            ));
619            None
620        }
621    }
622}
623
624pub fn changed_files_for_run(
625    resolved: &ProgrammaticAnalysisContext,
626) -> ProgrammaticResult<Option<FxHashSet<PathBuf>>> {
627    let Some(git_ref) = resolved.changed_since.as_deref() else {
628        return Ok(None);
629    };
630    fallow_engine::changed_files::changed_files(&resolved.root, git_ref)
631        .inspect(|files| resolved.record_changed_since_applied(git_ref, files))
632        .map(Some)
633        .map_err(|err| {
634            ProgrammaticError::new(
635                format!(
636                    "failed to resolve changed files for ref `{git_ref}`: {}",
637                    err.describe()
638                ),
639                2,
640            )
641            .with_code("FALLOW_CHANGED_FILES_FAILED")
642            .with_context("analysis.changedSince")
643        })
644}
645
646/// Check the workspace selection of the call against the session workspaces,
647/// for a route that reads the whole project but still rejects a selection
648/// that names no workspace.
649pub fn validate_workspace_selection(
650    resolved: &ProgrammaticAnalysisContext,
651    workspaces: &[WorkspaceInfo],
652) -> ProgrammaticResult<()> {
653    workspace_roots_for_session(resolved, workspaces).map(|_| ())
654}
655
656pub fn workspace_roots_for_session(
657    resolved: &ProgrammaticAnalysisContext,
658    workspaces: &[WorkspaceInfo],
659) -> ProgrammaticResult<Option<WorkspaceScope>> {
660    resolve_workspace_scope_from_workspaces(
661        &resolved.root,
662        resolved.workspace.as_deref(),
663        resolved.changed_workspaces.as_deref(),
664        workspaces,
665    )
666}
667
668fn resolve_workspace_scope_from_workspaces(
669    root: &Path,
670    workspace: Option<&[String]>,
671    changed_workspaces: Option<&str>,
672    workspaces: &[WorkspaceInfo],
673) -> ProgrammaticResult<Option<WorkspaceScope>> {
674    fallow_engine::workspace_scope::resolve_workspace_scope(
675        root,
676        workspace,
677        changed_workspaces,
678        workspaces,
679    )
680    .map_err(map_workspace_scope_error)
681}
682
683fn map_workspace_scope_error(err: WorkspaceScopeError) -> ProgrammaticError {
684    match err {
685        WorkspaceScopeError::NoWorkspaces {
686            mode,
687            patterns,
688            git_ref,
689        } => map_no_workspaces_error(mode, &patterns, git_ref.as_deref()),
690        WorkspaceScopeError::InvalidPattern { pattern, message } => ProgrammaticError::new(
691            format!("invalid `workspace` pattern '{pattern}': {message}"),
692            2,
693        )
694        .with_code("FALLOW_INVALID_WORKSPACE_PATTERN")
695        .with_context("analysis.workspace"),
696        WorkspaceScopeError::UnmatchedPatterns {
697            patterns,
698            available,
699        } => ProgrammaticError::new(
700            format!(
701                "`workspace` matched no workspace for pattern{}: {}. Available: {available}",
702                if patterns.len() == 1 { "" } else { "s" },
703                quote_owned_patterns(&patterns),
704            ),
705            2,
706        )
707        .with_code("FALLOW_WORKSPACE_PATTERN_UNMATCHED")
708        .with_context("analysis.workspace"),
709        WorkspaceScopeError::EmptyAfterExclusions { .. } => {
710            ProgrammaticError::new("`workspace` excluded every discovered workspace", 2)
711                .with_code("FALLOW_WORKSPACE_SCOPE_EMPTY")
712                .with_context("analysis.workspace")
713        }
714        WorkspaceScopeError::ChangedWorkspacesFailed { git_ref, message } => {
715            ProgrammaticError::new(
716                format!("failed to resolve changed workspaces for ref `{git_ref}`: {message}"),
717                2,
718            )
719            .with_code("FALLOW_CHANGED_WORKSPACES_FAILED")
720            .with_context("analysis.changedWorkspaces")
721        }
722        WorkspaceScopeError::MutuallyExclusive => ProgrammaticError::new(
723            "`workspace` and `changed_workspaces` are mutually exclusive",
724            2,
725        )
726        .with_code("FALLOW_MUTUALLY_EXCLUSIVE_SCOPE")
727        .with_context("analysis.workspace"),
728    }
729}
730
731fn map_no_workspaces_error(
732    mode: WorkspaceScopeMode,
733    patterns: &[String],
734    git_ref: Option<&str>,
735) -> ProgrammaticError {
736    match mode {
737        WorkspaceScopeMode::Workspace => ProgrammaticError::new(
738            format!(
739                "`workspace` {} specified but no workspaces found. Ensure root package.json has a \"workspaces\" field, pnpm-workspace.yaml exists, tsconfig.json has \"references\", or the project sets \"workspaces.patterns\" in the fallow config.",
740                quote_owned_patterns(patterns)
741            ),
742            2,
743        )
744        .with_code("FALLOW_WORKSPACES_NOT_FOUND")
745        .with_context("analysis.workspace"),
746        WorkspaceScopeMode::ChangedWorkspaces => {
747            let git_ref = git_ref.unwrap_or_default();
748            ProgrammaticError::new(
749                format!(
750                    "`changed_workspaces` '{git_ref}' specified but no workspaces found. Ensure root package.json has a \"workspaces\" field, pnpm-workspace.yaml exists, tsconfig.json has \"references\", or the project sets \"workspaces.patterns\" in the fallow config."
751                ),
752                2,
753            )
754            .with_code("FALLOW_WORKSPACES_NOT_FOUND")
755            .with_context("analysis.changedWorkspaces")
756        }
757    }
758}
759
760fn quote_owned_patterns(patterns: &[String]) -> String {
761    patterns
762        .iter()
763        .map(|pattern| format!("'{pattern}'"))
764        .collect::<Vec<_>>()
765        .join(", ")
766}
767
768#[cfg(test)]
769mod tests {
770    use std::process::Command;
771
772    use crate::AnalysisOptions;
773
774    const STACK_PROBE_ENV: &str = "FALLOW_API_STACK_PROBE_CHILD";
775    const STACK_PROBE_TEST: &str =
776        "analysis_context::tests::programmatic_pool_survives_deep_worker_stack_probe";
777
778    // A stack overflow aborts the whole process, so the probe re-runs this
779    // test binary as a child and asserts on its exit status; the same pattern
780    // guards the CLI global pool in crates/cli/src/rayon_pool.rs. The child
781    // drops RUST_MIN_STACK (pinned to 16 MiB in .cargo/config.toml, and
782    // inherited by default-sized rayon workers) so the probe still fails if
783    // the pool loses its explicit stack_size.
784    #[test]
785    fn programmatic_pool_survives_deep_worker_stack_probe() {
786        if std::env::var_os(STACK_PROBE_ENV).is_some() {
787            run_stack_probe_child();
788            return;
789        }
790
791        let current_exe = std::env::current_exe().expect("current test binary should be known");
792        let output = Command::new(current_exe)
793            .arg("--exact")
794            .arg(STACK_PROBE_TEST)
795            .arg("--nocapture")
796            .env(STACK_PROBE_ENV, "1")
797            .env_remove("RUST_MIN_STACK")
798            .output()
799            .expect("stack probe child should start");
800
801        assert!(
802            output.status.success(),
803            "stack probe child failed with status {:?}\nstdout:\n{}\nstderr:\n{}",
804            output.status.code(),
805            String::from_utf8_lossy(&output.stdout),
806            String::from_utf8_lossy(&output.stderr)
807        );
808    }
809
810    fn run_stack_probe_child() {
811        let root = tempfile::tempdir().expect("stack probe needs a temp analysis root");
812        let options = AnalysisOptions {
813            root: Some(root.path().to_path_buf()),
814            threads: Some(1),
815            ..AnalysisOptions::default()
816        };
817        let context = super::resolve_programmatic_analysis_context(&options)
818            .expect("stack probe context should resolve");
819        assert_eq!(context.install(|| consume_stack(5_000)), 5_000);
820    }
821
822    #[inline(never)]
823    fn consume_stack(depth: usize) -> usize {
824        let frame = [0_u8; 2048];
825        std::hint::black_box(&frame);
826        if depth == 0 {
827            usize::from(frame[0])
828        } else {
829            1 + consume_stack(depth - 1)
830        }
831    }
832
833    #[test]
834    fn no_workspaces_error_names_the_config_key() {
835        for (mode, git_ref) in [
836            (super::WorkspaceScopeMode::Workspace, None),
837            (super::WorkspaceScopeMode::ChangedWorkspaces, Some("main")),
838        ] {
839            let err = super::map_no_workspaces_error(mode, &["web".to_owned()], git_ref);
840            assert!(
841                err.message
842                    .contains("\"workspaces.patterns\" in the fallow config"),
843                "{}",
844                err.message
845            );
846        }
847    }
848}