Skip to main content

fallow_api/
list_runtime.rs

1//! Programmatic list-command runtime helpers.
2
3use std::path::{Path, PathBuf};
4
5use fallow_config::{AuthoredRule, LogicalGroup, LogicalGroupStatus, ResolvedBoundaryConfig};
6use fallow_output::{ListEntryPointOutput, WorkspaceInfo as WorkspaceOutputInfo, WorkspacesOutput};
7use fallow_types::discover::{DiscoveredFile, EntryPoint};
8use fallow_types::path_util::display_relative;
9use rustc_hash::FxHashMap;
10
11use crate::{
12    AnalysisOptions, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
13    BoundariesListing, ListJsonEnvelope, ListJsonOutputInput, ProgrammaticError,
14    analysis_context::{changed_files_for_run, validate_workspace_selection},
15    resolve_programmatic_analysis_context, serialize_list_json_output,
16};
17
18type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
19
20/// Options for MCP/project metadata listing through the programmatic API.
21#[derive(Debug, Clone, Default)]
22pub struct ProjectInfoOptions {
23    /// Shared analysis options: root, config path, and cache behavior.
24    pub analysis: AnalysisOptions,
25    /// Include the resolved entry points in the output.
26    pub entry_points: bool,
27    /// Include the discovered file list in the output.
28    pub files: bool,
29    /// Include the detected plugin names in the output.
30    pub plugins: bool,
31    /// Include the boundaries listing in the output.
32    pub boundaries: bool,
33}
34
35/// Options for `fallow list --boundaries` through the programmatic API.
36#[derive(Debug, Clone, Default)]
37pub struct ListBoundariesOptions {
38    /// Shared analysis options: root, config path, and cache behavior.
39    pub analysis: AnalysisOptions,
40}
41
42/// Typed output for project metadata listing before JSON serialization.
43#[derive(Debug, Clone)]
44pub struct ProjectInfoProgrammaticOutput {
45    /// Detected plugin names; `None` when the section was not requested.
46    pub plugins: Option<Vec<String>>,
47    /// Discovered file paths; `None` when the section was not requested.
48    pub files: Option<Vec<String>>,
49    /// Resolved entry points; `None` when the section was not requested.
50    pub entry_points: Option<Vec<ListEntryPointOutput>>,
51    /// Boundaries listing; `None` when the section was not requested.
52    pub boundaries: Option<BoundariesListing>,
53    /// Workspace listing; `None` when the section was not requested.
54    pub workspaces: Option<WorkspacesOutput<fallow_config::WorkspaceDiagnostic>>,
55    /// Diagnostics the plugin stage recorded, project-root-relative; empty when
56    /// the stage did not run or recorded none.
57    pub plugin_diagnostics: Vec<fallow_config::WorkspaceDiagnostic>,
58    /// Which list envelope shape wraps the serialized body.
59    pub envelope: ListJsonEnvelope,
60}
61
62/// Serialize typed project-info output to the stable JSON contract.
63///
64/// # Errors
65///
66/// Returns a structured programmatic error when JSON serialization fails.
67pub fn serialize_project_info_programmatic_json(
68    output: ProjectInfoProgrammaticOutput,
69) -> ProgrammaticResult<serde_json::Value> {
70    serialize_list_json_output(
71        ListJsonOutputInput {
72            plugins: output.plugins,
73            files: output.files,
74            entry_points: output.entry_points,
75            boundaries: output.boundaries,
76            entry_weight: None,
77            workspaces: output.workspaces,
78            plugin_diagnostics: output.plugin_diagnostics,
79        },
80        output.envelope,
81    )
82    .map_err(|err| {
83        ProgrammaticError::new(format!("failed to serialize project info output: {err}"), 2)
84            .with_code("FALLOW_PROJECT_INFO_SERIALIZE_FAILED")
85            .with_context("project_info")
86    })
87}
88
89/// Typed output for `fallow list --boundaries` before JSON serialization.
90#[derive(Debug, Clone)]
91pub struct ListBoundariesProgrammaticOutput {
92    /// Typed boundaries listing produced by the run.
93    pub boundaries: BoundariesListing,
94}
95
96/// Serialize typed boundary-list output to the stable JSON contract.
97///
98/// # Errors
99///
100/// Returns a structured programmatic error when JSON serialization fails.
101pub fn serialize_list_boundaries_programmatic_json(
102    output: ListBoundariesProgrammaticOutput,
103) -> ProgrammaticResult<serde_json::Value> {
104    serialize_list_json_output(
105        ListJsonOutputInput::<BoundariesListing, serde_json::Value> {
106            plugins: None,
107            files: None,
108            entry_points: None,
109            boundaries: Some(output.boundaries),
110            entry_weight: None,
111            workspaces: None,
112            plugin_diagnostics: Vec::new(),
113        },
114        ListJsonEnvelope::Boundaries,
115    )
116    .map_err(|err| {
117        ProgrammaticError::new(
118            format!("failed to serialize list boundaries output: {err}"),
119            2,
120        )
121        .with_code("FALLOW_LIST_BOUNDARIES_SERIALIZE_FAILED")
122        .with_context("list_boundaries")
123    })
124}
125
126/// Owned boundary listing data shared by CLI and programmatic renderers.
127#[derive(Debug, Clone)]
128pub struct BoundaryData {
129    /// Configured zones with per-zone matched file counts.
130    pub zones: Vec<ZoneInfo>,
131    /// Configured allow rules between zones.
132    pub rules: Vec<RuleInfo>,
133    /// Logical parent/child groups with derived file-count totals.
134    pub logical_groups: Vec<LogicalGroupInfo>,
135    /// Whether the resolved config declares no boundaries at all.
136    pub is_empty: bool,
137}
138
139/// One configured boundary zone with its matched file count.
140#[derive(Debug, Clone)]
141pub struct ZoneInfo {
142    /// Zone name from the config.
143    pub name: String,
144    /// Glob patterns that assign files to the zone.
145    pub patterns: Vec<String>,
146    /// Number of discovered files matching the zone.
147    pub file_count: usize,
148}
149
150/// One configured boundary allow rule.
151#[derive(Debug, Clone)]
152pub struct RuleInfo {
153    /// Source zone the rule applies to.
154    pub from: String,
155    /// Zone names the source zone may import from.
156    pub allow: Vec<String>,
157}
158
159/// View-model mirror of [`LogicalGroup`] with derived file-count totals.
160#[derive(Debug, Clone)]
161pub struct LogicalGroupInfo {
162    /// Parent zone name.
163    pub name: String,
164    /// Child zone names.
165    pub children: Vec<String>,
166    /// Authored `autoDiscover` paths.
167    pub auto_discover: Vec<String>,
168    /// Authored parent rule, if any.
169    pub authored_rule: Option<AuthoredRule>,
170    /// Fallback zone name, if the parent kept patterns.
171    pub fallback_zone: Option<String>,
172    /// Original `zones[]` index.
173    pub source_zone_index: usize,
174    /// Discovery status.
175    pub status: LogicalGroupStatus,
176    /// Total files across children plus the fallback zone.
177    pub file_count: usize,
178    /// Files matched by the child zones only.
179    pub child_file_count: usize,
180    /// Files matched by the fallback zone only.
181    pub fallback_file_count: usize,
182    /// Merged duplicate parent indices.
183    pub merged_from: Option<Vec<usize>>,
184    /// Authored parent root, if any.
185    pub original_zone_root: Option<String>,
186    /// Child-to-source zone indexes.
187    pub child_source_indices: Vec<usize>,
188}
189
190/// Run `list_boundaries` through the API-owned runtime path.
191///
192/// # Errors
193///
194/// Returns a structured programmatic error for invalid options or config-load
195/// failures, and `FALLOW_CANCELLED` when the caller's cancellation token is
196/// set. This route parses nothing: config load and file discovery are its only
197/// stage, so the token is observed on either side of that and nowhere within
198/// it.
199pub fn run_list_boundaries(
200    options: &ListBoundariesOptions,
201) -> ProgrammaticResult<ListBoundariesProgrammaticOutput> {
202    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
203    resolved.install(|| {
204        resolved.ensure_not_cancelled("config load and file discovery")?;
205        let project_config = load_list_project_config(&resolved)?;
206        let session = fallow_engine::session::AnalysisSession::from_config(project_config);
207        validate_workspace_selection(&resolved, session.workspaces())?;
208        resolved.ensure_not_cancelled("the boundary listing")?;
209        let changed_files = changed_files_for_run(&resolved)?;
210        let discovered = scoped_discovered_files(session.files(), changed_files.as_ref());
211        let data = compute_boundary_data(session.config(), Some(&discovered));
212
213        Ok(ListBoundariesProgrammaticOutput {
214            boundaries: boundary_data_to_output(&data),
215        })
216    })
217}
218
219/// Run project metadata listing through the API-owned runtime path.
220///
221/// # Errors
222///
223/// Returns a structured programmatic error for invalid options, config-load
224/// failures, or plugin regex errors, and `FALLOW_CANCELLED` when the caller's
225/// cancellation token is set. This route parses nothing: config load and file
226/// discovery are its only stage, so the token is observed on either side of
227/// that and nowhere within it.
228pub fn run_project_info(
229    options: &ProjectInfoOptions,
230) -> ProgrammaticResult<ProjectInfoProgrammaticOutput> {
231    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
232    resolved.install(|| {
233        resolved.ensure_not_cancelled("config load and file discovery")?;
234        let project_config = load_list_project_config(&resolved)?;
235        let session = fallow_engine::session::AnalysisSession::from_config(project_config);
236        validate_workspace_selection(&resolved, session.workspaces())?;
237        resolved.ensure_not_cancelled("the project listing")?;
238        let config = session.config();
239        let workspaces = session.workspaces();
240        let show_all = project_info_should_show_all(options);
241        let changed_files = changed_files_for_run(&resolved)?;
242        let discovered =
243            project_info_discovered_files(options, show_all, &session, changed_files.as_ref());
244        let discovered_ref = discovered.as_deref();
245
246        let inventory = collect_inventory(&session, options, show_all)?;
247        let (plugin_result, entry_points) = match inventory {
248            Some(inventory) => (
249                Some(inventory.plugins),
250                inventory
251                    .entry_points
252                    .map(|entries| scoped_entry_points(entries, changed_files.as_ref())),
253            ),
254            None => (None, None),
255        };
256        let plugin_diagnostics = plugin_result
257            .as_ref()
258            .map(|result| {
259                result
260                    .plugin_diagnostics(&config.root)
261                    .into_iter()
262                    .map(|diagnostic| diagnostic.into_root_relative(&config.root))
263                    .collect()
264            })
265            .unwrap_or_default();
266        let boundaries = options
267            .boundaries
268            .then(|| boundary_data_to_output(&compute_boundary_data(config, discovered_ref)));
269        let workspaces = if show_all {
270            Some(collect_workspace_output(
271                resolved.root(),
272                workspaces,
273                session.workspace_diagnostics(),
274            ))
275        } else {
276            None
277        };
278        let envelope = if boundaries.is_some() {
279            ListJsonEnvelope::Boundaries
280        } else {
281            ListJsonEnvelope::Plain
282        };
283
284        Ok(ProjectInfoProgrammaticOutput {
285            plugins: collect_plugins(options, show_all, plugin_result.as_ref()),
286            files: collect_files(options, show_all, discovered_ref, resolved.root()),
287            entry_points: entry_points
288                .map(|entries| entry_points_to_output(&entries, resolved.root())),
289            boundaries,
290            workspaces,
291            plugin_diagnostics,
292            envelope,
293        })
294    })
295}
296
297fn project_info_discovered_files(
298    options: &ProjectInfoOptions,
299    show_all: bool,
300    session: &fallow_engine::session::AnalysisSession,
301    changed_files: Option<&rustc_hash::FxHashSet<PathBuf>>,
302) -> Option<Vec<DiscoveredFile>> {
303    let needs_discovery =
304        options.files || options.entry_points || options.boundaries || options.plugins || show_all;
305    needs_discovery.then(|| scoped_discovered_files(session.files(), changed_files))
306}
307
308fn scoped_discovered_files(
309    files: &[DiscoveredFile],
310    changed_files: Option<&rustc_hash::FxHashSet<PathBuf>>,
311) -> Vec<DiscoveredFile> {
312    let Some(changed_files) = changed_files else {
313        return files.to_vec();
314    };
315    files
316        .iter()
317        .filter(|file| changed_files.contains(&file.path))
318        .cloned()
319        .collect()
320}
321
322fn load_list_project_config(
323    resolved: &crate::ProgrammaticAnalysisContext,
324) -> ProgrammaticResult<fallow_engine::project_config::ProjectConfig> {
325    fallow_engine::project_config::config_for_project_analysis(
326        resolved.root(),
327        resolved.config_path().as_deref(),
328        fallow_engine::project_config::ProjectConfigOptions {
329            output: fallow_types::output_format::OutputFormat::Json,
330            no_cache: resolved.no_cache(),
331            threads: resolved.threads(),
332            production_override: resolved.production_override(),
333            quiet: true,
334            analysis: fallow_config::ProductionAnalysis::DeadCode,
335            allow_remote_extends: resolved.allow_remote_extends(),
336        },
337    )
338    .map_err(|err| {
339        ProgrammaticError::new(format!("failed to load config: {err}"), 2)
340            .with_code("FALLOW_CONFIG_LOAD_FAILED")
341            .with_context("analysis.configPath")
342    })
343}
344
345const fn project_info_should_show_all(options: &ProjectInfoOptions) -> bool {
346    !options.entry_points && !options.files && !options.plugins && !options.boundaries
347}
348
349fn collect_plugins(
350    options: &ProjectInfoOptions,
351    show_all: bool,
352    plugin_result: Option<&fallow_engine::plugins::AggregatedPluginResult>,
353) -> Option<Vec<String>> {
354    if options.plugins || show_all {
355        plugin_result.map(|plugin_result| plugin_result.active_plugins().to_vec())
356    } else {
357        None
358    }
359}
360
361fn collect_files(
362    options: &ProjectInfoOptions,
363    show_all: bool,
364    discovered: Option<&[DiscoveredFile]>,
365    root: &Path,
366) -> Option<Vec<String>> {
367    if options.files || show_all {
368        discovered.map(|files| {
369            files
370                .iter()
371                .map(|file| display_relative(root, &file.path))
372                .collect()
373        })
374    } else {
375        None
376    }
377}
378
379/// Run the analysis prelude and entry-point discovery when the listing needs
380/// plugins or entry points, over the whole discovery: a changed-file scope
381/// narrows the listing, never which plugins are active.
382fn collect_inventory(
383    session: &fallow_engine::session::AnalysisSession,
384    options: &ProjectInfoOptions,
385    show_all: bool,
386) -> ProgrammaticResult<Option<fallow_engine::list_inventory::ListingInventory>> {
387    if !(options.plugins || options.entry_points || show_all) {
388        return Ok(None);
389    }
390    fallow_engine::list_inventory::collect_listing_inventory(
391        session,
392        options.entry_points || show_all,
393    )
394    .map(Some)
395    .map_err(|err| {
396        ProgrammaticError::new(err.message(), 2)
397            .with_code("FALLOW_PLUGIN_REGEX_FAILED")
398            .with_context("project_info.plugins")
399    })
400}
401
402/// Keep the entry points inside the changed-file scope, the way the listed
403/// files are kept. The analysis found them over the whole project.
404fn scoped_entry_points(
405    entry_points: Vec<EntryPoint>,
406    changed_files: Option<&rustc_hash::FxHashSet<PathBuf>>,
407) -> Vec<EntryPoint> {
408    let Some(changed_files) = changed_files else {
409        return entry_points;
410    };
411    entry_points
412        .into_iter()
413        .filter(|entry| changed_files.contains(&entry.path))
414        .collect()
415}
416
417fn entry_points_to_output(entries: &[EntryPoint], root: &Path) -> Vec<ListEntryPointOutput> {
418    entries
419        .iter()
420        .map(|entry| ListEntryPointOutput {
421            path: display_relative(root, &entry.path),
422            source: entry.source.to_string(),
423            script: entry.source.script().map(str::to_string),
424        })
425        .collect()
426}
427
428fn collect_workspace_output(
429    root: &Path,
430    workspaces: &[fallow_config::WorkspaceInfo],
431    diagnostics: &[fallow_config::WorkspaceDiagnostic],
432) -> WorkspacesOutput<fallow_config::WorkspaceDiagnostic> {
433    let workspaces = workspaces
434        .iter()
435        .map(|workspace| {
436            let relative = workspace.root.strip_prefix(root).unwrap_or(&workspace.root);
437            WorkspaceOutputInfo {
438                name: workspace.name.clone(),
439                path: relative.display().to_string().replace('\\', "/"),
440                is_internal_dependency: workspace.is_internal_dependency,
441            }
442        })
443        .collect::<Vec<_>>();
444    WorkspacesOutput {
445        workspace_count: workspaces.len(),
446        workspaces,
447        // Project-relative like the sibling `workspaces[].path` and like every
448        // analysis envelope's `workspace_diagnostics[]`. The list envelope has
449        // no post-serialization `strip_root_prefix` pass, so it normalises here.
450        workspace_diagnostics: diagnostics
451            .iter()
452            .map(|diagnostic| diagnostic.clone().into_root_relative(root))
453            .collect(),
454    }
455}
456
457/// Compute boundary listing data from resolved config and optional discovery.
458#[must_use]
459pub fn compute_boundary_data(
460    config: &fallow_config::ResolvedConfig,
461    discovered: Option<&[DiscoveredFile]>,
462) -> BoundaryData {
463    let boundaries = &config.boundaries;
464
465    if boundaries.is_empty() {
466        return BoundaryData {
467            zones: vec![],
468            rules: vec![],
469            logical_groups: vec![],
470            is_empty: true,
471        };
472    }
473
474    let zones = build_boundary_zones(&config.root, boundaries, discovered);
475    let rules = build_boundary_rules(boundaries);
476    let logical_groups = build_logical_groups(boundaries, &zones);
477
478    BoundaryData {
479        zones,
480        rules,
481        logical_groups,
482        is_empty: false,
483    }
484}
485
486fn build_boundary_zones(
487    root: &Path,
488    boundaries: &ResolvedBoundaryConfig,
489    discovered: Option<&[DiscoveredFile]>,
490) -> Vec<ZoneInfo> {
491    let file_counts = count_boundary_files_by_zone(root, boundaries, discovered);
492
493    boundaries
494        .zones
495        .iter()
496        .map(|zone| ZoneInfo {
497            name: zone.name.clone(),
498            patterns: zone.matchers.iter().map(|m| m.glob().to_string()).collect(),
499            file_count: file_counts.get(zone.name.as_str()).copied().unwrap_or(0),
500        })
501        .collect()
502}
503
504fn count_boundary_files_by_zone<'a>(
505    root: &Path,
506    boundaries: &'a ResolvedBoundaryConfig,
507    discovered: Option<&[DiscoveredFile]>,
508) -> FxHashMap<&'a str, usize> {
509    let mut file_counts = FxHashMap::default();
510    let Some(files) = discovered else {
511        return file_counts;
512    };
513
514    for file in files {
515        let Ok(relative_path) = file.path.strip_prefix(root) else {
516            continue;
517        };
518        let relative_path = relative_path.to_string_lossy().replace('\\', "/");
519        if let Some(zone_name) = boundaries.classify_zone(&relative_path) {
520            *file_counts.entry(zone_name).or_default() += 1;
521        }
522    }
523
524    file_counts
525}
526
527fn build_boundary_rules(boundaries: &ResolvedBoundaryConfig) -> Vec<RuleInfo> {
528    boundaries
529        .rules
530        .iter()
531        .map(|rule| RuleInfo {
532            from: rule.from_zone.clone(),
533            allow: rule.allowed_zones.clone(),
534        })
535        .collect()
536}
537
538fn build_logical_groups(
539    boundaries: &ResolvedBoundaryConfig,
540    zones: &[ZoneInfo],
541) -> Vec<LogicalGroupInfo> {
542    let zone_count_by_name: FxHashMap<&str, usize> = zones
543        .iter()
544        .map(|zone| (zone.name.as_str(), zone.file_count))
545        .collect();
546
547    boundaries
548        .logical_groups
549        .iter()
550        .map(|group| logical_group_info(group, &zone_count_by_name))
551        .collect()
552}
553
554fn logical_group_info(
555    group: &LogicalGroup,
556    zone_count_by_name: &FxHashMap<&str, usize>,
557) -> LogicalGroupInfo {
558    let child_file_count: usize = group
559        .children
560        .iter()
561        .filter_map(|child| zone_count_by_name.get(child.as_str()).copied())
562        .sum();
563    let fallback_file_count = group
564        .fallback_zone
565        .as_deref()
566        .and_then(|fallback| zone_count_by_name.get(fallback).copied())
567        .unwrap_or(0);
568
569    LogicalGroupInfo {
570        name: group.name.clone(),
571        children: group.children.clone(),
572        auto_discover: group.auto_discover.clone(),
573        authored_rule: group.authored_rule.clone(),
574        fallback_zone: group.fallback_zone.clone(),
575        source_zone_index: group.source_zone_index,
576        status: group.status,
577        file_count: child_file_count + fallback_file_count,
578        child_file_count,
579        fallback_file_count,
580        merged_from: group.merged_from.clone(),
581        original_zone_root: group.original_zone_root.clone(),
582        child_source_indices: group.child_source_indices.clone(),
583    }
584}
585
586/// Convert boundary listing data to the stable output contract.
587#[must_use]
588pub fn boundary_data_to_output(data: &BoundaryData) -> BoundariesListing {
589    if data.is_empty {
590        return BoundariesListing {
591            configured: false,
592            zone_count: 0,
593            zones: Vec::new(),
594            rule_count: 0,
595            rules: Vec::new(),
596            logical_group_count: 0,
597            logical_groups: Vec::new(),
598        };
599    }
600
601    BoundariesListing {
602        configured: true,
603        zone_count: data.zones.len(),
604        zones: data
605            .zones
606            .iter()
607            .map(|zone| BoundariesListZone {
608                name: zone.name.clone(),
609                patterns: zone.patterns.clone(),
610                file_count: zone.file_count,
611            })
612            .collect(),
613        rule_count: data.rules.len(),
614        rules: data
615            .rules
616            .iter()
617            .map(|rule| BoundariesListRule {
618                from: rule.from.clone(),
619                allow: rule.allow.clone(),
620            })
621            .collect(),
622        logical_group_count: data.logical_groups.len(),
623        logical_groups: data
624            .logical_groups
625            .iter()
626            .map(logical_group_info_to_output)
627            .collect(),
628    }
629}
630
631fn logical_group_info_to_output(group: &LogicalGroupInfo) -> BoundariesListLogicalGroup {
632    BoundariesListLogicalGroup {
633        name: group.name.clone(),
634        children: group.children.clone(),
635        auto_discover: group.auto_discover.clone(),
636        status: group.status,
637        source_zone_index: group.source_zone_index,
638        file_count: group.file_count,
639        authored_rule: group.authored_rule.clone(),
640        fallback_zone: group.fallback_zone.clone(),
641        merged_from: group.merged_from.clone(),
642        original_zone_root: group.original_zone_root.clone(),
643        child_source_indices: group.child_source_indices.clone(),
644    }
645}
646
647#[cfg(test)]
648mod tests {
649    use std::process::Command;
650
651    use fallow_config::ResolvedZone;
652    use fallow_types::discover::FileId;
653    use globset::Glob;
654    use serde_json::json;
655
656    use super::*;
657
658    /// The `fallow workspaces` / `fallow list --workspaces` envelope and the
659    /// MCP `project_info` tool have no post-serialization `strip_root_prefix`
660    /// pass, so `collect_workspace_output` is what makes their diagnostic
661    /// paths project-relative like every other envelope's.
662    #[test]
663    fn workspace_output_emits_project_relative_diagnostic_paths() {
664        let root = Path::new("/project");
665        let output = collect_workspace_output(
666            root,
667            &[],
668            &[fallow_config::WorkspaceDiagnostic::new(
669                root,
670                root.join("packages/inner"),
671                fallow_config::WorkspaceDiagnosticKind::UndeclaredWorkspace,
672            )],
673        );
674
675        let value = serde_json::to_value(&output).expect("workspaces output serializes");
676        assert_eq!(value["workspace_diagnostics"][0]["path"], "packages/inner");
677    }
678
679    fn empty_boundary_data() -> BoundaryData {
680        BoundaryData {
681            zones: vec![],
682            rules: vec![],
683            logical_groups: vec![],
684            is_empty: true,
685        }
686    }
687
688    fn boundary_data_to_json(data: &BoundaryData) -> serde_json::Value {
689        serde_json::to_value(boundary_data_to_output(data))
690            .expect("boundary list output should serialize")
691    }
692
693    fn resolved_zone(name: &str, patterns: &[&str]) -> ResolvedZone {
694        ResolvedZone {
695            name: name.to_string(),
696            patterns: patterns
697                .iter()
698                .map(|pattern| (*pattern).to_string())
699                .collect(),
700            matchers: patterns
701                .iter()
702                .map(|pattern| {
703                    Glob::new(pattern)
704                        .expect("valid test glob")
705                        .compile_matcher()
706                })
707                .collect(),
708            root: None,
709        }
710    }
711
712    fn discovered_files(root: &Path, relative_paths: &[&str]) -> Vec<DiscoveredFile> {
713        relative_paths
714            .iter()
715            .enumerate()
716            .map(|(index, relative_path)| DiscoveredFile {
717                id: FileId(u32::try_from(index).expect("test file count fits in u32")),
718                path: root.join(relative_path),
719                size_bytes: 0,
720            })
721            .collect()
722    }
723
724    fn git(project: &Path, args: &[&str]) {
725        let status = fallow_engine::changed_files::clear_ambient_git_env(&mut Command::new("git"))
726            .args(args)
727            .current_dir(project)
728            .status()
729            .expect("git command should run");
730        assert!(status.success(), "git {args:?} failed");
731    }
732
733    fn setup_changed_boundary_project() -> tempfile::TempDir {
734        let project = tempfile::tempdir().expect("project");
735        std::fs::write(
736            project.path().join("package.json"),
737            r#"{"name":"changed-list-api","main":"src/app/index.ts"}"#,
738        )
739        .expect("write package");
740        std::fs::write(
741            project.path().join(".fallowrc.json"),
742            r#"{
743                "boundaries": {
744                    "zones": [
745                        { "name": "app", "patterns": ["src/app/**"] },
746                        { "name": "shared", "patterns": ["src/shared/**"] }
747                    ]
748                }
749            }"#,
750        )
751        .expect("write config");
752        std::fs::create_dir_all(project.path().join("src/app")).expect("create app");
753        std::fs::create_dir_all(project.path().join("src/shared")).expect("create shared");
754        std::fs::write(
755            project.path().join("src/app/index.ts"),
756            "export const app = 1;\n",
757        )
758        .expect("write app");
759        std::fs::write(
760            project.path().join("src/shared/index.ts"),
761            "export const shared = 1;\n",
762        )
763        .expect("write shared");
764
765        git(project.path(), &["init", "-q"]);
766        git(
767            project.path(),
768            &["config", "user.email", "test@example.com"],
769        );
770        git(project.path(), &["config", "user.name", "Test User"]);
771        git(project.path(), &["config", "commit.gpgsign", "false"]);
772        git(project.path(), &["add", "."]);
773        git(project.path(), &["commit", "-qm", "initial"]);
774        std::fs::write(
775            project.path().join("src/app/index.ts"),
776            "export const app = 2;\n",
777        )
778        .expect("modify app");
779        project
780    }
781
782    #[test]
783    fn project_info_default_sections_match_plain_list_contract() {
784        let project = tempfile::tempdir().expect("project");
785        std::fs::write(
786            project.path().join("package.json"),
787            r#"{"name":"project-info-api","main":"src/index.ts"}"#,
788        )
789        .expect("write package");
790        std::fs::create_dir_all(project.path().join("src")).expect("create src");
791        std::fs::write(
792            project.path().join("src/index.ts"),
793            "export const value = 1;\n",
794        )
795        .expect("write source");
796
797        let output = serialize_project_info_programmatic_json(
798            run_project_info(&ProjectInfoOptions {
799                analysis: AnalysisOptions {
800                    root: Some(project.path().to_path_buf()),
801                    no_cache: true,
802                    ..AnalysisOptions::default()
803                },
804                ..ProjectInfoOptions::default()
805            })
806            .expect("project info should run"),
807        )
808        .expect("project info should serialize");
809
810        assert_eq!(output["file_count"], 1);
811        assert_eq!(output["files"][0], "src/index.ts");
812        assert_eq!(output["entry_point_count"], 1);
813        assert_eq!(output["workspace_count"], 0);
814        assert!(output.get("kind").is_none());
815    }
816
817    #[test]
818    fn project_info_surfaces_malformed_root_package_json() {
819        let project = tempfile::tempdir().expect("project");
820        std::fs::write(project.path().join("package.json"), "{").expect("write package");
821
822        let err = run_project_info(&ProjectInfoOptions {
823            analysis: AnalysisOptions {
824                root: Some(project.path().to_path_buf()),
825                no_cache: true,
826                ..AnalysisOptions::default()
827            },
828            ..ProjectInfoOptions::default()
829        })
830        .expect_err("malformed root package.json must fail project info");
831
832        assert_eq!(err.exit_code, 2);
833        assert_eq!(err.code.as_deref(), Some("FALLOW_CONFIG_LOAD_FAILED"));
834        assert!(
835            err.message.contains("package.json"),
836            "error should name the malformed root package.json"
837        );
838    }
839
840    #[test]
841    fn project_info_default_sections_include_undeclared_workspace_diagnostic() {
842        let project = tempfile::tempdir().expect("project");
843        std::fs::write(
844            project.path().join("package.json"),
845            r#"{"name":"project-info-api","workspaces":["packages/*"]}"#,
846        )
847        .expect("write package");
848        std::fs::create_dir_all(project.path().join("packages/app")).expect("workspace dir");
849        std::fs::write(
850            project.path().join("packages/app/package.json"),
851            r#"{"name":"app","main":"src/index.ts"}"#,
852        )
853        .expect("write workspace package");
854        std::fs::create_dir_all(project.path().join("tools/extra")).expect("extra package dir");
855        std::fs::write(
856            project.path().join("tools/extra/package.json"),
857            r#"{"name":"extra"}"#,
858        )
859        .expect("write extra package");
860
861        let output = serialize_project_info_programmatic_json(
862            run_project_info(&ProjectInfoOptions {
863                analysis: AnalysisOptions {
864                    root: Some(project.path().to_path_buf()),
865                    no_cache: true,
866                    ..AnalysisOptions::default()
867                },
868                ..ProjectInfoOptions::default()
869            })
870            .expect("project info should run"),
871        )
872        .expect("project info should serialize");
873
874        let diagnostics = output["workspace_diagnostics"]
875            .as_array()
876            .expect("project info should include workspace_diagnostics");
877        assert!(
878            diagnostics.iter().any(|diagnostic| {
879                diagnostic["kind"].as_str() == Some("undeclared-workspace")
880                    // Project-relative, like every other envelope's
881                    // `workspace_diagnostics[].path` (issue #2366 follow-up).
882                    && diagnostic["path"].as_str() == Some("tools/extra")
883            }),
884            "project info must include undeclared workspace diagnostics from the reused session, got {diagnostics:#?}"
885        );
886    }
887
888    /// Issue #2366: the MCP `project_info` tool reads the same workspace value
889    /// the `fallow workspaces` envelope does, so a glob declared in both
890    /// `package.json` and `pnpm-workspace.yaml` must reach an agent as one
891    /// entry per directory, project-relative, exactly as the CLI reports it.
892    #[test]
893    fn project_info_reports_one_entry_per_directory_for_a_glob_in_two_manifests() {
894        let project = tempfile::tempdir().expect("project");
895        let root = project.path();
896        std::fs::create_dir_all(root.join("pkgs/aaa")).expect("first package-less dir");
897        std::fs::create_dir_all(root.join("pkgs/bbb")).expect("second package-less dir");
898        std::fs::create_dir_all(root.join("src")).expect("source dir");
899        std::fs::write(
900            root.join("package.json"),
901            r#"{"name":"two-manifest-root","private":true,"workspaces":["./pkgs/*"]}"#,
902        )
903        .expect("write root manifest");
904        std::fs::write(
905            root.join("pnpm-workspace.yaml"),
906            "packages:\n  - \"pkgs/*\"\n",
907        )
908        .expect("write pnpm workspace manifest");
909        std::fs::write(root.join("src/index.ts"), "export const value = 1;\n")
910            .expect("write source");
911
912        let output = serialize_project_info_programmatic_json(
913            run_project_info(&ProjectInfoOptions {
914                analysis: AnalysisOptions {
915                    root: Some(root.to_path_buf()),
916                    no_cache: true,
917                    ..AnalysisOptions::default()
918                },
919                ..ProjectInfoOptions::default()
920            })
921            .expect("project info should run"),
922        )
923        .expect("project info should serialize");
924
925        let reported: Vec<(&str, &str)> = output["workspace_diagnostics"]
926            .as_array()
927            .expect("project info should include workspace_diagnostics")
928            .iter()
929            .filter(|diagnostic| diagnostic["kind"] == "glob-matched-no-package-json")
930            .map(|diagnostic| {
931                (
932                    diagnostic["pattern"].as_str().unwrap_or_default(),
933                    diagnostic["path"].as_str().unwrap_or_default(),
934                )
935            })
936            .collect();
937
938        assert_eq!(
939            reported,
940            vec![("pkgs/*", "pkgs/aaa"), ("pkgs/*", "pkgs/bbb")],
941            "project_info agrees with the CLI envelopes: {}",
942            output["workspace_diagnostics"]
943        );
944    }
945
946    #[test]
947    fn list_runtimes_scope_files_and_boundary_counts_to_changed_since() {
948        let project = setup_changed_boundary_project();
949        let analysis = AnalysisOptions {
950            root: Some(project.path().to_path_buf()),
951            changed_since: Some("HEAD".to_string()),
952            no_cache: true,
953            ..AnalysisOptions::default()
954        };
955
956        let project_info = serialize_project_info_programmatic_json(
957            run_project_info(&ProjectInfoOptions {
958                analysis: analysis.clone(),
959                files: true,
960                boundaries: true,
961                ..ProjectInfoOptions::default()
962            })
963            .expect("project info should run"),
964        )
965        .expect("project info should serialize");
966        let files = project_info["files"].as_array().expect("files array");
967        assert_eq!(files, &[json!("src/app/index.ts")]);
968        assert_eq!(project_info["boundaries"]["zones"][0]["file_count"], 1);
969        assert_eq!(project_info["boundaries"]["zones"][1]["file_count"], 0);
970
971        let boundaries = serialize_list_boundaries_programmatic_json(
972            run_list_boundaries(&ListBoundariesOptions { analysis })
973                .expect("list boundaries should run"),
974        )
975        .expect("list boundaries should serialize");
976        assert_eq!(boundaries["boundaries"]["zones"][0]["file_count"], 1);
977        assert_eq!(boundaries["boundaries"]["zones"][1]["file_count"], 0);
978    }
979
980    #[test]
981    fn boundary_zone_counts_preserve_first_match_for_overlapping_zones() {
982        let root = Path::new("project");
983        let boundaries = ResolvedBoundaryConfig {
984            zones: vec![
985                resolved_zone("source", &["src/**"]),
986                resolved_zone("shared", &["src/shared/**"]),
987            ],
988            ..ResolvedBoundaryConfig::default()
989        };
990        let files = discovered_files(root, &["src/app.ts", "src/shared/index.ts"]);
991
992        let zones = build_boundary_zones(root, &boundaries, Some(&files));
993
994        assert_eq!(zones[0].name, "source");
995        assert_eq!(zones[0].file_count, 2);
996        assert_eq!(zones[1].name, "shared");
997        assert_eq!(zones[1].file_count, 0);
998    }
999
1000    #[test]
1001    fn boundary_zone_counts_ignore_unmatched_and_out_of_root_files() {
1002        let root = Path::new("project");
1003        let boundaries = ResolvedBoundaryConfig {
1004            zones: vec![resolved_zone("matched", &["src/matched/**"])],
1005            ..ResolvedBoundaryConfig::default()
1006        };
1007        let mut files = discovered_files(root, &["src/matched/index.ts", "src/unmatched/index.ts"]);
1008        files.push(DiscoveredFile {
1009            id: FileId(2),
1010            path: PathBuf::from("outside/index.ts"),
1011            size_bytes: 0,
1012        });
1013
1014        let zones = build_boundary_zones(root, &boundaries, Some(&files));
1015
1016        assert_eq!(zones[0].file_count, 1);
1017    }
1018
1019    #[test]
1020    fn boundary_zone_counts_preserve_duplicate_name_semantics() {
1021        let root = Path::new("project");
1022        let boundaries = ResolvedBoundaryConfig {
1023            zones: vec![
1024                resolved_zone("shared", &["src/first/**"]),
1025                resolved_zone("shared", &["src/second/**"]),
1026            ],
1027            ..ResolvedBoundaryConfig::default()
1028        };
1029        let files = discovered_files(root, &["src/first/index.ts", "src/second/index.ts"]);
1030
1031        let zones = build_boundary_zones(root, &boundaries, Some(&files));
1032
1033        assert_eq!(zones[0].patterns, ["src/first/**"]);
1034        assert_eq!(zones[1].patterns, ["src/second/**"]);
1035        assert_eq!(zones[0].file_count, 2);
1036        assert_eq!(zones[1].file_count, 2);
1037    }
1038
1039    #[test]
1040    fn boundary_zone_output_is_deterministic_and_keeps_config_order() {
1041        let root = Path::new("project");
1042        let boundaries = ResolvedBoundaryConfig {
1043            zones: vec![
1044                resolved_zone("zeta", &["src/zeta/**"]),
1045                resolved_zone("alpha", &["src/alpha/**"]),
1046                resolved_zone("middle", &["src/middle/**"]),
1047            ],
1048            ..ResolvedBoundaryConfig::default()
1049        };
1050        let files = discovered_files(
1051            root,
1052            &[
1053                "src/middle/two.ts",
1054                "src/zeta/one.ts",
1055                "src/alpha/one.ts",
1056                "src/middle/one.ts",
1057            ],
1058        );
1059
1060        let first = build_boundary_zones(root, &boundaries, Some(&files));
1061        let second = build_boundary_zones(root, &boundaries, Some(&files));
1062        let signature = |zones: &[ZoneInfo]| {
1063            zones
1064                .iter()
1065                .map(|zone| (zone.name.clone(), zone.file_count))
1066                .collect::<Vec<_>>()
1067        };
1068
1069        assert_eq!(signature(&first), signature(&second));
1070        assert_eq!(
1071            signature(&first),
1072            vec![
1073                ("zeta".to_string(), 1),
1074                ("alpha".to_string(), 1),
1075                ("middle".to_string(), 2),
1076            ]
1077        );
1078    }
1079
1080    #[test]
1081    fn boundary_json_empty_includes_logical_groups_key() {
1082        let value = boundary_data_to_json(&empty_boundary_data());
1083
1084        assert_eq!(value["configured"], false);
1085        assert_eq!(value["zone_count"], 0);
1086        assert_eq!(value["rule_count"], 0);
1087        assert_eq!(value["logical_group_count"], 0);
1088        assert_eq!(value["logical_groups"], json!([]));
1089    }
1090
1091    #[test]
1092    fn boundary_json_logical_group_carries_all_fields() {
1093        let data = BoundaryData {
1094            zones: vec![ZoneInfo {
1095                name: "features/auth".to_string(),
1096                patterns: vec!["src/features/auth/**".to_string()],
1097                file_count: 3,
1098            }],
1099            rules: vec![],
1100            logical_groups: vec![LogicalGroupInfo {
1101                name: "features".to_string(),
1102                children: vec!["features/auth".to_string()],
1103                auto_discover: vec!["./src/features/".to_string()],
1104                authored_rule: Some(AuthoredRule {
1105                    allow: vec!["shared".to_string()],
1106                    allow_type_only: vec!["types".to_string()],
1107                }),
1108                fallback_zone: None,
1109                source_zone_index: 1,
1110                status: LogicalGroupStatus::Ok,
1111                file_count: 3,
1112                child_file_count: 3,
1113                fallback_file_count: 0,
1114                merged_from: None,
1115                original_zone_root: None,
1116                child_source_indices: vec![],
1117            }],
1118            is_empty: false,
1119        };
1120
1121        let value = boundary_data_to_json(&data);
1122        let group = &value["logical_groups"][0];
1123
1124        assert_eq!(value["logical_group_count"], 1);
1125        assert_eq!(group["name"], "features");
1126        assert_eq!(group["children"][0], "features/auth");
1127        assert_eq!(group["auto_discover"][0], "./src/features/");
1128        assert_eq!(group["status"], "ok");
1129        assert_eq!(group["source_zone_index"], 1);
1130        assert_eq!(group["file_count"], 3);
1131        assert_eq!(group["authored_rule"]["allow"][0], "shared");
1132        assert_eq!(group["authored_rule"]["allow_type_only"][0], "types");
1133        assert!(group.get("fallback_zone").is_none());
1134        assert!(group.get("merged_from").is_none());
1135        assert!(group.get("original_zone_root").is_none());
1136        assert!(group.get("child_source_indices").is_none());
1137    }
1138
1139    #[test]
1140    fn boundary_json_logical_group_optional_fields_round_trip() {
1141        let data = BoundaryData {
1142            zones: vec![],
1143            rules: vec![],
1144            logical_groups: vec![LogicalGroupInfo {
1145                name: "features".to_string(),
1146                children: vec!["features/auth".to_string(), "features/billing".to_string()],
1147                auto_discover: vec!["src/features".to_string(), "src/modules".to_string()],
1148                authored_rule: None,
1149                fallback_zone: Some("features".to_string()),
1150                source_zone_index: 0,
1151                status: LogicalGroupStatus::Empty,
1152                file_count: 2,
1153                child_file_count: 0,
1154                fallback_file_count: 2,
1155                merged_from: Some(vec![0, 3]),
1156                original_zone_root: Some("packages/app/".to_string()),
1157                child_source_indices: vec![0, 1],
1158            }],
1159            is_empty: false,
1160        };
1161
1162        let group = &boundary_data_to_json(&data)["logical_groups"][0];
1163
1164        assert_eq!(group["status"], "empty");
1165        assert_eq!(group["fallback_zone"], "features");
1166        assert_eq!(group["merged_from"][1], 3);
1167        assert_eq!(group["original_zone_root"], "packages/app/");
1168        assert_eq!(group["child_source_indices"][1], 1);
1169    }
1170}