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    /// Folder that the patterns are relative to, without a trailing slash.
147    /// `None` when the zone has no `root` and the patterns are relative to
148    /// the project root.
149    pub root: Option<String>,
150    /// Number of discovered files matching the zone.
151    pub file_count: usize,
152    /// Globs of the public entry files of the zone (`publicFiles`).
153    pub public_files: Vec<String>,
154}
155
156/// One configured boundary allow rule.
157#[derive(Debug, Clone)]
158pub struct RuleInfo {
159    /// Source zone the rule applies to.
160    pub from: String,
161    /// Zone names the source zone may import from.
162    pub allow: Vec<String>,
163}
164
165/// View-model mirror of [`LogicalGroup`] with derived file-count totals.
166#[derive(Debug, Clone)]
167pub struct LogicalGroupInfo {
168    /// Parent zone name.
169    pub name: String,
170    /// Child zone names.
171    pub children: Vec<String>,
172    /// Authored `autoDiscover` paths.
173    pub auto_discover: Vec<String>,
174    /// Authored parent rule, if any.
175    pub authored_rule: Option<AuthoredRule>,
176    /// Fallback zone name, if the parent kept patterns.
177    pub fallback_zone: Option<String>,
178    /// Original `zones[]` index.
179    pub source_zone_index: usize,
180    /// Discovery status.
181    pub status: LogicalGroupStatus,
182    /// Total files across children plus the fallback zone.
183    pub file_count: usize,
184    /// Files matched by the child zones only.
185    pub child_file_count: usize,
186    /// Files matched by the fallback zone only.
187    pub fallback_file_count: usize,
188    /// Merged duplicate parent indices.
189    pub merged_from: Option<Vec<usize>>,
190    /// Authored parent root, if any.
191    pub original_zone_root: Option<String>,
192    /// Child-to-source zone indexes.
193    pub child_source_indices: Vec<usize>,
194}
195
196/// Run `list_boundaries` through the API-owned runtime path.
197///
198/// # Errors
199///
200/// Returns a structured programmatic error for invalid options or config-load
201/// failures, and `FALLOW_CANCELLED` when the caller's cancellation token is
202/// set. This route parses nothing: config load and file discovery are its only
203/// stage, so the token is observed on either side of that and nowhere within
204/// it.
205pub fn run_list_boundaries(
206    options: &ListBoundariesOptions,
207) -> ProgrammaticResult<ListBoundariesProgrammaticOutput> {
208    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
209    resolved.install(|| {
210        resolved.ensure_not_cancelled("config load and file discovery")?;
211        let session = load_list_session(&options.analysis)?;
212        validate_workspace_selection(&resolved, session.workspaces())?;
213        resolved.ensure_not_cancelled("the boundary listing")?;
214        let changed_files = changed_files_for_run(&resolved)?;
215        let discovered = scoped_discovered_files(session.files(), changed_files.as_ref());
216        let data = compute_boundary_data(session.config(), Some(&discovered));
217
218        Ok(ListBoundariesProgrammaticOutput {
219            boundaries: boundary_data_to_output(&data),
220        })
221    })
222}
223
224/// Run project metadata listing through the API-owned runtime path.
225///
226/// # Errors
227///
228/// Returns a structured programmatic error for invalid options, config-load
229/// failures, or plugin regex errors, and `FALLOW_CANCELLED` when the caller's
230/// cancellation token is set. This route parses nothing: config load and file
231/// discovery are its only stage, so the token is observed on either side of
232/// that and nowhere within it.
233pub fn run_project_info(
234    options: &ProjectInfoOptions,
235) -> ProgrammaticResult<ProjectInfoProgrammaticOutput> {
236    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
237    resolved.install(|| {
238        resolved.ensure_not_cancelled("config load and file discovery")?;
239        let session = load_list_session(&options.analysis)?;
240        validate_workspace_selection(&resolved, session.workspaces())?;
241        resolved.ensure_not_cancelled("the project listing")?;
242        let config = session.config();
243        let workspaces = session.workspaces();
244        let show_all = project_info_should_show_all(options);
245        let changed_files = changed_files_for_run(&resolved)?;
246        let discovered =
247            project_info_discovered_files(options, show_all, &session, changed_files.as_ref());
248        let discovered_ref = discovered.as_deref();
249
250        let inventory = collect_inventory(&session, options, show_all)?;
251        let (plugin_result, entry_points) = match inventory {
252            Some(inventory) => (
253                Some(inventory.plugins),
254                inventory
255                    .entry_points
256                    .map(|entries| scoped_entry_points(entries, changed_files.as_ref())),
257            ),
258            None => (None, None),
259        };
260        let plugin_diagnostics = plugin_result
261            .as_ref()
262            .map(|result| {
263                result
264                    .plugin_diagnostics(&config.root)
265                    .into_iter()
266                    .map(|diagnostic| diagnostic.into_root_relative(&config.root))
267                    .collect()
268            })
269            .unwrap_or_default();
270        let boundaries = options
271            .boundaries
272            .then(|| boundary_data_to_output(&compute_boundary_data(config, discovered_ref)));
273        let workspaces = if show_all {
274            Some(collect_workspace_output(
275                resolved.root(),
276                workspaces,
277                session.workspace_diagnostics(),
278            ))
279        } else {
280            None
281        };
282        let envelope = if boundaries.is_some() {
283            ListJsonEnvelope::Boundaries
284        } else {
285            ListJsonEnvelope::Plain
286        };
287
288        Ok(ProjectInfoProgrammaticOutput {
289            plugins: collect_plugins(options, show_all, plugin_result.as_ref()),
290            files: collect_files(options, show_all, discovered_ref, resolved.root()),
291            entry_points: entry_points
292                .map(|entries| entry_points_to_output(&entries, resolved.root())),
293            boundaries,
294            workspaces,
295            plugin_diagnostics,
296            envelope,
297        })
298    })
299}
300
301fn project_info_discovered_files(
302    options: &ProjectInfoOptions,
303    show_all: bool,
304    session: &fallow_engine::session::AnalysisSession,
305    changed_files: Option<&rustc_hash::FxHashSet<PathBuf>>,
306) -> Option<Vec<DiscoveredFile>> {
307    let needs_discovery =
308        options.files || options.entry_points || options.boundaries || options.plugins || show_all;
309    needs_discovery.then(|| scoped_discovered_files(session.files(), changed_files))
310}
311
312fn scoped_discovered_files(
313    files: &[DiscoveredFile],
314    changed_files: Option<&rustc_hash::FxHashSet<PathBuf>>,
315) -> Vec<DiscoveredFile> {
316    let Some(changed_files) = changed_files else {
317        return files.to_vec();
318    };
319    files
320        .iter()
321        .filter(|file| changed_files.contains(&file.path))
322        .cloned()
323        .collect()
324}
325
326/// Open the session of a listing. The listing route opens the dead-code
327/// session of its run.
328fn load_list_session(
329    analysis: &crate::AnalysisOptions,
330) -> ProgrammaticResult<fallow_engine::session::AnalysisSession> {
331    let run = crate::run::resolve_programmatic_run(analysis, &crate::run::ProgrammaticEntry::List)?;
332    Ok(crate::run::runnable(&run, fallow_config::PlannedAnalysis::DeadCode)?.open_session())
333}
334
335const fn project_info_should_show_all(options: &ProjectInfoOptions) -> bool {
336    !options.entry_points && !options.files && !options.plugins && !options.boundaries
337}
338
339fn collect_plugins(
340    options: &ProjectInfoOptions,
341    show_all: bool,
342    plugin_result: Option<&fallow_engine::plugins::AggregatedPluginResult>,
343) -> Option<Vec<String>> {
344    if options.plugins || show_all {
345        plugin_result.map(|plugin_result| plugin_result.active_plugins().to_vec())
346    } else {
347        None
348    }
349}
350
351fn collect_files(
352    options: &ProjectInfoOptions,
353    show_all: bool,
354    discovered: Option<&[DiscoveredFile]>,
355    root: &Path,
356) -> Option<Vec<String>> {
357    if options.files || show_all {
358        discovered.map(|files| {
359            files
360                .iter()
361                .map(|file| display_relative(root, &file.path))
362                .collect()
363        })
364    } else {
365        None
366    }
367}
368
369/// Run the analysis prelude and entry-point discovery when the listing needs
370/// plugins or entry points, over the whole discovery: a changed-file scope
371/// narrows the listing, never which plugins are active.
372fn collect_inventory(
373    session: &fallow_engine::session::AnalysisSession,
374    options: &ProjectInfoOptions,
375    show_all: bool,
376) -> ProgrammaticResult<Option<fallow_engine::list_inventory::ListingInventory>> {
377    if !(options.plugins || options.entry_points || show_all) {
378        return Ok(None);
379    }
380    fallow_engine::list_inventory::collect_listing_inventory(
381        session,
382        options.entry_points || show_all,
383    )
384    .map(Some)
385    .map_err(|err| {
386        ProgrammaticError::new(err.message(), 2)
387            .with_code("FALLOW_PLUGIN_REGEX_FAILED")
388            .with_context("project_info.plugins")
389    })
390}
391
392/// Keep the entry points inside the changed-file scope, the way the listed
393/// files are kept. The analysis found them over the whole project.
394fn scoped_entry_points(
395    entry_points: Vec<EntryPoint>,
396    changed_files: Option<&rustc_hash::FxHashSet<PathBuf>>,
397) -> Vec<EntryPoint> {
398    let Some(changed_files) = changed_files else {
399        return entry_points;
400    };
401    entry_points
402        .into_iter()
403        .filter(|entry| changed_files.contains(&entry.path))
404        .collect()
405}
406
407fn entry_points_to_output(entries: &[EntryPoint], root: &Path) -> Vec<ListEntryPointOutput> {
408    entries
409        .iter()
410        .map(|entry| ListEntryPointOutput {
411            path: display_relative(root, &entry.path),
412            source: entry.source.to_string(),
413            script: entry.source.script().map(str::to_string),
414        })
415        .collect()
416}
417
418fn collect_workspace_output(
419    root: &Path,
420    workspaces: &[fallow_config::WorkspaceInfo],
421    diagnostics: &[fallow_config::WorkspaceDiagnostic],
422) -> WorkspacesOutput<fallow_config::WorkspaceDiagnostic> {
423    let workspaces = workspaces
424        .iter()
425        .map(|workspace| {
426            let relative = workspace.root.strip_prefix(root).unwrap_or(&workspace.root);
427            WorkspaceOutputInfo {
428                name: workspace.name.clone(),
429                path: relative.display().to_string().replace('\\', "/"),
430                is_internal_dependency: workspace.is_internal_dependency,
431            }
432        })
433        .collect::<Vec<_>>();
434    WorkspacesOutput {
435        workspace_count: workspaces.len(),
436        workspaces,
437        // Project-relative like the sibling `workspaces[].path` and like every
438        // analysis envelope's `workspace_diagnostics[]`. The list envelope has
439        // no post-serialization `strip_root_prefix` pass, so it normalises here.
440        workspace_diagnostics: diagnostics
441            .iter()
442            .map(|diagnostic| diagnostic.clone().into_root_relative(root))
443            .collect(),
444    }
445}
446
447/// Compute boundary listing data from resolved config and optional discovery.
448#[must_use]
449pub fn compute_boundary_data(
450    config: &fallow_config::ResolvedConfig,
451    discovered: Option<&[DiscoveredFile]>,
452) -> BoundaryData {
453    let boundaries = &config.boundaries;
454
455    if boundaries.is_empty() {
456        return BoundaryData {
457            zones: vec![],
458            rules: vec![],
459            logical_groups: vec![],
460            is_empty: true,
461        };
462    }
463
464    let zones = build_boundary_zones(&config.root, boundaries, discovered);
465    let rules = build_boundary_rules(boundaries);
466    let logical_groups = build_logical_groups(boundaries, &zones);
467
468    BoundaryData {
469        zones,
470        rules,
471        logical_groups,
472        is_empty: false,
473    }
474}
475
476fn build_boundary_zones(
477    root: &Path,
478    boundaries: &ResolvedBoundaryConfig,
479    discovered: Option<&[DiscoveredFile]>,
480) -> Vec<ZoneInfo> {
481    let file_counts = count_boundary_files_by_zone(root, boundaries, discovered);
482
483    boundaries
484        .zones
485        .iter()
486        .map(|zone| ZoneInfo {
487            name: zone.name.clone(),
488            patterns: zone.patterns.clone(),
489            root: zone_root_display(zone.root.as_deref()),
490            file_count: file_counts.get(zone.name.as_str()).copied().unwrap_or(0),
491            public_files: zone.public_files.clone(),
492        })
493        .collect()
494}
495
496/// The zone root as a user wrote it: the resolved root carries a trailing
497/// slash, and an empty root means the project root.
498fn zone_root_display(root: Option<&str>) -> Option<String> {
499    root.map(|root| root.trim_end_matches('/'))
500        .filter(|root| !root.is_empty())
501        .map(str::to_owned)
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                root: zone.root.clone(),
611                file_count: zone.file_count,
612                public_files: zone.public_files.clone(),
613            })
614            .collect(),
615        rule_count: data.rules.len(),
616        rules: data
617            .rules
618            .iter()
619            .map(|rule| BoundariesListRule {
620                from: rule.from.clone(),
621                allow: rule.allow.clone(),
622            })
623            .collect(),
624        logical_group_count: data.logical_groups.len(),
625        logical_groups: data
626            .logical_groups
627            .iter()
628            .map(logical_group_info_to_output)
629            .collect(),
630    }
631}
632
633fn logical_group_info_to_output(group: &LogicalGroupInfo) -> BoundariesListLogicalGroup {
634    BoundariesListLogicalGroup {
635        name: group.name.clone(),
636        children: group.children.clone(),
637        auto_discover: group.auto_discover.clone(),
638        status: group.status,
639        source_zone_index: group.source_zone_index,
640        file_count: group.file_count,
641        authored_rule: group.authored_rule.clone(),
642        fallback_zone: group.fallback_zone.clone(),
643        merged_from: group.merged_from.clone(),
644        original_zone_root: group.original_zone_root.clone(),
645        child_source_indices: group.child_source_indices.clone(),
646    }
647}
648
649#[cfg(test)]
650mod tests {
651
652    use fallow_config::ResolvedZone;
653    use fallow_types::discover::FileId;
654    use globset::Glob;
655    use serde_json::json;
656
657    use super::*;
658
659    /// The `fallow workspaces` / `fallow list --workspaces` envelope and the
660    /// MCP `project_info` tool have no post-serialization `strip_root_prefix`
661    /// pass, so `collect_workspace_output` is what makes their diagnostic
662    /// paths project-relative like every other envelope's.
663    #[test]
664    fn workspace_output_emits_project_relative_diagnostic_paths() {
665        let root = Path::new("/project");
666        let output = collect_workspace_output(
667            root,
668            &[],
669            &[fallow_config::WorkspaceDiagnostic::new(
670                root,
671                root.join("packages/inner"),
672                fallow_config::WorkspaceDiagnosticKind::UndeclaredWorkspace,
673            )],
674        );
675
676        let value = serde_json::to_value(&output).expect("workspaces output serializes");
677        assert_eq!(value["workspace_diagnostics"][0]["path"], "packages/inner");
678    }
679
680    fn empty_boundary_data() -> BoundaryData {
681        BoundaryData {
682            zones: vec![],
683            rules: vec![],
684            logical_groups: vec![],
685            is_empty: true,
686        }
687    }
688
689    fn boundary_data_to_json(data: &BoundaryData) -> serde_json::Value {
690        serde_json::to_value(boundary_data_to_output(data))
691            .expect("boundary list output should serialize")
692    }
693
694    fn resolved_zone(name: &str, patterns: &[&str]) -> ResolvedZone {
695        ResolvedZone {
696            name: name.to_string(),
697            patterns: patterns
698                .iter()
699                .map(|pattern| (*pattern).to_string())
700                .collect(),
701            matchers: patterns
702                .iter()
703                .map(|pattern| {
704                    Glob::new(pattern)
705                        .expect("valid test glob")
706                        .compile_matcher()
707                })
708                .collect(),
709            root: None,
710            public_files: vec![],
711            public_file_matchers: vec![],
712        }
713    }
714
715    fn discovered_files(root: &Path, relative_paths: &[&str]) -> Vec<DiscoveredFile> {
716        relative_paths
717            .iter()
718            .enumerate()
719            .map(|(index, relative_path)| DiscoveredFile {
720                id: FileId(u32::try_from(index).expect("test file count fits in u32")),
721                path: root.join(relative_path),
722                size_bytes: 0,
723            })
724            .collect()
725    }
726
727    use fallow_engine::git_fixture::fixture_git as git;
728
729    fn setup_changed_boundary_project() -> tempfile::TempDir {
730        let project = tempfile::tempdir().expect("project");
731        std::fs::write(
732            project.path().join("package.json"),
733            r#"{"name":"changed-list-api","main":"src/app/index.ts"}"#,
734        )
735        .expect("write package");
736        std::fs::write(
737            project.path().join(".fallowrc.json"),
738            r#"{
739                "boundaries": {
740                    "zones": [
741                        { "name": "app", "patterns": ["src/app/**"] },
742                        { "name": "shared", "patterns": ["src/shared/**"] }
743                    ]
744                }
745            }"#,
746        )
747        .expect("write config");
748        std::fs::create_dir_all(project.path().join("src/app")).expect("create app");
749        std::fs::create_dir_all(project.path().join("src/shared")).expect("create shared");
750        std::fs::write(
751            project.path().join("src/app/index.ts"),
752            "export const app = 1;\n",
753        )
754        .expect("write app");
755        std::fs::write(
756            project.path().join("src/shared/index.ts"),
757            "export const shared = 1;\n",
758        )
759        .expect("write shared");
760
761        git(project.path(), &["init", "-q"]);
762        git(
763            project.path(),
764            &["config", "user.email", "test@example.com"],
765        );
766        git(project.path(), &["config", "user.name", "Test User"]);
767        git(project.path(), &["config", "commit.gpgsign", "false"]);
768        git(project.path(), &["add", "."]);
769        git(project.path(), &["commit", "-qm", "initial"]);
770        std::fs::write(
771            project.path().join("src/app/index.ts"),
772            "export const app = 2;\n",
773        )
774        .expect("modify app");
775        project
776    }
777
778    #[test]
779    fn project_info_default_sections_match_plain_list_contract() {
780        let project = tempfile::tempdir().expect("project");
781        std::fs::write(
782            project.path().join("package.json"),
783            r#"{"name":"project-info-api","main":"src/index.ts"}"#,
784        )
785        .expect("write package");
786        std::fs::create_dir_all(project.path().join("src")).expect("create src");
787        std::fs::write(
788            project.path().join("src/index.ts"),
789            "export const value = 1;\n",
790        )
791        .expect("write source");
792
793        let output = serialize_project_info_programmatic_json(
794            run_project_info(&ProjectInfoOptions {
795                analysis: AnalysisOptions {
796                    root: Some(project.path().to_path_buf()),
797                    no_cache: true,
798                    ..AnalysisOptions::default()
799                },
800                ..ProjectInfoOptions::default()
801            })
802            .expect("project info should run"),
803        )
804        .expect("project info should serialize");
805
806        assert_eq!(output["file_count"], 1);
807        assert_eq!(output["files"][0], "src/index.ts");
808        assert_eq!(output["entry_point_count"], 1);
809        assert_eq!(output["workspace_count"], 0);
810        assert!(output.get("kind").is_none());
811    }
812
813    #[test]
814    fn project_info_surfaces_malformed_root_package_json() {
815        let project = tempfile::tempdir().expect("project");
816        std::fs::write(project.path().join("package.json"), "{").expect("write package");
817
818        let err = run_project_info(&ProjectInfoOptions {
819            analysis: AnalysisOptions {
820                root: Some(project.path().to_path_buf()),
821                no_cache: true,
822                ..AnalysisOptions::default()
823            },
824            ..ProjectInfoOptions::default()
825        })
826        .expect_err("malformed root package.json must fail project info");
827
828        assert_eq!(err.exit_code, 2);
829        assert_eq!(err.code.as_deref(), Some("FALLOW_CONFIG_LOAD_FAILED"));
830        assert!(
831            err.message.contains("package.json"),
832            "error should name the malformed root package.json"
833        );
834    }
835
836    #[test]
837    fn project_info_default_sections_include_undeclared_workspace_diagnostic() {
838        let project = tempfile::tempdir().expect("project");
839        std::fs::write(
840            project.path().join("package.json"),
841            r#"{"name":"project-info-api","workspaces":["packages/*"]}"#,
842        )
843        .expect("write package");
844        std::fs::create_dir_all(project.path().join("packages/app")).expect("workspace dir");
845        std::fs::write(
846            project.path().join("packages/app/package.json"),
847            r#"{"name":"app","main":"src/index.ts"}"#,
848        )
849        .expect("write workspace package");
850        std::fs::create_dir_all(project.path().join("tools/extra")).expect("extra package dir");
851        std::fs::write(
852            project.path().join("tools/extra/package.json"),
853            r#"{"name":"extra"}"#,
854        )
855        .expect("write extra package");
856
857        let output = serialize_project_info_programmatic_json(
858            run_project_info(&ProjectInfoOptions {
859                analysis: AnalysisOptions {
860                    root: Some(project.path().to_path_buf()),
861                    no_cache: true,
862                    ..AnalysisOptions::default()
863                },
864                ..ProjectInfoOptions::default()
865            })
866            .expect("project info should run"),
867        )
868        .expect("project info should serialize");
869
870        let diagnostics = output["workspace_diagnostics"]
871            .as_array()
872            .expect("project info should include workspace_diagnostics");
873        assert!(
874            diagnostics.iter().any(|diagnostic| {
875                diagnostic["kind"].as_str() == Some("undeclared-workspace")
876                    // Project-relative, like every other envelope's
877                    // `workspace_diagnostics[].path` (issue #2366 follow-up).
878                    && diagnostic["path"].as_str() == Some("tools/extra")
879            }),
880            "project info must include undeclared workspace diagnostics from the reused session, got {diagnostics:#?}"
881        );
882    }
883
884    /// Issue #2366: the MCP `project_info` tool reads the same workspace value
885    /// the `fallow workspaces` envelope does, so a glob declared in both
886    /// `package.json` and `pnpm-workspace.yaml` must reach an agent as one
887    /// entry per directory, project-relative, exactly as the CLI reports it.
888    #[test]
889    fn project_info_reports_one_entry_per_directory_for_a_glob_in_two_manifests() {
890        let project = tempfile::tempdir().expect("project");
891        let root = project.path();
892        std::fs::create_dir_all(root.join("pkgs/aaa")).expect("first package-less dir");
893        std::fs::create_dir_all(root.join("pkgs/bbb")).expect("second package-less dir");
894        std::fs::create_dir_all(root.join("src")).expect("source dir");
895        std::fs::write(
896            root.join("package.json"),
897            r#"{"name":"two-manifest-root","private":true,"workspaces":["./pkgs/*"]}"#,
898        )
899        .expect("write root manifest");
900        std::fs::write(
901            root.join("pnpm-workspace.yaml"),
902            "packages:\n  - \"pkgs/*\"\n",
903        )
904        .expect("write pnpm workspace manifest");
905        std::fs::write(root.join("src/index.ts"), "export const value = 1;\n")
906            .expect("write source");
907
908        let output = serialize_project_info_programmatic_json(
909            run_project_info(&ProjectInfoOptions {
910                analysis: AnalysisOptions {
911                    root: Some(root.to_path_buf()),
912                    no_cache: true,
913                    ..AnalysisOptions::default()
914                },
915                ..ProjectInfoOptions::default()
916            })
917            .expect("project info should run"),
918        )
919        .expect("project info should serialize");
920
921        let reported: Vec<(&str, &str)> = output["workspace_diagnostics"]
922            .as_array()
923            .expect("project info should include workspace_diagnostics")
924            .iter()
925            .filter(|diagnostic| diagnostic["kind"] == "glob-matched-no-package-json")
926            .map(|diagnostic| {
927                (
928                    diagnostic["pattern"].as_str().unwrap_or_default(),
929                    diagnostic["path"].as_str().unwrap_or_default(),
930                )
931            })
932            .collect();
933
934        assert_eq!(
935            reported,
936            vec![("pkgs/*", "pkgs/aaa"), ("pkgs/*", "pkgs/bbb")],
937            "project_info agrees with the CLI envelopes: {}",
938            output["workspace_diagnostics"]
939        );
940    }
941
942    #[test]
943    fn list_runtimes_scope_files_and_boundary_counts_to_changed_since() {
944        let project = setup_changed_boundary_project();
945        let analysis = AnalysisOptions {
946            root: Some(project.path().to_path_buf()),
947            changed_since: Some("HEAD".to_string()),
948            no_cache: true,
949            ..AnalysisOptions::default()
950        };
951
952        let project_info = serialize_project_info_programmatic_json(
953            run_project_info(&ProjectInfoOptions {
954                analysis: analysis.clone(),
955                files: true,
956                boundaries: true,
957                ..ProjectInfoOptions::default()
958            })
959            .expect("project info should run"),
960        )
961        .expect("project info should serialize");
962        let files = project_info["files"].as_array().expect("files array");
963        assert_eq!(files, &[json!("src/app/index.ts")]);
964        assert_eq!(project_info["boundaries"]["zones"][0]["file_count"], 1);
965        assert_eq!(project_info["boundaries"]["zones"][1]["file_count"], 0);
966
967        let boundaries = serialize_list_boundaries_programmatic_json(
968            run_list_boundaries(&ListBoundariesOptions { analysis })
969                .expect("list boundaries should run"),
970        )
971        .expect("list boundaries should serialize");
972        assert_eq!(boundaries["boundaries"]["zones"][0]["file_count"], 1);
973        assert_eq!(boundaries["boundaries"]["zones"][1]["file_count"], 0);
974    }
975
976    #[test]
977    fn boundary_zone_counts_preserve_first_match_for_overlapping_zones() {
978        let root = Path::new("project");
979        let boundaries = ResolvedBoundaryConfig {
980            zones: vec![
981                resolved_zone("source", &["src/**"]),
982                resolved_zone("shared", &["src/shared/**"]),
983            ],
984            ..ResolvedBoundaryConfig::default()
985        };
986        let files = discovered_files(root, &["src/app.ts", "src/shared/index.ts"]);
987
988        let zones = build_boundary_zones(root, &boundaries, Some(&files));
989
990        assert_eq!(zones[0].name, "source");
991        assert_eq!(zones[0].file_count, 2);
992        assert_eq!(zones[1].name, "shared");
993        assert_eq!(zones[1].file_count, 0);
994    }
995
996    #[test]
997    fn boundary_zone_counts_ignore_unmatched_and_out_of_root_files() {
998        let root = Path::new("project");
999        let boundaries = ResolvedBoundaryConfig {
1000            zones: vec![resolved_zone("matched", &["src/matched/**"])],
1001            ..ResolvedBoundaryConfig::default()
1002        };
1003        let mut files = discovered_files(root, &["src/matched/index.ts", "src/unmatched/index.ts"]);
1004        files.push(DiscoveredFile {
1005            id: FileId(2),
1006            path: PathBuf::from("outside/index.ts"),
1007            size_bytes: 0,
1008        });
1009
1010        let zones = build_boundary_zones(root, &boundaries, Some(&files));
1011
1012        assert_eq!(zones[0].file_count, 1);
1013    }
1014
1015    #[test]
1016    fn boundary_zone_counts_preserve_duplicate_name_semantics() {
1017        let root = Path::new("project");
1018        let boundaries = ResolvedBoundaryConfig {
1019            zones: vec![
1020                resolved_zone("shared", &["src/first/**"]),
1021                resolved_zone("shared", &["src/second/**"]),
1022            ],
1023            ..ResolvedBoundaryConfig::default()
1024        };
1025        let files = discovered_files(root, &["src/first/index.ts", "src/second/index.ts"]);
1026
1027        let zones = build_boundary_zones(root, &boundaries, Some(&files));
1028
1029        assert_eq!(zones[0].patterns, ["src/first/**"]);
1030        assert_eq!(zones[1].patterns, ["src/second/**"]);
1031        assert_eq!(zones[0].file_count, 2);
1032        assert_eq!(zones[1].file_count, 2);
1033    }
1034
1035    #[test]
1036    fn boundary_zone_output_is_deterministic_and_keeps_config_order() {
1037        let root = Path::new("project");
1038        let boundaries = ResolvedBoundaryConfig {
1039            zones: vec![
1040                resolved_zone("zeta", &["src/zeta/**"]),
1041                resolved_zone("alpha", &["src/alpha/**"]),
1042                resolved_zone("middle", &["src/middle/**"]),
1043            ],
1044            ..ResolvedBoundaryConfig::default()
1045        };
1046        let files = discovered_files(
1047            root,
1048            &[
1049                "src/middle/two.ts",
1050                "src/zeta/one.ts",
1051                "src/alpha/one.ts",
1052                "src/middle/one.ts",
1053            ],
1054        );
1055
1056        let first = build_boundary_zones(root, &boundaries, Some(&files));
1057        let second = build_boundary_zones(root, &boundaries, Some(&files));
1058        let signature = |zones: &[ZoneInfo]| {
1059            zones
1060                .iter()
1061                .map(|zone| (zone.name.clone(), zone.file_count))
1062                .collect::<Vec<_>>()
1063        };
1064
1065        assert_eq!(signature(&first), signature(&second));
1066        assert_eq!(
1067            signature(&first),
1068            vec![
1069                ("zeta".to_string(), 1),
1070                ("alpha".to_string(), 1),
1071                ("middle".to_string(), 2),
1072            ]
1073        );
1074    }
1075
1076    #[test]
1077    fn boundary_json_empty_includes_logical_groups_key() {
1078        let value = boundary_data_to_json(&empty_boundary_data());
1079
1080        assert_eq!(value["configured"], false);
1081        assert_eq!(value["zone_count"], 0);
1082        assert_eq!(value["rule_count"], 0);
1083        assert_eq!(value["logical_group_count"], 0);
1084        assert_eq!(value["logical_groups"], json!([]));
1085    }
1086
1087    #[test]
1088    fn boundary_json_logical_group_carries_all_fields() {
1089        let data = BoundaryData {
1090            zones: vec![ZoneInfo {
1091                name: "features/auth".to_string(),
1092                patterns: vec!["src/features/auth/**".to_string()],
1093                root: None,
1094                file_count: 3,
1095                public_files: vec![],
1096            }],
1097            rules: vec![],
1098            logical_groups: vec![LogicalGroupInfo {
1099                name: "features".to_string(),
1100                children: vec!["features/auth".to_string()],
1101                auto_discover: vec!["./src/features/".to_string()],
1102                authored_rule: Some(AuthoredRule {
1103                    allow: vec!["shared".to_string()],
1104                    allow_type_only: vec!["types".to_string()],
1105                }),
1106                fallback_zone: None,
1107                source_zone_index: 1,
1108                status: LogicalGroupStatus::Ok,
1109                file_count: 3,
1110                child_file_count: 3,
1111                fallback_file_count: 0,
1112                merged_from: None,
1113                original_zone_root: None,
1114                child_source_indices: vec![],
1115            }],
1116            is_empty: false,
1117        };
1118
1119        let value = boundary_data_to_json(&data);
1120        let group = &value["logical_groups"][0];
1121
1122        assert_eq!(value["logical_group_count"], 1);
1123        assert_eq!(group["name"], "features");
1124        assert_eq!(group["children"][0], "features/auth");
1125        assert_eq!(group["auto_discover"][0], "./src/features/");
1126        assert_eq!(group["status"], "ok");
1127        assert_eq!(group["source_zone_index"], 1);
1128        assert_eq!(group["file_count"], 3);
1129        assert_eq!(group["authored_rule"]["allow"][0], "shared");
1130        assert_eq!(group["authored_rule"]["allow_type_only"][0], "types");
1131        assert!(group.get("fallback_zone").is_none());
1132        assert!(group.get("merged_from").is_none());
1133        assert!(group.get("original_zone_root").is_none());
1134        assert!(group.get("child_source_indices").is_none());
1135    }
1136
1137    #[test]
1138    fn boundary_json_logical_group_optional_fields_round_trip() {
1139        let data = BoundaryData {
1140            zones: vec![],
1141            rules: vec![],
1142            logical_groups: vec![LogicalGroupInfo {
1143                name: "features".to_string(),
1144                children: vec!["features/auth".to_string(), "features/billing".to_string()],
1145                auto_discover: vec!["src/features".to_string(), "src/modules".to_string()],
1146                authored_rule: None,
1147                fallback_zone: Some("features".to_string()),
1148                source_zone_index: 0,
1149                status: LogicalGroupStatus::Empty,
1150                file_count: 2,
1151                child_file_count: 0,
1152                fallback_file_count: 2,
1153                merged_from: Some(vec![0, 3]),
1154                original_zone_root: Some("packages/app/".to_string()),
1155                child_source_indices: vec![0, 1],
1156            }],
1157            is_empty: false,
1158        };
1159
1160        let group = &boundary_data_to_json(&data)["logical_groups"][0];
1161
1162        assert_eq!(group["status"], "empty");
1163        assert_eq!(group["fallback_zone"], "features");
1164        assert_eq!(group["merged_from"][1], 3);
1165        assert_eq!(group["original_zone_root"], "packages/app/");
1166        assert_eq!(group["child_source_indices"][1], 1);
1167    }
1168}